Source code for quantum_launcher.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"""
 6from typing import Optional
 7from copy import copy
 8from qiskit.quantum_info import SparsePauliOp
 9from .object import Equation, Variable
10
11
[docs] 12def one_in_n(variables: list[int | Variable], size: Optional[int] = None, quadratic: bool = False) -> Equation: 13 """ 14 Generates Equation for One in N problem. 15 16 One in N returns True if and only if exactly one of targeted indexes in 1, and all others are 0. 17 18 Args: 19 variables (list[int | Variable]): Triggered variables or variable indexes 20 size (Optional[int], optional): Size of problem, if not given it takes the first found Variable.size value. Defaults to None. 21 22 Returns: 23 Equation: Equation returning True if exactly one of passed indexes is 1, False otherwise 24 """ 25 if size is None: 26 for var in variable: 27 if isinstance(var, Variable): 28 size = var.size 29 break 30 31 eq = Equation(size) 32 new_variables = set() 33 for var in copy(variables): 34 if isinstance(var, int): 35 new_variables.add(eq.get_variable(var)) 36 elif isinstance(var, Variable): 37 new_variables.add(eq.get_variable(var.index)) 38 39 if quadratic: 40 for variable in new_variables: 41 eq += variable 42 I = SparsePauliOp.from_sparse_list([('I', [], 1)], size) 43 hamiltonian = I - eq.hamiltonian 44 return Equation(hamiltonian.compose(hamiltonian)) 45 46 for variable in new_variables: 47 equation = variable 48 for different_var in new_variables - {variable}: 49 equation &= ~different_var 50 eq |= equation 51 52 return eq