Skip to content
This repository has been archived by the owner on Dec 7, 2021. It is now read-only.

Fix problem in qp.from_docplex when no explicit varnames are given. #963

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions qiskit/optimization/problems/quadratic_program.py
Original file line number Diff line number Diff line change
Expand Up @@ -555,16 +555,14 @@ def from_docplex(self, model: Model) -> None:
for x in model.iter_variables():
if x.get_vartype().one_letter_symbol() == 'C':
x_new = self.continuous_var(x.lb, x.ub, x.name)
var_names[x] = x_new.name
elif x.get_vartype().one_letter_symbol() == 'B':
x_new = self.binary_var(x.name)
var_names[x] = x_new.name
elif x.get_vartype().one_letter_symbol() == 'I':
x_new = self.integer_var(x.lb, x.ub, x.name)
var_names[x] = x_new.name
else:
raise QiskitOptimizationError(
"Unsupported variable type: {} {}".format(x.name, x.vartype))
var_names[x] = x_new.name

# objective sense
minimize = model.objective_sense.is_minimize()
Expand Down Expand Up @@ -620,7 +618,7 @@ def from_docplex(self, model: Model) -> None:

lhs = {}
for x in constraint.iter_net_linear_coefs():
lhs[x[0].name] = x[1]
lhs[var_names[x[0]]] = x[1]

if sense == sense.EQ:
self.linear_constraint(lhs, '==', rhs, name)
Expand Down
27 changes: 27 additions & 0 deletions test/optimization/test_quadratic_program.py
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,33 @@ def test_docplex(self):
mod.add(mod.not_equal_constraint(x, y + 1))
q_p.from_docplex(mod)

# test from_docplex without explicit variable names
mod = Model()
x = mod.binary_var()
y = mod.continuous_var()
z = mod.integer_var()
mod.minimize(x+y+z + x*y + y*z + x*z)
mod.add_constraint(x+y == z) # linear EQ
mod.add_constraint(x+y >= z) # linear GE
mod.add_constraint(x+y <= z) # linear LE
mod.add_constraint(x*y == z) # quadratic EQ
mod.add_constraint(x*y >= z) # quadratic GE
mod.add_constraint(x*y <= z) # quadratic LE
q_p = QuadraticProgram()
q_p.from_docplex(mod)
var_names = [v.name for v in q_p.variables]
self.assertListEqual(var_names, ['x0', 'x1', 'x2'])
senses = [Constraint.Sense.EQ, Constraint.Sense.GE, Constraint.Sense.LE]
for i, c in enumerate(q_p.linear_constraints):
self.assertDictEqual(c.linear.to_dict(use_name=True), {'x0': 1, 'x1': 1, 'x2': -1})
self.assertEqual(c.rhs, 0)
self.assertEqual(c.sense, senses[i])
for i, c in enumerate(q_p.quadratic_constraints):
self.assertEqual(c.rhs, 0)
self.assertDictEqual(c.linear.to_dict(use_name=True), {'x2': -1})
self.assertDictEqual(c.quadratic.to_dict(use_name=True), {('x0', 'x1'): 1})
self.assertEqual(c.sense, senses[i])

def test_substitute_variables(self):
"""test substitute variables"""
q_p = QuadraticProgram('test')
Expand Down