我有三个产品和五盒:盒包装的Gurobi C#优化
var products = new string[] { "A", "B", "C"};
var boxes = new string[] { "1", "2", "3" ,"4","5"};
和尺寸是:
double[,] boxDimensions = new double[,]
{{8},
{15},
{30},
{40},
{50}};
double[,] productDimensions = new double[,]
{ { 5 },
{ 10 },
{ 20 } };
我想选择与所有的产品将被安装在minumum体块
我写了下面的代码,我知道我应该添加约束来选择只有他们一个框。 但它不工作(给不可行的溶胶)与当前状态。 代码如下可供选择:
感谢提前4侑帮助,
static void Main()
{
try
{
var products = new string[] { "A", "B", "C" };
var boxes = new string[] { "1", "2", "3", "4", "5" };
double[,] boxDimensions = new double[,] {{8},
{15},
{30},
{40},
{50}};
double[,] productDimensions =
new double[,] { { 5 },
{ 5 },
{ 20 }};
// Model
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.Set(GRB.StringAttr.ModelName, "box");
// Box decision variables: open[p] == 1 if box i is choosen.
GRBVar[] open = new GRBVar[boxes.Length];
for (int i = 0; i < boxes.Length; i++)
{
open[i] = model.AddVar(0, 1, boxDimensions[i, 0], GRB.BINARY, boxes[i]);
}
GRBVar[] x = new GRBVar[products.Length];
for (int j = 0; j < products.Length; j++)
{
x[j] = model.AddVar(productDimensions[j, 0], productDimensions[j, 0], 0, GRB.CONTINUOUS, products[j]);
}
// The objective is to minimize the total fixed and variable costs
model.Set(GRB.IntAttr.ModelSense, 1);
// Update model to integrate new variables
model.Update();
GRBLinExpr lhs = 0.0;
GRBLinExpr rhs = 0.0;
// Production constraints
// Note that the right-hand limit sets the production to zero if
// the plant is closed
// Constraint: assign exactly shiftRequirements[s] workers
// to each shift s
for (int s = 0; s < products.Length; ++s)
{
lhs.AddTerm(1.0, x[s]);
}
for (int w = 0; w < boxes.Length; w++)
{
rhs.AddTerm(boxDimensions[w, 0], open[w]);
}
model.AddConstr(lhs <= rhs, "BoxConstraint");
model.GetEnv().Set(GRB.IntParam.Method, GRB.METHOD_BARRIER);
// Solve
model.Optimize();
// Print solution
int status = model.Get(GRB.IntAttr.Status);
if (status == GRB.Status.UNBOUNDED)
{
Console.WriteLine("The model cannot be solved "
+ "because it is unbounded");
return;
}
if (status == GRB.Status.OPTIMAL)
{
Console.WriteLine("The optimal objective is " +
model.Get(GRB.DoubleAttr.ObjVal));
return;
}
if ((status != GRB.Status.INF_OR_UNBD) &&
(status != GRB.Status.INFEASIBLE))
{
Console.WriteLine("Optimization was stopped with status " + status);
return;
}
// Dispose of model and env
model.Dispose();
env.Dispose();
}
catch (GRBException e)
{
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
注:我给简单的问题(1D),其实我真正的问题是3D的问题。在这种情况下,我只考虑产品和盒子的长度,但在实际中我应该考虑宽度和高度。
出了什么问题?什么是(确切)问题?你使用了调试器吗?将预期值与实际值进行比较? – DrKoch 2015-02-10 10:57:30
我们希望模型只选择1个盒子,而不是其中两个(最小尺寸)。 @Jodrell你不懂吗?这是一维问题。所有长度的盒子(假设为棍子)。我们的问题将是3D – 2015-02-10 11:05:59
你为什么使用多维数组? – Jodrell 2015-02-10 11:10:42