Как я go могу создать оптимизацию, которая LpMaximmизирует прибыль и LpMinimize дисперсия?
Я попытался сделать VAR отрицательным, чем с помощью LpMaximize. Код ниже только максимальная переменная, а не минимальная переменная и максимальная прибыль.
prob += lpSum([profits[i]*x[i] for i in N] and [var[v]*x[v] for v in N]) #tried this
my full code is below
from pulp import *
# PROBLEM DATA:
costs = [15, 25, 35, 40, 45, 55]
profits = [1.7, 2, 2.4, 3.2, 5.6, 6.2]
var=[24, 12, 24, 32, 52, 62]
city = ["NYC","SF","LA","SF","NYC","LA"]
max_cost = 2500
max_to_pick = 4
# DECLARE PROBLEM OBJECT:
prob = LpProblem("Mixed Problem", LpMaximize)
# VARIABLES
n = len(costs)
N = range(n)
x = LpVariable.dicts('x', N, cat="Binary")
# OBJECTIVE
prob += lpSum([profits[i]*x[i] for i in N] and [var[v]*x[v] for v in N])
# CONSTRAINTS
prob += lpSum([x[i] for i in N]) == max_to_pick # to include
prob += lpSum([x[i]*costs[i] for i in N]) <= max_cost # Limit max.
# NEW CONSTRAINT
for c in set(city):
index_list = [i for i in N if city[i] == c]
prob += lpSum([x[i] for i in index_list]) <= 1
# SOLVE & PRINT RESULTS
prob.solve()
print(LpStatus[prob.status])
print('Profit = ' + str(value(prob.objective)))
print('Cost = ' + str(sum([x[i].varValue*costs[i] for i in N])))
for v in prob.variables ():
print (v.name, "=", v.varValue)
Большое спасибо!
Я думаю, что это окончательный ответ
from pulp import *
# PROBLEM DATA:
costs = [15, 25, 35, 40, 45, 55]
profits = [1.7, 2, 2.4, 3.2, 5.6, 6.2]
var=[24, 12, 24, 32, 52, 62]
city = ["NYC","SF","LA","SF","NYC","LA"]
max_cost = 2500
max_to_pick = 4
# DECLARE PROBLEM OBJECT:
prob = LpProblem("Mixed Problem", LpMaximize)
# VARIABLES
n = len(costs)
N = range(n)
x = LpVariable.dicts('x', N, cat="Binary")
# OBJECTIVE
prob += lpSum([profits[i]*x[i] for i in N])
# CONSTRAINTS
prob += lpSum([x[i] for i in N]) == max_to_pick #Limit number
prob += lpSum([x[i]*costs[i] for i in N]) <= max_cost #max cost
# NEW CONSTRAINT
for c in set(city):
index_list = [i for i in N if city[i] == c]
prob += lpSum([x[i] for i in index_list]) <= 1
# SOLVE & PRINT RESULTS
prob.solve()
obj = value(prob.objective)
print(LpStatus[prob.status])
print('obj = ' + str(value(prob.objective)))
# MODIFY PROBLEM FOR 2ND PROBLEM
prob.sense = LpMinimize # change sense to LpMinimize
prob += lpSum([var[v]*x[v] for v in N]) # Reset the objective
prob += lpSum([profits[i]*x[i] for i in N]) == obj #Add constraint
fixes profits
# SOLVE 2ND PROBLEM
prob.solve()
print(LpStatus[prob.status])
print('obj = ' + str(value(prob.objective)))
print('Profits ='+str(sum([x[i].varValue*profits[i] for i in N])))
print('Variance = ' + str(sum([x[i].varValue*var[i] for i in N])))
print('Cost = ' + str(sum([x[i].varValue*costs[i] for i in N])))
Я использовал комбинированное решение Магнуса Эландера. Из максимизации прибыли и мин. Вар.