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