Using lpsolve from Microsoft Solver Foundation

Microsoft Solver Foundation?

Microsoft Solver Foundation is an extensible .NET framework that helps you model and solve complex problems by:

Modeling and solving capabilities
Solver Foundation Services (SFS) can automatically analyze models and determine which solver is most appropriate. If you are an advanced modeler, you can choose specific solvers and solver attributes. While solving the models, SFS manages all threading, many-core, synchronization, scheduling, and model execution issues. When finished, SFS produces reports about solver behavior and results, and provides additional information about solutions, including sensitivity. Finally, SFS allows LINQ data binding of model parameters and delivery of results in multiple formats.

Program in OML, F#, C#, VB, C++, IronPython, and more
Solver Foundation supports all the .NET Framework languages and provides samples in many of them. In addition, if you prefer a modeling language, you can use Solver Foundation's type safe optimization modeling language (OML).

Integrated and Third-Party Solvers
Solver Foundation allows new or existing third-party solvers to plug into the SFS directly, avoiding the need to learn a new modeling language or the significant overhead in managing solver specific solutions. These solvers include numerical, symbolic, and search algorithms that you can use in your models. There is a collection of certified partner wrappers for Gurobi, Mosek™, FICO™ Xpress, and LINDO, as well as reference wrapper source code for CPLEX® and lp_solve.

The following system diagram describes the extensible architecture of Microsoft Solver Foundation.

sf-arch.jpg

For more information see Microsoft Solver Foundation blog

Introduction

Solver Foundation can be approached either at the Solver Foundation Services (SFS) level or via the APIs for specific kinds of solver.

The SFS level is recommended for conceptual clarity of modeling, for ease of binding to data from various sources, for educational use, for introducing you to all the capabilities of Solver Foundation, for automatic selection of a solver to suit your model, and for construction of models which may require the use of more than one kind of solver. Solver Foundation will be heavily investing in the SFS.

The Solver-specific APIs are intended for use by experienced programmers who clearly know which kind of solver they need to use, are prepared to write code to translate a model into a sequence of API calls, and where the usage is to be embedded in an application where the application is fully responsible for capturing the model and supplying the instance data.

The advantage of using the SFS level is that code is (almost) solver independent. In the ideal case the system chooses which solver to use dependent of the model and availability of solvers. Solver choice can also be instructed via the configuration file. To have more control of the chosen solver and its parameters also a specific solver directive can be chosen in the code. Only that directive code is then solver specific.

The advantage of using the API of the specific solver is that you have more control over the solvers' specific features. But the disadvantage is that you are targetting specifically that solver and it is thus more difficult to change solver.

The Microsoft solver foundation team recommend use of the Solver Foundation Services unless you are absolutely sure you need to program direct to a specific solver API.

Microsoft Foundation Solver and lpsolve

lpsolve is callable from Microsoft Foundation Solver via a wrapper or plugin. As such, it looks like lpsolve is fully integrated with Microsoft Foundation Solver.

This plugin acts as a bridge between Solver foundation and lpsolve.
Users of the plugin and MSF need to register the new solver in the app.config in order to use it.

To use the lpsolve plugin with MSF:

LpSolveDirective object

Microsoft Foundation Services can instruct the solver via a directive. All properties and methods starting with LpSolve are lp_solve specific and control the solver. All others are inherited from the base Directive object. These are the available properties and methods:

Arithmetic Get or set the arithmetic to use for numeric solving. lp_solve only allows double arithmetic. Setting this property to something different from Double or Default will result in a NotImplementedException exception.
GetSensitivity Whether to generate sensitivity information at report. The default is False.
LpSolveLogFunc A log callback function to allow lp_solve to return information to the application. See put_logfunc
LpSolveMsgFunc A message callback function to allow lp_solve to return information to the application. See put_msgfunc
LpSolveAntiDegen See set_anti_degen
LpSolveBasiscrash See set_basiscrash
LpSolveBbDepthlimit See set_bb_depthlimit
LpSolveBbFloorfirst See set_bb_floorfirst
LpSolveBbRule See set_bb_rule
LpSolveBreakAtFirst See set_break_at_first
LpSolveBreakAtValue See set_break_at_value
LpSolveDebug See set_debug
LpSolveEpsb See set_epsb
LpSolveEpsd See set_epsd
LpSolveEpsel See set_epsel
LpSolveEpsint See set_epsint
LpSolveEpsperturb See set_epsperturb
LpSolveEpspivot See set_epspivot
LpSolveImprove See set_improve
LpSolveInfinite See set_infinite
LpSolveLogFile See set_outputfile
LpSolveMaxpivot See set_maxpivot
LpSolveMipGapAbs See set_mip_gap
LpSolveMipGapRel See set_mip_gap
LpSolveNegrange See set_negrange
LpSolveObjBound See set_obj_bound
LpSolveObjInBasis See set_obj_in_basis
LpSolvePivoting See set_pivoting
LpSolvePresolve See set_presolve
LpSolvePresolveMaxLoops See set_presolve
LpSolveReadParams Read all settings from a file. See read_params
LpSolveScalelimit See set_scalelimit
LpSolveScaling See set_scaling
LpSolveSimplextype See set_simplextype
LpSolveSolutionlimit See set_solutionlimit
LpSolveTimeout See set_timeout
LpSolveTrace See set_trace
LpSolveVerbose See set_verbose
MaximumGoalCount Get and set the maximum number of goals to optimize. lp_solve allows only one goal. If something different from 1 is specified, a NotImplementedException will be thrown.
TimeLimit Get and set the time-limit (in milliseconds) of Solve. No limit if it is set to a negative value. Default value is -1 (no limit).
WaitLimit Get and set the amount of time (in milliseconds) the SFS will wait for a result after requesting a timeout/abort.

LpSolveSolver object (API)

When the solver is called directly via the API, the LpSolveSolver object is used to build and solve the model. All properties and methods starting with LpSolve are lp_solve specific and control the solver. All others are inherited from the base object. These are the available properties and methods:

