Source code for qlauncher.hampy.debug

 1""" Module with functionalities for debugging Hamiltonians and checking their boolean properties """
 2from itertools import product
 3import numpy as np
 4import matplotlib.pyplot as plt
 5from qiskit.quantum_info import SparsePauliOp
 6
 7from qlauncher.hampy.object import Equation
 8
 9
[docs] 10class TruthTable: 11 def __init__(self, equation: Equation | SparsePauliOp, return_int: bool = True): 12 if isinstance(equation, SparsePauliOp): 13 hamiltonian = equation 14 self.size = hamiltonian.num_qubits 15 if isinstance(equation, Equation): 16 hamiltonian = equation.hamiltonian 17 self.size = equation.size 18 self.return_int = return_int 19 self.truth_table = self._ham_to_truth(hamiltonian) 20 self.lowest_value = min(self.truth_table.values()) 21
[docs] 22 def count(self, value: float) -> int: 23 return list(self.truth_table.values()).count(value)
24
[docs] 25 def get_solutions(self, value: float) -> list[str]: 26 return list(filter(lambda x: self.truth_table[x] == value, self.truth_table.keys()))
27
[docs] 28 def count_min_value_solutions(self) -> int: 29 return self.count(self.lowest_value)
30
[docs] 31 def get_min_value_solutions(self) -> list[str]: 32 return self.get_solutions(self.lowest_value)
33
[docs] 34 def check_if_binary(self) -> bool: 35 return all((value == 0 or value == 1) for value in self.truth_table.values())
36
[docs] 37 def plot_distribution(self) -> None: 38 values = list(self.truth_table.values()) 39 counts, bins = np.histogram(values, max(values)+1) 40 plt.stairs(counts, bins) 41 plt.show()
42 43 def _ham_to_truth(self, hamiltonian: SparsePauliOp): 44 return { 45 ''.join(reversed(bitstring)): value for bitstring, value in 46 zip( 47 product(('0', '1'), repeat=self.size), 48 map(lambda x: int(x.real), hamiltonian.to_matrix().diagonal()) 49 if self.return_int else 50 hamiltonian.to_matrix().diagonal() 51 ) 52 } 53 54 def __getitem__(self, index: str | int): 55 if isinstance(index, int): 56 index = bin(index)[2:].zfill(self.size) 57 return self.truth_table[index]