dimod
dimod copied to clipboard
add_discrete using dimod.Binary raises error
Application When adding a set of binary variables as a discrete variable, an error is raised that indicates the variable is not hashable. This is not a bug because the function expects variable labels. However, if one is using dimod.Binary or dimod.Integer to build a model, it's convenient to be able to pass a set of such variables to construct a discrete variable.
This raises error,
import dimod
n = 10
cqm = dimod.CQM()
x = {}
for i in range(n):
x[i] = dimod.Binary(i)
cqm.add_discrete([v for v in x.values()])
currently I can do:
import dimod
n = 10
cqm = dimod.CQM()
x = {}
for i in range(n):
x[i] = dimod.Binary(i)
cqm.add_discrete([v.variables[0] for v in x.values()])
to get around it.
How would you expect
x = Binary('x')
y = Binary('y')
z = Binary('z')
# 1
cqm.add_discrete([x+y, z+1])
# 2
cqm.add_discrete([2*x, y, z])
to behave? Would you expect it to fail for anything except zero offset, one variable with linear bias of 1?
oh, that raises very good questions. I had not thought about it. For now, I think it should just raise an error.
FWIW numpy handles a similar case, bool(np.asarray([0, 1]))
, with ValueError: The truth value of an array with more than one element is ambiguous
.
At the very least we should probably update the docstring to make the current usage clearer (credit to @pau557 for the suggestion).
https://github.com/dwavesystems/dimod/pull/1089 adds support for
x, y, z = dimod.Binaries('xyz')
cqm.add_discrete(sum((x, y, z)))
cqm.add_discrete(x + y + z)
cqm.add_discrete(x + y + z == 1)
and similar.