LpSolveLogFunc A log callback function to allow lp_solve to return information to the application. See put_logfunc
LpSolveMsgFunc A message callback function to allow lp_solve to return information to the application. See put_msgfunc
LpSolvePrintDebugDump See print_debugdump
LpSolveWriteLp See write_lp
LpSolveWriteMPS See write_mps
LpSolveWriteParams See write_params
LpSolveWriteXLI See write_XLI

The LpSolveSolver object can also be subclassed to override the LpSolveLogFunc and LpSolveMsgFunc methods. That is an alternative for providing the these functions via the LpSolveLogFunc and LpSolveMsgFunc properties. That will be shown in the examples below.

SFS examples

Example1

static void Example1()
{
    // Create the model
    SolverContext context = SolverContext.GetContext();
    Model model = context.CreateModel();
    // Add a decision
    Decision x = new Decision(Domain.RealNonnegative, "x");
    model.AddDecisions(x);
    // Add a constraint
    model.AddConstraints("one", x == 1);

    //SimplexDirective simplex = new SimplexDirective();
    LpSolveDirective simplex = new LpSolveDirective();

    // Solve the problem
    Solution sol = context.Solve(simplex);
    // Display the results
    Console.WriteLine("x: {0}", x);

    Report report = sol.GetReport();

    Console.WriteLine(report);

    using (StreamWriter sw = new StreamWriter("Example1.mps"))
    {
        context.SaveModel(FileFormat.FreeMPS, sw);
    }
}

This gives as output:

x: 1
===Solver Foundation Service Report===
Date: 16-May-10 17:20:36
Version: Microsoft Solver Foundation 2.0.3.9657 Express Edition
Model Name: Default
Capabilities Applied: LP
Solve Time (ms): 34
Total Time (ms): 113
Solve Completion Status: Optimal
Solver Selected: SolverFoundation.Plugin.LpSolve.LpSolveSolver
Directives:
LpSolve(SolveAntiDegen:ANTIDEGEN_FIXEDVARS, ANTIDEGEN_STALLING,SolveBasiscrash:C
RASH_NOTHING,SolveBbDepthlimit:-50,SolveBbFloorfirst:BRANCH_AUTOMATIC,SolveBbRul
e:NODE_PSEUDONONINTSELECT, NODE_GREEDYMODE, NODE_DYNAMICMODE, NODE_RCOSTFIXING,S
olveBreakAtFirst:False,SolveBreakAtValue:-1E+30,SolveDebug:False,SolveEpsb:1E-10
,SolveEpsd:1E-09,SolveEpsel:1E-12,SolveEpsint:1E-07,SolveEpsperturb:1E-05,SolveE
pspivot:2E-07,SolveImprove:IMPROVE_DEFAULT,SolveInfinite:1E+30,SolveMaxpivot:250
,SolveMipGapAbs:1E-11,SolveMipGapRel:1E-11,SolveNegrange:-1000000,SolveObjBound:
1E+30,SolveObjInBasis:True,SolvePivoting:PRICER_DEVEX, PRICE_ADAPTIVE,SolvePreso
lve:PRESOLVE_NONE,SolvePresolveMaxLoops:2147483647,SolveScalelimit:5,SolveScalin
g:SCALE_GEOMETRIC, SCALE_EQUILIBRATE, SCALE_INTEGERS,SolveSimplextype:SIMPLEX_DU
AL_PRIMAL,SolveSolutionlimit:1,SolveTimeout(s):4294967296,SolveTrace:False,Solve
Verbose:4,Arithmetic:Double,TimeLimit (ms):-1,GetSensitivity:False,MaximumGoalCo
unt:1)
===SolverDetails====
Iteration Count:1
Presolve loops:2147483647
Pivot count:250
===Model details===
Variables:1
Rows:1
Non-zeros:1
===Solution Details===
Goals:

Decisions:
x: 1

Example2

static void Example2()
{
    // Get the context and create a new model.
    SolverContext context = SolverContext.GetContext();
    Model model = context.CreateModel();
    // Create two decision variables representing the number of barrels to
    // purchase from two countries.
    // AddDecisions tells the model about the two variables.
    Decision vz = new Decision(Domain.RealNonnegative, "barrels_venezuela");
    Decision sa = new Decision(Domain.RealNonnegative, "barrels_saudiarabia");
    model.AddDecisions(vz, sa);
    // Adding five constraints. The first line defines the allowable range // for the two decision variables. The other constraints put
    // minimums on the total yield of three products.
    model.AddConstraints("limits",
    0 <= vz <= 9000,
    0 <= sa <= 6000);
    model.AddConstraints("production",
    0.3 * sa + 0.4 * vz >= 2000,
    0.4 * sa + 0.2 * vz >= 1500,
    0.2 * sa + 0.3 * vz >= 500);
    // AddGoal states that we want to minimize the total cost subject to the
    // above constraints
    model.AddGoal("cost", GoalKind.Minimize,
    20 * sa + 15 * vz);

    // Solve the problem using the simplex solver
    //SimplexDirective simplex = new SimplexDirective();
    LpSolveDirective simplex = new LpSolveDirective();
    Solution solution = context.Solve(simplex);
    // Report the solution values
    Report report = solution.GetReport();
    Console.WriteLine("vz: {0}, sa: {1}", vz, sa);
    Console.Write("{0}", report);

    using (StreamWriter sw = new StreamWriter("Example2.mps"))
    {
        context.SaveModel(FileFormat.FreeMPS, sw);
    }
}

This gives as output:

