Source code for quantum_launcher.hampy.debug

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