-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdense.py
executable file
·83 lines (65 loc) · 2.09 KB
/
dense.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env python3.9
# Copyright 2022, Gurobi Optimization, LLC
# This example formulates and solves the following simple QP model:
#
# minimize x + y + x^2 + x*y + y^2 + y*z + z^2
# subject to x + 2 y + 3 z >= 4
# x + y >= 1
# x, y, z non-negative
#
# The example illustrates the use of dense matrices to store A and Q
# (and dense vectors for the other relevant data). We don't recommend
# that you use dense matrices, but this example may be helpful if you
# already have your data in this format.
import sys
import gurobipy as gp
from gurobipy import GRB
def dense_optimize(rows, cols, c, Q, A, sense, rhs, lb, ub, vtype,
solution):
model = gp.Model()
# Add variables to model
vars = []
for j in range(cols):
vars.append(model.addVar(lb=lb[j], ub=ub[j], vtype=vtype[j]))
# Populate A matrix
for i in range(rows):
expr = gp.LinExpr()
for j in range(cols):
if A[i][j] != 0:
expr += A[i][j]*vars[j]
model.addLConstr(expr, sense[i], rhs[i])
# Populate objective
obj = gp.QuadExpr()
for i in range(cols):
for j in range(cols):
if Q[i][j] != 0:
obj += Q[i][j]*vars[i]*vars[j]
for j in range(cols):
if c[j] != 0:
obj += c[j]*vars[j]
model.setObjective(obj)
# Solve
model.optimize()
# Write model to a file
model.write('dense.lp')
if model.status == GRB.OPTIMAL:
x = model.getAttr('X', vars)
for i in range(cols):
solution[i] = x[i]
return True
else:
return False
# Put model data into dense matrices
c = [1, 1, 0]
Q = [[1, 1, 0], [0, 1, 1], [0, 0, 1]]
A = [[1, 2, 3], [1, 1, 0]]
sense = [GRB.GREATER_EQUAL, GRB.GREATER_EQUAL]
rhs = [4, 1]
lb = [0, 0, 0]
ub = [GRB.INFINITY, GRB.INFINITY, GRB.INFINITY]
vtype = [GRB.CONTINUOUS, GRB.CONTINUOUS, GRB.CONTINUOUS]
sol = [0]*3
# Optimize
success = dense_optimize(2, 3, c, Q, A, sense, rhs, lb, ub, vtype, sol)
if success:
print('x: %g, y: %g, z: %g' % (sol[0], sol[1], sol[2]))