Python优化(spicy.optimize) - 约束问题

时间:2018-05-03 12:37:34

标签: python optimization scipy mathematical-optimization

我正在尝试使用下面提供的代码优化数学问题。代码运行时没有错误,但它会在不考虑约束的情况下打印结果。 p1和p2是工厂的产品,m1,m2,m3是生产所需的原材料(我提供这条信息,以防有人想知道m1,m2,m3和p1之间的等式,p2代表什么)。知道什么可能是错的吗?

import numpy as np
from scipy.optimize import minimize

earnings_p1 = 150
earnings_p2 = 175
costs_m1 = 10
costs_m2 = 17
costs_m3 = 25

def objective(x):
    quantity_p1 = x[0]
    quantity_p2 = x[1]
    quantity_m1 = 2 * quantity_p1 + 1 * quantity_p2
    quantity_m2 = 5 * quantity_p1 + 3 * quantity_p2
    quantity_m3 = 0 * quantity_p1 + 4 * quantity_p2
    total_costs = quantity_m1 * costs_m1 + quantity_m2 * costs_m2 + quantity_m3 * costs_m3
    total_earnings = quantity_p1 * earnings_p1 + quantity_p2 * earnings_p2
    total_profit = total_earnings - total_costs
    return -total_profit

def constraint1(x):
    quantity_p1 = x[0]
    quantity_p2 = x[1]
    quantity_m1 = 2 * quantity_p1 + 1 * quantity_p2
    return 100 - quantity_m1

def constraint2(x):
    quantity_p1 = x[0]
    quantity_p2 = x[1]
    quantity_m2 = 5 * quantity_p1 + 3 * quantity_p2
    return 80 - quantity_m2

def constraint3(x):
    quantity_p1 = x[0]
    quantity_p2 = x[1]
    quantity_m3 = 0 * quantity_p1 + 4 * quantity_p2
    return 150 - quantity_m3

cons1 = ({'type': 'ineq', 'fun': constraint1})
cons2 = ({'type': 'ineq', 'fun': constraint2})
cons3 = ({'type': 'ineq', 'fun': constraint3})
cons = [cons1, cons2, cons3]

quantity_p1_guess = 10
quantity_p2_guess = 20

x0 = np.array([quantity_p1_guess, quantity_p2_guess])

solution = minimize(objective, x0, method='SLSQP', constraints=cons, options={'disp': True})
print(solution)

0 个答案:

没有答案