• Community Moderator

Hi Zahra,

first of all, I would suggest you post a minimal, reproducible example of the problem you are struggling with.

Further, take a look at those two links (here and here). Perhaps they will guide you a little bit in formulating your objective.

As a general remark: as stated in the documentation, model.setObjective() only accepts LinExpr or QuadExpr (or arguments which can be converted to these). Your obj object:

obj=trace_Jinv.subs({(x * x.conjugate().T)[0,0]: R1,    (x * x.conjugate().T)[1,1]: R2})

does not meet these criteria. You may be better-off rewriting the objective directly, the way you wrote it down at the end of your question.

Also, you may want to store your variables as R1 and R2:

R1 = m.addVar(lb=0.0, ub=GRB.INFINITY, name="R1")R2 = m.addVar(lb=0.0, ub=GRB.INFINITY, name="R2")

as otherwise Gurobi will see them as sp.Symbol objects and you'll get an error.

Hope this helps.

Best regards
Jonasz

Hi Jonasz

thanks for your response. I narrow down my objective function to the numerator of trace which is 29*R1+17*R2 in which R1 and R2 are symbols coming from sympy library. I want to solve a minimization problem like this but still receiving the same error:

Min 29*R1+17*R2

constraints: R1+R2=5

R2>=3*R1-3

R1,R2>0

my code for the objective function is :

from gurobipy import Model, GRB
import gurobipy as gp
import sympy as sp
R1,R2 =sp.symbols('R1 R2')
objective=R1+R2
# Create a model
m = Model("Minimize expression")

obj=objective.subs({ R1:r1,
R2: r2})

m.setObjective(obj, gp.GRB.MINIMIZE)

------------------------------------------------------------------------------------------

GurobiError                               Traceback (most recent call last)
Cell In[2], line 15
10 r2 = m.addVar(lb=0.0, ub=gp.GRB.INFINITY, name="r2")
11 obj=objective.subs({ R1:r1,
12     R2: r2})
---> 15 m.setObjective(obj, gp.GRB.MINIMIZE)

File src\\gurobipy\\model.pxi:1488, in gurobipy.Model.setObjective()

File src\\gurobipy\\util.pxi:44, in gurobipy._simpleexpr()

GurobiError: Unable to convert argument to an expression

• Community Moderator

Hi Zahra,

as I wrote earlier, you cannot use Sympy objects as arguments to your objective function.

Perhaps this:

m.setObjective(r1 + r2, gp.GRB.MINIMIZE)

is what you are looking for?

Best regards
Jonasz