vz: 3848290697215999/1099511627776, sa: 2199023255552001/1099511627776
===Solver Foundation Service Report===
Date: 16-May-10 17:27:53
Version: Microsoft Solver Foundation 2.0.3.9657 Express Edition
Model Name: Default
Capabilities Applied: LP
Solve Time (ms): 35
Total Time (ms): 119
Solve Completion Status: Optimal
Solver Selected: SolverFoundation.Plugin.LpSolve.LpSolveSolver
Directives:
LpSolve(SolveAntiDegen:ANTIDEGEN_FIXEDVARS, ANTIDEGEN_STALLING,SolveBasiscrash:C
RASH_NOTHING,SolveBbDepthlimit:-50,SolveBbFloorfirst:BRANCH_AUTOMATIC,SolveBbRul
e:NODE_PSEUDONONINTSELECT, NODE_GREEDYMODE, NODE_DYNAMICMODE, NODE_RCOSTFIXING,S
olveBreakAtFirst:False,SolveBreakAtValue:-1E+30,SolveDebug:False,SolveEpsb:1E-10
,SolveEpsd:1E-09,SolveEpsel:1E-12,SolveEpsint:1E-07,SolveEpsperturb:1E-05,SolveE
pspivot:2E-07,SolveImprove:IMPROVE_DEFAULT,SolveInfinite:1E+30,SolveMaxpivot:250
,SolveMipGapAbs:1E-11,SolveMipGapRel:1E-11,SolveNegrange:-1000000,SolveObjBound:
1E+30,SolveObjInBasis:True,SolvePivoting:PRICER_DEVEX, PRICE_ADAPTIVE,SolvePreso
lve:PRESOLVE_NONE,SolvePresolveMaxLoops:2147483647,SolveScalelimit:5,SolveScalin
g:SCALE_GEOMETRIC, SCALE_EQUILIBRATE, SCALE_INTEGERS,SolveSimplextype:SIMPLEX_DU
AL_PRIMAL,SolveSolutionlimit:1,SolveTimeout(s):4294967296,SolveTrace:False,Solve
Verbose:4,Arithmetic:Double,TimeLimit (ms):-1,GetSensitivity:False,MaximumGoalCo
unt:1)
===SolverDetails====
Iteration Count:2
Presolve loops:2147483647
Pivot count:250
===Model details===
Variables:2
Rows:6
Non-zeros:10
===Solution Details===
Goals:
cost: 92500

Decisions:
barrels_venezuela: 3500
barrels_saudiarabia: 2000

Example3

It is also possible to return and access the sensitivity information (from MSF version 2.1). This is demonstrated by this example. This is the same example as in the sensitivity section.

static void Example3()
{
    SolverContext context = SolverContext.GetContext();
    Model model = context.CreateModel();
    Decision COLONE = new Decision(Domain.RealRange(28.6, Rational.PositiveInfinity), "COLONE");
    Decision COLTWO = new Decision(Domain.RealNonnegative, "COLTWO");
    Decision COLTHREE = new Decision(Domain.RealNonnegative, "COLTHREE");
    Decision COLFOUR = new Decision(Domain.RealRange(18.0, 48.98), "COLFOUR");
    model.AddDecisions(COLONE, COLTWO, COLTHREE, COLFOUR);

    model.AddConstraints("THISROW",
    +78.26 * COLTWO + 2.9 * COLFOUR >= 92.3);

    model.AddConstraints("THATROW",
    +0.24 * COLONE + 11.31 * COLTHREE <= 14.8);

    model.AddConstraints("LASTROW",
    +12.68 * COLONE + 0.08 * COLTHREE + 0.9 * COLFOUR >= 4);

    model.AddGoal("cost", GoalKind.Minimize, COLONE + 3 * COLTWO + 6.24 * COLTHREE + 0.1 * COLFOUR);

    //SimplexDirective simplex = new SimplexDirective(); simplex.GetSensitivity = true;
    //LindoSimplexDirective simplex = new LindoSimplexDirective();
    //GurobiDirective simplex = new GurobiDirective(); simplex.GetSensitivity = true;
    LpSolveDirective simplex = new LpSolveDirective(); simplex.GetSensitivity = true;

    Solution solution = context.Solve(simplex);
    Report report = solution.GetReport();
    Console.Write("{0}", report);

    LinearReport lpReport = report as LinearReport;
    object ShadowPrices = lpReport.GetAllShadowPrices();
    object ConstraintBoundsSensitivity = lpReport.GetAllConstraintBoundsSensitivity();

    Console.WriteLine("Decisions");
    foreach (Decision d in solution.Decisions)
        Console.WriteLine("Name: " + d.Name + ", Description: " + d.Description);

    Console.WriteLine("GetAllShadowPrices:");
    foreach (KeyValuePair<string, Rational> o in lpReport.GetAllShadowPrices())
        Console.WriteLine("Key: " + o.Key + ", Value: " + o.Value.ToDouble().ToString());

    Console.WriteLine("GetAllConstraintBoundsSensitivity:");
    foreach (KeyValuePair<string, LinearSolverSensitivityRange> o in lpReport.GetAllConstraintBoundsSensitivity())
        Console.WriteLine("Key: " + o.Key + ", Current: " + o.Value.Current.ToDouble().ToString()  + ", Value.Lower: " + o.Value.Lower.ToDouble().ToString() + ", Value.Upper: " + o.Value.Upper.ToDouble().ToString());

    object[] indexes = new object[0];
    Console.WriteLine("GetGoalCoefficientSensitivity:");
    foreach (Decision d in solution.Decisions)
    {
        LinearSolverSensitivityRange ? o = lpReport.GetGoalCoefficientSensitivity(d, indexes);
        Console.WriteLine("Name: " + d.Name + ", Current: " + o.Value.Current.ToDouble().ToString() + ", Lower: " + o.Value.Lower.ToDouble().ToString() + ", Upper: " + o.Value.Upper.ToDouble().ToString());
    }

    using (StreamWriter sw = new StreamWriter("Example3.mps"))
    {
        context.SaveModel(FileFormat.FreeMPS, sw);
    }
}

Note that GetSensitivity on the directive must be set on true to get sensitivity information. By default this is not set and as in the examples above there is no sensitivity information provided if not set.

This gives as output:

