Create custom penalty terms with WithPenalty
masterTo define complex penalty terms that are automatically added to a Hamiltonian (similar to how OneHotEncInteger works), inherit from WithPenalty. The constructor should call super().__init__(hamiltonian, penalty, label), where penalty is the expression to be added to the total Hamiltonian.
from pyqubo import WithPenalty, Binary
class CustomPenalty(WithPenalty):
def __init__(self, hamiltonian, label, strength):
# Define the penalty term: strength * (h - 1)^2
penalty = strength * (hamiltonian - 1)**2
super().__init__(hamiltonian, penalty, label)
a, b = Binary("a"), Binary("b")
p = CustomPenalty(a + b, label="penalty", strength=2.0)
model = (p + 1).compile()
qubo, offset = model.to_qubo()