dwavesystems / dimod

A shared API for QUBO/Ising samplers.
https://docs.ocean.dwavesys.com/en/stable/docs_dimod/
Apache License 2.0
121 stars 80 forks source link

add_discrete using dimod.Binary raises error #921

Open hsadeghidw opened 3 years ago

hsadeghidw commented 3 years ago

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.

arcondello commented 3 years ago

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?

hsadeghidw commented 3 years ago

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

arcondello commented 3 years ago

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 commented 3 years ago

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

arcondello commented 2 years ago

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.