Skip to content

Commit

Permalink
Merge pull request #1335 from arcondello/fix/CQM.from_dqm
Browse files Browse the repository at this point in the history
Fix ConstrainedQuadraticModel.from_discrete_quadratic_model()
  • Loading branch information
arcondello authored Jun 14, 2023
2 parents 7501b31 + d0117d4 commit b5d3c0d
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
9 changes: 5 additions & 4 deletions dimod/constrained/cyconstrained.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -415,18 +415,19 @@ cdef class cyConstrainedQuadraticModel:
cqm.cppcqm.set_objective(cydqm.cppbqm)
cqm.variables._extend(relabel_func(v, case) for v in dqm.variables for case in dqm.get_cases(v))

cqm.cppcqm.add_constraints(cydqm.num_variables())
cqm.constraint_labels._extend(dqm.variables)

cdef Py_ssize_t vi, ci
for vi in range(cydqm.num_variables()):
constraint = cqm.cppcqm.constraint_ref(vi)
constraint = cqm.cppcqm.new_constraint()
for ci in range(cydqm.case_starts_[vi], cydqm.case_starts_[vi+1]):
constraint.add_linear(ci, 1)
constraint.set_sense(cppSense.EQ)
constraint.set_rhs(1)
constraint.mark_discrete()

cqm.cppcqm.add_constraint(move(constraint))

cqm.constraint_labels._extend(dqm.variables) # adjust the labels to match

assert(cqm.cppcqm.num_variables() == cqm.variables.size())
assert(cqm.cppcqm.num_constraints() == cqm.constraint_labels.size())

Expand Down
4 changes: 4 additions & 0 deletions releasenotes/notes/fix-CQM.from_dqm-f9b7b35c91118d0a.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
fixes:
- Fix ``ConstrainedQuadraticModel.from_discrete_quadratic_model()`` incorrectly
formulating the discrete constraints. This bug was introcued in version 0.12.7.
11 changes: 11 additions & 0 deletions tests/test_constrained.py
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,13 @@ def test_case_label(self):

self.assertEqual(set(cqm.constraints), set(dqm.variables))

for v in dqm.variables:
self.assertEqual(cqm.constraints[v].lhs.num_variables, dqm.num_cases(v))
self.assertTrue(cqm.constraints[v].lhs.is_discrete())

self.assertEqual(cqm.constraints["v"].lhs.variables,
[('v', 'blue'), ('v', 'yellow'), ('v', 'brown')])

def test_empty(self):
dqm = dimod.DiscreteQuadraticModel()

Expand Down Expand Up @@ -914,6 +921,10 @@ def test_typical(self):
# keys of constraints are the variables of DQM
self.assertEqual(set(cqm.constraints), set(dqm.variables))

for v in dqm.variables:
self.assertEqual(cqm.constraints[v].lhs.num_variables, dqm.num_cases(v))
self.assertTrue(cqm.constraints[v].lhs.is_discrete())


class TestNumBiases(unittest.TestCase):
def test_simple(self):
Expand Down

0 comments on commit b5d3c0d

Please sign in to comment.