我有三个产品和五个盒子:
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 } };
我想选择最小容量的盒子,所有产品都适合。
我写了下面的代码,我知道我应该添加约束来在它们中只选择1个框。 但它没有工作(给不可行的溶胶)当前的状态。 代码如下:
先谢谢你的帮助,
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问题。在这种情况下,我只考虑产品和盒子的长度,但实际上我也应该考虑宽度和高度。
答案 0 :(得分:0)
您编写模型的一般方法是可以的。
然而,对于x,您将下限和上限设置为修复x的相同值。此外,我想知道为什么你让Gurobi使用障碍法。我不确定您正在使用的MIP设置中是否正确。