使用C#语言求解您的第一个LOCAL SOLVER数学模型
我们是用C++语言实施LocalSolver的。不过,也为.NET 2.0(或更高版本)提供了“面向对象”的应用程序编程接口(API),允许在.NET业务应用程序中完全集成LocalSolver数学求解器算法。LocalSolver的API是轻量级的,只需要操纵几个类。请注意,LocalSolver是一个建模-运行方式的数学规划解算器:在实例化了模型之后,不需要编写额外的代码就能运行解算器。在本节中,我们将向您展示如何用C#建模和解决您的第一个问题:桶形的优化。在有限的材料表面(S=π)下,我们试图设计建造一个容量最大的桶。
这个小例子在我们的示例教程中有更精确的描述。在这里,我们的主要目标是学习如何编写和启动这个模型!下一章节:编译和运行C#程序(LOCAL SOLVER).
编写模型
下面是C#程序代码,它模拟了这个非线性问题(参见 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);
}
}
}
}
创建LocalSolver环境LocalSolver()之后,模型的所有决策变量都用函数Float()声明(也可以是Bool()、Int()、Set()、List()等)。中间表达式可以使用其他运算符或函数建立在这些决策变量的基础上。例如,在上面的模型中:幂(Pow),平方根(Sqrt),小于或等于(<=)等函数或运算符。还有许多其他的数学运算符是可用的,允许您建模和解决高度非线性的组合优化问题。函数Constraint(约束)或Maximize(最大化)用于将表达式标记为Constrained(受约束的)或maximized(最大化的)。如有其他问题或需求,请联系LOCALSOLVER中国区总代理‘无锡迅合信息科技有限公司“工作人员。。。(未完待续)2021-4-11