===Solver Foundation Service Report===
Date: 16-May-10 17:32:08
Version: Microsoft Solver Foundation 2.0.3.9657 Express Edition
Model Name: Default
Capabilities Applied: LP
Solve Time (ms): 34
Total Time (ms): 119
Solve Completion Status: Optimal
Solver Selected: SolverFoundation.Plugin.LpSolve.LpSolveSolver
Directives:
LpSolve(SolveAntiDegen:ANTIDEGEN_FIXEDVARS, ANTIDEGEN_STALLING,SolveBasiscrash:C
RASH_NOTHING,SolveBbDepthlimit:-50,SolveBbFloorfirst:BRANCH_AUTOMATIC,SolveBbRul
e:NODE_PSEUDONONINTSELECT, NODE_GREEDYMODE, NODE_DYNAMICMODE, NODE_RCOSTFIXING,S
olveBreakAtFirst:False,SolveBreakAtValue:-1E+30,SolveDebug:False,SolveEpsb:1E-10
,SolveEpsd:1E-09,SolveEpsel:1E-12,SolveEpsint:1E-07,SolveEpsperturb:1E-05,SolveE
pspivot:2E-07,SolveImprove:IMPROVE_DEFAULT,SolveInfinite:1E+30,SolveMaxpivot:250
,SolveMipGapAbs:1E-11,SolveMipGapRel:1E-11,SolveNegrange:-1000000,SolveObjBound:
1E+30,SolveObjInBasis:True,SolvePivoting:PRICER_DEVEX, PRICE_ADAPTIVE,SolvePreso
lve:PRESOLVE_NONE,SolvePresolveMaxLoops:2147483647,SolveScalelimit:5,SolveScalin
g:SCALE_GEOMETRIC, SCALE_EQUILIBRATE, SCALE_INTEGERS,SolveSimplextype:SIMPLEX_DU
AL_PRIMAL,SolveSolutionlimit:1,SolveTimeout(s):4294967296,SolveTrace:False,Solve
Verbose:4,Arithmetic:Double,TimeLimit (ms):-1,GetSensitivity:True,MaximumGoalCou
nt:1)
===SolverDetails====
Iteration Count:1
Presolve loops:2147483647
Pivot count:250
===Model details===
Variables:4
Rows:4
Non-zeros:11
===Solution Details===
Goals:
cost: 31.7827586206897

Decisions:
COLONE: 28.6
COLTWO: 0
COLTHREE: 0
COLFOUR: 31.8275862068966

Shadow Pricing:
THISROW: 0.0344827586206897
THATROW: 0
LASTROW: 0

Goal Coefficients:
COLONE: 1 [0 Infinity]
COLTWO: 3 [2.69862068965517 Infinity]
COLTHREE: 6.24 [0 Infinity]
COLFOUR: 0.1 [-Infinity 0.111167901865576]

Constraint Bounds:
THISROW: 92.3 [52.2 142.042]
THATROW: 14.8 [-Infinity Infinity]
LASTROW: 4 [-Infinity Infinity]

Note that sensitivity information can also be retrieved from the report in variables via the methods GetAllShadowPrices() and GetAllConstraintBoundsSensitivity()

Example4

This example is an extension to Example3. Sensitivity is not asked and thus not reported. COLFOUR is defined as integer and an extra constraint is added. This constraint will be removed afterwards. Also log and message callback functions are set to show the lp_solve optimization process.

private static void LpSolveLogFunc(int lp, int userhandle, string buffer)
{
    Console.Write("{0}", buffer);
}

private static void LpSolveMsgFunc(int lp, int userhandle, LpSolveNativeInterface.lpsolve.lpsolve_msgmask message)
{
    Console.Write("{0}\n", message);
}

static void Example4()
{
    SolverContext context = SolverContext.GetContext();
    Model model = context.CreateModel();
    Decision COLONE = new Decision(Domain.RealRange(28.6, Rational.PositiveInfinity), "COLONE");
    Decision COLTWO = new Decision(Domain.RealNonnegative, "COLTWO");
    Decision COLTHREE = new Decision(Domain.RealNonnegative, "COLTHREE");
    Decision COLFOUR = new Decision(Domain.IntegerRange(18.0, 48.98), "COLFOUR");
    model.AddDecisions(COLONE, COLTWO, COLTHREE, COLFOUR);

    model.AddConstraints("THISROW",
    +78.26 * COLTWO + 2.9 * COLFOUR >= 92.3);

    model.AddConstraints("THATROW",
    +0.24 * COLONE + 11.31 * COLTHREE <= 14.8);

    model.AddConstraints("LASTROW",
    +12.68 * COLONE + 0.08 * COLTHREE + 0.9 * COLFOUR >= 4);

    Constraint extrarow = model.AddConstraints("EXTRAROW", +78.26 * COLTWO + 2.9 * COLFOUR >= 92.4);

    model.AddGoal("cost", GoalKind.Minimize, COLONE + 3 * COLTWO + 6.24 * COLTHREE + 0.1 * COLFOUR);

    //SimplexDirective simplex = new SimplexDirective();
    //LindoSimplexDirective simplex = new LindoSimplexDirective();
    //GurobiDirective simplex = new GurobiDirective();
    LpSolveDirective simplex = new LpSolveDirective(); simplex.LpSolveMsgFunc = LpSolveMsgFunc; simplex.LpSolveVerbose = 4; simplex.LpSolveLogFunc = LpSolveLogFunc;

    Solution solution = context.Solve(simplex);
    Report report = solution.GetReport();
    Console.Write("{0}", report);

    model.RemoveConstraint(extrarow);

    solution = context.Solve(simplex);
    report = solution.GetReport();
    Console.Write("{0}", report);
}

This gives as output:

Model name:  '' - run #1
Objective:   Minimize(R0)

SUBMITTED
Model size:        4 constraints,       4 variables,            9 non-zeros.
Sets:                                   0 GUB,                  0 SOS.

Using DUAL simplex for phase 1 and PRIMAL simplex for phase 2.
The primal and dual simplex pricing strategy set to 'Devex'.


Relaxed solution       31.7862068966 after          2 iter is B&B base.

MSG_LPOPTIMAL
Feasible solution               31.8 after          3 iter,         1 nodes (gap
 0.0%)
MSG_MILPFEASIBLE
Improved solution      31.7958343982 after          4 iter,         2 nodes (gap
 0.0%)
