Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
self._vartype = vartype = as_vartype(vartype)
if isinstance(linear, (abc.Mapping, abc.Iterator)):
self.linear.update(linear)
else:
# assume a sequence
self.linear.update(enumerate(linear))
adj = self._adj
if isinstance(quadratic, abc.Mapping):
for (u, v), bias in quadratic.items():
self.add_variable(u)
self.add_variable(v)
if u == v and vartype is Vartype.SPIN:
offset = offset + bias # not += on off-chance it's mutable
elif u in adj[v]:
adj[u][v] = adj[v][u] = adj[u][v] + bias
else:
adj[u][v] = adj[v][u] = bias
elif isinstance(quadratic, abc.Iterator):
for u, v, bias in quadratic:
self.add_variable(u)
self.add_variable(v)
if u == v and vartype is Vartype.SPIN:
offset = offset + bias # not += on off-chance it's mutable
elif u in adj[v]:
adj[u][v] = adj[v][u] = adj[u][v] + bias
else:
adj[u][v] = adj[v][u] = bias
def to_spin(self, copy=False):
"""Return a binary polynomial over `{-1, +1}` variables.
Args:
copy (optional, default=False):
If True, the returned polynomial is always a copy. Otherwise,
if the polynomial is spin-valued already it returns itself.
Returns:
:obj:`.BinaryPolynomial`
"""
if self.vartype is Vartype.SPIN:
if copy:
return self.copy()
else:
return self
new = BinaryPolynomial({}, Vartype.SPIN)
# x = (s + 1) / 2
for term, bias in self.items():
newbias = bias / (2**len(term))
for t in map(frozenset, powerset(term)):
if t in new:
new[t] += newbias
else:
new[t] = newbias
Args:
H (dict):
Coefficients of a higher-order unconstrained binary optimization
(HUBO) model.
Returns:
:obj:`.BinaryPolynomial`
Examples:
>>> poly = dimod.BinaryPolynomial.from_hubo({('a', 'b', 'c'): -1})
>>> poly.degree
3
"""
poly = cls(H, Vartype.BINARY)
if offset is not None:
poly[()] = poly.get((), 0) + offset
return poly
vartype.
"""
if not inplace:
return self.copy().change_vartype(vartype, inplace=True)
vartype = as_vartype(vartype)
# in place and we are already correct, so nothing to do
if self.vartype == vartype:
return self
if vartype is Vartype.BINARY:
lin_mp, lin_offset_mp = 2.0, -1.0
quad_mp, lin_quad_mp, quad_offset_mp = 4.0, -2.0, 1.0
elif vartype is Vartype.SPIN:
lin_mp, lin_offset_mp = 0.5, .5
quad_mp, lin_quad_mp, quad_offset_mp = 0.25, 0.25, 0.25
else:
raise ValueError("unkown vartype")
for v, bias in self.linear.items():
self.linear[v] = lin_mp * bias
self.offset += lin_offset_mp * bias
for (u, v), bias in self.quadratic.items():
self.adj[u][v] = quad_mp * bias
self.linear[u] += lin_quad_mp * bias
self.linear[v] += lin_quad_mp * bias
self.offset += quad_offset_mp * bias
def __init__(self, info=None, vartype=Vartype.BINARY):
NumpyResponse.__init__(self, info=info, vartype=vartype)
"""
# we try to use the matching sample method if possible
if bqm.vartype is Vartype.SPIN:
if not getattr(self.sample_ising, '__issamplemixin__', False):
# sample_ising is implemented
h, J, offset = bqm.to_ising()
sampleset = self.sample_ising(h, J, **parameters)
sampleset.record.energy += offset
return sampleset
else:
Q, offset = bqm.to_qubo()
sampleset = self.sample_qubo(Q, **parameters)
sampleset.change_vartype(Vartype.SPIN, energy_offset=offset)
return sampleset
elif bqm.vartype is Vartype.BINARY:
if not getattr(self.sample_qubo, '__issamplemixin__', False):
# sample_qubo is implemented
Q, offset = bqm.to_qubo()
sampleset = self.sample_qubo(Q, **parameters)
sampleset.record.energy += offset
return sampleset
else:
h, J, offset = bqm.to_ising()
sampleset = self.sample_ising(h, J, **parameters)
sampleset.change_vartype(Vartype.BINARY, energy_offset=offset)
return sampleset
else:
raise RuntimeError("binary quadratic model has an unknown vartype")
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
Returns:
:class:`.Vartype`: Either :class:`.Vartype.SPIN` or
:class:`.Vartype.BINARY`.
See also:
:func:`~dimod.decorators.vartype_argument`
"""
if isinstance(vartype, Vartype):
return vartype
try:
if isinstance(vartype, str):
vartype = Vartype[vartype] # raises KeyError
elif isinstance(vartype, frozenset):
vartype = Vartype(vartype) # raise ValueError
else:
# raises ValueError if not a bqm
# raises TypeError if not iterable
vartype = Vartype(frozenset(vartype))
except (ValueError, KeyError, TypeError):
# avoid the "During handling of the above exception..." message that
# removes the full traceback
pass
else:
return vartype
raise TypeError(("expected input vartype to be one of: "
"Vartype.SPIN, 'SPIN', {-1, 1}, "