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