Solving your first model in C#¶
LocalSolver is implemented in C++ language. Nevertheless, object-oriented application programming interfaces (APIs) are provided for .NET 2.0 (or superior), allowing a full integration of LocalSolver in your .NET business applications. LocalSolver’s APIs are lightweight, with only a few classes to manipulate. Note that LocalSolver is a model-and-run math programming solver: having instantiated the model, no additional code has to be written in order to run the solver.
In this section, we show you how to model and solve your first problem in C#: the optimization of the shape of a bucket. With a limited surface of material (S=π), we try to build a bucket that holds the largest volume.
This small example is more precisely described in our example tour. Here our main goal is to learn how to write and launch a model.
Writing the model¶
Below is the C# program which models this non linear problem (see examples/optimal_bucket).
/********** optimal_bucket.cs **********/
using System;
using System.IO;
using localsolver;
public class OptimalBucket : IDisposable
{
// Solver.
LocalSolver localsolver;
// LS Program variables.
LSExpression R;
LSExpression r;
LSExpression h;
LSExpression surface;
LSExpression volume;
public OptimalBucket()
{
localsolver = new LocalSolver();
}
public void Dispose()
{
if (localsolver != null)
localsolver.Dispose();
}
public void Solve(int limit)
{
// Declares the optimization model.
LSModel model = localsolver.GetModel();
// Numerical decisions
R = model.Float(0, 1);
r = model.Float(0, 1);
h = model.Float(0, 1);
// Surface must not exceed the surface of the plain disc
surface = Math.PI * model.Pow(r, 2) + Math.PI * (R + r) * model.Sqrt(model.Pow(R - r, 2) + model.Pow(h, 2));
model.AddConstraint(surface <= Math.PI);
// Maximize the volume
volume = Math.PI * h / 3 * (model.Pow(R, 2) + R * r + model.Pow(r, 2));
model.Maximize(volume);
model.Close();
// Parameterizes the solver.
localsolver.GetParam().SetTimeLimit(limit);
localsolver.Solve();
}
// Writes the solution in a file with the following format:
// - surface and volume of the bucket
// - values of R, r and h
public void WriteSolution(string fileName)
{
using (StreamWriter output = new StreamWriter(fileName))
{
output.WriteLine(surface.GetDoubleValue() + " " + volume.GetDoubleValue());
output.WriteLine(R.GetDoubleValue() + " " + r.GetDoubleValue() + " " + h.GetDoubleValue());
}
}
public static void Main(string[] args)
{
string outputFile = args.Length > 0 ? args[0] : null;
string strTimeLimit = args.Length > 1 ? args[1] : "2";
using (OptimalBucket model = new OptimalBucket())
{
model.Solve(int.Parse(strTimeLimit));
if (outputFile != null)
{
model.WriteSolution(outputFile);
}
}
}
}
After creating the LocalSolver environment LocalSolver(),
all the decision variables of the model, are declared with function
Float()
(or also Bool()
, Int()
, Set()
, List()
).
Intermediate expressions can be built upon these decision variables by using other
operators or functions. For example, in the model above: power (Pow
),
square root (Sqrt
), less than or equal to (<=
). Many other mathematical
operators are available, allowing you to model and solve highly-nonlinear
combinatorial optimization problems. The functions Constraint
or Maximize
are used for tagging expressions as constrained or maximized.
Compiling and running the C# program¶
On Windows, the above program is compiled and launched using the following lines in Visual Studio Command Prompt x64. Note that if you use directly Visual Studio IDE for building your program, you must specify the Platform target x64, in the Properties of your Visual Studio project.
copy %LS_HOME%\bin\localsolvernet.dll .
csc OptimalBucket.cs /reference:localsolvernet.dll
OptimalBucket
On Windows, in a PowerShell window you would use the following lines:
cp $env:LS_HOME/bin/localsolvernet.dll .
csc OptimalBucket.cs /reference:localsolvernet.dll
.\OptimalBucket
Then, the following trace will appear in your console:
LocalSolver 9.5.20200409-Win64. All rights reserved.
Load .\optimal_bucket.lsp...
Run model...
Run param...
Run solver...
Model: expressions = 26, decisions = 3, constraints = 1, objectives = 1
Param: time limit = 2 sec, no iteration limit
[objective direction ]: maximize
[ 0 sec, 0 itr]: 0
[ optimality gap ]: 100%
[ 0 sec, 42898 itr]: 0.68709
[ optimality gap ]: < 0.01%
42898 iterations performed in 0 seconds
Optimal solution:
obj = 0.68709
gap = < 0.01%
bounds = 0.687189
If no time limit is set, the search will continue until optimality is proven
(Optimal solution
message) or until you force the stop of the program by
pressing Ctrl+C
. The trace in console starts with the key
figures of the model: number of expressions, decisions, constraints
and objectives.
Once the search is finished, the total number of iterations and the elapsed time
are displayed, as well as the status and the value of the best solution
found. The solution status can be Inconsistent
, Infeasible
,
Feasible
or Optimal
.
If you have trouble compiling or launching the program, please have a look at the Installation & licensing. We invite users willing to go further with APIs to consult the C# API Reference.