dimod.ConstrainedQuadraticModel.flip_variable#
- ConstrainedQuadraticModel.flip_variable(v: Hashable)[source]#
Flip the specified binary variable in the objective and constraints.
Note that this may terminate a constraint’s status as a discrete constraint (see
add_discrete()
). Subsequently flipping the variable again does not restore that status.- Parameters:
- Raises:
ValueError – If given a non-binary variable to flip.
Examples
This example flips \(x`\) in an objective, \(2xy-2x\), which is equivalent for binary variables with values \(\{0, 1\}\) to the substitution \(x \Rightarrow 1-x\), creating a new objective, \(2xy-2x \Rightarrow 2(1-x)y -2(1-x) = 2y -2xy -2 -2x\).
>>> cqm = dimod.ConstrainedQuadraticModel() >>> x, y = dimod.Binaries(["x", "y"]) >>> cqm.set_objective(2 * x * y - 2 * x) >>> cqm.flip_variable("x") >>> print(cqm.objective.to_polystring()) -2 + 2*x + 2*y - 2*x*y
The next example flips a variable in a one-hot constraint. Subsequently fixing one of this discrete constaint’s binary variables to 1 does not ensure the remaining variables are assigned 0.
>>> r, b, g = dimod.Binaries(["red", "blue", "green"]) >>> cqm.add_discrete_from_comparison(r + b + g == 1, label="One color") 'One color' >>> cqm.flip_variable("red") >>> cqm.fix_variable("blue", 1, cascade=True) {}