VB Quadratic Programming Example

← All NMath Code Examples

 

Imports System

Imports CenterSpace.NMath.Core
Imports CenterSpace.NMath.Analysis

Namespace CenterSpace.NMath.Core.Examples.VisualBasic

  ''' A .NET example in Visual Basic
  Module QuadraticProgrammingExample

    ' Example illustrating the use of the ActiveSetQPSolver Module to
    ' solve a Quadratic Programming (QP) problem.
    Sub Main()

      ' 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)
      Dim H As New DoubleMatrix("2x2[2 0  0 2]")
      Dim C As New DoubleVector(-2.0, -5.0)

      ' Set up the QP problem
      Dim Problem As 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)

      Dim solver As New ActiveSetQPSolver()

      Console.WriteLine()

      If (solver.Solve(Problem) <> True) Then
        ' Solver failed to find a solution. Print out the solver status.
        Console.WriteLine("Solver failed. Status = {0}", solver.Status)
        Return
      End If

      ' 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()

    End Sub
  End Module
End Namespace

← All NMath Code Examples
Top