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