Solving your first model in C#¶
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. The main goal of this page is to show how to write and launch a model.
Writing the model¶
Below is the C# program which models this nonlinear problem (see examples/optimal_bucket).
using System;
using System.IO;
using Hexaly.Optimizer;
public class OptimalBucket : IDisposable
{
// Hexaly Optimizer
HexalyOptimizer optimizer;
// Hexaly Program variables
HxExpression R;
HxExpression r;
HxExpression h;
HxExpression surface;
HxExpression volume;
public OptimalBucket()
{
optimizer = new HexalyOptimizer();
}
public void Dispose()
{
if (optimizer != null)
optimizer.Dispose();
}
public void Solve(int limit)
{
// Declare the optimization model
HxModel model = optimizer.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();
// Parametrize the optimizer
optimizer.GetParam().SetTimeLimit(limit);
optimizer.Solve();
}
// Write 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 Hexaly Optimizer environment with HexalyOptimizer()
,
all the decision variables of the model are declared with the Float()
function (or also Bool()
, Int()
, Set()
, List()
, Interval()
).
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 methods Constraint
or
Maximize
are used for tagging expressions as constrained or maximized.
Compiling and running the C# program with .NET¶
You can use the following lines on any platform:
dotnet create console
Copy Hexaly.NET.dll from your install directory into a libs subfolder, then edit
your .csproj
file to add the following lines:
<ItemGroup>
<Reference Include="LibraryName">
<HintPath>libs\Hexaly.NET.dll</HintPath>
</Reference>
</ItemGroup>
Finally, you can go back to your terminal to write the following lines:
dotnet build
dotnet run
Compiling and running the C# program with .NET Framework¶
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 %HX_HOME%\bin\Hexaly.NET.dll .
csc OptimalBucket.cs /reference:Hexaly.NET.dll
OptimalBucket
Generated output¶
The following trace will appear in your terminal:
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.