fix: single shot visualizer

This commit is contained in:
Kristofers Solo 2025-04-22 14:13:48 +03:00
parent 7ecd4fe13a
commit a8b7b054f0

View File

@ -10,6 +10,7 @@ from collections.abc import Iterator
from itertools import product from itertools import product
from math import floor, pi, sqrt from math import floor, pi, sqrt
import matplotlib.pyplot as plt
from matplotlib.axes import Axes from matplotlib.axes import Axes
from qiskit import QuantumCircuit from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator from qiskit_aer import AerSimulator
@ -27,7 +28,7 @@ def oracle(qc: QuantumCircuit, target_state: QubitState) -> None:
def diffusion(qc: QuantumCircuit, n: int) -> None: def diffusion(qc: QuantumCircuit, n: int) -> None:
"""Apply the Grovers diffusion operator""" """Apply the Grovers diffusion operator."""
qc.h(range(n)) qc.h(range(n))
qc.x(range(n)) qc.x(range(n))
apply_phase_inversion(qc, n) apply_phase_inversion(qc, n)
@ -75,49 +76,43 @@ def all_states(n_qubits: int) -> Iterator[QubitState]:
def main() -> None: def main() -> None:
shots = 20 shots = 128
target = QubitState("11111111111111111") target = QubitState("1" * 4)
n_qubits = len(target) n_qubits = len(target)
qc = grover_search(target, iterations=4) qc = grover_search(target, iterations=1)
print(qc)
simulator = AerSimulator() simulator = AerSimulator()
job = simulator.run(qc, shots=shots, memory=True) job = simulator.run(qc, shots=shots, memory=True)
result = job.result() result = job.result()
memory = result.get_memory(qc) # List of measurement results, one per shot memory = result.get_memory(qc) # List of measurement results, one per shot
counts = result.get_counts(qc) # Dict: state string -> count
print(counts)
# print(qc.draw("text")) print(qc) # draw scheme
print(f"Target: {target}") print(f"Target: {target}")
# Ensure all possible states are present in the bar chart # Ensure all possible states are present in the bar chart
all_states = ["".join(bits) for bits in product("01", repeat=n_qubits)] all_states = ["".join(bits) for bits in product("01", repeat=n_qubits)]
counts = dict.fromkeys(all_states, 0) counts = dict.fromkeys(all_states, 0)
# print(counts)
# plt.ion() plt.ion()
# _, ax = plt.subplots(figsize=(6, 2)) _, ax = plt.subplots(figsize=(6, 2))
# bars = ax.bar(all_states, [0] * len(all_states), color="skyblue") bars = ax.bar(all_states, [0] * len(all_states), color="skyblue")
# ax.set_xlabel("Measured State") ax.set_xlabel("Measured State")
# ax.set_ylabel("Counts") ax.set_ylabel("Counts")
# ax.set_title(f"Measurement Variability for Target: {target}") ax.set_title(f"Measurement Variability for Target: {target}")
# ax.set_ylim(0, shots) ax.set_ylim(0, shots)
for i, measured in enumerate(memory, 1): for i, measured in enumerate(memory, 1):
pass measured_be = measured[::-1] # Qiskit returns little-endian
# print(measured) counts[measured_be] += 1
# measured_be = measured[::-1] for bar, state in zip(bars, all_states, strict=False):
# if measured_be in counts: bar.set_height(counts[state])
# counts[measured_be] += 1 bar.set_color("orange" if state == str(target) else "skyblue")
# for bar, state in zip(bars, all_states, strict=False): ax.set_title(f"Measurement Variability (Shot {i}/{shots})\nTarget: {target}")
# bar.set_height(counts[state]) plt.pause(0.5)
# bar.set_color("orange" if state == str(target) else "skyblue")
# ax.set_title(f"Measurement Variability for Target: {target} (Shot {i}/{shots})")
# plt.pause(1)
# plt.ioff() plt.ioff()
# plt.show() plt.show()
if __name__ == "__main__": if __name__ == "__main__":