我正在尝试将CVXPY问题投射到Gurobi的Python API。
以下是CVXPY问题(我忽略了先前的变量定义,因为它们对我的问题来说是次要的。请检查注释的类型和形状。)
import cvxpy as cp
import numpy as np
"""
ma, mx, mb, my: type=int
radius: type=float
meas: type=numpy.ndarray, shape=(3, 3)
detp: type=numpy.ndarray, shape=(18, 10000)
state_vecs: type=numpy.ndarray, shape=(3, 3)
weights: type=cvxpy.expressions.variable.Variable, shape=(10000,)
d: type=cvxpy.expressions.variable.Variable, shape=(1,)
"""
ma, mx, mb, my, meas, radius, detp, state_vecs = # Previously defined
weights = cp.Variable(detp.shape[1])
d = cp.Variable(1)
dot = np.inner(state_vecs, meas).flatten()
# Attention to this line:
behaviors = 0.5 * (1 + d * dot / radius)
constrs = [behaviors == detp @ weights, d >= 0, d <= 1, sum(weights) == 1, weights >= 0]
prob = cp.Problem(cp.Maximize(d), constrs)
prob.solve(solver=cp.GUROBI, verbose=True)
这可以正常工作,但是对于大型实例,CVXPY会占用所有内存,并且需要很长时间才能设置问题,然后才能调用求解器。
我现在尝试将其翻译为Gurobi的API:
import gurobipy as gp
import numpy as np
"""
ma, mx, mb, my: type=int
radius: type=float
meas: type=numpy.ndarray, shape=(3, 3)
detp: type=numpy.ndarray, shape=(18, 10000)
state_vecs: type=numpy.ndarray, shape=(3, 3)
weights: type=gurobipy.MVar, shape=(10000,)
d: type=gurobipy.Var, has no attribute shape
"""
ma, mx, mb, my, meas, radius, detp, state_vecs = # Previously defined
prob = gp.Model("LPMModel")
weights = prob.addMVar(shape=detp.shape[1])
d = prob.addVar()
prob.setObjective(d, GRB.MAXIMIZE)
dot = np.inner(state_vecs, meas).flatten()
# So far so good, but now:
behaviors = 0.5 * (1 + d * dot / radius)
prob.addConstr(behaviors == detp @ weights)
prob.addConstr(weights >= 0)
prob.addConstr(weights.sum() == 1)
prob.addConstr(d >= 0)
prob.addConstr(d <= 1)
prob.optimize()
发表评论后的那行是困扰我的事情。我打算将dot
的每个元素乘以应最大化的优化变量d
。解释器吐出以下错误堆栈:
TypeError Traceback (most recent call last)
var.pxi in gurobipy.Var.__mul__()
TypeError: only size-1 arrays can be converted to Python scalars
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
linexpr.pxi in gurobipy.LinExpr.__imul__()
TypeError: only size-1 arrays can be converted to Python scalars
During handling of the above exception, another exception occurred:
GurobiError Traceback (most recent call last)
<ipython-input-135-5b4ee6d552a9> in <module>
----> 1 grb = lpm.grb_local_model(st)
~/lpm.py in grb_local_model(state_vecs, detp, meas, verb)
97
98 dot = np.inner(state_vecs, meas).flatten()
---> 99 behaviors = 0.5 * (1 + d * dot / radius)
100
101 prob.addConstr(behaviors == detp @ weights)
var.pxi in gurobipy.Var.__mul__()
linexpr.pxi in gurobipy.LinExpr.__imul__()
linexpr.pxi in gurobipy.LinExpr.__mul__()
linexpr.pxi in gurobipy.LinExpr._mul()
GurobiError: Invalid argument to LinExpr multiplication
这是我的问题。
我错过了什么?
(也欢迎提出任何有关如何改进其他地方代码的建议。)