MSG_MILPBETTER

Optimal solution       31.7958343982 after          4 iter,         2 nodes (gap
 0.0%).

Excellent numeric accuracy ||*|| = 0

 MEMO: lp_solve version 5.5.2.5 for 32 bit OS, with 64 bit REAL variables.
      In the total iteration count 4, 0 (0.0%) were bound flips.
      There were 1 refactorizations, 0 triggered by time and 0 by density.
       ... on average 4.0 major pivots per refactorization.
      The largest [LUSOL v2.2.1.0] fact(B) had 8 NZ entries, 1.0x largest basis.

      The maximum B&B level was 2, 1.0x MIP order, 2 at the optimal solution.
      The constraint matrix inf-norm is 78.26, with a dynamic range of 978.25.
      Time to load data was 0.011 seconds, presolve used 0.005 seconds,
       ... 0.003 seconds in simplex solver, in total 0.019 seconds.
===Solver Foundation Service Report===
Date: 17-May-10 22:41:11
Version: Microsoft Solver Foundation 2.0.3.9657 Express Edition
Model Name: Default
Capabilities Applied: MILP
Solve Time (ms): 39
Total Time (ms): 133
Solve Completion Status: Optimal
Solver Selected: SolverFoundation.Plugin.LpSolve.LpSolveSolver
Directives:
LpSolve(SolveAntiDegen:ANTIDEGEN_FIXEDVARS, ANTIDEGEN_STALLING,SolveBasiscrash:C
RASH_NOTHING,SolveBbDepthlimit:-50,SolveBbFloorfirst:BRANCH_AUTOMATIC,SolveBbRul
e:NODE_PSEUDONONINTSELECT, NODE_GREEDYMODE, NODE_DYNAMICMODE, NODE_RCOSTFIXING,S
olveBreakAtFirst:False,SolveBreakAtValue:-1E+30,SolveDebug:False,SolveEpsb:1E-10
,SolveEpsd:1E-09,SolveEpsel:1E-12,SolveEpsint:1E-07,SolveEpsperturb:1E-05,SolveE
pspivot:2E-07,SolveImprove:IMPROVE_DEFAULT,SolveInfinite:1E+30,SolveMaxpivot:250
,SolveMipGapAbs:1E-11,SolveMipGapRel:1E-11,SolveNegrange:-1000000,SolveObjBound:
1E+30,SolveObjInBasis:True,SolvePivoting:PRICER_DEVEX, PRICE_ADAPTIVE,SolvePreso
lve:PRESOLVE_NONE,SolvePresolveMaxLoops:2147483647,SolveScalelimit:5,SolveScalin
g:SCALE_GEOMETRIC, SCALE_EQUILIBRATE, SCALE_INTEGERS,SolveSimplextype:SIMPLEX_DU
AL_PRIMAL,SolveSolutionlimit:1,SolveTimeout(s):4294967296,SolveTrace:False,Solve
Verbose:4,Arithmetic:Double,TimeLimit (ms):-1,GetSensitivity:False,MaximumGoalCo
unt:1)
===SolverDetails====
Iteration Count:4
Presolve loops:2147483647
Node Count:2
===Model details===
Variables:4
Rows:5
Non-zeros:13
===Solution Details===
Goals:
cost: 31.79583439816

Decisions:
COLONE: 28.6
COLTWO: 0.03194479938666
COLTHREE: 0
COLFOUR: 31

Model name:  '' - run #1
Objective:   Minimize(R0)

SUBMITTED
Model size:        3 constraints,       4 variables,            7 non-zeros.
Sets:                                   0 GUB,                  0 SOS.

Using DUAL simplex for phase 1 and PRIMAL simplex for phase 2.
The primal and dual simplex pricing strategy set to 'Devex'.


Relaxed solution       31.7827586207 after          1 iter is B&B base.

MSG_LPOPTIMAL
Feasible solution               31.8 after          2 iter,         1 nodes (gap
 0.1%)
MSG_MILPFEASIBLE
Improved solution      31.7920010222 after          3 iter,         2 nodes (gap
 0.0%)
MSG_MILPBETTER

Optimal solution       31.7920010222 after          3 iter,         2 nodes (gap
 0.0%).

Excellent numeric accuracy ||*|| = 0

 MEMO: lp_solve version 5.5.2.5 for 32 bit OS, with 64 bit REAL variables.
      In the total iteration count 3, 0 (0.0%) were bound flips.
      There were 1 refactorizations, 0 triggered by time and 0 by density.
       ... on average 3.0 major pivots per refactorization.
      The largest [LUSOL v2.2.1.0] fact(B) had 6 NZ entries, 1.0x largest basis.

      The maximum B&B level was 2, 1.0x MIP order, 2 at the optimal solution.
      The constraint matrix inf-norm is 78.26, with a dynamic range of 978.25.
      Time to load data was 0.000 seconds, presolve used 0.001 seconds,
       ... 0.002 seconds in simplex solver, in total 0.003 seconds.
