我有三個產品和五盒:盒包裝的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