C# Quadratic Programming Example

[TOC]

using System;

using CenterSpace.NMath.Core;
using CenterSpace.NMath.Analysis;

namespace CenterSpace.NMath.Core.Examples.CSharp
{
  class QuadraticProgrammingExample
  {
    /// Example illustrating the use of the ActiveSetQPSolver class to
    /// solve a Quadratic Programming (QP) problem.
    static void Main( string[] args )
    {
      // Minimize q(x) = (x0 - 1)^2 + (x1 - 2.5)^2
      // subject to -x0 + 2*x1 <= 2
      //             x0 - 2*x1 >= -6
      //            -x0 + 2*x1 >= -2
      //                    x0 >= 0
      //                    x1 >= 0

      // Translating the objective function into the form
      // 0.5*x'Hx + x'c 
      // yields
      // H = | 2 0 |
      //     | 0 2 |
      //
      // x = [-2 -5]
      DoubleMatrix H = new DoubleMatrix( "2x2[2 0  0 2]" );
      DoubleVector c = new DoubleVector( -2.0, -5.0 );

      // Set up the QP problem
      QuadraticProgrammingProblem problem = new QuadraticProgrammingProblem( H, c );
      problem.AddUpperBoundConstraint( new DoubleVector( -1.0, 2.0 ), 2.0 );
      problem.AddLowerBoundConstraint( new DoubleVector( 1.0, -2.0 ), -6.0 );
      problem.AddLowerBoundConstraint( new DoubleVector( -1.0, 2.0 ), -2.0 );
      // add the lower bound of 0 for x0
      problem.AddLowerBound( 0, 0 );
      // add the lower bound of 0 for x1
      problem.AddLowerBound( 1, 0 );
      ActiveSetQPSolver solver = new ActiveSetQPSolver();

      Console.WriteLine();

      if ( !solver.Solve( problem ) )
      {
        // Solver failed to find a solution. Print out the solver status.
        Console.WriteLine( "Solver failed. Status = {0}", solver.Status );
        return;
      }

      // Solver found a solution. Print out the optimal x and objective function
      // values and the number of iterations.
      Console.WriteLine( "Solver found solution (x0, x1) = ({0}, {1}) after {2} iterations",
        solver.OptimalX[0], solver.OptimalX[1], solver.Iterations );
      Console.WriteLine( "Optimal objective function value = {0}", solver.OptimalObjectiveFunctionValue );

      Console.WriteLine();
      Console.WriteLine( "Press Enter Key" );
      Console.Read();
    }
  }
}

[TOC]