Source code for qlauncher.hampy.equations

 1"""
 2`equations` module provides additional binary operations for Hampy objects.
 3
 4It's goal is too simplify the creation of more complex problem implementations, by creating them with use of smaller ones.
 5"""
 6
 7from copy import copy
 8
 9from qiskit.quantum_info import SparsePauliOp
10
11from .object import Equation, Variable
12
13
[docs] 14def one_in_n(variables: list[int | Variable], size: int, quadratic: bool = False) -> Equation: 15 """ 16 Generates Equation for One in N problem. 17 18 One in N returns True if and only if exactly one of targeted indexes in 1, and all others are 0. 19 20 Args: 21 variables (list[int | Variable]): Triggered variables or variable indexes 22 size (int | None, optional): Size of problem, if not given it takes the first found Variable.size value. Defaults to None. 23 24 Returns: 25 Equation: Equation returning True if exactly one of passed indexes is 1, False otherwise 26 """ 27 eq = Equation(size) 28 new_variables = set() 29 for var in copy(variables): 30 if isinstance(var, int): 31 new_variables.add(eq.get_variable(var)) 32 elif isinstance(var, Variable): 33 new_variables.add(eq.get_variable(var.index)) 34 35 if quadratic: 36 for variable in new_variables: 37 eq += variable 38 identity = SparsePauliOp.from_sparse_list([('I', [], 1)], size) 39 hamiltonian = identity - eq.hamiltonian 40 return Equation(hamiltonian.compose(hamiltonian)) 41 42 for variable in new_variables: 43 equation = variable 44 for different_var in new_variables - {variable}: 45 equation &= ~different_var 46 eq |= equation 47 48 return eq