===Solver Foundation Service Report===
Date: 17-May-10 22:41:12
Version: Microsoft Solver Foundation 2.0.3.9657 Express Edition
Model Name: Default
Capabilities Applied: MILP
Solve Time (ms): 4
Total Time (ms): 5
Solve Completion Status: Optimal
Solver Selected: SolverFoundation.Plugin.LpSolve.LpSolveSolver
Directives:
LpSolve(SolveAntiDegen:ANTIDEGEN_FIXEDVARS, ANTIDEGEN_STALLING,SolveBasiscrash:C
RASH_NOTHING,SolveBbDepthlimit:-50,SolveBbFloorfirst:BRANCH_AUTOMATIC,SolveBbRul
e:NODE_PSEUDONONINTSELECT, NODE_GREEDYMODE, NODE_DYNAMICMODE, NODE_RCOSTFIXING,S
olveBreakAtFirst:False,SolveBreakAtValue:-1E+30,SolveDebug:False,SolveEpsb:1E-10
,SolveEpsd:1E-09,SolveEpsel:1E-12,SolveEpsint:1E-07,SolveEpsperturb:1E-05,SolveE
pspivot:2E-07,SolveImprove:IMPROVE_DEFAULT,SolveInfinite:1E+30,SolveMaxpivot:250
,SolveMipGapAbs:1E-11,SolveMipGapRel:1E-11,SolveNegrange:-1000000,SolveObjBound:
1E+30,SolveObjInBasis:True,SolvePivoting:PRICER_DEVEX, PRICE_ADAPTIVE,SolvePreso
lve:PRESOLVE_NONE,SolvePresolveMaxLoops:2147483647,SolveScalelimit:5,SolveScalin
g:SCALE_GEOMETRIC, SCALE_EQUILIBRATE, SCALE_INTEGERS,SolveSimplextype:SIMPLEX_DU
AL_PRIMAL,SolveSolutionlimit:1,SolveTimeout(s):4294967296,SolveTrace:False,Solve
Verbose:4,Arithmetic:Double,TimeLimit (ms):-1,GetSensitivity:False,MaximumGoalCo
unt:1)
===SolverDetails====
Iteration Count:3
Presolve loops:2147483647
Node Count:2
===Model details===
Variables:4
Rows:4
Non-zeros:11
===Solution Details===
Goals:
cost: 31.7920010222336

Decisions:
COLONE: 28.6
COLTWO: 0.0306670074111935
COLTHREE: 0
COLFOUR: 31

API examples

Example5

private static void LpSolveLogFunc(int lp, int userhandle, string buffer)
{
    Console.Write("{0}", buffer);
}

private static void LpSolveMsgFunc(int lp, int userhandle, LpSolveNativeInterface.lpsolve.lpsolve_msgmask message)
{
    Console.Write("{0}\n", message);
}

static void Example5()
{
    LpSolveSolver solver = new LpSolveSolver();
    //SimplexSolver solver = new SimplexSolver();

    // data about the projects.
    double[] estimatedProfitOfProjectX = new double[] { 1, 1.8, 1.6, 0.8, 1.4 };
    double[] capitalRequiredForProjectX = new double[] { 6, 12, 10, 4, 8 };
    double availableCapital = 20;
    // decision variables.
    int[] chooseProjectX = new int[5];
    int goal;
    solver.AddRow("goal", out goal);
    solver.AddGoal(goal, 0, false);
    int expenditure;
    solver.AddRow("expenditure", out expenditure);
    solver.SetBounds(expenditure, 0, availableCapital);
    for (int i = 0; i < 5; i++)
    {
        solver.AddVariable(string.Format("project{0}", i),
        out chooseProjectX[i]);
        solver.SetBounds(chooseProjectX[i], 0, 1);
        // we either choose or don't choose the project; no half way decisions.
        solver.SetIntegrality(chooseProjectX[i], true);
        solver.SetCoefficient(goal, chooseProjectX[i],
        estimatedProfitOfProjectX[i]);
        solver.SetCoefficient(expenditure, chooseProjectX[i],
        capitalRequiredForProjectX[i]);
    }

    LpSolveDirective simplex = new LpSolveDirective(); simplex.LpSolveReadParams(@"params.par", ""); simplex.GetSensitivity = true; simplex.LpSolveLogFunc = LpSolveLogFunc; simplex.LpSolveMsgFunc = LpSolveMsgFunc; LpSolveParams param = new LpSolveParams(simplex);
    //SimplexSolverParams param = new SimplexSolverParams(); param.MixedIntegerGenerateCuts = true;

    ILinearSolution solution = solver.Solve(param);

    ILinearSolverReport sensitivity = solver.GetReport(LinearSolverReportType.Sensitivity);

    Console.WriteLine(solver.MipResult);
    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine("Project {0} is {1} selected.", i,
        solver.GetValue(chooseProjectX[i]) == 1 ? "" : "not ");
    }
    Console.WriteLine("The estimated total profit is: ${0}.",
    (double)solver.GetValue(goal).ToDouble());
    Console.WriteLine("The total expenditure is: ${0}.",
    solver.GetValue(expenditure).ToDouble());

    solver.LpSolveWriteParams(@"params.par", "");
    solver.LpSolveWriteLp(@"a.lp");
    solver.LpSolveWriteMPS(@"a.mps", true);
    solver.LpSolvePrintDebugDump(@"a.txt");
}

This gives as output:

Model name:  '' - run #1
Objective:   Maximize(R0)

SUBMITTED
Model size:        1 constraints,       5 variables,            5 non-zeros.
Sets:                                   0 GUB,                  0 SOS.

Using DUAL simplex for phase 1 and PRIMAL simplex for phase 2.
The primal and dual simplex pricing strategy set to 'Devex'.


Relaxed solution                3.52 after          2 iter is B&B base.

MSG_LPOPTIMAL
Feasible solution                  3 after          8 iter,         8 nodes (gap
 11.5%)
MSG_MILPFEASIBLE
Improved solution                3.4 after          9 iter,         9 nodes (gap
 2.7%)
MSG_MILPBETTER

Optimal solution                 3.4 after         10 iter,        10 nodes (gap
 2.7%).

Excellent numeric accuracy ||*|| = 0

 MEMO: lp_solve version 5.5.2.5 for 32 bit OS, with 64 bit REAL variables.
      In the total iteration count 10, 2 (20.0%) were bound flips.
      There were 5 refactorizations, 0 triggered by time and 0 by density.
       ... on average 1.6 major pivots per refactorization.
      The largest [LUSOL v2.2.1.0] fact(B) had 3 NZ entries, 1.0x largest basis.

      The maximum B&B level was 6, 0.6x MIP order, 3 at the optimal solution.
      The constraint matrix inf-norm is 12, with a dynamic range of 3.
      Time to load data was 0.013 seconds, presolve used 0.002 seconds,
       ... 0.003 seconds in simplex solver, in total 0.018 seconds.
Optimal
Project 0 is  selected.
Project 1 is not  selected.
Project 2 is  selected.
Project 3 is  selected.
Project 4 is not  selected.
The estimated total profit is: $3.4.
The total expenditure is: $20.

