quadratische optimization problem with constraints

mit matplotlib, NumPy, pandas, SciPy, SymPy und weiteren mathematischen Programmbibliotheken.
Antworten
Geoff
User
Beiträge: 1
Registriert: Mittwoch 1. Juli 2020, 11:49

Hallo,
i have tried to optimize this model in Jupyter Notebook with python,but it didn't work well. can you help me?
Thks!!!

my code:

import pandas as pd
import numpy as np
from gurobipy import*
from random import randint,seed
from gurobipy import GRB
import gurobipy as gp

n=3
p=np.random.rand(n,n) # P_ij
Q=np.random.rand(n)
q=np.diag(Q) # P_jj
u=[randint(1,10) for i in range(n)] # w
v=[randint(1,20) for j in range(n)] # w[j]
c=[randint(5, sum(v[j] for j in range(n)))]
sense = [GRB.LESS_EQUAL]
lb = [0, 0, 0]
ub = [GRB.INFINITY, GRB.INFINITY, GRB.INFINITY]
vtype = [GRB.BINARY, GRB.BINARY, GRB.BINARY]
print(p,q,u,v,c)

def model_qkp(c,p,q,u,v,sense,lb,ub,vtype,LogToConsole=True, TimeLimit=60):

model= gp.Model()
model.params.LogToConsole = LogToConsole
model.params.TimeLimit= TimeLimit # seconds
A=[(i,j)for i in range(n)for j in range(n) if i!=j]
x= model.addVar(n,vtype=GRB.BINARY)
y= model.addVar(A,vtype=GRB.BINARY)
for i in range(n):
expr = gp.LinExpr()
exp = gp.LinExpr()
for j in range(n):
if v[j]!=0 & u!=0:
expr += v[j]*x[j]
exp += (u*y[i,j]) + (v[j] *x[j])

model.addConstr(expr,sense,c)
model.addConstr(exp,sense,c*x[j])

for i in range(n):
obj=gp.QuadExpr()
for j in range(n):
if p[i,j] != 0:
obj += p[i,j]*y[i,j]
else:
return False
for j in range(n):
if q[j,j] != 0:
obj += q[j]*x[j].T
else:
return False


model.setObjective(obj,GRB.MAXIMIZE)
model.optimize()
for i in range(n):
for j in range(n):
if y[i,j].X <= x[j].X :
items_selected=[j]
elif y[i,j].X <= x.X :
items_selected=
elif x.X + x[j].X <= 1+ (y[i,j].X):
items_selected = [i,j]
else:
return False


total_profit= int(model.ObjVal)
return items_selected, total_profit

items_selected, total_profit = model_qkp(c,p,q,u,v,sense,lb,ub,vtype,False)
print('Items selected are',items_selected, 'and the total profit is', total_profit)
Antworten