BlackBear
BlackBear

Reputation: 22979

AttributeErrors when adding variables/constraints to Gurobi persistent

I am trying to modify a model by adding variables/constraints and re-solving the updated model, following the guide.

The problem is that both cases fail with attribute errors, for a variable:

Traceback (most recent call last):
  File "seqdesign.py", line 98, in <module>
    main()
  File "seqdesign.py", line 71, in main
    problem._solver.add_var(problem._model.McBernoulliTrials)
  File "/home/edo/miniconda3/envs/spacers/lib/python3.7/site-packages/pyomo/solvers/plugins/solvers/persistent_solver.py", line 153, in add_var
    self._add_var(var)
  File "/home/edo/miniconda3/envs/spacers/lib/python3.7/site-packages/pyomo/solvers/plugins/solvers/gurobi_direct.py", line 208, in _add_var
    vtype = self._gurobi_vtype_from_var(var)
  File "/home/edo/miniconda3/envs/spacers/lib/python3.7/site-packages/pyomo/solvers/plugins/solvers/gurobi_direct.py", line 377, in _gurobi_vtype_from_var
    if var.is_binary():
AttributeError: 'IndexedVar' object has no attribute 'is_binary'

And for a constraint:

Traceback (most recent call last):
  File "seqdesign.py", line 98, in <module>
    main()
  File "seqdesign.py", line 71, in main
    problem._solver.add_constraint(problem._model.McBernoulliTrialsSetPositive)
  File "/home/edo/miniconda3/envs/spacers/lib/python3.7/site-packages/pyomo/solvers/plugins/solvers/persistent_solver.py", line 132, in add_constraint
    self._add_constraint(con)
  File "/home/edo/miniconda3/envs/spacers/lib/python3.7/site-packages/pyomo/solvers/plugins/solvers/gurobi_direct.py", line 272, in _add_constraint
    if is_fixed(con.body):
AttributeError: 'IndexedConstraint' object has no attribute 'body'

Is the problem that I am using indexed variables and constraints? How to make this work without migrating all code from pyomo.environ to pyomo.core?

Upvotes: 0

Views: 882

Answers (1)

Michael Bynum
Michael Bynum

Reputation: 71

You cannot pass an IndexedVar or and IndexedConstraint into the add_var and add_constraint methods. You have to loop over the individual variables and constraints and add them one at a time:

for v in my_var.values():
    solver.add_var(v)

for c in my_con.values():
    solver.add_constraint(c)

Additionally, you can check if a variable or constraint is indexed with my_var.is_indexed() or my_con.is_indexed().

Upvotes: 1

Related Questions