我试图通过使用apache-commons的Simplex解算器来解决以下线性问题:org.apache.commons.math3.optim.linear.SimplexSolver
。
n
是行数
m
是列数
L
是每行总和值的全局限制
这是我到目前为止所做的:
List<LinearConstraint> constraints = new ArrayList<>();
double[][] A = calculateAValues();
// m = count of columns
// constraint 1: the sum of values in all column must be <= 1
for(int i = 0; i < m; i++) {
double[] v = new double[n];
for(int j=0; j < n; j++) {
v[j] = 1;
}
constraints.add(new LinearConstraint(v, Relationship.LEQ, 1));
}
// n = count of rows
// constraint 2: sum of a_i,j in all row must be <= L (Limit)
for(int i = 0; i < n; i++) {
double[] v = new double[m];
for(int j=0; j < m; j++) {
v[j] = A[i][j];
}
constraints.add(new LinearConstraint(v, Relationship.LEQ, L));
}
double[] objectiveCoefficients = new double[n * m];
for(int i = 0; i < n * m; ++i) {
objectiveCoefficients[i] = 1;
}
LinearObjectiveFunction objective = new LinearObjectiveFunction(objectiveCoefficients, 0);
LinearConstraintSet constraintSet = new LinearConstraintSet(constraints);
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(objective, constraintSet, GoalType.MAXIMIZE);
return solution.getValue();
我无法正确获得目标函数,也可能缺少其他一些东西。到目前为止,我的所有尝试都产生了UnboundedSolutionException
。
答案 0 :(得分:4)
错误似乎在线性约束的系数数组中。
您有checkLevel(1,4)
个变量因此约束的系数数组和目标函数的长度必须为n*m
。不幸的是,n*m
如果它们比目标函数的数组短,则会静默扩展约束数组。因此,您的代码未指定导致无限制解决方案的正确约束。
约束1:所有列中的值之和必须为&lt; = 1
SimplexSolver
约束2:所有行中a_i,j的总和必须为&lt; = L(限制)
for(int j=0; j<m; j++)
{
double[] v = new double[n*m];
for(int i=0; i<n; i++)
v[i*n + j] = 1;
constraints.add(new LinearConstraint(v, Relationship.LEQ, 1));
}
目标coffecifients:
// n = count of rows
for(int i=0; i<n; i++)
{
double[] v = new double[n*m];
for(int j=0; j<m; j++)
v[i*n + j] = A[i][j];
constraints.add(new LinearConstraint(v, Relationship.LEQ, L));
}
由于约束2,约束double[] objectiveCoefficients = new double[n * m];
Arrays.fill(objectiveCoefficients, 1.0);
LinearObjectiveFunction objective = LinearObjectiveFunction(objectiveCoefficients, 0);
已经完成。
也许使用x_ij <= 1
明确指定0 <= x_ij
的约束会更清楚:
NonNegativeConstraint