dimod icon indicating copy to clipboard operation
dimod copied to clipboard

add_discrete using dimod.Binary raises error

Open hsadeghidw opened this issue 3 years ago • 5 comments

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.

hsadeghidw avatar Jul 26 '21 20:07 hsadeghidw

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?

arcondello avatar Jul 26 '21 22:07 arcondello

oh, that raises very good questions. I had not thought about it. For now, I think it should just raise an error.

hsadeghidw avatar Jul 26 '21 22:07 hsadeghidw

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.

arcondello avatar Aug 20 '21 19:08 arcondello

At the very least we should probably update the docstring to make the current usage clearer (credit to @pau557 for the suggestion).

arcondello avatar Sep 01 '21 18:09 arcondello

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.

arcondello avatar Jan 28 '22 19:01 arcondello