Example6

private class MyLpSolveSolver : LpSolveSolver
{
    public override void LpSolveLogFunc(int lp, int userhandle, string buffer)
    {
        base.LpSolveLogFunc(lp, userhandle, buffer);
        Console.Write("{0}", buffer);
    }

    public override void LpSolveMsgFunc(int lp, int userhandle, LpSolveNativeInterface.lpsolve.lpsolve_msgmask message)
    {
        base.LpSolveMsgFunc(lp, userhandle, message);
        Console.Write("{0}", message);
    }
}

static void Example6()
{
    MyLpSolveSolver solver = new MyLpSolveSolver();
    //SimplexSolver solver = new SimplexSolver();

    // add variables with their lower and upper bounds
    int savid, vzvid;
    solver.AddVariable("Saudi Arabia", out savid);
    solver.SetBounds(savid, 0, 9000);
    solver.AddVariable("Venezuela", out vzvid);
    solver.SetBounds(vzvid, 0, 6000);
    solver.SetIntegrality(vzvid, true);
    // add constraints to model
    int c1rid, c2rid, c3rid, goalrid;
    solver.AddRow("constraint1", out c1rid);
    solver.AddRow("constraint2", out c2rid);
    solver.AddRow("constraint3", out c3rid);
    solver.AddRow("goal", out goalrid);
    // add coefficients to constraint rows
    solver.SetCoefficient(c1rid, savid, 0.3);
    solver.SetCoefficient(c1rid, vzvid, 0.4);
    solver.SetBounds(c1rid, 2000, Rational.PositiveInfinity);
    solver.SetCoefficient(c2rid, savid, 0.4);
    solver.SetCoefficient(c2rid, vzvid, 0.2);
    solver.SetBounds(c2rid, 1500, Rational.PositiveInfinity);
    solver.SetCoefficient(c3rid, savid, 0.2);
    solver.SetCoefficient(c3rid, vzvid, 0.3);
    solver.SetBounds(c3rid, 500, Rational.PositiveInfinity);
    // add objective (goal) to model and specify minimization (==true)
    solver.SetCoefficient(goalrid, savid, 20);
    solver.SetCoefficient(goalrid, vzvid, 15);
    solver.AddGoal(goalrid, 1, true);
    // solve the model

    LpSolveDirective simplex = new LpSolveDirective(); simplex.GetSensitivity = true; ; simplex.LpSolveVerbose = 4; LpSolveParams parameter = new LpSolveParams(simplex);
    //SimplexSolverParams parameter = new SimplexSolverParams(); parameter.GetSensitivityReport = true;
    //SimplexSolverParams parameter = new DemoSimplexSolverParams(); parameter.GetSensitivityReport = true;

    ILinearSolution solution = solver.Solve(parameter);
    Console.WriteLine("SA {0}, VZ {1}, C1 {2}, C2 {3}, C3 {4}, Goal {5}",
    solver.GetValue(savid).ToDouble(), solver.GetValue(vzvid).ToDouble(),
    solver.GetValue(c1rid).ToDouble(), solver.GetValue(c2rid).ToDouble(),
    solver.GetValue(c3rid).ToDouble(), solver.GetValue(goalrid).ToDouble());

    Console.WriteLine("{0}", solver.PivotCount);
    Console.WriteLine("{0}", solver.AlgorithmUsed);

    Console.WriteLine("{0}", solver.GetDualValue(2).ToDouble());
    solver.LpSolveWriteParams(@"d:\brol\params.par", "");

    ILinearSolverReport report = solver.GetReport(LinearSolverReportType.Sensitivity);

    Report Report = report as Report;
    LinearReport lpReport = report as LinearReport;
}

This gives as output:

Model name:  '' - run #1
Objective:   Minimize(R0)

SUBMITTED
Model size:        3 constraints,       2 variables,            6 non-zeros.
Sets:                                   0 GUB,                  0 SOS.

Using DUAL simplex for phase 1 and PRIMAL simplex for phase 2.
The primal and dual simplex pricing strategy set to 'Devex'.


Relaxed solution               92500 after          2 iter is B&B base.

MSG_LPOPTIMALFeasible solution              92500 after          2 iter,
 0 nodes (gap 0.0%)
MSG_MILPFEASIBLE
Optimal solution               92500 after          2 iter,         0 nodes (gap
 0.0%).

Excellent numeric accuracy ||*|| = 0

 MEMO: lp_solve version 5.5.2.5 for 32 bit OS, with 64 bit REAL variables.
      In the total iteration count 2, 0 (0.0%) were bound flips.
      There were 0 refactorizations, 0 triggered by time and 0 by density.
       ... on average 2.0 major pivots per refactorization.
      The largest [LUSOL v2.2.1.0] fact(B) had 4 NZ entries, 1.0x largest basis.

      The maximum B&B level was 1, 0.5x MIP order, 1 at the optimal solution.
      The constraint matrix inf-norm is 0.4, with a dynamic range of 2.
      Time to load data was 0.014 seconds, presolve used 0.002 seconds,
       ... 3.674 seconds in simplex solver, in total 3.690 seconds.
SA 2000, VZ 3500, C1 2000, C2 1500, C3 1450, Goal 92500
250
Primal
20

Example7

