我有一些由化学元素制成的材料,每公斤的价格是:
A: { cu: 0.02, mg: 0.3, nc: 0.005, price: 1000 }
这意味着 1 公斤材料 A 由 0.02 克“cu”、0.3 克“mg”、0.005 克“nc”制成,价格为 1000 美元。我还有一些其他类似的材料:
A: { cu: 0.02, mg: 0.3, nc: 0.005, price: 1000 }
B: { cu: 0.033, mg: 0.2, nc: 0.00, price: 1500 }
C: { cu: 0.05, mg: 0.35, nc: 0.00, price: 1700 }
我想制造一个产品,我们称之为 Pr_1,重量为 10 公斤,由材料 A、B 和/或 C 制成,因此 Pr_1 的价格最低。 Pr_1 也有一些限制:
Pr_1: {minCu: 0.00, maxCu: 1.2, minMg: 1.2, maxMg: 1.9, minNc: 0, maxNc: 0}
这意味着10公斤的Pr_1应该含有至少0.00g和最多1.2g“cu”,并且它应该含有至少1.2g和最多1.9g“mg”,并且不应该有任何“nc” 。正如我提到的,Pr_1 必须在材料 A、B 和 C 的所有可能组合中具有最低价格。
因此,我们将由材料 A、B 和 C 制成的 Pr_1 的重量分别表示为 x_A、x_B 和 x_C。目标是最小化总成本:
最小化:
1000*x_A + 1500*x_B + 1700*x_C
我们有 3 个不等式:
0.00 <= 0.02*x_A + 0.033*x_B + 0.05*x_C <= 1.2 // cu constraint
1.2 <= 0.03*x_A + 0.2*x_B + 0.35*x_C <= 1.9 // mg constraint
0.005*x_A + 0.00*x_B + 0.00*x_C = 0 // nc constraint
我不知道如何使用 Scipy 和 Python 来解决这个问题。
from scipy.optimize import linprog
# Coefficients of the objective function (costs)
c = [1000, 1500, 1700]
# Coefficients of the inequality constraints matrix
A = [
[-0.02, -0.033, -0.05], # Cu constraint
[-0.3, -0.2, -0.35], # Mg constraint
[-0.005, 0, 0] # Nc constraint
]
# Right-hand side of the inequality constraints
b = ???? # I don't know what this should be
# Bounds for each variable (x_A, x_B, x_C)
x_bounds = (0, None)
# Solve the linear programming problem
result = linprog(c, A_ub=A, b_ub=b, bounds=[x_bounds, x_bounds, x_bounds], method='highs')
# Print the results
print("Optimal weights for Pr_1 from A, B, and C:", result.x)
print("Minimum cost of Pr_1:", result.fun)
您帖子中定义的系统可以写如下:
from scipy import optimize
c = [1000, 1500, 1700]
A_ub = [
[0.02, 0.033, 0.05],
[0.3, 0.2, 0.35],
[-0.02, -0.033, -0.05],
[-0.3, -0.2, -0.35],
]
b_ub = [1.2, 1.9, 0.0, -1.2]
A_eq = [
[0.005, 0., 0.]
]
b_eq = [0.]
result = optimize.linprog(
c,
A_ub=A_ub, b_ub=b_ub,
A_eq=A_eq, b_eq=b_eq,
bounds=[(0., None)] * 3,
method='highs'
)
注意
0.005*x_A + 0.00*x_B + 0.00*x_C = 0
约束力x_A = 0.