Skip to content

Commit

Permalink
Merge pull request #1348 from kevinchern/feature/expose_onehot
Browse files Browse the repository at this point in the history
Feature/expose onehot
  • Loading branch information
arcondello authored Jun 30, 2023
2 parents 3873226 + f928dbf commit 4d7c907
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
3 changes: 3 additions & 0 deletions dimod/constrained/cyexpression.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,9 @@ cdef class cyConstraintView(_cyExpression):
constraint = self.constraint()
return constraint.marked_discrete() and constraint.is_onehot()

def is_onehot(self):
return self.constraint().is_onehot()

def is_soft(self):
return self.constraint().is_soft()

Expand Down
4 changes: 4 additions & 0 deletions releasenotes/notes/expose-is_onehot-044d860d5eb7b115.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
features:
- |
Add ``Constraint.is_onehot()`` method.
30 changes: 29 additions & 1 deletion tests/test_constrained.py
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,34 @@ def test_simple(self):
cqm1.add_constraint(x*y == 1)
self.assertFalse(cqm0.is_equal(cqm1))

class TestIsOnehot(unittest.TestCase):
def test_onehot(self):
x, y, z = dimod.Binaries('xyz')

cqm = dimod.CQM()
cqm.add_constraint(x + y + z == 1, label="x+y+z=1")
cqm.add_constraint(x + y == 1, label="x+y=1")
for label, constraint in cqm.constraints.items():
with self.subTest(label=label):
self.assertTrue(constraint.lhs.is_onehot())

def test_not_onehot(self):
x, y, z = dimod.Binaries('xyz')
i = dimod.Integer('i')

cqm = dimod.CQM()
cqm.add_constraint(x*y + y + z == 1, label='quadratic')
cqm.add_constraint(x + y + z >= 1, label='le')
cqm.add_constraint(x + y + z <= 1, label='ge')
cqm.add_constraint(x + y == 2, label="not_one")
cqm.add_constraint(x == 1, label="one_variable")
cqm.add_constraint(i + x == 1, label='integer')
cqm.add_constraint(y + x + 1 == 1, label='offset')

for label, constraint in cqm.constraints.items():
with self.subTest(label=label):
self.assertFalse(constraint.lhs.is_onehot())


class TestIsLinear(unittest.TestCase):
def test_empty(self):
Expand Down Expand Up @@ -1882,7 +1910,7 @@ def test_constraint_energies(self):
self.assertEqual(cqm.constraints[c1].lhs.energy(sample), 0)
self.assertEqual(cqm.constraints[c2].lhs.energy(sample), 1)

np.testing.assert_array_equal(cqm.objective.energies(([[0, 0, 1], [1, 0, 0]], 'abc')),
np.testing.assert_array_equal(cqm.objective.energies(([[0, 0, 1], [1, 0, 0]], 'abc')),
[-1, 1])

self.assertEqual(cqm.constraints[c1].lhs.energy({'a': 1, 'b': 1}), 1)
Expand Down

0 comments on commit 4d7c907

Please sign in to comment.