static void Example7()
{
    LpSolveSolver solver = new LpSolveSolver();
    int COLONE, COLTWO, COLTHREE, COLFOUR;

    solver.AddVariable("COLONE", out COLONE); solver.SetBounds(COLONE, 28.6, Rational.PositiveInfinity);
    solver.AddVariable("COLTWO", out COLTWO); solver.SetBounds(COLTWO, 0.0, Rational.PositiveInfinity);
    solver.AddVariable("COLTHREE", out COLTHREE); solver.SetBounds(COLTHREE, 0.0, Rational.PositiveInfinity);
    solver.AddVariable("COLFOUR", out COLFOUR); solver.SetBounds(COLFOUR, 18.0, 48.98);

    int THISROW, THATROW, LASTROW, goal;
    solver.AddRow("THISROW", out THISROW); solver.SetBounds(THISROW, 92.3, Rational.PositiveInfinity); solver.SetCoefficient(THISROW, COLTWO, 78.26); solver.SetCoefficient(THISROW, COLFOUR, 2.9);
    solver.AddRow("THATROW", out THATROW); solver.SetBounds(THATROW, Rational.NegativeInfinity, 14.8); solver.SetCoefficient(THATROW, COLONE, 0.24); solver.SetCoefficient(THATROW, COLTHREE, 11.31);
    solver.AddRow("LASTROW", out LASTROW); solver.SetBounds(LASTROW, 4.0, Rational.PositiveInfinity); solver.SetCoefficient(LASTROW, COLONE, 12.68); solver.SetCoefficient(LASTROW, COLTHREE, 0.08); solver.SetCoefficient(LASTROW, COLFOUR, 0.9);

    solver.AddRow("goal", out goal); solver.SetCoefficient(goal, COLONE, 1.0); solver.SetCoefficient(goal, COLTWO, 3.0); solver.SetCoefficient(goal, COLTHREE, 6.24); solver.SetCoefficient(goal, COLFOUR, 0.1);
    solver.AddGoal(goal, 1, true);

    LpSolveDirective simplex = new LpSolveDirective(); simplex.GetSensitivity = true; ; simplex.LpSolveVerbose = 4; LpSolveParams parameter = new LpSolveParams(simplex);
    ILinearSolution solution = solver.Solve(parameter);

    solver.LpSolveWriteLp("con");

    double Value;

    Console.WriteLine("GetValue:");
    foreach (int vid in solver.VariableIndices)
    {
        Value = solver.GetValue(vid).ToDouble();
        Console.WriteLine(solver.GetKeyFromIndex(vid) + ": Value: " + Value.ToString());
    }

    Console.WriteLine("GetDualValue:");
    foreach (int rid in solver.RowIndices)
    {
        if (!solver.IsGoal(rid))
        {
            Value = solver.GetDualValue(rid).ToDouble();
            Console.WriteLine(solver.GetKeyFromIndex(rid) + ": Value: " + Value.ToString());
        }
    }
    foreach (int vid in solver.VariableIndices)
    {
        Value = solver.GetDualValue(vid).ToDouble();
        Console.WriteLine(solver.GetKeyFromIndex(vid) + ": Value: " + Value.ToString());
    }

    LinearSolverSensitivityRange x;

    Console.WriteLine("Variable GetVariableRange:");
    foreach (int vid in solver.VariableIndices)
    {
        x = solver.GetVariableRange(vid);
        Console.WriteLine(solver.GetKeyFromIndex(vid) + ": Current: " + x.Current.ToDouble().ToString() + ", Lower: " + x.Lower.ToDouble().ToString() + ", Upper: " + x.Upper.ToDouble().ToString());
    }

    Console.WriteLine("RHS GetVariableRange:");
    foreach (int rid in solver.RowIndices)
    {
        if (!solver.IsGoal(rid))
        {
            x = solver.GetVariableRange(rid);
            Console.WriteLine(solver.GetKeyFromIndex(rid) + ": Current: " + x.Current.ToDouble().ToString() + ", Lower: " + x.Lower.ToDouble().ToString() + ", Upper: " + x.Upper.ToDouble().ToString());
        }
    }

    Console.WriteLine("GetObjectiveCoefficientRange:");
    foreach (int vid in solver.VariableIndices)
    {
        x = solver.GetObjectiveCoefficientRange(vid);
        Console.WriteLine(solver.GetKeyFromIndex(vid) + ": Current: " + x.Current.ToDouble().ToString() + ", Lower: " + x.Lower.ToDouble().ToString() + ", Upper: " + x.Upper.ToDouble().ToString());
    }
}

This gives as output:

/* Objective function */
min: +C1 +3 C2 +6.24 C3 +0.1 C4;

/* Constraints */
+78.26 C2 +2.9 C4 >= 92.3;
+0.24 C1 +11.31 C3 <= 14.8;
+12.68 C1 +0.08 C3 +0.9 C4 >= 4;

/* Variable bounds */
C1 >= 28.6;
18 <= C4 <= 48.98;
GetValue:
COLONE: Value: 28.6
COLTWO: Value: 0
COLTHREE: Value: 0
COLFOUR: Value: 31.8275862068966
GetDualValue:
THISROW: Value: 0.0344827586206897
THATROW: Value: 0
LASTROW: Value: 0
COLONE: Value: 1
COLTWO: Value: 0.301379310344828
COLTHREE: Value: 6.24
COLFOUR: Value: 0
Variable GetVariableRange:
COLONE: Current: 28.6, Lower: -1.94359839007941, Upper: 61.6666666666667
COLTWO: Current: 0, Lower: -0.635599284436494, Upper: 0.512394582162024
COLTHREE: Current: 0, Lower: -4841.16034482759, Upper: 0.701679929266136
COLFOUR: Current: 18, Lower: -Infinity, Upper: Infinity
RHS GetVariableRange:
THISROW: Current: 92.3, Lower: 52.2, Upper: 142.042
THATROW: Current: 14.8, Lower: -Infinity, Upper: Infinity
LASTROW: Current: 4, Lower: -Infinity, Upper: Infinity
GetObjectiveCoefficientRange:
COLONE: Current: 1, Lower: 0, Upper: Infinity
COLTWO: Current: 3, Lower: 2.69862068965517, Upper: Infinity
COLTHREE: Current: 6.24, Lower: 0, Upper: Infinity
COLFOUR: Current: 0.1, Lower: -Infinity, Upper: 0.111167901865576

See also Using lpsolve from MATLAB, Using lpsolve from O-Matrix, Using lpsolve from Sysquake, Using lpsolve from Octave, Using lpsolve from FreeMat, Using lpsolve from Euler, Using lpsolve from Python, Using lpsolve from Sage, Using lpsolve from PHP, Using lpsolve from Scilab