由于您的变量和约束很少,我们可以这样编写您的约束:
# (A) protein, at least (*)
15 <= 0.85*x[tomato] + 1.62*x[lettuce] + 12.78*x[spinach] + 8.39*x[carrot] + 0.0*x[oil]
# (B1) fat, at least (*)
2 <= 0.33*x[tomato] + 0.2*x[lettuce] + 1.58*x[spinach] + 1.39*x[carrot] + 100.0*x[oil]
# (B2) fat, at most
0.33*x[tomato] + 0.2*x[lettuce] + 1.58*x[spinach] + 1.39*x[carrot] + 100.0*x[oil] <= 6
# (C) carbo, at least (*)
4 <= 4.64*x[tomato] + 2.37*x[lettuce] + 74.69*x[spinach] + 80.7*x[carrot] + 0.0*x[oil]
# (D) sodium, at most
9.0*x[tomato] + 8.0*x[lettuce] + 7.0*x[spinach] + 508.2*x[carrot] + 0.0*x[oil] <= 100
(*)然而,正如@AirSquid所写的那样,你不能用linprog
来传递约束的下限,你必须改变约束的意义来设置上限.
# (A) protein, at least -> change inequation sens
-0.85*x[tomato] + -1.62*x[lettuce] + -12.78*x[spinach] + -8.39*x[carrot] + -0.0*x[oil] <= -15
# (B1) fat, at least -> change inequation sense
-0.33*x[tomato] + -0.2*x[lettuce] + -1.58*x[spinach] + -1.39*x[carrot] + -100.0*x[oil] <= -2
# (B2) fat, at most
0.33*x[tomato] + 0.2*x[lettuce] + 1.58*x[spinach] + 1.39*x[carrot] + 100.0*x[oil] <= 6
# (C) carbo, at least -> change inequation sense
-4.64*x[tomato] + -2.37*x[lettuce] + -74.69*x[spinach] + -80.7*x[carrot] + -0.0*x[oil] <= -4
# (D) sodium, at most
9.0*x[tomato] + 8.0*x[lettuce] + 7.0*x[spinach] + 508.2*x[carrot] + 0.0*x[oil] <= 100
(E)你不希望你的沙拉含有超过50%的蔬菜.
这意味着:
# (E) green mass
x[lettuce] + x[spinach] <= 0.5*(x[tomato] + x[lettuce] + x[spinach] + x[carrot] + x[oil])
您必须简化此表达式以提取系数:
# (E) green mass
-0.5*x[tomato] + 0.5*x[lettuce] + 0.5*x[spinach] + -0.5*x[carrot] + -0.5*x[oil] <= 0
现在,您可以创建c
、A_ub
和b_ub
参数:
c = [21, 16, 371, 346, 884]
A_ub = [[-0.85, -1.62, -12.78, -8.39, -0.0],
[-0.33, -0.2, -1.58, -1.39, -100.0],
[0.33, 0.2, 1.58, 1.39, 100.0],
[-4.64, -2.37, -74.69, -80.7, -0.0],
[9.0, 8.0, 7.0, 508.2, 0.0],
[-0.5, 0.5, 0.5, -0.5, -0.5]]
b_ub = [-15, -2, 6, -4, 100, 0]
bounds = [(0, None), (0, None), (0, None), (0, None), (0, None)])
linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds)
输出:
message: Optimization terminated successfully. (HiGHS Status 7: Optimal)
success: True
status: 0
fun: 232.5146989957854
x: [ 5.885e+00 5.843e+00 4.163e-02 0.000e+00 0.000e+00]
nit: 3
lower: residual: [ 5.885e+00 5.843e+00 4.163e-02 0.000e+00
0.000e+00]
marginals: [ 0.000e+00 0.000e+00 0.000e+00 1.292e+03
8.681e+02]
upper: residual: [ inf inf inf inf
inf]
marginals: [ 0.000e+00 0.000e+00 0.000e+00 0.000e+00
0.000e+00]
eqlin: residual: []
marginals: []
ineqlin: residual: [ 0.000e+00 1.176e+00 2.824e+00 4.026e+01
0.000e+00 0.000e+00]
marginals: [-3.159e+01 -0.000e+00 -0.000e+00 -0.000e+00
-2.414e+00 -3.174e+01]
mip_node_count: 0
mip_dual_bound: 0.0
mip_gap: 0.0