repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/intrinsicvardhan/QuantumComputingAlgos
intrinsicvardhan
# Importing everything from qiskit import QuantumCircuit from qiskit import IBMQ, Aer, transpile from qiskit.visualization import plot_histogram def create_bell_pair(): """ Returns: QuantumCircuit: Circuit that produces a Bell pair """ qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): """Encodes a two-bit message on qc using the superdense coding protocol Args: qc (QuantumCircuit): Circuit to encode message on qubit (int): Which qubit to add the gate to msg (str): Two-bit message to send Returns: QuantumCircuit: Circuit that, when decoded, will produce msg Raises: ValueError if msg is wrong length or contains invalid characters """ if len(msg) != 2 or not set(msg).issubset({"0","1"}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc # Charlie creates the entangled pair between Alice and Bob qc = create_bell_pair() # We'll add a barrier for visual separation qc.barrier() # At this point, qubit 0 goes to Alice and qubit 1 goes to Bob # Next, Alice encodes her message onto qubit 1. In this case, # we want to send the message '10'. You can try changing this # value and see how it affects the circuit message = '10' qc = encode_message(qc, 1, message) qc.barrier() # Alice then sends her qubit to Bob. # After receiving qubit 0, Bob applies the recovery protocol: qc = decode_message(qc) # Finally, Bob measures his qubits to read Alice's message qc.measure_all() # Draw our output qc.draw() aer_sim = Aer.get_backend('aer_simulator') result = aer_sim.run(qc).result() counts = result.get_counts(qc) print(counts) plot_histogram(counts) from qiskit import IBMQ from qiskit.providers.ibmq import least_busy shots = 1024 # Load local account information IBMQ.load_account() # Get the least busy backend provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit t_qc = transpile(qc, backend, optimization_level=3) job = backend.run(t_qc) # Monitoring our job from qiskit.tools.monitor import job_monitor job_monitor(job) # Plotting our result result = job.result() plot_histogram(result.get_counts(qc)) correct_results = result.get_counts(qc)[message] accuracy = (correct_results/shots)*100 print(f"Accuracy = {accuracy:.2f}%") import qiskit.tools.jupyter %qiskit_version_table
https://github.com/intrinsicvardhan/QuantumComputingAlgos
intrinsicvardhan
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import IBMQ, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex from qiskit.extensions import Initialize from qiskit.ignis.verification import marginal_counts from qiskit.quantum_info import random_statevector # Loading your IBM Quantum account(s) provider = IBMQ.load_account() ## SETUP # Protocol uses 3 qubits and 2 classical bits in 2 different registers qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical bits crx = ClassicalRegister(1, name="crx") # in 2 different registers teleportation_circuit = QuantumCircuit(qr, crz, crx) def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a,b) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, psi, a): qc.cx(psi, a) qc.h(psi) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() def measure_and_send(qc, a, b): """Measures qubits a & b and 'sends' the results to Bob""" qc.barrier() qc.measure(a,0) qc.measure(b,1) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) measure_and_send(teleportation_circuit, 0 ,1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) # Apply gates if the registers qc.z(qubit).c_if(crz, 1) # are in the state '1' qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) ## STEP 3 measure_and_send(teleportation_circuit, 0, 1) ## STEP 4 teleportation_circuit.barrier() # Use barrier to separate steps bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() # Create random 1-qubit state psi = random_statevector(2) # Display it nicely display(array_to_latex(psi, prefix="|\\psi\\rangle =")) # Show it on a Bloch sphere plot_bloch_multivector(psi) init_gate = Initialize(psi) init_gate.label = "init" ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) ## STEP 0 # First, let's initialize Alice's q0 qc.append(init_gate, [0]) qc.barrier() ## STEP 1 # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() ## STEP 2 # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) ## STEP 3 # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) ## STEP 4 # Bob decodes qubits bob_gates(qc, 2, crz, crx) # Display the circuit qc.draw() sim = Aer.get_backend('aer_simulator') qc.save_statevector() out_vector = sim.run(qc).result().get_statevector() plot_bloch_multivector(out_vector)
https://github.com/lynkos/grovers-algorithm
lynkos
my_list = [1, 3, 5, 2, 4, 9, 5, 8, 0, 7, 6] def the_oracle(my_input): winner = 7 return my_input == winner for index, trial_number in enumerate(my_list): if the_oracle(trial_number): print(f"Found the winner at index {index}!") print(f"{index+1} calls made") break from qiskit import * from qiskit.visualization import plot_histogram, array_to_latex from qiskit.providers.ibmq import least_busy import matplotlib.pyplot as plt import numpy as np grover_circuit = QuantumCircuit(2) def init_state(qc, qubits): for q in qubits: qc.h(q) return qc grover_circuit = init_state(grover_circuit, [0, 1]) grover_circuit.draw("mpl") #define the oracle circuit def oracle(qc, qubits): qc.cz(qubits[0], qubits[1]) qc = QuantumCircuit(2) oracle(qc, [0, 1]) qc.draw("mpl") usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{One can see that only the state }\ket{11}\\text{ has been flipped: }\n") def diffusion(qc, qubits): qc.h([0, 1]) qc.z([0, 1]) qc.cz(0, 1) qc.h([0, 1]) grover_circuit.barrier() oracle(grover_circuit, [0, 1]) grover_circuit.barrier() diffusion(grover_circuit, [0, 1]) grover_circuit.measure_all() grover_circuit.draw("mpl") # Let's see if the final statevector matches our expectations sv_sim = Aer.get_backend('statevector_simulator') result = sv_sim.run(grover_circuit).result() statevec = result.get_statevector() statevec aer_sim = Aer.get_backend('aer_simulator') result = execute(grover_circuit, aer_sim, shots=1024).result() result.get_counts() # Load IBM Q account and get the least busy backend device # Run the following line with your API token to use IBM's own quantum computers #IBMQ.save_account('') provider = IBMQ.load_account() provider = IBMQ.get_provider("ibm-q") device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_grover_circuit = transpile(grover_circuit, device, optimization_level=3) job = device.run(transpiled_grover_circuit) job_monitor(job, interval=2) # Get the results from the computation results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) grover_circuit = QuantumCircuit(3) grover_circuit = init_state(grover_circuit, [0, 1, 2]) grover_circuit.draw("mpl") oracle_qc = QuantumCircuit(3) oracle_qc.cz(0, 1) oracle_qc.cz(0, 2) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "U$_\omega$" def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> -> |11..1> for qubit in range(nqubits): qc.h(qubit) qc.x(qubit) # When these are combined, they function as a multi-controlled Z gate # A negative phase is added to |11..1> to flip the state qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> -> |s> for qubit in range(nqubits): qc.x(qubit) qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "U$_s$" return U_s num_qubits = 3 grover_circuit = QuantumCircuit(num_qubits) grover_circuit = init_state(grover_circuit, [0, 1, 2]) grover_circuit.barrier() grover_circuit.append(oracle_gate, [0, 1, 2]) grover_circuit.barrier() grover_circuit.append(diffuser(num_qubits), [0, 1, 2]) grover_circuit.measure_all() grover_circuit.draw("mpl") qasm_sim = Aer.get_backend('qasm_simulator') transpiled_grover_circuit = transpile(grover_circuit, qasm_sim) results = qasm_sim.run(transpiled_grover_circuit).result() counts = results.get_counts() plot_histogram(counts) backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_grover_circuit = transpile(grover_circuit, device, optimization_level=3) job = device.run(transpiled_grover_circuit) job_monitor(job, interval=2) # Get the results from the computation results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer)
https://github.com/lynkos/grovers-algorithm
lynkos
from argparse import ArgumentParser, Namespace, BooleanOptionalAction from qiskit import QuantumCircuit as qc from qiskit import QuantumRegister as qr from qiskit import transpile from qiskit_aer import AerSimulator from qiskit.result import Counts from matplotlib.pyplot import show, subplots, xticks, yticks from math import pi, sqrt from heapq import nlargest class GroversAlgorithm: def __init__(self, title: str = "Grover's Algorithm", n_qubits: int = 5, search: set[int] = { 11, 9, 0, 3 }, shots: int = 1000, fontsize: int = 10, print: bool = False, combine_states: bool = False) -> None: """ _summary_ Args: title (str, optional): Window title. Defaults to "Grover's Algorithm". n_qubits (int, optional): Number of qubits. Defaults to 5. search (set[int], optional): Set of nonnegative integers to search for using Grover's algorithm. Defaults to { 11, 9, 0, 3 }. shots (int, optional): Amount of times the algorithm is simulated. Defaults to 10000. fontsize (int, optional): Histogram's font size. Defaults to 10. print (bool, optional): Whether or not to print quantum circuit(s). Defaults to False. combine_states (bool, optional): Whether to combine all non-winning states into 1 bar labeled "Others" or not. Defaults to False. """ # Parsing command line arguments self._parser: ArgumentParser = ArgumentParser(description = "Run grover's algorithm via command line", add_help = False) self._init_parser(title, n_qubits, search, shots, fontsize, print, combine_states) self._args: Namespace = self._parser.parse_args() # Set of nonnegative ints to search for self.search: set[int] = set(self._args.search) # Set of m N-qubit binary strings representing target state(s) (i.e. self.search in base 2) self._targets: set[str] = { f"{s:0{self._args.n_qubits}b}" for s in self.search } # N-qubit quantum register self._qubits: qr = qr(self._args.n_qubits, "qubit") def _print_circuit(self, circuit: qc, name: str) -> None: """Print quantum circuit. Args: circuit (qc): Quantum circuit to print. name (str): Quantum circuit's name. """ print(f"\n{name}:\n{circuit}") def _oracle(self, targets: set[str]) -> qc: """Mark target state(s) with negative phase. Args: targets (set[str]): N-qubit binary string(s) representing target state(s). Returns: qc: Quantum circuit representation of oracle. """ # Create N-qubit quantum circuit for oracle oracle = qc(self._qubits, name = "Oracle") for target in targets: # Reverse target state since Qiskit uses little-endian for qubit ordering target = target[::-1] # Flip zero qubits in target for i in range(self._args.n_qubits): if target[i] == "0": # Pauli-X gate oracle.x(i) # Simulate (N - 1)-control Z gate # 1. Hadamard gate oracle.h(self._args.n_qubits - 1) # 2. (N - 1)-control Toffoli gate oracle.mcx(list(range(self._args.n_qubits - 1)), self._args.n_qubits - 1) # 3. Hadamard gate oracle.h(self._args.n_qubits - 1) # Flip back to original state for i in range(self._args.n_qubits): if target[i] == "0": # Pauli-X gate oracle.x(i) # Display oracle, if applicable if self._args.print: self._print_circuit(oracle, "ORACLE") return oracle def _diffuser(self) -> qc: """Amplify target state(s) amplitude, which decreases the amplitudes of other states and increases the probability of getting the correct solution (i.e. target state(s)). Returns: qc: Quantum circuit representation of diffuser (i.e. Grover's diffusion operator). """ # Create N-qubit quantum circuit for diffuser diffuser = qc(self._qubits, name = "Diffuser") # Hadamard gate diffuser.h(self._qubits) # Oracle with all zero target state diffuser.append(self._oracle({"0" * self._args.n_qubits}), list(range(self._args.n_qubits))) # Hadamard gate diffuser.h(self._qubits) # Display diffuser, if applicable if self._args.print: self._print_circuit(diffuser, "DIFFUSER") return diffuser def _grover(self) -> qc: """Create quantum circuit representation of Grover's algorithm, which consists of 4 parts: (1) state preparation/initialization, (2) oracle, (3) diffuser, and (4) measurement of resulting state. Steps 2-3 are repeated an optimal number of times (i.e. Grover's iterate) in order to maximize probability of success of Grover's algorithm. Returns: qc: Quantum circuit representation of Grover's algorithm. """ # Create N-qubit quantum circuit for Grover's algorithm grover = qc(self._qubits, name = "Grover Circuit") # Intialize qubits with Hadamard gate (i.e. uniform superposition) grover.h(self._qubits) # # Apply barrier to separate steps grover.barrier() # Apply oracle and diffuser (i.e. Grover operator) optimal number of times for _ in range(int((pi / 4) * sqrt((2 ** self._args.n_qubits) / len(self._targets)))): grover.append(self._oracle(self._targets), list(range(self._args.n_qubits))) grover.append(self._diffuser(), list(range(self._args.n_qubits))) # Measure all qubits once finished grover.measure_all() # Display grover circuit, if applicable if self._args.print: self._print_circuit(grover, "GROVER CIRCUIT") return grover def _outcome(self, winners: list[str], counts: Counts) -> None: """Print top measurement(s) (state(s) with highest frequency) and target state(s) in binary and decimal form, determine if top measurement(s) equals target state(s), then print result. Args: winners (list[str]): State(s) (N-qubit binary string(s)) with highest probability of being measured. counts (Counts): Each state and its respective frequency. """ print("WINNER(S):") print(f"Binary = {winners}\nDecimal = {[ int(key, 2) for key in winners ]}\n") print("TARGET(S):") print(f"Binary = {self._targets}\nDecimal = {self.search}\n") if not all(key in self._targets for key in winners): print("Target(s) not found...") else: winners_frequency, total = 0, 0 for value, frequency in counts.items(): if value in winners: winners_frequency += frequency total += frequency print(f"Target(s) found with {winners_frequency / total:.2%} accuracy!") def _show_histogram(self, histogram_data) -> None: """Print outcome and display histogram of simulation results. Args: data: Each state and its respective frequency. """ # State(s) with highest count and their frequencies winners = { winner : histogram_data.get(winner) for winner in nlargest(len(self._targets), histogram_data, key = histogram_data.get) } # Print outcome self._outcome(list(winners.keys()), histogram_data) # X-axis and y-axis value(s) for winners, respectively winners_x_axis = [ str(winner) for winner in [*winners] ] winners_y_axis = [ *winners.values() ] # All other states (i.e. non-winners) and their frequencies others = { state : frequency for state, frequency in histogram_data.items() if state not in winners } # X-axis and y-axis value(s) for all other states, respectively other_states_x_axis = "Others" if self._args.combine else [*others] other_states_y_axis = [ sum([*others.values()]) ] if self._args.combine else [ *others.values() ] # Create histogram for simulation results figure, axes = subplots(num = "Grover's Algorithm — Results", layout = "constrained") axes.bar(winners_x_axis, winners_y_axis, color = "green", label = "Target") axes.bar(other_states_x_axis, other_states_y_axis, color = "red", label = "Non-target") axes.legend(fontsize = self._args.fontsize) axes.grid(axis = "y", ls = "dashed") axes.set_axisbelow(True) # Set histogram title, x-axis title, and y-axis title respectively axes.set_title(f"Outcome of {self._args.shots} Simulations", fontsize = int(self._args.fontsize * 1.45)) axes.set_xlabel("States (Qubits)", fontsize = int(self._args.fontsize * 1.3)) axes.set_ylabel("Frequency", fontsize = int(self._args.fontsize * 1.3)) # Set font properties for x-axis and y-axis labels respectively xticks(fontsize = self._args.fontsize, family = "monospace", rotation = 0 if self._args.combine else 70) yticks(fontsize = self._args.fontsize, family = "monospace") # Set properties for annotations displaying frequency above each bar annotation = axes.annotate("", xy = (0, 0), xytext = (5, 5), xycoords = "data", textcoords = "offset pixels", ha = "center", va = "bottom", family = "monospace", weight = "bold", fontsize = self._args.fontsize, bbox = dict(facecolor = "white", alpha = 0.4, edgecolor = "None", pad = 0) ) def _hover(event) -> None: """Display frequency above each bar upon hovering over it. Args: event: Matplotlib event. """ visibility = annotation.get_visible() if event.inaxes == axes: for bars in axes.containers: for bar in bars: cont, _ = bar.contains(event) if cont: x, y = bar.get_x() + bar.get_width() / 2, bar.get_y() + bar.get_height() annotation.xy = (x, y) annotation.set_text(y) annotation.set_visible(True) figure.canvas.draw_idle() return if visibility: annotation.set_visible(False) figure.canvas.draw_idle() # Display histogram id = figure.canvas.mpl_connect("motion_notify_event", _hover) show() figure.canvas.mpl_disconnect(id) def run(self) -> None: """ Run Grover's algorithm simulation. """ # Simulate Grover's algorithm locally backend = AerSimulator(method = "density_matrix") # Generate optimized grover circuit for simulation transpiled_circuit = transpile(self._grover(), backend, optimization_level = 2) # Run Grover's algorithm simulation job = backend.run(transpiled_circuit, shots = self._args.shots) # Get simulation results results = job.result() # Get each state's histogram data (including frequency) from simulation results data = results.get_counts() # Display simulation results self._show_histogram(data) def _init_parser(self, title: str, n_qubits: int, search: set[int], shots: int, fontsize: int, print: bool, combine_states: bool) -> None: """ Helper method to initialize command line argument parser. Args: title (str): Window title. n_qubits (int): Number of qubits. search (set[int]): Set of nonnegative integers to search for using Grover's algorithm. shots (int): Amount of times the algorithm is simulated. fontsize (int): Histogram's font size. print (bool): Whether or not to print quantum circuit(s). combine_states (bool): Whether to combine all non-winning states into 1 bar labeled "Others" or not. """ self._parser.add_argument("-H, --help", action = "help", help = "show this help message and exit") self._parser.add_argument("-T, --title", type = str, default = title, dest = "title", metavar = "<title>", help = f"window title (default: \"{title}\")") self._parser.add_argument("-n, --n-qubits", type = int, default = n_qubits, dest = "n_qubits", metavar = "<n_qubits>", help = f"number of qubits (default: {n_qubits})") self._parser.add_argument("-s, --search", default = search, type = int, nargs = "+", dest = "search", metavar = "<search>", help = f"nonnegative integers to search for with Grover's algorithm (default: {search})") self._parser.add_argument("-S, --shots", type = int, default = shots, dest = "shots", metavar = "<shots>", help = f"amount of times the algorithm is simulated (default: {shots})") self._parser.add_argument("-f, --font-size", type = int, default = fontsize, dest = "fontsize", metavar = "<font_size>", help = f"histogram's font size (default: {fontsize})") self._parser.add_argument("-p, --print", action = BooleanOptionalAction, type = bool, default = print, dest = "print", help = f"whether or not to print quantum circuit(s) (default: {print})") self._parser.add_argument("-c, --combine", action = BooleanOptionalAction, type = bool, default = combine_states, dest = "combine", help = f"whether to combine all non-winning states into 1 bar labeled \"Others\" or not (default: {combine_states})") if __name__ == "__main__": GroversAlgorithm().run()
https://github.com/Rassska/QuantumPack
Rassska
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi qreg_q = QuantumRegister(2, 'q') creg_c = ClassicalRegister(2, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.h(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.cx(qreg_q[0], qreg_q[1]) circuit.measure(qreg_q[0], creg_c[0]) circuit.measure(qreg_q[1], creg_c[1])
https://github.com/AnuvabSen1/Quantum-Computing-Algorithms-Implemented-on-IBM-s-QSAM-Qiskit
AnuvabSen1
import numpy as np import math import gmpy2 from gmpy2 import powmod,mpz,isqrt,invert from qiskit.aqua.algorithms import Shor from qiskit.aqua import QuantumInstance from qiskit import Aer,execute,QuantumCircuit from qiskit.tools.visualization import plot_histogram from qiskit.providers.ibmq import least_busy from qiskit import IBMQ, execute def generate_keys(): # prime number of 3 digits i.e 7 bits random1 = np.random.randint(3,40) random2 = np.random.randint(3,40) p = int(gmpy2.next_prime(random1)) q = int(gmpy2.next_prime(random2)) n = p*q while (n<100 or n>127): random1 = np.random.randint(3,40) random2 = np.random.randint(3,40) p = int(gmpy2.next_prime(random1)) q = int(gmpy2.next_prime(random2)) n = p*q phi = (p-1)*(q-1) e = 2 while True: if gmpy2.gcd(phi,e) != 1: e = e + 1 else : break d = gmpy2.invert(e,phi) return n,e,d def encrypt(plain_text_blocks,public_keys): cipher_text_blocks = [] n,e = public_keys for plain_text in plain_text_blocks: cipher_text = (gmpy2.powmod(plain_text,e,n)) cipher_text_blocks.append(cipher_text) return cipher_text_blocks def decrypt(cipher_text_blocks,secret_key,public_keys): n,e = public_keys d = secret_key decypted_plain_text_blocks = [] for cipher_text in cipher_text_blocks: plain_text = (gmpy2.powmod(cipher_text,d,n)) decypted_plain_text_blocks.append(plain_text) return decypted_plain_text_blocks def get_factors(public_keys): n,e = public_keys # backend = Aer.get_backend('qasm_simulator') provider = IBMQ.load_account() backend = provider.get_backend('ibmq_qasm_simulator') quantum_instance = QuantumInstance(backend,shots=2500) find_factors = Shor(n,a=2,quantum_instance=quantum_instance) factors = Shor.run(find_factors) p = ((factors['factors'])[0])[0] q = ((factors['factors'])[0])[1] print('Factors of',n,'are :',p,q) return p,q # taken in 'Hello World!!!' returns ['Hello World!','!!'] def get_blocks(PT,block_size): blocks = [] i = 0 while i<len(PT): temp_str='' if i+block_size-1 < len(PT): temp_str=temp_str+PT[i:i+block_size] else : temp_str=temp_str+PT[i::] blocks.append(temp_str) i=i+block_size return blocks # covert plain_text block from characters to the numbers def format_plain_text(PT): plain_text_blocks = [] for block in PT: plain_text = 0 for i in range(len(block)): # for 'd' if ord(block[i]) == 100: plain_text = plain_text*100 + 28 # between (101,127) elif ord(block[i])>100: plain_text = plain_text*100 + (ord(block[i])-100) else : plain_text = plain_text*100 + (ord(block[i])) plain_text_blocks.append(plain_text) return plain_text_blocks # convert numeric decypted_plain_text_blocks into a single plain text of characters def format_decrypted_plain_text(decypted_plain_text_blocks): plain_text_blocks = [] for dc_pt in decypted_plain_text_blocks: plain_text = '' temp = dc_pt # for 'd' temp = 28 while temp > 0: if temp%100 == 28: plain_text = plain_text + 'd' elif (temp%100) in range(0,27): plain_text = plain_text + chr((temp%100)+100) else : plain_text = plain_text + chr((temp%100)) temp = temp//100 plain_text = plain_text[::-1] plain_text_blocks.append(plain_text) final_plain_text = '' for plain_text_block in plain_text_blocks: final_plain_text = final_plain_text + plain_text_block return final_plain_text n,e,d = generate_keys() public_keys = (n,e) secret_key = d print("\nPublic Key :") print('n :',n) print('e :',e) print("Secret Key :\nd :",d) PT = input("\nEnter Plain Text to encrypt : ") original_plain_text = PT block_size = 1 PT = get_blocks(PT,block_size) print('\nPlain Text after converting to blocks',PT) plain_text_blocks = format_plain_text(PT) print('\nPlain text blocks after formatting to numbers:',plain_text_blocks) cipher_text_blocks = encrypt(plain_text_blocks,public_keys) print("\nCipher Text Blocks After RSA encryption :",cipher_text_blocks) p,q = get_factors(public_keys) phi = (p-1)*(q-1) broken_d = gmpy2.invert(e,phi) compromised_PT = decrypt(cipher_text_blocks,broken_d,public_keys) compromised_PT = format_decrypted_plain_text(compromised_PT) compromised_PT = '!!!Your message has been attacked!!! ' + compromised_PT compromised_PT = get_blocks(compromised_PT,block_size) compromised_PT = format_plain_text(compromised_PT) compromised_CT = encrypt(compromised_PT,public_keys) cipher_text_blocks = compromised_CT decypted_plain_text_blocks = decrypt(cipher_text_blocks,secret_key,public_keys) print("\nPlain Text blocks after decryption of Cipher Text blocks :",decypted_plain_text_blocks) plain_text_after_decryption = format_decrypted_plain_text(decypted_plain_text_blocks) print("\nAfter decryption Plain Text :",plain_text_after_decryption) if (original_plain_text == plain_text_after_decryption): print("\nHurrayyy!!!\n\nDecrypted plain_text is same as original plain_text! :) ") else : print('RSA was attacked!!! :(')
https://github.com/AnuvabSen1/Quantum-Computing-Algorithms-Implemented-on-IBM-s-QSAM-Qiskit
AnuvabSen1
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.utils import QuantumInstance import numpy as np from qiskit.algorithms import Shor IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here provider = IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) my_shor = Shor(quantum_instance) result_dict = my_shor.factor(15) print(result_dict)
https://github.com/psasanka1729/nisq-grover-qiskit-floquet-model
psasanka1729
import sys from qiskit import* #from qiskit import Aer import qiskit.quantum_info as qi import numpy as np #from math import pi #import matplotlib.pyplot as plt import re L = 4; qc = QuantumCircuit(L) qc.mcx([i for i in range(L-1)],L-1) qc.draw("mpl",style="clifford") trans_qc = transpile(qc, basis_gates = ['u1','rx','cx'], optimization_level = 3) #trans_qc = transpile(qc, basis_gates = ['rz','cx','h'], optimization_level = 3) #trans_qc.draw("mpl") trans_qc.draw("mpl") #len(trans_qc) def extract_gate_details(gate_index, gate_instruction_string): gate_string = str(gate_instruction_string[gate_index]) gate_as_list = [] # u1 gate. if "u1" in gate_string: # Extract the number using a more specific pattern number_match = re.search(r"params=\[([-\d.]+)\]", gate_string) angle = number_match.group(1) # '0.09817477042468103' # Extract the qubit index using a tailored pattern qubit_index_match = re.search(r"Qubit\(.*?, (\d+)\)", gate_string) qubit_acted_on = qubit_index_match.group(1) # '4' gate_as_list.append(["u1",angle,qubit_acted_on]) # rz gate. elif "rz" in gate_string: # Extract the number using a more specific pattern number_match = re.search(r"params=\[([-\d.]+)\]", gate_string) angle = number_match.group(1) # '0.09817477042468103' # Extract the qubit index using a tailored pattern qubit_index_match = re.search(r"Qubit\(.*?, (\d+)\)", gate_string) qubit_acted_on = qubit_index_match.group(1) # '4' gate_as_list.append(["rz",angle,qubit_acted_on]) # rx gate. elif "rx" in gate_string: # Extract the number using a more specific pattern number_match = re.search(r"params=\[([-\d.]+)\]", gate_string) angle = number_match.group(1) # '0.09817477042468103' # Extract the qubit index using a tailored pattern qubit_index_match = re.search(r"Qubit\(.*?, (\d+)\)", gate_string) qubit_acted_on = qubit_index_match.group(1) # '4' gate_as_list.append(["rx",angle,qubit_acted_on]) # controlled gate. elif "cx" in gate_string: match = re.search(r"(\d+)(?=\), Qubit\(QuantumRegister)", gate_string) if match: control_qubit = int(match.group()) match = re.search(r"(\d+)(?=\)\), clbits=\(\))", gate_string) if match: target_qubit = int(match.group()) gate_as_list.append(["cx",control_qubit,target_qubit]) # hadamard gate. elif "h" in gate_string: match = re.search(r"(\d+)(?=\),\), clbits=\(\))", string) if match: qubit_acted_on = int(match.group(1)) gate_as_list.append(["h", qubit_acted_on, qubit_acted_on ]) else: print("Kant") return gate_as_list trans_qc[2] trans_qc[5] # search for qubits string = str(trans_qc[0]) match = re.search(r"(\d+)(?=\),\), clbits=\(\))", string) int(match.group(1)) file = open('gates_list_'+str(L)+'.txt', 'w') # U_0. for i in range(L): # gate qubit qubt. file.write("x" + "\t" + str(i) + "\t" + str(i) + "\n") file.write("h" + "\t" + str(L-1) + "\t" + str(L-1) + "\n") for i in range(len(trans_qc)): print(i) gate_as_list = extract_gate_details(i,trans_qc)[0] print(gate_as_list) file.write(gate_as_list[0] + "\t" + str(gate_as_list[1]) + "\t" + str(gate_as_list[2]) + "\n") file.write("h" + "\t" + str(L-1) + "\t" + str(L-1) + "\n") for i in range(L): # gate qubit qubt. file.write("x" + "\t" + str(i) + "\t" + str(i) + "\n") # U_x. for i in range(L-1): file.write("h" + "\t" + str(i) + "\t" + str(i) + "\n") for i in range(L-1): file.write("x" + "\t" + str(i) + "\t" + str(i) + "\n") file.write("z" + "\t" + str(L-1) + "\t" + str(L-1) + "\n") for i in range(len(trans_qc)): gate_as_list = extract_gate_details(i,trans_qc)[0] file.write(gate_as_list[0] + "\t" + str(gate_as_list[1]) + "\t" + str(gate_as_list[2]) + "\n") file.write("z" + "\t" + str(L-1) + "\t" + str(L-1) + "\n") for i in range(L-1): file.write("x" + "\t" + str(i) + "\t" + str(i) + "\n") for i in range(L-1): file.write("h" + "\t" + str(i) + "\t" + str(i) + "\n") file.close()
https://github.com/psasanka1729/nisq-grover-qiskit-floquet-model
psasanka1729
L = 8; using PyCall using Random using LinearAlgebra using SparseArrays using DelimitedFiles file = raw"gates_list_"*string(L)*".txt" # Change for every L. M = readdlm(file) # Name. Gates_data_1 = M[:,1]; # Angle. Gates_data_2 = M[:,2]; # Qubit. Gates_data_3 = M[:,3]; Number_of_Gates = length(Gates_data_1) #Gates_data_2; SEED = 100 Random.seed!(SEED) NOISE = 2*rand(Float64,Number_of_Gates).-1; I2 = [1 0; 0 1]; Pauli_Z = [1 0; 0 -1]; Pauli_X = [0 1; 1 0] H = (1/sqrt(2))*[1 1; 1 -1] U_1(theta) = [1 0; 0 exp(1im*theta)]; Rx(theta) = sparse(exp(-1im*(theta/2)*collect(Pauli_X))); Rz(theta) = sparse(exp(-1im*(theta/2)*collect(Pauli_Z))); U1(theta) = sparse(exp(-1im*(theta/2)*(collect(Pauli_Z)-I2))); Hadamard(noise) = sparse(exp(-1im*(pi/2+noise)*collect(I2-H))) X(noise) = sparse(exp(-1im*(pi/2+noise)*collect(I2-Pauli_X))); Z_gate(noise) = sparse(exp(-1im*(pi/2+noise)*collect(I2-Pauli_Z))) Identity(dimension) = spdiagm(0 => ones(dimension)); int(x) = floor(Int,x); function single_qubit_gate_matrix(single_qubit_gate, qubit) ## The case Qubit=1 is treated differently because we need to # initialize the matrix as U before starting the kronecker product. if qubit == 1 gate_matrix = sparse(single_qubit_gate) for i=2:L gate_matrix = kron(gate_matrix, I2) end #= Single qubit gates acting on qubits othe than the first. =# else gate_matrix = I2 for i=2:L if i == qubit gate_matrix = kron(gate_matrix, single_qubit_gate) else gate_matrix = kron(gate_matrix, I2) end end end return gate_matrix end; function single_qubit_controlled_gate_exponential(single_qubit_gate, c, t) I2 = [1 0;0 1] Z = [1 0;0 -1] Matrices = Dict("I" => I2,"PI_1" => I2-Z,"U" => I2 - single_qubit_gate) p = fill("I", L) p[c] = "PI_1" p[t] = "U" H_matrix = Matrices[p[1]] for i = 2:L H_matrix = kron(H_matrix, Matrices[p[i]]) end #= pi/4 = (pi)/(2*2)=# return sparse(H_matrix)/4 end; function single_qubit_controlled_gate_matrix(single_qubit_gate,c,t) # c t Z = [1 0; 0 -1] # |0><0|. PI_0 = (I2+Z)/2 # |1><1|. PI_1 = (I2-Z)/2 Matrices = Dict("I" => I2,"PI_0" => PI_0,"U" => single_qubit_gate, "PI_1" => PI_1) p0 = fill("I", L) p1 = fill("I", L) p0[c] = "PI_0" p1[c] = "PI_1" p1[t] = "U" PI_0_matrix = Matrices[p0[1]] for i = 2:L PI_0_matrix = kron(PI_0_matrix,Matrices[p0[i]]) end PI_1_matrix = Matrices[p1[1]] for i = 2:L PI_1_matrix = kron(PI_1_matrix,Matrices[p1[i]]) end return sparse(PI_0_matrix + PI_1_matrix) end; #L = 2 #single_qubit_controlled_gate_matrix(Pauli_X,1,2) using PyCall py""" import numpy import numpy.linalg def adjoint(psi): return psi.conjugate().transpose() def psi_to_rho(psi): return numpy.outer(psi,psi.conjugate()) def exp_val(psi, op): return numpy.real(numpy.dot(adjoint(psi),op.dot(psi))) def norm_sq(psi): return numpy.real(numpy.dot(adjoint(psi),psi)) def normalize(psi,tol=1e-9): ns=norm_sq(psi)**0.5 if ns < tol: raise ValueError return psi/ns def is_herm(M,tol=1e-9): if M.shape[0]!=M.shape[1]: return False diff=M-adjoint(M) return max(numpy.abs(diff.flatten())) < tol def is_unitary(M,tol=1e-9): if M.shape[0]!=M.shape[1]: return False diff=M.dot(adjoint(M))-numpy.identity((M.shape[0])) return max(numpy.abs(diff.flatten())) < tol def eigu(U,tol=1e-9): (E_1,V_1)=numpy.linalg.eigh(U+adjoint(U)) U_1=adjoint(V_1).dot(U).dot(V_1) H_1=adjoint(V_1).dot(U+adjoint(U)).dot(V_1) non_diag_lst=[] j=0 while j < U_1.shape[0]: k=0 while k < U_1.shape[0]: if j!=k and abs(U_1[j,k]) > tol: if j not in non_diag_lst: non_diag_lst.append(j) if k not in non_diag_lst: non_diag_lst.append(k) k+=1 j+=1 if len(non_diag_lst) > 0: non_diag_lst=numpy.sort(numpy.array(non_diag_lst)) U_1_cut=U_1[non_diag_lst,:][:,non_diag_lst] (E_2_cut,V_2_cut)=numpy.linalg.eigh(1.j*(U_1_cut-adjoint(U_1_cut))) V_2=numpy.identity((U.shape[0]),dtype=V_2_cut.dtype) for j in range(len(non_diag_lst)): V_2[non_diag_lst[j],non_diag_lst]=V_2_cut[j,:] V_1=V_1.dot(V_2) U_1=adjoint(V_2).dot(U_1).dot(V_2) # Sort by phase U_1=numpy.diag(U_1) inds=numpy.argsort(numpy.imag(numpy.log(U_1))) return (U_1[inds],V_1[:,inds]) # = (U_d,V) s.t. U=V*U_d*V^\dagger """ U_0 = Identity(2^L)#[-1 0 0 0; 0 1 0 0; 0 0 1 0;0 0 0 1]; U_0[1,1] = -1 A = ones(2^L,2^L); U_x = (2/2^L)*A-Identity(2^L); # 2\s><s|-I G_exact = U_x*U_0; #V = py"eigu"(G_exact)[2]; function grover_delta(DELTA) U_list = [] GROVER_DELTA = Identity(2^L) # U_x for i = 1:Number_of_Gates if Gates_data_1[i] == "x" epsilon = NOISE[i] GROVER_DELTA *= single_qubit_gate_matrix(X(DELTA*epsilon), Gates_data_3[i]+1) #push!(U_list,single_qubit_gate_matrix(X(0.0), Gates_data_3[i]+1)) elseif Gates_data_1[i] == "h" epsilon = NOISE[i] GROVER_DELTA *= single_qubit_gate_matrix(Hadamard(DELTA*epsilon), Gates_data_3[i]+1) #push!(U_list,single_qubit_gate_matrix(Hadamard(0.0), Gates_data_3[i]+1)) elseif Gates_data_1[i] == "z" epsilon = NOISE[i] GROVER_DELTA *= single_qubit_gate_matrix(Z_gate(DELTA*epsilon), Gates_data_3[i]+1) #push!(U_list,single_qubit_gate_matrix(Z_gate(0.0), Gates_data_3[i]+1)) elseif Gates_data_1[i] == "rx" epsilon = NOISE[i] GROVER_DELTA *= single_qubit_gate_matrix(Rx(Gates_data_2[i]+DELTA*epsilon),Gates_data_3[i]+1) #push!(U_list,single_qubit_gate_matrix(Rx(Gates_data_2[i]),Gates_data_3[i]+1)) elseif Gates_data_1[i] == "rz" epsilon = NOISE[i] GROVER_DELTA *= single_qubit_gate_matrix(Rz(Gates_data_2[i]+DELTA*epsilon),Gates_data_3[i]+1) #push!(U_list,single_qubit_gate_matrix(Rz(Gates_data_2[i]),Gates_data_3[i]+1)) elseif Gates_data_1[i] == "u1" epsilon = NOISE[i] GROVER_DELTA *= single_qubit_gate_matrix(U1(Gates_data_2[i]+DELTA*epsilon),Gates_data_3[i]+1) #push!(U_list,single_qubit_gate_matrix(U1(Gates_data_2[i]),Gates_data_3[i]+1)) elseif Gates_data_1[i] == "cx" epsilon = NOISE[i] GROVER_DELTA *= single_qubit_controlled_gate_matrix(X(DELTA*epsilon), Gates_data_2[i]+1, Gates_data_3[i]+1) #push!(U_list, single_qubit_controlled_gate_matrix(Pauli_X, Gates_data_2[i]+1, Gates_data_3[i]+1)) else println("Kant") end end #= function kth_term(k) f_k = Identity(2^L); for i = k:length(U_list) f_k = f_k*collect(U_list[length(U_list)-i+k]) end #= Corresponding H for the kth term. =# if Gates_data_1[k] == "h" Qubit = Gates_data_3[k]+1 # qubit. H_k = single_qubit_gate_matrix(I2-H,Qubit) #= H_H = I2-H. =# elseif Gates_data_1[k] == "x" Qubit = Gates_data_3[k]+1 # qubit. H_k = single_qubit_gate_matrix([1 0;0 1]-[0 1;1 0],Qubit) #= H_X = I2-X. =# elseif Gates_data_1[k] == "z" Qubit = Gates_data_3[k]+1 # qubit. H_k = single_qubit_gate_matrix([1 0;0 1]-[1 0;0 -1],Qubit) #= H_Z = I2-Z. =# elseif Gates_data_1[k] == "rz" Qubit = Gates_data_3[k]+1 # qubit. H_k = single_qubit_gate_matrix([1 0;0 -1],Qubit) #= H_Z = I2-Z. =# elseif Gates_data_1[k] == "rx" Qubit = Gates_data_3[k]+1 # qubit. H_k = single_qubit_gate_matrix(Pauli_X,Qubit) #= H_Z = I2-Z. =# elseif Gates_data_1[k] == "cx" Angle = Gates_data_1[k] Control_Qubit = int(Gates_data_2[k])+1 Target_Qubit = int(Gates_data_3[k])+1 Z = [1 0;0 -1] #= H = ((I-Z)/2)_c \otimes ((I-X)/2)_t.=# Matrices = Dict("I" => [1 0;0 1],"U" => [1 0; 0 1]-[0 1;1 0], "PI_1" => [1 0;0 1]-[1 0;0 -1]) p1 = fill("I", L) p1[Control_Qubit] = "PI_1" p1[Target_Qubit] = "U" H_k = Matrices[p1[1]] for i = 2:L H_k = kron(H_k,Matrices[p1[i]]) end elseif Gates_data_1[k] == "u1" Qubit = Gates_data_3[k]+1 # qubit. H_k = single_qubit_gate_matrix(Pauli_Z-I2,Qubit) #= H_Z = I2-Z. =# else println(Gates_data_1[k]*" H_k cannot be calculated") end return f_k*H_k*(f_k') end; h_eff = zeros(2^L,2^L); for i = 1:length(U_list) h_eff += NOISE[i]*kth_term(i) end #h_eff_D = h_eff #h_eff_D = (V')*h_eff*(V) # Matrix in |0> and |xbar> basis. #E_eff_D = eigvals(h_eff_D) # Diagonalizing H_eff matrix. #E_eff_D_sorted = sort(real(E_eff_D),rev = true); # Soring the eigenvalues in descending order. #EIGU = py"eigu"(collect(-GROVER_DELTA')) #E_exact = real(1im*log.(EIGU[1])); # Eigenvalue. #return E_exact, E_eff_D_sorted return h_eff =# return -GROVER_DELTA' #return GROVER_DELTA end; #real.((collect(grover_delta(0.0))))-G_exact #= The following function returns the matrix of rolling operator. =# function One_Roll_Operator(number_of_qubits::Int64) #= Function converts a binary number to a decimal number. =# Bin2Dec(BinaryNumber) = parse(Int, string(BinaryNumber); base=2); #= Function converts a decimal number to a binary number. =# function Dec2Bin(DecimalNumber::Int64) init_binary = string(DecimalNumber, base = 2); #= While converting numbers from decimal to binary, for example, 1 is mapped to 1, to make sure that every numbers have N qubits in them, the following loop adds leading zeros to make the length of the binary string equal to N. Now, 1 is mapped to 000.....1 (string of length N). =# while length(init_binary) < number_of_qubits init_binary = "0"*init_binary end return init_binary end #= The following function takes a binary string as input and rolls the qubits by one and returns the rolled binary string. =# Roll_String_Once(binary_string) = binary_string[end]*binary_string[1:end-1] #= Initializing the rolling operator. =# R = zeros(Float64,2^number_of_qubits,2^number_of_qubits); #= The numbers are started from 0 to 2^L-1 because for L qubits, binary representation goes from 0 to 2^L-1.=# for i = 0:2^number_of_qubits-1 #= Steps in the following loop. (1) The number is converted from decimal to binary. (2) The qubits are rolled once. (3) The rolled binary number is converted to decimal number. (4) The corresponding position in R is replaced by 1. =# #= The index in R will be shifted by 1 as Julia counts from 1. =# R[i+1,Bin2Dec(Roll_String_Once(Dec2Bin(i)))+1] = 1 end return sparse(R) end; #= The following function returns the von-Neumann entropy of a given wavefunction. The sub-system size is L/2. =# function entanglement_entropy(Psi) sub_system_size = floor(Int,L/2) Psi = Psi/norm(Psi) function psi(s) return Psi[2^(sub_system_size)*s+1:2^(sub_system_size)*s+2^(sub_system_size)] end #= (s,s_p) element of the reduced density matrix is given by psi(s_p)^(\dagger)*psi(s). =# rhoA(s,s_p) = psi(s_p)' * psi(s) M = zeros(ComplexF64,2^sub_system_size,2^sub_system_size) #= Since the matrix is symmetric only terms above the diagonal will be calculated. =# for i = 0:2^sub_system_size-1 for j = 0:2^sub_system_size-1 if i <= j M[i+1,j+1] = rhoA(i,j) else M[i+1,j+1] = M[j+1,i+1]' end end end #= Eigenvalues of M. The small quantity is added to avoid singularity in log.=# w = eigvals(M).+1.e-10 return real(-sum([w[i]*log(w[i]) for i = 1:2^(sub_system_size)])) end; function average_entanglement_entropy(initial_wavefunction) initial_wavefunction = initial_wavefunction/norm(initial_wavefunction) R = One_Roll_Operator(L) rolled_wavefunction = R * initial_wavefunction rolled_entropies = [entanglement_entropy(rolled_wavefunction)] for i = 2:L rolled_wavefunction = R * rolled_wavefunction push!(rolled_entropies,entanglement_entropy(rolled_wavefunction)) end return sum(rolled_entropies)/L end; #H_EFF = h_eff_from_derivative(1.e-5); #= h_eff = H_EFF # Matrix in Z basis. h_eff = (V')*h_eff*(V) # Matrix in |0> and |xbar> basis. h_eff_D = h_eff[3:2^L,3:2^L];=# #h_eff_D """function Level_Statistics(n,Es) return min(abs(Es[n]-Es[n-1]),abs(Es[n+1]-Es[n])) / max(abs(Es[n]-Es[n-1]),abs(Es[n+1]-Es[n])) end; h_eff_level_statistics = Array{Float64, 1}(undef, 0) for i = 2:2^L-3 # relative index i.e length of the eigenvector array. push!(h_eff_level_statistics,Level_Statistics(i,h_eff_D )) end level_statistics_file = open("level_statistics.txt", "w") for i = 1:2^L-4 write(level_statistics_file, string(i)) write(level_statistics_file, "\t") # Add a tab indentation between the columns write(level_statistics_file, string(h_eff_level_statistics[i])) write(level_statistics_file, "\n") # Add a newline character to start a new line end close(level_statistics_file)"""; #h_eff_level_statistics #using Statistics #mean(h_eff_level_statistics) #Eigvals_h_eff = eigvals(collect(h_eff_D)); #Eigvecs_h_eff = eigvecs(collect(h_eff)); #= using Plots using DelimitedFiles using ColorSchemes using LaTeXStrings eigenvalue_file = open("compare_h_eff_G_exact_eigenvalues.txt", "w") Exact_list = [] Effec_list = [] delta_list = [] Num = 10; for i = 1:Num delta = 0.1*(i/Num) EE = -Grover_delta(delta) EIGU = py"eigu"(collect(EE)) Exact = real(1im*log.(EIGU[1]))[2:2^L-1] Effec = delta*real(Eigvals_h_eff) #println(Exact) #println(Effec) for j = 1:2^L-2 write(eigenvalue_file, string(delta)) write(eigenvalue_file, "\t") write(eigenvalue_file, string(Exact[j])) write(eigenvalue_file, "\t") write(eigenvalue_file, string(Effec[j])) write(eigenvalue_file, "\n") #py"Write_file2"(delta,Exact[j],Effec[j]) push!(delta_list,delta) push!(Exact_list, Exact[j]) push!(Effec_list, Effec[j]) #println(delta); end end delta = delta_list exact = Exact_list # exact energy. effec = Effec_list # effective energy. S_Page = 0.5*L*log(2)-0.5 gr() L = 4; S_Page = 0.5*L*log(2)-0.5 MyTitle = "L = 4 "; p = plot(delta,exact, seriestype = :scatter, markercolor = "firebrick1 ",#"red2", markerstrokewidth=0.0, markersize=3.2, thickness_scaling = 1.4, xlims=(0,0.3), ylims=(-3.14,3.14), #title = MyTitle, label = "Exact energy", legend = :bottomleft, dpi=500, #zcolor = entropy, grid = false, #colorbar_title = "Average entanglement entropy", font="CMU Serif", color = :jet1, right_margin = 5Plots.mm, left_margin = Plots.mm, titlefontsize=10, guidefontsize=13, tickfontsize=13, legendfontsize=15, framestyle = :box ) p = plot!(delta,effec, seriestype = :scatter, markercolor = "blue2", markershape=:pentagon,#:diamond, markerstrokewidth=0.0, markersize=2.2, thickness_scaling = 1.4, xlims=(0,0.1), ylims=(-3.14,3.14), #title = MyTitle, label = "Effective energy", legend = :bottomleft, dpi=100, #zcolor = entropy, grid = false, #colorbar_title = "Average entanglement entropy", font="CMU Serif", right_margin = 5Plots.mm, left_margin = Plots.mm, titlefontsize=10, guidefontsize=13, tickfontsize=13, legendfontsize=15, framestyle = :box ) plot!(size=(830,700)) xlabel!("Noise") ylabel!("Energy of the bulk states") #savefig("exact_effec_4_2000.png") =# """function KLd(Eigenvectors_Matrix) KL = [] for n = 1:2^L-1 # Eigenvector index goes from 1 to dim(H)-1. #= Here n is the index of the eigenstate e.g n = 3 denotes the third eigenstate of the h_eff matrix in sigma_z basis. =# #= Calculates the p(i) = |<i|n>|^2 for a given i. This is the moduli squared of the i-th component of the n-th eigenstate. This is because in the sigma_z basis <i|n> = i-th component of |n>. =# # Initialize the sum. KLd_sum = 0.0 # The sum goes from 1 to dim(H) i.e length of an eigenvector. for i = 1:2^L p = abs(Eigenvectors_Matrix[:,n][i])^2 + 1.e-9 # To avoid singularity in log. q = abs(Eigenvectors_Matrix[:,n+1][i])^2 + 1.e-9 KLd_sum += p*log(p/q) end #println(KLd_sum) push!(KL,KLd_sum) end return KL end;"""; #KLd_h_eff = KLd(Eigvecs_h_eff); #mean(KLd_h_eff) #= KLd_file = open("KLd.txt", "w") for i = 1:2^L-1 write(KLd_file , string(i)) write(KLd_file , "\t") # Add a tab indentation between the columns write(KLd_file , string(KLd_h_eff[i])) write(KLd_file , "\n") # Add a newline character to start a new line end # Close the file close(KLd_file)=# eigenvalue_file = open(string(L)*"_"*string(SEED)*"_eigenvalues.txt", "w"); deltas = [] Ys = [] Entropies = [] Num = 200 for i=0:Num println(i) delta = 0.1*i/Num Op = -collect(grover_delta(delta)) EIGU = py"eigu"(Op) deltas = string(delta) Y = real(1im*log.(EIGU[1])) V = EIGU[2] for j=1:2^L write(eigenvalue_file , string(delta)) write(eigenvalue_file , "\t") # Add a tab indentation between the columns write(eigenvalue_file , string(real(Y[j]))) write(eigenvalue_file , "\t") write(eigenvalue_file , string(average_entanglement_entropy(V[1:2^L,j:j]))) write(eigenvalue_file , "\n") # Add a newline character to start a new line #end #py"Write_file"(delta, real(Y[j]), average_entanglement_entropy(V[1:2^L,j:j])) end end close(eigenvalue_file) #= using Plots using DelimitedFiles using ColorSchemes #using CSV using LaTeXStrings #using PyPlot=# #= file = "eigenvalues.txt" M = readdlm(file) delta = M[:,1]; # eigenvalue index quasienergy = M[:,2]; # level stat entanglement = M[:,3]; # level stat std gr() MSW = 0.4 Linewidth = 0.6 Markersize = 1.7 MarkerStrokeWidth = 0.0; plot_font = "Computer Modern" default(fontfamily=plot_font) MyTitle = "L = "*string(L)*", Page Value = "*string(round(0.5*L*log(2)-0.5;digits = 2))*" "; p = plot(delta,quasienergy , seriestype = :scatter, markerstrokecolor = "grey30", markerstrokewidth=MarkerStrokeWidth, markersize=Markersize, thickness_scaling = 2.5, xlims=(0,0.4), ylims=(-3.2,3.2), title = "", label = "", #legend = :bottomleft, dpi=300, zcolor = entanglement, grid = false, #colorbar_title = "Average entanglement entropy", right_margin = Plots.mm, font="CMU Serif", color = :jet1, #:linear_bmy_10_95_c78_n256,#:diverging_rainbow_bgymr_45_85_c67_n256,#:linear_bmy_10_95_c78_n256,#:rainbow1, #right_margin = 2Plots.mm, left_margin = Plots.mm, titlefontsize=10, guidefontsize=10, tickfontsize=9, legendfontsize=8, framestyle = :box ) yticks!([-pi,-3*pi/4,-pi/2,-pi/4,0,pi/4,pi/2,3*pi/4,pi], [L"-\pi",L"-3\pi/4",L"-\pi/2",L"-\pi/4",L"0",L"\pi/4",L"\pi/2",L"3\pi/4",L"\pi"]) function ticks_length!(;tl=0.01) p = Plots.current() xticks, yticks = Plots.xticks(p)[1][1], Plots.yticks(p)[1][1] xl, yl = Plots.xlims(p), Plots.ylims(p) x1, y1 = zero(yticks) .+ xl[1], zero(xticks) .+ yl[1] sz = p.attr[:size] r = sz[1]/sz[2] dx, dy = tl*(xl[2] - xl[1]), tl*r*(yl[2] - yl[1]) plot!([xticks xticks]', [y1 y1 .+ dy]', c=:black, labels=false,linewidth = 1.3) plot!([x1 x1 .+ dx]', [yticks yticks]', c=:black, labels=false,linewidth = 1.3, xlims=xl, ylims=yl) return Plots.current() end ticks_length!(tl=0.005) plot!(size=(1200,800)) #plot!(yticks = ([(-pi) : (-pi/2): (-pi/4): 0: (pi/4) : (pi/2) : pi;], ["-\\pi", "-\\pi/2", "-\\pi/4","0","\\pi/4","\\pi/2","\\pi"])) #hline!([[-quasienergy]],lc=:deeppink1,linestyle= :dashdotdot,legend=false) #hline!([ [0]],lc=:deeppink1,linestyle= :dashdotdot,legend=false) #hline!([ [quasienergy]],lc=:deeppink1,linestyle= :dashdotdot,legend=false) xlabel!("Disorder strength, \$\\delta\$") ylabel!("Quasienergy, \$\\phi_{F}\$") plot!(background_color=:white) #savefig(string(L)*"_"*string(SEED)*"_plot_data_0.0_0.15.png") =# #round(0.5*L*log(2)-0.5;digits = 2)
https://github.com/psasanka1729/nisq-grover-qiskit-floquet-model
psasanka1729
import numpy as np from scipy.sparse import identity from scipy import sparse from qiskit import* L = 4 gates_list = open('gates_list_'+str(L)+'.txt','r') MCX_transpile = [] for gates in gates_list: MCX_transpile.append(gates.split(",")) len(MCX_transpile) number_of_gates = len(MCX_transpile) Seed = 4000 np.random.seed(Seed) Noise = np.random.rand(number_of_gates) def H_fixed(): # Hadamad gate acting on one qubit. return 1/np.sqrt(2)*np.matrix([[1,1], [1,-1]]) def Ry(theta): return np.matrix([[np.cos(theta/2), -np.sin(theta/2)], [np.sin(theta/2), np.cos(theta/2)]]) def sigma_Z(): return np.matrix([[1,0], [0,-1]]) def sigma_X(): return np.matrix([[0,1], [1,0]]) def Rz(theta): return np.matrix([[np.exp(-1j*theta/2), 0], [0, np.exp(1j*theta/2)]]) ''' For noise = 0; the following returns the fixed Hadamard gate. ''' def Hadamard_variable(noise): return Ry(np.pi/2+noise)*sigma_Z() def sigma_X_variable(noise): return Hadamard_variable(noise)*sigma_Z()*Hadamard_variable(noise) def Cx(noise): Pi_0 = np.matrix([[1,0],[0,0]]) final_matrix_1 = sparse.kron(Pi_0,np.identity(2)) Pi_1 = np.matrix([[0,0],[0,1]]) final_matrix_2 = sparse.kron(Pi_1,sigma_X_variable(noise)) return final_matrix_1+final_matrix_2 def CU_gate(quantum_gate,control_qubit,target_qubit): Pi_0 = np.matrix([[1,0],[0,0]]) Pi_1 = np.matrix([[0,0],[0,1]]) ''' List below will hold gates acting on one qubit. For example, for L = 8, gate U acting on control qubit c and target qubit t is I x I x ...x (Pi_0)_c x ...x (I)_t x ... x I + I x I x ...x (Pi_1)_c x ...x (U)_t x ... x I ''' qubits_list_1 = [] for i in range(L): if i == control_qubit: qubits_list_1.append(Pi_0) else: # Other gates are identity operators. qubits_list_1.append(np.identity(2)) qubits_list_2 = [] for i in range(L): if i == control_qubit: qubits_list_2.append(Pi_1) elif i == target_qubit: qubits_list_2.append(quantum_gate) else: # Other gates are identity operators. qubits_list_2.append(np.identity(2)) #qubits_list_1.reverse() #qubits_list_2.reverse() final_matrix_1 = sparse.csr_matrix(qubits_list_1[0]) # Initializes the final matrix. for g in range(1,len(qubits_list_1)): final_matrix_1 = sparse.kron(qubits_list_1[g],final_matrix_1) # kronecker product. final_matrix_2 = sparse.csr_matrix(qubits_list_2[0]) # Initializes the final matrix. for g in range(1,len(qubits_list_2)): final_matrix_2 = sparse.kron(qubits_list_2[g],final_matrix_2) # kronecker product. return final_matrix_1+final_matrix_2 def N_th_qubit_gate(quantum_gate,qubit_number): ''' List below will hold gates acting on one qubit. For example, for L = 3, the Hadamard gate acting on the qubit 1 is given by = 1 x H x 1, where x is the Kronecker product. Then, qubits_list = [1,H,1]. ''' qubits_list = [] for i in range(L): if i == qubit_number: # qubit_number^th position in the list is the quantum_gate. qubits_list.append(quantum_gate) else: # Other gates are identity operators. qubits_list.append(np.identity(2)) ''' The following loop performs the Kronecker product. ''' final_matrix = sparse.csr_matrix(qubits_list[0]) # Initializes the final matrix. for i in range(1,len(qubits_list)): final_matrix = sparse.kron(final_matrix,qubits_list[i]) # kronecker product. return final_matrix U_0 = np.identity(2**L, dtype = complex); Delta = 0.0 noise_counter = 0 for i in MCX_transpile: if i[0] == 'h': epsilon = Delta*Noise[noise_counter] noise_counter += 1 qubit = int(i[2]) U_0 = U_0*N_th_qubit_gate(Hadamard_variable(epsilon),qubit) #np.matmul(U_0,N_th_qubit_gate(Hadamard_variable(epsilon),qubit)) elif i[0] == 'cx': epsilon = Delta*Noise[noise_counter] noise_counter += 1 control_qubit = int(i[1]) target_qubit = int(i[2]) U_0 = U_0*CU_gate(sigma_X_variable(epsilon),control_qubit,target_qubit) #np.matmul(U_0,CU_gate(sigma_X_variable(epsilon),control_qubit,target_qubit)) elif i[0] == 'rz': epsilon = Delta*Noise[noise_counter] noise_counter += 1 qubit = int(i[2]) angle = float(i[1]) U_0 = U_0*N_th_qubit_gate(Rz(epsilon+angle),qubit) m = np.around(U_0,2) m = m/m[0,0] m.real def Grover_operator(Delta): noise_counter = 0 ''' First the U_x will be created. ''' U_x = np.identity(2**L, dtype = complex); for i in range(L): epsilon = Delta*Noise[noise_counter] noise_counter += 1 U_x = U_x*N_th_qubit_gate(Hadamard_variable(epsilon),i) #np.matmul(U_x,N_th_qubit_gate(Hadamard_variable(epsilon),i)) for i in range(L): epsilon = Delta*Noise[noise_counter] noise_counter += 1 U_x = U_x*N_th_qubit_gate(sigma_X_variable(epsilon),i) #np.matmul(U_x,N_th_qubit_gate(sigma_X_variable(epsilon),i)) # mcx gate of U_x for i in MCX_transpile: if i[0] == 'h': epsilon = Delta*Noise[noise_counter] noise_counter += 1 qubit = int(i[2]) U_x = U_x*N_th_qubit_gate(Hadamard_variable(epsilon),qubit) #np.matmul(U_x,N_th_qubit_gate(Hadamard_variable(epsilon),qubit)) elif i[0] == 'cx': epsilon = Delta*Noise[noise_counter] noise_counter += 1 control_qubit = int(i[1]) target_qubit = int(i[2]) U_x = U_x*CU_gate(sigma_X_variable(epsilon),control_qubit,target_qubit) #np.matmul(U_x,CU_gate(sigma_X_variable(epsilon),control_qubit,target_qubit)) elif i[0] == 'rz': epsilon = Delta*Noise[noise_counter] noise_counter += 1 qubit = int(i[2]) angle = float(i[1]) U_x = U_x*N_th_qubit_gate(Rz(epsilon+angle),qubit) #np.matmul(U_x,N_th_qubit_gate(Rz_variable(epsilon+angle),qubit)) for i in range(L): epsilon = Delta*Noise[noise_counter] noise_counter += 1 U_x = U_x*N_th_qubit_gate(sigma_X_variable(epsilon),i) #np.matmul(U_x,N_th_qubit_gate(sigma_X_variable(epsilon),i)) for i in range(L): epsilon = Delta*Noise[noise_counter] noise_counter += 1 U_x = U_x*N_th_qubit_gate(Hadamard_variable(epsilon),i) #np.matmul(U_x,N_th_qubit_gate(Hadamard_variable(epsilon),i)) ''' First the U_0 will be created. ''' U_0 = np.identity(2**L, dtype = complex); for i in range(L): epsilon = Delta*Noise[noise_counter] noise_counter += 1 U_0 = U_0*N_th_qubit_gate(sigma_X_variable(epsilon),i) #np.matmul(U_0,N_th_qubit_gate(sigma_X_variable(epsilon),i)) epsilon = Delta*Noise[noise_counter] noise_counter += 1 U_0 = U_0*N_th_qubit_gate(Hadamard_variable(epsilon),L) #np.matmul(U_0,N_th_qubit_gate(Hadamard_variable(epsilon),L)) # mcx gate of U_0 for i in MCX_transpile: if i[0] == 'h': epsilon = Delta*Noise[noise_counter] noise_counter += 1 qubit = int(i[2]) U_0 = U_0*N_th_qubit_gate(Hadamard_variable(epsilon),qubit) #np.matmul(U_0,N_th_qubit_gate(Hadamard_variable(epsilon),qubit)) elif i[0] == 'cx': epsilon = Delta*Noise[noise_counter] noise_counter += 1 control_qubit = int(i[1]) target_qubit = int(i[2]) U_0 = U_0*CU_gate(sigma_X_variable(epsilon),control_qubit,target_qubit) #np.matmul(U_0,CU_gate(sigma_X_variable(epsilon),control_qubit,target_qubit)) elif i[0] == 'rz': epsilon = Delta*Noise[noise_counter] noise_counter += 1 qubit = int(i[2]) angle = float(i[1]) U_0 = U_0*N_th_qubit_gate(Rz(epsilon+angle),qubit) #np.matmul(U_0,N_th_qubit_gate(Rz_variable(epsilon+angle),qubit)) for i in range(L): epsilon = Delta*Noise[noise_counter] noise_counter += 1 U_0 = U_0*N_th_qubit_gate(sigma_X_variable(epsilon),i) #np.matmul(U_0,N_th_qubit_gate(sigma_X_variable(epsilon),i)) epsilon = Delta*Noise[noise_counter] noise_counter += 1 U_0 = U_0*N_th_qubit_gate(Hadamard_variable(epsilon),L) #np.matmul(U_0,N_th_qubit_gate(Hadamard_variable(epsilon),L)) return U_0
https://github.com/LeDernier/qiskit-HHL
LeDernier
#Imports non Qiskit import numpy as np from numpy import pi #Imports Qiskit #Généraux from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ #Aqua from qiskit.aqua.algorithms import HHL, NumPyLSsolver from qiskit.aqua.components.eigs import EigsQPE from qiskit.aqua.components.reciprocals import LookupRotation from qiskit.aqua.operators import MatrixOperator from qiskit.aqua.components.initial_states import Custom #Plot tools from qiskit.visualization import plot_histogram, plot_bloch_multivector from qiskit_textbook.tools import array_to_latex #Autres from qiskit.circuit import Gate from qiskit.circuit.library import QFT from qiskit.quantum_info import state_fidelity from qiskit.providers.ibmq import least_busy #QFT from qiskit_textbook.tools import random_state from qiskit.tools.monitor import job_monitor #QFTe from typing import Optional, List import numpy as np from qiskit import Aer, execute, QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.circuit.library import HGate, RYGate, ZGate, XGate, CSwapGate, SwapGate from qiskit.quantum_info import Operator from qiskit.aqua.components.initial_states import InitialState from qiskit.aqua.utils.validation import validate_min from qiskit.aqua.components.initial_states import Custom from qiskit.visualization import plot_histogram %config InlineBackend.figure_format = 'svg' # Makes the images look nice ''' import sys sys.setrecursionlimit(1000) ''' # memory structure B_x proposed by (Prakash, 2014) to store the information of the classical vector b. # structured slightly modified for complex vectors class BinaryTree: def __init__(self, value, level=0,branch=0): self.value = value self.child_left = None self.child_right = None self.level = level self.branch = branch def insert_left(self, value, branch): if self.child_left == None: self.child_left = BinaryTree(value, self.get_level()+1, branch) else: new_node = BinaryTree(value, self.get_level()+1, branch) self.child_left.set_level(self.child_left.get_level()+1) self.child_left.set_branch(self.child_left.get_branch()*2) new_node.child_left = self.child_left self.child_left = new_node def insert_right(self, value, branch): if self.child_right == None: self.child_right = BinaryTree(value, self.get_level()+1, branch) else: new_node = BinaryTree(value, self.get_level()+1, branch) self.child_right.set_level(self.child_right.get_level()+1) self.child_right.set_branch(self.child_right.get_branch()*2+1) new_node.child_right = self.child_right self.child_right = new_node def get_value(self): return self.value def get_left(self): return self.child_left def get_right(self): return self.child_right def get_level(self): return self.level def get_branch(self): return self.branch def set_level(self, level): self.level = level def set_branch(self, branch): self.branch = branch def show_tree(T): if T != None: return ([T.get_value(),T.get_level(),T.get_branch()],show_tree(T.get_left()),show_tree(T.get_right())) def create_tree_from_vector(x: list): norm = np.linalg.norm(x) u_x = [x_i/norm for x_i in x] if(len(u_x)<1): print("Please enter a non-null vector") elif(len(u_x)==1): s = 1 phase = np.angle(u_x[0]) tree = BinaryTree([s, phase]) else: tree = BinaryTree(1) u_x_left=u_x[0:(len(x)+1)//2] u_x_right=u_x[(len(x)+1)//2:len(x)] create_tree_recursively(u_x_left, tree, "left", tree.get_branch()) create_tree_recursively(u_x_right, tree, "right", tree.get_branch()) return norm, tree def create_tree_recursively(x: list, tree: BinaryTree, side: str, branch: int): # adding the new node to the tree s = 0 for i in range(len(x)): s += x[i].real**2+x[i].imag**2 if(len(x) == 1): phase = np.angle(x[0]) s=[s,phase] if(side == "left"): tree.insert_left(s, branch*2) elif(side == "right"): tree.insert_right(s, branch*2+1) else: print("problem in a switch case, create tree recursively") # calling recursively the fonction if(len(x) > 1): x_left=x[0:(len(x)+1)//2] x_right=x[(len(x)+1)//2:len(x)] # creating a perfect binary tree (all interior nodes have two children and all leaves have the same depth or same level) if(len(x_left) == 1 and len(x_right) > 1): x_left = [x_left[0], 0] elif(len(x_right) == 1 and len(x_left) > 1): x_right = [x_right[0], 0] if(side == "left"): create_tree_recursively(x_left, tree.get_left(), "left", tree.get_left().get_branch()) create_tree_recursively(x_right, tree.get_left(), "right", tree.get_left().get_branch()) elif(side == "right"): create_tree_recursively(x_left, tree.get_right(), "left", tree.get_right().get_branch()) create_tree_recursively(x_right, tree.get_right(), "right", tree.get_right().get_branch()) else: print("Error: a branch of the tree has not been considered") else: return # state preparation procedure of (Grover & Rudolph, 2002) to get |psi>=|b> from b # procedure slightly modified for complex vectors def load_vector_from_qRAM(x: list, qc: Optional[QuantumCircuit]=None, pos_init: int=0, normIntegerPrecision: int=0, normDecimalPrecision: int=0, Qiskit_reading_direction: bool=False): norm, B_x = create_tree_from_vector(x) n = int(np.ceil(np.log(len(x)))) if(n == 0): n = 1 # Code if there is not a quantum circuit as an input if(qc is None): cr3 = ClassicalRegister(n) qr3 = QuantumRegister(n, 'tree') if(normIntegerPrecision > 0): cr1 = ClassicalRegister(normIntegerPrecision) qr1 = QuantumRegister(normIntegerPrecision, 'n_int') if(normDecimalPrecision > 0): cr2 = ClassicalRegister(normDecimalPrecision) qr2 = QuantumRegister(normDecimalPrecision, 'n_dec') qc = QuantumCircuit(qr1,qr2,qr3,cr1,cr2,cr3) else: qc = QuantumCircuit(qr1,qr3,cr1,cr3) else: if(normDecimalPrecision > 0): cr2 = ClassicalRegister(normDecimalPrecision) qr2 = QuantumRegister(normDecimalPrecision, 'n_dec') qc = QuantumCircuit(qr2,qr3,cr2,cr3) else: qc = QuantumCircuit(qr3,cr3) ## loading norm_l2(x) if(normIntegerPrecision + normDecimalPrecision > 0): norm_binary = getBinary(norm) # integer part of the norm if(len(norm_binary[0]) > normIntegerPrecision): for i in range(normIntegerPrecision): qc.x(pos_init+i) else: for i in range(len(norm_binary[0])): if(norm_binary[0][i] == '1'): qc.x(pos_init+normIntegerPrecision-len(norm_binary[0])+i) # decimal part of the norm if(len(norm_binary[1]) > normDecimalPrecision): for i in range(normDecimalPrecision): if(norm_binary[1][i] == '1'): qc.x(pos_init+normIntegerPrecision+i) else: for i in range(len(norm_binary[1])): if(norm_binary[1][i] == '1'): qc.x(pos_init+normIntegerPrecision+i) ## loading u=x/norm_l2(x) if(n > 0): ## rotation level 1 # getting the left and right child nodes B_l = B_x.get_left() B_r = B_x.get_right() # calculating the angle of rotation 'theta': cos('theta') = sqrt(value(u_l)/value(u)) B_lIsALeave = False if(B_l.get_left() is None): B_lIsALeave = True if(B_lIsALeave): node_value = B_l.get_value()[0] else: node_value = B_l.get_value() theta_0 = 2*np.arccos(np.sqrt(node_value)) qc.ry(theta_0, pos_init+normIntegerPrecision+normDecimalPrecision) # processPhase if the nodes u_l and u_r are leaves (personal approach) isAComplexPair = False if(B_lIsALeave == True): if(B_l.get_value()[1] == 0.0 and B_r.get_value()[1] == 0.0): pass elif(B_l.get_value()[1] == 0.0 and B_r.get_value()[1] == np.pi): theta_0 = -theta_0 elif(B_l.get_value()[1] == np.pi and B_r.get_value()[1] == 0.0): theta_0 = np.pi-theta_0 elif(B_l.get_value()[1] == np.pi and B_r.get_value()[1] == np.pi): theta_0 = np.pi+theta_0 else: isAComplexPair = True # changing the local phase if necessary using the quantum gate diag(e^{i*angle_l},e^{i*angle_r}) = X*U_1(angle_l)*X*U_1(angle_r) if(isAComplexPair == True): qc.u1(B_r.get_value()[1]-B_l.get_value()[1],0) if(n > 1): processNode(qc, pos_init+normIntegerPrecision+normDecimalPrecision, n, B_l) processNode(qc, pos_init+normIntegerPrecision+normDecimalPrecision, n, B_r) # swap the qubits in the quantum register if demanded (Qiskit_reading_direction == False). if(Qiskit_reading_direction == False): for qubit in range(pos_init, pos_init+normIntegerPrecision//2): qc.swap(qubit, normIntegerPrecision-qubit-1) for qubit in range(pos_init+normIntegerPrecision, (pos_init+normIntegerPrecision+normDecimalPrecision)//2): qc.swap(qubit, normDecimalPrecision-qubit-1) for qubit in range(pos_init+normIntegerPrecision+normDecimalPrecision, (pos_init+normIntegerPrecision+normDecimalPrecision+n)//2): qc.swap(qubit, n-qubit-1) qc.barrier() return qc def processNode(q_circuit: QuantumCircuit, first_qubit: int, sizeRegisterTree: int, u_x: BinaryTree): ## rotation level k > 1 # getting the left and right child nodes u_l = u_x.get_left() u_r = u_x.get_right() # if value(u) = 0 then value(u_c) = 0 for all the child nodes in the subtree whose parent is u. Therefore, no calculation is performed. if(u_x.get_value() != 0): # calculating the angle of rotation 'theta': cos('theta') = sqrt(value(u_l)/value(u)) u_lIsALeave = False if(u_l.get_left() is None): u_lIsALeave = True if(u_l is not None): if(u_lIsALeave): node_value = u_l.get_value()[0] else: node_value = u_l.get_value() theta = 2*np.arccos(np.sqrt(node_value/u_x.get_value())) else: print("Error: processNode() to a node without childs") # processPhase if the nodes u_l and u_r are leaves (personal approach) isAComplexPair = False if(u_lIsALeave): if(u_l.get_value()[1] == 0.0 and u_r.get_value()[1] == 0.0): pass elif(u_l.get_value()[1] == 0.0 and u_r.get_value()[1] == np.pi): theta = -theta elif(u_l.get_value()[1] == np.pi and u_r.get_value()[1] == 0.0): theta = np.pi-theta elif(u_l.get_value()[1] == np.pi and u_r.get_value()[1] == np.pi): theta = np.pi+theta else: isAComplexPair = True # choosing the quantum eigenstate associated to the parent node (the control eigenstate q_1q_2...q_{k-1}) list_binary = getBinary(u_x.get_branch(), u_l.get_level()-1)[0] for i in range(len(list_binary)): if(list_binary[i] == '0'): #q_circuit.x(first_qubit+len(list_binary)-(i+1)) q_circuit.x(first_qubit+i) ## Multi-controlled Rotation gate around the y-axis (*) qc_custom = QuantumCircuit(1) qc_custom.ry(theta,0) # changing the local phase if necessary using the quantum gate diag(e^{i*angle_l},e^{i*angle_r}) = X*U_1(angle_l)*X*U_1(angle_r) if(isAComplexPair == True): qc_custom.u1(u_r.get_value()[1]-u_l.get_value()[1],0) #MC_Ry = RYGate(theta).control(u_l.get_level()-1) MC_Ry = qc_custom.to_gate(label="Ry(\u03B8)*U1(\u03B2 - \u03B1)").control(u_l.get_level()-1) q_circuit.append(MC_Ry, [first_qubit+x_i for x_i in range(u_l.get_level())]) # uncomputing the quantum eigenstate associated to the parent node list_binary = getBinary(u_x.get_branch(), u_l.get_level()-1)[0] for i in range(len(list_binary)): if(list_binary[i] == '0'): #q_circuit.x(first_qubit++len(list_binary)-(i+1)) q_circuit.x(first_qubit+i) ## recursive call if(u_lIsALeave == False): q_circuit.barrier() processNode(q_circuit, first_qubit, sizeRegisterTree, u_l) processNode(q_circuit, first_qubit, sizeRegisterTree, u_r) else: return def getBinary(number: float, integerPrecision: int=1): # integer part int_part = int(number) binary_int = format(int_part, '#0'+str(int(2+integerPrecision))+'b')[2:] # decimal part dec_part = number - float(int_part) binary_dec = '' while(dec_part > 0): dec_part = 2*dec_part if(dec_part >= 1): binary_dec += '1' dec_part = dec_part-1 else: binary_dec += '0' return binary_int, binary_dec def hamiltonian_simulation(H,t,r = 1): """Prends un observable H (matrice numpy) et un temps t en entrée et renvoie opérateur d'évolution exp(-itH)""" def taylor(H,t,n=100): """Première implémentation naïve avec le developpement de taylor de l'exponentielle""" U = np.eye(len(H)) for k in range(n): U = np.dot(U,(-1j)*t*H)/(n-k) U += np.eye(len(H)) return U def trotter_suzuki(H,t,r): """Ici H doit être de la forme [A,B] où A[i] est la liste des termes non nuls dans la colonne i et B[i][A[i]] leur valeurs""" def separate(H, L = []): S1 = [[i for i in range(len(H[0]))],[[0 for i in range(len(H[0]))] for j in range(len(H[0]))]] if L == []: for i in range(len(H[0])): for j in range(len(H[0][i])): if H[0][i][j] == i: S1[0][i] = i S1[1][i][i] = H[1][i][i] del H[0][i][j] break L += [S1] return separate(H,L) Hvide = True for k in range(len(H[0])): if H[0][k] != []: Hvide = False if Hvide: return L Colored = len(H[0])*[0] for i in range(len(H[0])): for j in range(len(H[0][i])): if not(Colored[H[0][i][j]]): Colored[H[0][i][j]] = 1 Colored[i] = 1 S1[0][i] = H[0][i][j] S1[0][H[0][i][j]] = i S1[1][i][H[0][i][j]] = H[1][i][H[0][i][j]] S1[1][H[0][i][j]][i] = H[1][H[0][i][j]][i] temp = 0 for k in range(len(H[0][H[0][i][j]])): if H[0][H[0][i][j]][k]==i: temp = k del H[0][H[0][i][j]][temp] del H[0][i][j] break L += [S1] return separate(H,L) def fastexp(M,t): done = len(M[0])*[0] for k in range(len(done)): if not(done[k]): if M[0][k] == k: M[1][k][k] = np.exp(1j*t*M[1][k][k]) done[k] = 1 else: if M[1][k][M[0][k]].imag == 0: M[1][k][k] = np.cos(t*M[1][k][M[0][k]]) M[1][M[0][k]][M[0][k]] = np.cos(t*M[1][k][M[0][k]]) M[1][M[0][k]][k] = 1j*np.sin(t*M[1][k][M[0][k]]) M[1][k][M[0][k]] = 1j*np.sin(t*M[1][k][M[0][k]]) else: M[1][k][k] = np.cos(t*M[1][k][M[0][k]]) M[1][M[0][k]][M[0][k]] = np.cos(t*M[1][k][M[0][k]]) M[1][M[0][k]][k] = np.sin(t*M[1][k][M[0][k]]) M[1][k][M[0][k]] = -np.sin(t*M[1][k][M[0][k]]) done[k] = 1 done[M[0][k]] = 1 return M L1 = separate(H) L = [] for k in range(len(L1)): Sr = [[i for i in range(len(H[0]))],[[0 for i in range(len(H[0]))] for j in range(len(H[0]))]] Sc = [[i for i in range(len(H[0]))],[[0 for i in range(len(H[0]))] for j in range(len(H[0]))]] for i in range(len(L1[k][0])): Sr[0][i] = L1[k][0][i] Sc[0][i] = L1[k][0][i] Sr[1][i][Sr[0][i]] = L1[k][1][i][L1[k][0][i]].real Sc[1][i][Sc[0][i]] = L1[k][1][i][L1[k][0][i]].imag L += [Sr]+[Sc] for k in range(len(L)): L[k] = fastexp(L[k],t/r) L1 = [] for k in range(len(L)): L1 += [L[k][1]] return L1,r return trotter_suzuki(H,t,r) def qft_rotations(circuit,position_initial,nombre_qubits): """Performs qft on the first n qubits ("nombre_qubits") in circuit (without swaps)""" if nombre_qubits == 0: return circuit nombre_qubits -= 1 circuit.h(position_initial+nombre_qubits) for qubit in range(nombre_qubits): circuit.cu1(pi/2**(nombre_qubits-qubit), position_initial+qubit, position_initial+nombre_qubits) # At the end of our function, we call the same function again on # the next qubits (we reduced "nombre_qubits" by one earlier in the function) qft_rotations(circuit,position_initial,nombre_qubits) def swap_registers(circuit,position_initial,nombre_qubits): for qubit in range(nombre_qubits//2): circuit.swap(position_initial+qubit,position_initial+nombre_qubits-qubit-1) return circuit def qft(circuit: QuantumCircuit,position_initial: int,nombre_qubits: int): """QFT on the first n qubits ("nombre_qubits") in circuit""" qft_rotations(circuit,position_initial,nombre_qubits) swap_registers(circuit,position_initial,nombre_qubits) return circuit # Let's see how it looks for a circuit with 4 qubits (intial state |0000>): qc = QuantumCircuit(6) circ_=qc position_initial=1 n_qubits=4 qft(circ_,position_initial,n_qubits) #qc.measure_all() qc.draw('mpl') def inverse_qft(circuit: QuantumCircuit, position_initial: int=0, nombre_qubits: int=2, nombre_total_qubits: int=2): """Does the inverse QFT on the first n qubits ("nombre_qubits") in circuit""" # First we create a QFT circuit of the correct size: qft_circ = qft(QuantumCircuit(nombre_total_qubits), position_initial, nombre_qubits) # Then we take the inverse of this circuit invqft_circ = qft_circ.inverse() # And add it to the first n qubits (nombre_qubits) in our existing circuit circuit.append(invqft_circ, circuit.qubits) return circuit.decompose() # .decompose() allows us to see the individual gates nqubits = 4 n_total_qubits = 6 position_initial=1 number = 5 qc = QuantumCircuit(n_total_qubits) ''' for qubit in range(nqubits): qc.h(qubit) qc.u1(number*pi/4,0) qc.u1(number*pi/2,1) qc.u1(number*pi,2) ''' qc.draw('mpl') qc = inverse_qft(qc,position_initial,nqubits,n_total_qubits) #qc.measure_all() qc.draw('mpl') def qft_dagger(circ_,position_initial,n_qubits): """n-qubit QFTdagger the first n qubits in circ""" for qubit in range(int(n_qubits/2)): circ_.swap(position_initial+qubit,position_initial+n_qubits-1-qubit) for j in range(0,n_qubits): for m in range(j): circ_.cp(-np.pi/float(2**(j-m)), position_initial+m, position_initial+j) circ_.h(position_initial+j) qc = QuantumCircuit(6) qc.draw('mpl') circ_=qc position_initial=1 n_qubits=4 qft_dagger(circ_,position_initial,n_qubits) #qc.measure_all() qc.draw('mpl') # a: clock register (HHL+) or phase register (rapport intermédiaire) or ancillae register (Qiskit textbook chapter 3.6) # q: input register (HHL+, rapport intermédiaire) # s: ancilla register (HHL+) or auxiliary register (rapport intermédiaire, Qiskit textbook Chapter 3.6) # global variables to test the second call to the Hamiltonian Simulation module list_CU_operators = None exponent_r = None flag_get_CU_gate = False # variable to modify list_CU_operators each repetition of HHL def get_CU_gate(num_qubits_a: int=1, num_qubits_q: int=1, t: int=50, unitary_matrix: Optional[List]=None, # parameter to test the validity of the model matrix: Optional[List]=None, nonzero_entries: Optional[List]=None, inverse_gate: bool=False): global list_CU_operators, exponent_r, flag_get_CU_gate # if qpe_hhl has called this function if(list_CU_operators is None or flag_get_CU_gate == False): ## get the matrices U_1,...,U_n and and the scalar r so that U=(U1*...*Un)*...*(U1*...*Un): r times "(U1*...*Un)". if(matrix is not None and nonzero_entries is not None): list_U_matrices, exponent_r = hamiltonian_simulation([nonzero_entries, matrix],t) dim_U_matrix = len(matrix) elif(unitary_matrix is not None): list_U_matrices = [unitary_matrix] exponent_r = 1 dim_U_matrix = len(unitary_matrix) else: print("list_U_operators cannot be properly implemented. Provide a matrix or a valid operator (or see the Hamiltonien Simulation module).") ## construct the operators controlled-(Uj) to be applied in reverse order of qiskit convention list_CU_operators = [] for k in range(len(list_U_matrices)): matrix_CU = np.identity(dim_U_matrix*2, dtype = 'complex_') for i in range(dim_U_matrix): for j in range(dim_U_matrix): matrix_CU[dim_U_matrix+i][dim_U_matrix+j] = list_U_matrices[k][i][j] operator_CU = Operator(matrix_CU) list_CU_operators.append(operator_CU) flag_get_CU_gate = True else: flag_get_CU_gate = False ## convert the unitary operators into a quantum gates controlled-(U1*...*Un) to be applied r times qc_temp = QuantumCircuit(1+num_qubits_q) prefix_gate_name = "C-U" for i in range(len(list_CU_operators)): suffix_gate_name = str(i) if(inverse_gate): suffix_gate_name += "^dagger" qc_temp.append(list_CU_operators[i].to_instruction().copy(prefix_gate_name+suffix_gate_name), [x for x in range(num_qubits_q,-1,-1)]) # the order of qubits is reversed taking into account the Qiskit convention of ordering qubits ## deciding if returning the CU_gate or its inverse CU_gate = qc_temp.to_gate() if(inverse_gate == False): return CU_gate, exponent_r else: CU_gate_inv = CU_gate.inverse() CU_gate_inv.name = "C-U^dagger" return CU_gate_inv, exponent_r def qpe_hhl(circuit, pos_init_qreg_a: int, num_qubits_a: int, pos_init_qreg_q: int, num_qubits_q: int=1, unitary_matrix: Optional[List]=None, # parameter to test the validity of the model matrix: Optional[List]=None, nonzero_entries: Optional[List]=None, t: int=45, measurement: bool=False, Qiskit_reading_direction: bool=True): ## apply the Hadamard gate for qubit in range(pos_init_qreg_a, pos_init_qreg_a+num_qubits_a): circuit.h(qubit) ## create the controlled-U operator and turn it into a gate if (unitary_matrix != None) : CU_gate, exponent_r = get_CU_gate(num_qubits_a, num_qubits_q, t, unitary_matrix, matrix, nonzero_entries) else : CU_gate, exponent_r = get_CU_gate(num_qubits_a, num_qubits_q, t,None, matrix, nonzero_entries) ## apply the controlled-U^{2^j} gates repetitions = 1 for qubit_qreg_a in range(pos_init_qreg_a, pos_init_qreg_a+num_qubits_a): for i in range(repetitions): # apply the Controlled-U gate (or the approximation: C-U=C-((U1*...*Un)^r) to the main circuit qubits_control = [qubit_qreg_a] qubits_controlled = [x for x in range(pos_init_qreg_q, pos_init_qreg_q+num_qubits_q)] for j in range(exponent_r): circuit.append(CU_gate.copy("controlled-U"), qubits_control+qubits_controlled) repetitions *= 2 ## apply inverse QFT qft_dagger(circuit, pos_init_qreg_a, num_qubits_a) # swap the qubits in the quantum register "a" if demanded (Qiskit_reading_direction == False). if(Qiskit_reading_direction == False): for qubit_qreg_a in range(pos_init_qreg_a, pos_init_qreg_a+num_qubits_a//2): circuit.swap(qubit_qreg_a, num_qubits_a-qubit_qreg_a-1) # add a measurement section at the end of the circuit if necessary (measurement == True). if measurement: c_a = ClassicalRegister(num_qubits_a, name='ca') circuit.add_register(c_a) circuit.barrier() # the safeguard-barrier for qubit_qreg_a in range(pos_init_qreg_a, pos_init_qreg_a+num_qubits_a): circuit.measure(qubit_qreg_a, c_a[qubit_qreg_a-pos_init_qreg_a]) def qpedagger_hhl(circuit, pos_init_qreg_a: int, num_qubits_a: int, pos_init_qreg_q: int, num_qubits_q: int=1, unitar_matrix: Optional[List]=None, matrix: Optional[List]=None, nonzero_entries: Optional[List]=None, t: int=45, measurement: bool=False, Qiskit_reading_direction: bool=True): # parameter to test the validity of the model # swap the qubits in the quantum register "a" if demanded (Qiskit_reading_direction == False). if(Qiskit_reading_direction == False): for qubit_qreg_a in range(pos_init_qreg_a, pos_init_qreg_a+num_qubits_a//2): circuit.swap(qubit_qreg_a, num_qubits_a-qubit_qreg_a-1) ## apply QFT qft(circuit, pos_init_qreg_a, num_qubits_a) ## create the controlled-U^dagger operator and turn it into a gate if (unitar_matrix != None) : CU_gate, exponent_r = get_CU_gate(num_qubits_a, num_qubits_q, t, unitary_matrix, matrix, nonzero_entries, inverse_gate=True) else : CU_gate, exponent_r = get_CU_gate(num_qubits_a, num_qubits_q, t,None, matrix, nonzero_entries, inverse_gate=True) ## apply the controlled-U^{2^j} gates repetitions = 2**(num_qubits_a-1) for qubit_qreg_a in range(pos_init_qreg_a+num_qubits_a-1, pos_init_qreg_a-1, -1): for i in range(repetitions): # apply the Controlled-U gate (or the approximation: C-U=C-((U1*...*Un)^r) to the main circuit qubits_control = [qubit_qreg_a] qubits_controlled = [x for x in range(pos_init_qreg_q, pos_init_qreg_q+num_qubits_q)] for j in range(exponent_r): circuit.append(CU_gate.copy("controlled-U^dagger"), qubits_control+qubits_controlled) repetitions //= 2 ## apply the Hadamard gate for qubit in range(pos_init_qreg_a, num_qubits_a): circuit.h(qubit) # add a measurement section at the end of the circuit if necessary (measurement == True). if measurement: c_a = ClassicalRegister(num_qubits_a, name='ca') circuit.add_register(c_a) circuit.barrier() # the safeguard-barrier for qubit_qreg_a in range(pos_init_qreg_a, pos_init_qreg_a+num_qubits_a): circuit.measure(qubit_qreg_a, c_a[qubit_qreg_a-pos_init_qreg_a]) num_ancillae = 2 #n_l num_state = 2 #n_b t = 6*np.pi/8 qr_a = QuantumRegister(num_ancillae, name='theta') qr_q = QuantumRegister(num_state, name='b') c = ClassicalRegister(num_ancillae+num_state, name='cr') # matrix A #matrix = [[1, -1/3], # [-1/3, 1]] matrix = [[1, -1/3,0,0], [-1/3, 1,0,0], [0,0,1, -1/3], [0,0,-1/3, 1]] #nonzero_entries = [[0, 1], # [0, 1]] nonzero_entries = [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]] initial_state = [1, 1, 1, 1] #initial_state = [1, 1, 1, 1] qc = QuantumCircuit(qr_q,qr_a,c) # set the initial state using qiskit state_in = Custom(num_qubits=num_state, state_vector = np.array(initial_state)) qc.data += state_in.construct_circuit('circuit', qr_q).data #qc.data : Return the circuit data (instructions and context). # call the modules hamiltonian simulation (classical) + QPE + QFT qpe_hhl(circuit=qc, pos_init_qreg_a=2, num_qubits_a=num_ancillae, pos_init_qreg_q=0, num_qubits_q=2, matrix=matrix, nonzero_entries=nonzero_entries, t=t, measurement=False, Qiskit_reading_direction=True) #qpedagger_hhl(circuit=qc, pos_init_qreg_a=0, num_qubits_a=num_ancillae, pos_init_qreg_q=num_ancillae, unitar_matrix=None, matrix=matrix, nonzero_entries=nonzero_entries, t=t, measurement=False, Qiskit_reading_direction=True) qc.data += state_in.construct_circuit('circuit', qr_q).inverse().data qc.draw(scale=0.8) #use "qc.decompose().draw(scale=0.8)" to see all the black-boxes (decomposed in the set of universal gates of Open-QASM: {u1, u2, u3, CNOT}) for i in range(num_ancillae+num_state): qc.measure(i,i) backend = Aer.get_backend('qasm_simulator') shots = 2048 results = execute(qc, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) ########### ####QFT#### ########### def qca_qft(qc,r): #Adds QFT operations on circuit qc, on the register indexed by r #cf. Qiskit textbook, 3.5, for explanation of the algorithm n=len(r) for i in range(n): qc.h(r[n-1-i]) for j in range(n-i-1): qc.cp(pi/2**(n-1-i-j),r[j],r[n-1-i]) for i in range(n//2): qc.swap(r[i],r[n-1-i]) def qca_qftdagger(qc,r): #Adds QFTdagger operations on circuit qc, on the register indexed by r n=len(r) for i in range(n//2): qc.swap(r[i],r[n-1-i]) for i in reversed(range(n)): for j in reversed(range(n-i-1)): qc.cp(-pi/2**(n-1-i-j),r[j],r[n-1-i]) qc.h(r[n-1-i]) def qca_c_qft(qc,r,pos_ctrl): #Does the same thing as qca_qft, but with all the gates controlled by qubit in position qctrl n=len(r) for i in range(n): qc.ch(pos_ctrl,r[n-1-i]) for j in range(n-i-1): qc.mcp(pi/2**(n-1-i-j),[pos_ctrl,r[j]],r[n-1-i]) for i in range(n//2): qc.cswap(pos_ctrl,r[i],r[n-1-i]) def qca_c_qftdagger(qc,r,pos_ctrl): #Does the same thing as qca_qftdagger, but with all the gates controlled by qubit in position qctrl n=len(r) for i in range(n//2): qc.cswap(pos_ctrl,r[i],r[n-1-i]) for i in reversed(range(n)): for j in reversed(range(n-i-1)): qc.mcp(-pi/2**(n-1-i-j),[pos_ctrl,r[j]],r[n-1-i]) qc.ch(pos_ctrl,r[n-1-i]) ################ ##Arithmétique## ################ #Addition ######### def qca_adder(qc,a,b): #Input: #n+1 qubits of register indexed by a : (binary represantion in the computational basis of) a and |0\rangle on the last qubit #n+1 qubits of register indexed by b : |b\rangle on the first n qubits, |0\rangle on the last qubit (last qubit used to store last carry) #Output: #n qubits of register indexed by a : |a\rangle #n+1 qubits of register indexed by b : |a+b\rangle n=len(a)-1 qca_qft(qc,b) qc.barrier() for i in range(n+1,0,-1): for j in range(i,0,-1): if j<=n: qc.cp(pi/2**(i-j),a[j-1],b[n+1-i]) qc.barrier() qca_qftdagger(qc,b) def qca_ccp(qc,theta,ctrl1,ctrl2,target): #Double controlled phase gate qc.cp(theta/2,ctrl2,target) qc.cx(ctrl1,ctrl2) qc.cp(-theta/2,ctrl2,target) qc.cx(ctrl1,ctrl2) qc.cp(theta/2,ctrl1,target) def qca_c_adder(qc,a,b,pos_ctrl): #ctrl version of qca_adder n=len(a)-1 qca_c_qft(qc,b,pos_ctrl) qc.barrier() for i in range(n+1,0,-1): for j in range(i,0,-1): if j<=n: qca_ccp(qc,pi/2**(i-j),pos_ctrl,a[j-1],b[n+1-i]) qc.barrier() qca_c_qftdagger(qc,b,pos_ctrl) #Pseudo-soustraction #################### def qca_subber(qc,a,b): #Input: #n+1 qubits of register indexed by a : (binary represantion in the computational basis of) a and |0\rangle on the last qubit #n+1 qubits of register indexed by b : |b\rangle on the first n qubits, |0\rangle on the last qubit (last qubit used to store last carry) #Output: #n qubits of register indexed by a : |a\rangle #n+1 qubits of register indexed by b : |a-b\rangle n=len(a)-1 qca_qft(qc,b) qc.barrier() for i in range(n+1,0,-1): for j in range(i,0,-1): if j<=n: qc.cp(-pi/2**(i-j),a[j-1],b[n+1-i]) qc.barrier() qca_qftdagger(qc,b) def qca_subber_swap(qc,a,b): #Input: #n+1 qubits of register indexed by a : (binary represantion in the computational basis of) a and |0\rangle on the last qubit #n+1 qubits of register indexed by b : |b\rangle on the first n qubits, |0\rangle on the last qubit (last qubit used to store last carry) #Output: #n qubits of register indexed by a : |a-b\rangle #n+1 qubits of register indexed by b : |b\rangle n=len(a)-1 qca_qft(qc,a) qc.barrier() for i in range(n+1,0,-1): for j in range(i,0,-1): if j<=n: qc.cp(-pi/2**(i-j),b[j-1],a[n+1-i]) qc.barrier() qca_qftdagger(qc,a) #Division ######### def qca_ls(qc,a,n): #left shifts register indexed by a n times. if(n==1): for i in range(len(a)-1): qc.swap(a[len(a)-1-i],a[len(a)-2-i]) elif(n>1): for i in range(len(a)-1): qc.swap(a[len(a)-1-i],a[len(a)-2-i]) qca_ls(qc,a,n-1) def listrs(L): #Returns list obtained by right-shifting 1 time L return([L[-1]]+L[:-1]) def listls(L): #Returns list obtained by left-shifting 1 time L return(L[1:]+[L[0]]) def qca_divider_V2(qc,p,d,q): n=len(q) for i in range(n-1,-1,-1): # Multipliying |p\rangle by 2 : is equivalent to shifting it to the left by one unit qca_ls(qc,p,1) # Subtracting |d\rangle to |p\rangle, forcing rightmost qubit to be the subbing pad qca_subber_swap(qc,listls(p),listls(d)) # If the result is positive, indicated by |p\rangle rightmost qubit being |0\rangle, then the i-th bit of the quotient is 1 qc.x(p[0]) qc.cx(p[0],q[i]) qc.x(p[0]) # Else, the result is negative and we add back |d\rangle to |p\rangle # This operation is controlled by the fact that the i-th qubit of the quotient is still |0\rangle qc.x(q[i]) qca_c_adder(qc,listls(d),listls(p),q[i]) qc.x(q[i]) def div(qc,p,d,q,n): qca_divider_V2(qc,p,d,q) def qc_rotation (qc, n, control_qubit, target_qubit): # qc : object quantum circuit # n : number of qubits on which we control our rotation # control_qubit : first position of controlled qubits # target_qubit : position of target qubit for i in range (n) : qc.ry(1/2**(i+1), target_qubit) qc.cx(n+control_qubit-i-1 , target_qubit) qc.ry(-1/2**(i+1), target_qubit) qc.cx(n+control_qubit-i-1, target_qubit) # for specific reasons, we would like to divide the controlled register in two parts # this is motivated by the fact that our implementation of division gives a quotient and rest # and concerned qubits are located in two different regiters def qc_rotation_bis (qc, n, control_qubit_1, control_qubit_2, target_qubit): # qc : object quantum circuit # n : number of qubits divided by two on which we control our rotation # control_qubit_1 : first position of first register of controlled qubits # control_qubit_2 : first position of second register of controlled qubits # target_qubit : position of target qubit for i in range (n) : qc.ry(1/2**(i+1), target_qubit) qc.cx(n+control_qubit_1-i-1 , target_qubit) qc.ry(-1/2**(i+1), target_qubit) qc.cx(n+control_qubit_1-i-1, target_qubit) for i in range (n) : qc.ry(1/2**(n+i+1), target_qubit) qc.cx(n+control_qubit_2-i-1 , target_qubit) qc.ry(-1/2**(n+i+1), target_qubit) qc.cx(n+control_qubit_2-i-1, target_qubit) qc = QuantumCircuit (4) # init theta = |111> qc.x(0) qc.x(1) qc.x(2) #qc.barrier() qc_rotation (qc, 3, 0, 3) qc.measure_all() qc.draw() backend = Aer.get_backend('qasm_simulator') shots = 2048 results = execute(qc, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) def HHL (num_ancille, num_state, t, matrix, initial_state, C=0) : print(t) # num_ancillae is the number of qubits used in QPE for phase estimation (n_l) # num_state is the number of qubits used for |b> (n_b) # matrix is the matrix of the system # initial state is the value of vector b # C parameter, if set 0 then C=|11...1> (biggest value possible but not a good ida, see remark) # 5*num_ancillae + num_state + 1 qr_theta = QuantumRegister(num_ancillae, name='theta') qr_b = QuantumRegister(num_state, name='b') qr_aux = QuantumRegister(num_ancillae, name='aux') qr_r = QuantumRegister(num_ancillae, name='r') qr_d = QuantumRegister(num_ancillae, name='d') qr_q = QuantumRegister(num_ancillae, name='q') qr_S = QuantumRegister(1, name='s') qc = QuantumCircuit (qr_theta, qr_b, qr_aux, qr_r, qr_d, qr_q, qr_S) # set the initial state using qiskit state_in = Custom(num_qubits=num_state, state_vector = np.array(initial_state)) qc = qc.compose (state_in.construct_circuit('circuit', qr_b), [2]) #qc.data : Return the circuit data (instructions and context). # call the modules hamiltonian simulation (classical) + QPE + QFT global list_CU_operators, exponent_r, flag_get_CU_gate list_CU_operators = None exponent_r = None flag_get_CU_gate = None qpe_hhl(circuit=qc, pos_init_qreg_a=0, num_qubits_a=num_ancillae, pos_init_qreg_q=num_ancillae, unitary_matrix=None, matrix=matrix, t=t, measurement=False, Qiskit_reading_direction=True, nonzero_entries=nonzero_entries) qc.barrier() # call eigenvalue rotation # step 1 : ASNINV for i in range (num_ancillae) : qc.x(num_state+3*num_ancillae+i) #qc.x(num_state+4*num_ancillae-1) # Divider that takes |p>|d>|q>. # |p> is length 2n and has n zeros on the left: 0 ... 0 p_n ... p_1. # |d> has length 2n and has n zeros on the right: d_2n ... d_{n+1) 0 ... 0. # |q> has length n and is initially all zeros. # At the end of the algorithm, |q> will contain the quotient of p/d, and the # left n qubits of |p> will contain the remainder of p/d. #Qiskit order of qubits may be a little be confusing since qubits order are inverted meaning # 0 ... 0 p_n ... p_1 will appear as |p_1 ... p_n 0 ... 0> # p_idx = list (range(num_state+3*num_ancillae, num_state+4*num_ancillae)) + list (range(num_state+2*num_ancillae, num_state+3*num_ancillae)) print("p_idx: ",p_idx) d_idx = list(range(num_state+num_ancillae,num_state+2*num_ancillae)) + list (range(num_ancillae)) print("d_idx: ",d_idx) q_idx = list (range (num_state+4*num_ancillae, num_state+5*num_ancillae)) print("q_idx: ",q_idx) div (qc=qc, p=p_idx, d=d_idx, q=q_idx, n=num_ancillae) qc.barrier() # step 2 : controlled rotaiotn qc_rotation_bis (qc, num_ancillae, num_state+4*num_ancillae, num_state+2*num_ancillae,num_state+5*num_ancillae) qc.barrier() # step 3 : ASNINV_dagger qc_aux = QuantumCircuit (5*num_ancillae + num_state) div (qc_aux, list (range(num_state+3*num_ancillae, num_state+4*num_ancillae)) + list (range(num_state+2*num_ancillae, num_state+3*num_ancillae)), list(range(num_state+num_ancillae,num_state+2*num_ancillae)) + list (range(num_ancillae)), list (range (num_state+4*num_ancillae, num_state+5*num_ancillae)), num_ancillae) qc = qc.compose (qc_aux.inverse(), list(range(num_state+ 5*num_ancillae))) for i in range (num_ancillae) : qc.x(num_state+3*num_ancillae+i) #qc.x(num_state+4*num_ancillae-1) qc.barrier() # QPE dagger qpedagger_hhl(circuit=qc, pos_init_qreg_a=0, num_qubits_a=num_ancillae, pos_init_qreg_q=num_ancillae, unitar_matrix=None, matrix=matrix, t=t, measurement=False, Qiskit_reading_direction=True, nonzero_entries=nonzero_entries) qc.barrier() #qc.draw(filename="nouveau") qc.measure_all() return qc def liste_state (n_b, n_l) : def liste_ket (n_b) : if (n_b == 1) : return ['0', '1'] else : L = liste_ket (n_b-1) res = [] for x in L : res.append (x+'1') res.append (x+'0') return res L = liste_ket (n_b) res = [] for x in L : res.append ((x,'1'+'0'*(4*n_l)+x+ '0'*n_l)) return res def analysis (num_state, num_ancillae, answer) : nombre_1 = 0 nombre_tot = 0 for cle, valeur in answer.items(): nombre_tot += valeur if (str(cle)[0] == '1') : nombre_1 += valeur print ("la probabilité de réussite de l'algorithme est d'environ", nombre_1*1.0/nombre_tot*100, "% de chance") for x,y in liste_state (num_state, num_ancillae) : try: print ("la probabilité de mesurer l'état |"+ x +">", "est", answer[y]*1.0/nombre_1) except: pass num_ancillae = 2 # n_l num_state = 1 # n_b t = 6*np.pi/8 matrix = [[1, -1/3], [-1/3, 1]] initial_state = [1, 1] qc = HHL (num_ancillae, num_state, t, matrix, initial_state) # pour visualiser le circuit qc.draw (scale=0.55) backend = Aer.get_backend('qasm_simulator') shots = 2048*10 results = execute(qc, backend=backend, shots=shots).result() answer = results.get_counts() # calcul de la probabilité estimée de réussite de l'algorithme analysis (num_state, num_ancillae, answer) plot_histogram(answer) num_ancillae = 2 # n_l num_state = 1 # n_b t = 6*np.pi/8 # t matrix = [[1, -1/3], [-1/3, 1]] initial_state = [1, 0] qc = HHL (num_ancillae, num_state, t, matrix, initial_state) # pour visualiser le circuit # qc.draw (scale=0.55) backend = Aer.get_backend('qasm_simulator') shots = 2048*10 results = execute(qc, backend=backend, shots=shots).result() answer = results.get_counts() # calcul de la probabilité estimée de réussite de l'algorithme analysis (num_state, num_ancillae, answer) plot_histogram(answer)
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
from qiskit.circuit.library import QuantumVolume as QuantumVolumeCircuit from qiskit.quantum_info import Statevector qv_circuit = QuantumVolumeCircuit(4) qv_circuit.decompose().draw() def get_heavy_outputs(counts): """Extract heavy outputs from counts dict. Args: counts (dict): Output of `.get_counts()` Returns: list: All states with measurement probability greater than the mean. """ # sort the keys of `counts` by value of counts.get(key) sorted_counts = sorted(counts.keys(), key=counts.get) # discard results with probability < median heavy_outputs = sorted_counts[len(sorted_counts)//2:] return heavy_outputs def check_threshold(nheavies, ncircuits, nshots): """Evaluate adjusted threshold inequality for quantum volume. Args: nheavies (int): Total number of heavy outputs measured from device ncircuits (int): Number of different square circuits run on device nshots (int): Number of shots per circuit Returns: Bool: True if heavy output probability is > 2/3 with 97% certainty, otherwise False """ from numpy import sqrt numerator = nheavies - 2*sqrt(nheavies*(nshots-(nheavies/ncircuits))) return bool(numerator/(ncircuits*nshots) > 2/3) from qiskit import transpile from qiskit.visualization import plot_histogram def test_qv(device, nqubits, ncircuits, nshots): """Try to achieve 2**nqubits quantum volume on device. Args: device (qiskit.providers.Backend): Device to test. nqubits (int): Number of qubits to use for test. ncircuits (int): Number of different circuits to run on the device. nshots (int): Number of shots per circuit. Returns: Bool True if device passes test, otherwise False. """ def get_ideal_probabilities(circuit): """Simulates circuit behaviour on a device with no errors.""" state_vector = Statevector.from_instruction( circuit.remove_final_measurements(inplace=False) ) #print(state_vector.probabilities_dict()) return state_vector.probabilities_dict() def get_real_counts(circuit, backend, shots): """Runs circuit on device and returns counts dict.""" t_circuit = transpile(circuit, backend) job = backend.run(t_circuit, shots=shots, memory=True) #print(job.result().get_counts()) return job.result().get_counts() # generate set of random circuits qv_circuits = [ QuantumVolumeCircuit(nqubits) for c in range(ncircuits) ] nheavies = 0 # number of measured heavy outputs for circuit in qv_circuits: # simulate circuit ideal_heavy_outputs = get_heavy_outputs( get_ideal_probabilities(circuit) ) # run circuit on device circuit.measure_all() real_counts = get_real_counts(circuit, device, nshots) # record whether device result is in the heavy outputs for output, count in real_counts.items(): if output in ideal_heavy_outputs: nheavies += count # do statistical check to see if device passes test is_pass = check_threshold(nheavies, ncircuits, nshots) # calculate percentage of measurements that are heavy outputs percent_heavy_outputs = nheavies*100/(ncircuits * nshots) print(f"Quantum Volume: {2**nqubits}\n" f"Percentage Heavy Outputs: {percent_heavy_outputs:.1f}%\n" f"Passed?: {is_pass}\n") return is_pass from qiskit.providers.fake_provider import FakeSantiago santiago = FakeSantiago() test_qv(santiago, 5, ncircuits=150, nshots=50)
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=2 max_qubits=3 skip_qubits=1 max_circuits=3 num_shots=1000 Noise_Inclusion = False saveplots = False Memory_utilization_plot = False gate_counts_plots = True Type_of_Simulator = "FAKEV2" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np import copy # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute import time import matplotlib.pyplot as plt # Benchmark Name benchmark_name = "Amplitude Estimation" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) num_gates = 0 depth = 0 def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved subcircuits circuits for printing A_ = None Q_ = None cQ_ = None QC_ = None QFTI_ = None ############### Circuit Definition def AmplitudeEstimation(num_state_qubits, num_counting_qubits, a, psi_zero=None, psi_one=None): num_qubits = num_state_qubits + 1 + num_counting_qubits qr_state = QuantumRegister(num_state_qubits+1) qr_counting = QuantumRegister(num_counting_qubits) cr = ClassicalRegister(num_counting_qubits) qc = QuantumCircuit(qr_counting, qr_state, cr, name=f"qae-{num_qubits}-{a}") # create the Amplitude Generator circuit A = A_gen(num_state_qubits, a, psi_zero, psi_one) # create the Quantum Operator circuit and a controlled version of it cQ, Q = Ctrl_Q(num_state_qubits, A) # save small example subcircuits for visualization global A_, Q_, cQ_, QFTI_ if (cQ_ and Q_) == None or num_state_qubits <= 6: if num_state_qubits < 9: cQ_ = cQ; Q_ = Q; A_ = A if QFTI_ == None or num_qubits <= 5: if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits) # Prepare state from A, and counting qubits with H transform qc.append(A, [qr_state[i] for i in range(num_state_qubits+1)]) for i in range(num_counting_qubits): qc.h(qr_counting[i]) repeat = 1 for j in reversed(range(num_counting_qubits)): for _ in range(repeat): qc.append(cQ, [qr_counting[j]] + [qr_state[l] for l in range(num_state_qubits+1)]) repeat *= 2 qc.barrier() # inverse quantum Fourier transform only on counting qubits qc.append(inv_qft_gate(num_counting_qubits), qr_counting) qc.barrier() # measure counting qubits qc.measure([qr_counting[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits))) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc return qc # Construct A operator that takes |0>_{n+1} to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> def A_gen(num_state_qubits, a, psi_zero=None, psi_one=None): if psi_zero==None: psi_zero = '0'*num_state_qubits if psi_one==None: psi_one = '1'*num_state_qubits theta = 2 * np.arcsin(np.sqrt(a)) # Let the objective be qubit index n; state is on qubits 0 through n-1 qc_A = QuantumCircuit(num_state_qubits+1, name=f"A") # takes state to |0>_{n} (sqrt(1-a) |0> + sqrt(a) |1>) qc_A.ry(theta, num_state_qubits) # takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |0>_{n}|1> qc_A.x(num_state_qubits) for i in range(num_state_qubits): if psi_zero[i]=='1': qc_A.cnot(num_state_qubits,i) qc_A.x(num_state_qubits) # takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> for i in range(num_state_qubits): if psi_one[i]=='1': qc_A.cnot(num_state_qubits,i) return qc_A # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qc = QuantumCircuit(num_state_qubits+1, name=f"Q") temp_A = copy.copy(A_circ) A_gate = temp_A.to_gate() A_gate_inv = temp_A.inverse().to_gate() ### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ # -S_chi qc.x(num_state_qubits) qc.z(num_state_qubits) qc.x(num_state_qubits) # A_circ_inverse qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)]) # S_0 for i in range(num_state_qubits+1): qc.x(i) qc.h(num_state_qubits) qc.mcx([x for x in range(num_state_qubits)], num_state_qubits) qc.h(num_state_qubits) for i in range(num_state_qubits+1): qc.x(i) # A_circ qc.append(A_gate, [i for i in range(num_state_qubits+1)]) # Create a gate out of the Q operator qc.to_gate(label='Q') # and also a controlled version of it Ctrl_Q_ = qc.control(1) # and return both return Ctrl_Q_, qc ############### Inverse QFT Circuit def inv_qft_gate(input_size): global QFTI_, num_gates, depth qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="inv_qft") # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.h(qr[hidx]) num_gates += 1 depth += 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1]) num_gates += 1 depth += 1 qc.barrier() if QFTI_ == None or input_size <= 5: if input_size < 9: QFTI_= qc return qc # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def a_to_bitstring(a, num_counting_qubits): m = num_counting_qubits # solution 1 num1 = round(np.arcsin(np.sqrt(a)) / np.pi * 2**m) num2 = round( (np.pi - np.arcsin(np.sqrt(a))) / np.pi * 2**m) if num1 != num2 and num2 < 2**m and num1 < 2**m: counts = {format(num1, "0"+str(m)+"b"): 0.5, format(num2, "0"+str(m)+"b"): 0.5} else: counts = {format(num1, "0"+str(m)+"b"): 1} return counts def bitstring_to_a(counts, num_counting_qubits): est_counts = {} m = num_counting_qubits precision = int(num_counting_qubits / (np.log2(10))) + 2 for key in counts.keys(): r = counts[key] num = int(key,2) / (2**m) a_est = round((np.sin(np.pi * num) )** 2, precision) if a_est not in est_counts.keys(): est_counts[a_est] = 0 est_counts[a_est] += r return est_counts def a_from_s_int(s_int, num_counting_qubits): theta = s_int * np.pi / (2**num_counting_qubits) precision = int(num_counting_qubits / (np.log2(10))) + 2 a = round(np.sin(theta)**2, precision) return a def analyzer(s_int, num_counting_qubits,counts): secret_int = int(s_int) #print("secret_int = ",secret_int) # calculate expected output histogram a = a_from_s_int(s_int, num_counting_qubits) correct_dist = a_to_bitstring(a, num_counting_qubits) #print("correct_dist=",correct_dist) # generate thermal_dist for polarization calculation thermal_dist = uniform_dist(num_counting_qubits) #print("thermal_dist=",thermal_dist) # convert counts, expectation, and thermal_dist to app form for visibility # app form of correct distribution is measuring amplitude a 100% of the time # app_counts = bitstring_to_a(counts, num_counting_qubits) # app_correct_dist = correct_dist#{a: 1.0} # app_thermal_dist = bitstring_to_a(thermal_dist, num_counting_qubits) return correct_dist,thermal_dist num_state_qubits=1 #(default) not exposed to users def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, num_state_qubits=num_state_qubits): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") if gate_counts_plots == True: list_of_standardgates() # validate parameters (smallest circuit is 3 qubits) num_state_qubits = max(1, num_state_qubits) if max_qubits < num_state_qubits + 2: print(f"ERROR: AE Benchmark needs at least {num_state_qubits + 2} qubits to run") return min_qubits = max(max(3, min_qubits), num_state_qubits + 2) skip_qubits = max(1, skip_qubits) global qc_o global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # reset random seed np.random.seed(0) # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (num_counting_qubits), max_circuits) print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}") numckts.append(num_circuits) # determine range of secret strings to loop over if 2**(num_counting_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_counting_qubits), num_circuits, False) for s_int in s_range: print("*********************************************") print(f"qc of {num_qubits} qubits for integer {s_int}") #creation of Quantum Circuit. ts = time.time() a_ = (a_from_s_int(s_int, num_counting_qubits)) qc = AmplitudeEstimation(num_state_qubits, num_counting_qubits, a_) #creation time creation_time = time.time() - ts creation_times.append(creation_time) #print(qc) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose().decompose().decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() s_int = int(s_int) #Correct distribution to compare with counts correct_dist,thermal_dist = analyzer(s_int,num_counting_qubits,counts) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist,thermal_dist) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nControlled Quantum Operator 'cQ' ="); print(cQ_ if cQ_ != None else " ... too large!") print("\nQuantum Operator 'Q' ="); print(Q_ if Q_ != None else " ... too large!") print("\nAmplitude Generator 'A' ="); print(A_ if A_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QC_ != None else " ... too large!") return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=3 max_qubits=31 skip_qubits=1 max_circuits=2 num_shots=1000 method=1 #Use method=2 for another approach of Benchmarking (default->1) num_resets = 2 # Variable for number of resets to perform after mid circuit measurements (default->1) Only for method-2 input_value=None #assign any number to it to perform benchmark for that number.(Default->None) Noise_Inclusion = False saveplots = False Memory_utilization_plot = True gate_counts_plots = True Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute import time import matplotlib.pyplot as plt # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) benchmark_name = "Bernstein-Vazirani" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved circuits for display QC_ = None Uf_ = None ############### Circuit Definition def create_oracle(num_qubits, input_size, secret_int): # Initialize first n qubits and single ancilla qubit qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name="Uf") # perform CX for each qubit that matches a bit in secret string s = ('{0:0' + str(input_size) + 'b}').format(secret_int) print("s = ",s) print("input size in oracle =",input_size) for i_qubit in range(input_size): if s[input_size - 1 - i_qubit] == '1': qc.cx(qr[i_qubit], qr[input_size]) return qc def BersteinVazirani (num_qubits, secret_int, method = 1): # size of input is one less than available qubits input_size = num_qubits - 1 if method == 1: # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(input_size) qc = QuantumCircuit(qr, cr, name=f"bv({method})-{num_qubits}-{secret_int}") # put ancilla in |1> state qc.x(qr[input_size]) # start with Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() #generate Uf oracle Uf = create_oracle(num_qubits, input_size, secret_int) qc.append(Uf,qr) qc.barrier() # start with Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) # uncompute ancilla qubit, not necessary for algorithm qc.x(qr[input_size]) qc.barrier() # measure all data qubits for i in range(input_size): qc.measure(i, i) global Uf_ if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf elif method == 2: # allocate qubits qr = QuantumRegister(2); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name="main") # put ancilla in |-> state qc.x(qr[1]) qc.h(qr[1]) qc.barrier() # perform CX for each qubit that matches a bit in secret string s = ('{0:0' + str(input_size) + 'b}').format(secret_int) for i in range(input_size): if s[input_size - 1 - i] == '1': qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.measure(qr[0], cr[i]) # Perform num_resets reset operations qc.reset([0]*num_resets) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def analyzer(num_qubits,s_int): input_size = num_qubits-1 secret_int = int(s_int) # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{input_size}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} return correct_dist def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() # validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) # Variable for new qubit group ordering if using mid_circuit measurements mid_circuit_qubit_group = [] # If using mid_circuit measurements, set transform qubit group to true transform_qubit_group = True if method ==2 else False global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): input_size = num_qubits - 1 fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] num_circuits = min(2**(input_size), max_circuits) print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}") numckts.append(num_circuits) # determine range of secret strings to loop over if 2**(input_size) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(input_size), num_circuits, False) for s_int in s_range: print("*********************************************") if input_value is not None: s_int = input_value # If mid circuit, then add 2 to new qubit group since the circuit only uses 2 qubits if method == 2: mid_circuit_qubit_group.append(2) print(f"qc of {num_qubits} qubits with secret integer {s_int}") #creation of Quantum Circuit. ts = time.time() qc = BersteinVazirani(num_qubits, s_int, method) #creation time creation_time = time.time() - ts creation_times.append(creation_time) #print(qc) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time *1000} ms") #counts in result object counts = result.get_counts() #Correct distribution to compare with counts correct_dist = analyzer(num_qubits, s_int) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append((np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append((np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append((np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append((np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram class DeutschJozsa: ''' Class to generate a DeutschJozsa object containing: - init functions - oracle function - dj function ''' def __init__(self, case, input_str): ''' Initialization of the object: @case: (str) type of oracle balanced or constant @input_str: (str) string input state values ''' self.case = case self.number_qubit = len(input_str) self.str_input = input_str def oracle(self): ''' Will create the oracle needed for the Deutsch-Jozsa algorithm No input, the function will be used in the dj function @return the oracle in form of a gate ''' # Create the QuantumCircuit with n+1 qubits self.oracle_circuit = QuantumCircuit(self.number_qubit+1) # Balanced case if self.case == "balanced": # apply an X-gate to a qubit when its value is 1 for qubit in range(len(self.str_input)): if self.str_input[qubit] == '1': self.oracle_circuit.x(qubit) # Apply CNOT gates on each qubit for qubit in range(self.number_qubit): self.oracle_circuit.cx(qubit, self.number_qubit) # apply another set of X gates when the input qubit == 1 for qubit in range(len(self.str_input)): if self.str_input[qubit] == '1': self.oracle_circuit.x(qubit) # Constant case if self.case == "constant": # Output 0 for a constant oracle self.output = np.random.randint(2) if self.output == 1: self.oracle_circuit.x(self.number_qubit) # convert the quantum circuit into a gate self.oracle_gate = self.oracle_circuit.to_gate() # name of the oracle self.oracle_gate.name = "Oracle" return self.oracle_gate def dj(self): ''' Create the Deutsch-Jozsa algorithm in the general case with n qubit No input @return the quantum circuit of the DJ ''' self.dj_circuit = QuantumCircuit(self.number_qubit+1, self.number_qubit) # Set up the output qubit: self.dj_circuit.x(self.number_qubit) self.dj_circuit.h(self.number_qubit) # Psi_0 for qubit in range(self.number_qubit): self.dj_circuit.h(qubit) # Psi_1 + oracle self.dj_circuit.append(self.oracle(), range(self.number_qubit+1)) # Psi_2 for qubit in range(self.number_qubit): self.dj_circuit.h(qubit) # Psi_3 # Let's put some measurement for i in range(self.number_qubit): self.dj_circuit.measure(i, i) return self.dj_circuit test = DeutschJozsa('constant', '0110') #circuit = test.oracle() dj_circuit = test.dj() dj_circuit.draw('mpl') qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) from qiskit import IBMQ #TOKEN = 'paste your token here' #IBMQ.save_account(TOKEN) IBMQ.load_account() # Load account from disk IBMQ.providers() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() provider.backends(filters=lambda x: x.configuration().n_qubits >= 5 and not x.configuration().simulator and x.status().operational==True) backend = provider.get_backend('ibmq_manila') backend mapped_circuit = transpile(dj_circuit, backend=backend) qobj = assemble(mapped_circuit, backend=backend, shots=1024) job = backend.run(qobj) job.status() # 9:17 pm result = job.result() counts = result.get_counts() print(counts) plot_histogram(counts) plot_histogram(counts,figsize=(10,8), filename='DJ.jpeg')
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
import matplotlib.pyplot as plt import numpy as np from qiskit import QuantumCircuit, Aer, execute, transpile, assemble, QuantumRegister, ClassicalRegister from qiskit.visualization import plot_histogram def binary(num,length): #converts an integer to a binary number with defined length b = bin(num)[2:] return "0"*(length-len(b))+str(b) ncon = 4 controlreg = QuantumRegister(ncon,"control") hreg = QuantumRegister(1,"y") cc = ClassicalRegister(ncon,"cc") #xi = np.random.randint(0,2**ncon-1) #xi as in the greek letter xi = 7 R = int(np.pi/4*np.sqrt(2**ncon)) qc = QuantumCircuit(controlreg,hreg,cc) def Uf(controlreg,hreg,xi,ncon): #the oracle gate, a multi=controlled x gate which is one iff the input = xi hcirc = QuantumCircuit(hreg) circ = QuantumCircuit(controlreg,hreg) xiBin = binary(xi,ncon) zerolist = [i for i in range(ncon) if (xiBin[i] == "0")] circ.x(zerolist) circ.mct(list(range(ncon)),ncon) circ.x(zerolist) circ.name = "Uf" return circ def ccz(controls=2): #multi controlled Z gate (decomposed here as a multi controlled X with H gates placed either side) circ = QuantumCircuit(controls+1) circ.h(controls) circ.mct(list(range(controls)),[controls]) circ.h(controls) circ.name = "c"*controls+"z" return circ def diffusion(ncon): #https://rdcu.be/cLzsq circ = QuantumCircuit(ncon) circ.h(range(ncon)) circ.x(range(ncon)) circ.append(ccz(ncon-1),list(range(ncon))) circ.barrier() circ.x(range(ncon)) circ.h(range(ncon)) circ.name = "Diffusion" return circ Ufgate = Uf(controlreg,hreg,xi,ncon) qc.x(hreg[0]) qc.h(hreg[0]) qc.h(range(ncon)) for e in range(R): qc.barrier() qc.append(Ufgate,controlreg[:]+hreg[:]) qc.barrier() qc.append(diffusion(ncon).decompose(),controlreg[:ncon]) qc.barrier() qc.measure([controlreg[i] for i in range(ncon-1,-1,-1)],cc,) print(xi) qc.draw(plot_barriers=False,fold = -1,output = "latex") ?aersim aersim = Aer.get_backend('aer_simulator') #set memory=True to see measurements tqc = transpile(qc,aersim) results = aersim.run(tqc,shots=10000).result() plot_histogram(results.get_counts()) aersim = Aer.get_backend('aer_simulator') #set memory=True to see measurements tqc = transpile(qc,aersim) results = aersim.run(tqc,shots=10000).result() d = results.get_counts() oldkeys = list(d.keys()) for key in oldkeys: d[str(int(key,2))] = d[key] del d[key] x = np.arange(0,2**ncon-1,1) y = np.zeros(len(x)) for i,xi in enumerate(x): if str(xi) in d.keys(): y[i] = d[str(xi)] plt.xlim(-1,2**ncon) plt.bar(x,y,color=(0.4,0.6,1)) controlreg,hreg = QuantumRegister(4,"control"),QuantumRegister(1,"y") xi = 7 hcirc = QuantumCircuit(hreg) circ = QuantumCircuit(controlreg,hreg) xiBin = binary(xi,ncon) zerolist = [i for i in range(ncon) if (xiBin[i] == "0")] circ.x(zerolist) circ.mct(list(range(ncon)),ncon) circ.x(zerolist) circ.name = "Uf" circ.draw(output="latex") circ = QuantumCircuit(ncon) circ.h(range(ncon)) circ.x(range(ncon)) circ.h(ncon-1) circ.mct(list(range(ncon-1)),[ncon-1]) circ.h(ncon-1) circ.barrier() circ.x(range(ncon)) circ.h(range(ncon)) circ.name = "Diffusion" circ.draw(output="latex",plot_barriers=False) from qiskit import IBMQ IBMQ.enable_account("") provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = provider.get_backend("ibmq_quito") res = backend.retrieve_job("622a012c9e029c54a90deedc").result() plot_histogram(res.get_counts()) nbits = 4 d = res.get_counts() oldkeys = list(d.keys()) for key in oldkeys: d[str(int(key,2))] = d[key] del d[key] x = list(range(0,7))+list(range(8,16)) xi, yi = 7,d["7"]/10000 del d["7"] y = [d[str(xi)]/10000 for xi in x] plt.xlim(-1,15.9) plt.bar(x,y,color=(0.4,0.6,1)) plt.bar(xi,yi,color=(1,0,0)) plt.ylabel("Probability") plt.xlabel("x")
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=1 max_qubits=3 skip_qubits=1 max_circuits=3 num_shots=1000 use_XX_YY_ZZ_gates = True Noise_Inclusion = False saveplots = False Memory_utilization_plot = True Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends gate_counts_plots = True #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np import os,json from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute import time import matplotlib.pyplot as plt # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) # Benchmark Name benchmark_name = "Hamiltonian Simulation" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) num_gates = 0 depth = 0 def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved circuits and subcircuits for display QC_ = None XX_ = None YY_ = None ZZ_ = None XXYYZZ_ = None # import precalculated data to compare against filename = os.path.join("precalculated_data.json") with open(filename, 'r') as file: data = file.read() precalculated_data = json.loads(data) ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z): ''' Construct a Qiskit circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :return: return a Qiskit circuit for this Hamiltonian ''' num_qubits = n_spins secret_int = f"{K}-{t}" # allocate qubits qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins); qc = QuantumCircuit(qr, cr, name=f"hamsim-{num_qubits}-{secret_int}") tau = t / K # start with initial state of 1010101... for k in range(0, n_spins, 2): qc.x(qr[k]) qc.barrier() # loop over each trotter step, adding gates to the circuit defining the hamiltonian for k in range(K): # the Pauli spin vector product [qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)] [qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)] qc.barrier() # Basic implementation of exp(i * t * (XX + YY + ZZ)) if _use_XX_YY_ZZ_gates: # XX operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # YY operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # Use an optimal XXYYZZ combined operator # See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf else: # optimized XX + YY + ZZ operator on each pair of qubits in linear chain for j in range(2): for i in range(j % 2, n_spins - 1, 2): qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) qc.barrier() # measure all the qubits used in the circuit for i_qubit in range(n_spins): qc.measure(qr[i_qubit], cr[i_qubit]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 6: if n_spins < 9: QC_ = qc return qc ############### XX, YY, ZZ Gate Implementations # Simple XX gate on q0 and q1 with angle 'tau' def xx_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate") qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) # save circuit example for display global XX_ XX_ = qc return qc # Simple YY gate on q0 and q1 with angle 'tau' def yy_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate") qc.s(qr[0]) qc.s(qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.sdg(qr[0]) qc.sdg(qr[1]) # save circuit example for display global YY_ YY_ = qc return qc # Simple ZZ gate on q0 and q1 with angle 'tau' def zz_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate") qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) # save circuit example for display global ZZ_ ZZ_ = qc return qc # Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau' def xxyyzz_opt_gate(tau): alpha = tau; beta = tau; gamma = tau qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt") qc.rz(3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(3.1416*gamma - 3.1416/2, qr[0]) qc.ry(3.1416/2 - 3.1416*alpha, qr[1]) qc.cx(qr[0], qr[1]) qc.ry(3.1416*beta - 3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(-3.1416/2, qr[0]) # save circuit example for display global XXYYZZ_ XXYYZZ_ = qc return qc # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def analyzer(num_qubits): # we have precalculated the correct distribution that a perfect quantum computer will return # it is stored in the json file we import at the top of the code correct_dist = precalculated_data[f"Qubits - {num_qubits}"] return correct_dist num_state_qubits=1 #(default) not exposed to users def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") global _use_XX_YY_ZZ_gates _use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates if _use_XX_YY_ZZ_gates: print("... using unoptimized XX YY ZZ gates") global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # reset random seed np.random.seed(0) # determine number of circuits to execute for this group num_circuits = max(1, max_circuits) print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}") numckts.append(num_circuits) # parameters of simulation #### CANNOT BE MODIFIED W/O ALSO MODIFYING PRECALCULATED DATA ######### w = precalculated_data['w'] # strength of disorder k = precalculated_data['k'] # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. t = precalculated_data['t'] # time of simulation ####################################################################### for circuit_id in range(num_circuits): print("*********************************************") print(f"qc of {num_qubits} qubits for circuit_id: {circuit_id}") #creation of Quantum Circuit. ts = time.time() h_x = precalculated_data['h_x'][:num_qubits] # precalculated random numbers between [-1, 1] h_z = precalculated_data['h_z'][:num_qubits] qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z) #creation time creation_time = time.time() - ts creation_times.append(creation_time) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() #Correct distribution to compare with counts correct_dist = analyzer(num_qubits) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if _use_XX_YY_ZZ_gates: print("\nXX, YY, ZZ =") print(XX_); print(YY_); print(ZZ_) else: print("\nXXYYZZ_opt =") print(XXYYZZ_) return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
import sys sys.path[1:1] = ["_common", "_common/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit"] from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import time import math import os import numpy as np np.random.seed(0) import execute as ex import metrics as metrics from collections import defaultdict from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule from qiskit_nature.circuit.library import HartreeFock as HF from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.transformers import ActiveSpaceTransformer from qiskit_nature.operators.second_quantization import FermionicOp from qiskit.opflow import PauliTrotterEvolution, CircuitStateFn, Suzuki from qiskit.opflow.primitive_ops import PauliSumOp # Function that converts a list of single and double excitation operators to Pauli operators def readPauliExcitation(norb, circuit_id=0): # load pre-computed data filename = os.path.join(os.getcwd(), f'../qiskit/ansatzes/{norb}_qubit_{circuit_id}.txt') with open(filename) as f: data = f.read() ansatz_dict = json.loads(data) # initialize Pauli list pauli_list = [] # current coefficients cur_coeff = 1e5 # current Pauli list cur_list = [] # loop over excitations for ext in ansatz_dict: if cur_coeff > 1e4: cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4: pauli_list.append(PauliSumOp.from_list(cur_list)) cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] else: cur_list.append((ext, ansatz_dict[ext])) # add the last term pauli_list.append(PauliSumOp.from_list(cur_list)) # return Pauli list return pauli_list # Get the Hamiltonian by reading in pre-computed file def ReadHamiltonian(nqubit): # load pre-computed data filename = os.path.join(os.getcwd(), f'../qiskit/Hamiltonians/{nqubit}_qubit.txt') with open(filename) as f: data = f.read() ham_dict = json.loads(data) # pauli list pauli_list = [] for p in ham_dict: pauli_list.append( (p, ham_dict[p]) ) # build Hamiltonian ham = PauliSumOp.from_list(pauli_list) # return Hamiltonian return ham def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1): ''' Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz :param n_spin_orbs:The number of spin orbitals :return: return a Qiskit circuit for this VQE ansatz ''' # allocate qubits num_qubits = n_spin_orbs qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name="main") # number of alpha spin orbitals norb_a = int(n_spin_orbs / 2) # number of beta spin orbitals norb_b = norb_a # construct the Hamiltonian qubit_op = ReadHamiltonian(n_spin_orbs) # initialize the HF state qc = HartreeFock(n_spin_orbs, na, nb) # form the list of single and double excitations singles = [] doubles = [] for occ_a in range(na): for vir_a in range(na, norb_a): singles.append((occ_a, vir_a)) for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): singles.append((occ_b, vir_b)) for occ_a in range(na): for vir_a in range(na, norb_a): for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): doubles.append((occ_a, vir_a, occ_b, vir_b)) # get cluster operators in Paulis pauli_list = readPauliExcitation(n_spin_orbs, circuit_id) # loop over the Pauli operators for index, PauliOp in enumerate(pauli_list): # get circuit for exp(-iP) cluster_qc = ClusterOperatorCircuit(PauliOp) # add to ansatz qc.compose(cluster_qc, inplace=True) # method 2, only compute the last term in the Hamiltonian if method == 2: # last term in Hamiltonian qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits) # return the circuit return qc_with_mea # now we need to add the measurement parts to the circuit # circuit list qc_list = [] diag = [] off_diag = [] for p in qubit_op: # get the circuit with expectation measurements qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits) # add to circuit list qc_list.append(qc_with_mea) # diagonal term if is_diag: diag.append(p) # off-diagonal term else: off_diag.append(p) return qc_list def ClusterOperatorCircuit(pauli_op): # compute exp(-iP) exp_ip = pauli_op.exp_i() # Trotter approximation qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip) # convert to circuit qc = qc_op.to_circuit() # return this circuit return qc # Function that adds expectation measurements to the raw circuits def ExpectationCircuit(qc, pauli, nqubit, method=1): # a flag that tells whether we need to perform rotation need_rotate = False # copy the unrotated circuit raw_qc = qc.copy() # whether this term is diagonal is_diag = True # primitive Pauli string PauliString = pauli.primitive.to_list()[0][0] # coefficient coeff = pauli.coeffs[0] # basis rotation for i, p in enumerate(PauliString): target_qubit = nqubit - i - 1 if (p == "X"): need_rotate = True is_diag = False raw_qc.h(target_qubit) elif (p == "Y"): raw_qc.sdg(target_qubit) raw_qc.h(target_qubit) need_rotate = True is_diag = False # perform measurements raw_qc.measure_all() # name of this circuit raw_qc.name = PauliString + " " + str(np.real(coeff)) return raw_qc, is_diag # Function that implements the Hartree-Fock state def HartreeFock(norb, na, nb): # initialize the quantum circuit qc = QuantumCircuit(norb) # alpha electrons for ia in range(na): qc.x(ia) # beta electrons for ib in range(nb): qc.x(ib+int(norb/2)) # return the circuit return qc import json from qiskit import execute, Aer backend = Aer.get_backend("qasm_simulator") precalculated_data = {} def run(min_qubits=4, max_qubits=4, max_circuits=3, num_shots=4092 * 2**8, method=2): print(f"... using circuit method {method}") # validate parameters (smallest circuit is 4 qubits) max_qubits = max(4, max_qubits) min_qubits = min(max(4, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even if method == 1: max_circuits = 1 # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for input_size in range(min_qubits, max_qubits + 1, 2): # determine the number of circuits to execute fo this group num_circuits = max_circuits num_qubits = input_size # decides number of electrons na = int(num_qubits/4) nb = int(num_qubits/4) # decides number of unoccupied orbitals nvira = int(num_qubits/2) - na nvirb = int(num_qubits/2) - nb # determine the size of t1 and t2 amplitudes t1_size = na * nvira + nb * nvirb t2_size = na * nb * nvira * nvirb # random seed np.random.seed(0) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() # circuit list qc_list = [] # method 1 (default) if method == 1: # sample t1 and t2 amplitude t1 = np.random.normal(size=t1_size) t2 = np.random.normal(size=t2_size) # construct all circuits qc_list = VQEEnergy(num_qubits, na, nb, 0, method) else: # loop over circuits for circuit_id in range(num_circuits): # sample t1 and t2 amplitude t1 = np.random.normal(size=t1_size) t2 = np.random.normal(size=t2_size) # construct circuit qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method) qc_single.name = qc_single.name + " " + str(circuit_id) # add to list qc_list.append(qc_single) print(f"************\nExecuting VQE with num_qubits {num_qubits}") for qc in qc_list: # get circuit id if method == 1: circuit_id = qc.name.split()[0] else: circuit_id = qc.name.split()[2] # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) job = execute(qc, backend, shots=num_shots) # executation result result = job.result() # get measurement counts counts = result.get_counts(qc) # initialize empty dictionary dist = {} for key in counts.keys(): prob = counts[key] / num_shots dist[key] = prob # add dist values to precalculated data for use in fidelity calculation precalculated_data[f"{circuit_id}"] = dist with open(f'precalculated_data_qubit_{num_qubits}_method1.json', 'w') as f: f.write(json.dumps( precalculated_data, sort_keys=True, indent=4, separators=(',', ': ') )) run()
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=3 #min_qubits are incremented to 4 w.r.t algorithm "qubits should be of even number" max_qubits=31 skip_qubits=1 #minimum Skip_qubits used is 2 (by default skip_qubits=2 when skip_qubits<2) max_circuits=2 num_shots=1000 Noise_Inclusion = False saveplots = False Memory_utilization_plot = True gate_counts_plots = True Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeJakartaV2() import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute import time import matplotlib.pyplot as plt # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) # Benchmark Name benchmark_name = "Hidden Shift" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 2 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved circuits for display QC_ = None Uf_ = None Ug_ = None # Circuit Definition # Uf oracle where Uf|x> = f(x)|x>, f(x) = {-1,1} def Uf_oracle(num_qubits, secret_int): # Initialize qubits qubits qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"Uf") # Perform X on each qubit that matches a bit in secret string s = ('{0:0'+str(num_qubits)+'b}').format(secret_int) for i_qubit in range(num_qubits): if s[num_qubits-1-i_qubit]=='1': qc.x(qr[i_qubit]) for i_qubit in range(0,num_qubits-1,2): qc.cz(qr[i_qubit], qr[i_qubit+1]) # Perform X on each qubit that matches a bit in secret string s = ('{0:0'+str(num_qubits)+'b}').format(secret_int) for i_qubit in range(num_qubits): if s[num_qubits-1-i_qubit]=='1': qc.x(qr[i_qubit]) return qc # Generate Ug oracle where Ug|x> = g(x)|x>, g(x) = f(x+s) def Ug_oracle(num_qubits): # Initialize first n qubits qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"Ug") for i_qubit in range(0,num_qubits-1,2): qc.cz(qr[i_qubit], qr[i_qubit+1]) return qc def HiddenShift (num_qubits, secret_int): # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name=f"hs-{num_qubits}-{secret_int}") # Start with Hadamard on all input qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() # Generate Uf oracle where Uf|x> = f(x)|x>, f(x) = {-1,1} Uf = Uf_oracle(num_qubits, secret_int) qc.append(Uf,qr) qc.barrier() # Again do Hadamard on all qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() # Generate Ug oracle where Ug|x> = g(x)|x>, g(x) = f(x+s) Ug = Ug_oracle(num_qubits) qc.append(Ug,qr) qc.barrier() # End with Hadamard on all qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() # measure all qubits qc.measure(qr, cr) # save smaller circuit example for display global QC_, Uf_, Ug_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf if Ug_ == None or num_qubits <= 6: if num_qubits < 9: Ug_ = Ug # return a handle on the circuit return qc # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def analyzer(num_qubits,s_int): # create the key that is expected to have all the measurements (for this circuit) key = format(s_int, f"0{num_qubits}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} #print("correct_dist=",correct_dist) return correct_dist def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(2, skip_qubits) global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() # Execute Benchmark Program N times for multiple circuit sizes for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # determine number of circuits to execute for this group num_circuits = min(2 ** (num_qubits), max_circuits) numckts.append(num_circuits) print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_qubits), num_circuits, False) for s_int in s_range: print("*********************************************") print(f"qc of {num_qubits} qubits for integer {s_int}") #creation of Quantum Circuit. ts = time.time() qc = HiddenShift(num_qubits, s_int) #creation time creation_time = time.time() - ts creation_times.append(creation_time) #print(qc) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() #print("Counts = ",counts) #Correct distribution to compare with counts correct_dist = analyzer(num_qubits,s_int) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") print("\nQuantum Oracle 'Ug' ="); print(Ug_ if Ug_ != None else " ... too large!") return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion method = 2 min_qubits=4 # must be at least (MIN_STATE_QUBITS=1) + 3 = 4 ## for method-1 min_qubits = 5 (MIN_STATE_QUBITS = 2)+3 = 5 max_qubits=10 # Because circuit size grows significantly with num_qubits limit the max_qubits here ... skip_qubits=1 max_circuits=3 num_shots=1000 epsilon=0.05 degree=2 Noise_Inclusion = False saveplots = False Memory_utilization_plot = True gate_counts_plots = True Type_of_Simulator = "FAKEV2" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np import copy import functools import mc_utils as mc_utils from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute import time import matplotlib.pyplot as plt from numpy.polynomial.polynomial import Polynomial from numpy.polynomial.polynomial import polyfit from qiskit.circuit.library.standard_gates.ry import RYGate # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) # Benchmark Name benchmark_name = "Monte Carlo Sampling" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) num_gates = 0 depth = 0 QV_=0 def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved circuits and subcircuits for display A_ = None Q_ = None cQ_ = None QC_ = None R_ = None F_ = None QFTI_ = None # default function is f(x) = x^2 f_of_X = functools.partial(mc_utils.power_f, power=2) # default distribution is gaussian distribution p_distribution = mc_utils.gaussian_dist ############### Circuit Definition def MonteCarloSampling(target_dist, f, num_state_qubits, num_counting_qubits, epsilon=0.05, degree=2, method=2): A_qr = QuantumRegister(num_state_qubits+1) A = QuantumCircuit(A_qr, name=f"A_ckt") num_qubits = num_state_qubits + 1 + num_counting_qubits # initialize R and F circuits R_qr = QuantumRegister(num_state_qubits+1) F_qr = QuantumRegister(num_state_qubits+1) R = QuantumCircuit(R_qr, name=f"R") F = QuantumCircuit(F_qr, name=f"F") # method 1 takes in the abitrary function f and arbitrary dist if method == 1: state_prep(R, R_qr, target_dist, num_state_qubits) f_on_objective(F, F_qr, f, epsilon=epsilon, degree=degree) # method 2 chooses to have lower circuit depth by choosing specific f and dist elif method == 2: uniform_prep(R, R_qr, num_state_qubits) square_on_objective(F, F_qr) # append R and F circuits to A A.append(R.to_gate(), A_qr) A.append(F.to_gate(), A_qr) # run AE subroutine given our A composed of R and F qc = AE_Subroutine(num_state_qubits, num_counting_qubits, A, method) # save smaller circuit example for display global QC_, R_, F_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc if (R_ and F_) == None or num_state_qubits <= 3: if num_state_qubits < 5: R_ = R; F_ = F return qc ############### def f_on_objective(qc, qr, f, epsilon=0.05, degree=2): """ Assume last qubit is the objective. Function f is evaluated on first n-1 qubits """ num_state_qubits = qc.num_qubits - 1 c_star = (2*epsilon)**(1/(degree+1)) f_ = functools.partial(f, num_state_qubits=num_state_qubits) zeta_ = functools.partial(mc_utils.zeta_from_f, func=f_, epsilon=epsilon, degree=degree, c=c_star) x_eval = np.linspace(0.0, 2**(num_state_qubits) - 1, num= degree+1) poly = Polynomial(polyfit(x_eval, zeta_(x_eval), degree)) b_exp = mc_utils.binary_expansion(num_state_qubits, poly) for controls in b_exp.keys(): theta = 2*b_exp[controls] controls = list(controls) if len(controls)==0: qc.ry(-theta, qr[num_state_qubits]) else: # define a MCRY gate: # this does the same thing as qc.mcry, but is clearer in the circuit printing MCRY = RYGate(-theta).control(len(controls)) qc.append(MCRY, [*(qr[i] for i in controls), qr[num_state_qubits]]) def square_on_objective(qc, qr): """ Assume last qubit is the objective. Shifted square wave function: if x is even, f(x) = 0; if x i s odd, f(x) = 1 """ num_state_qubits = qc.num_qubits - 1 for control in range(num_state_qubits): qc.cx(control, num_state_qubits) def state_prep(qc, qr, target_dist, num_state_qubits): """ Use controlled Ry gates to construct the superposition Sum \sqrt{p_i} |i> """ r_probs = mc_utils.region_probs(target_dist, num_state_qubits) regions = r_probs.keys() r_norm = {} for r in regions: num_controls = len(r) - 1 super_key = r[:num_controls] if super_key=='': r_norm[super_key] = 1 elif super_key == '1': r_norm[super_key] = r_probs[super_key] r_norm['0'] = 1-r_probs[super_key] else: try: r_norm[super_key] = r_probs[super_key] except KeyError: r_norm[super_key] = r_norm[super_key[:num_controls-1]] - r_probs[super_key[:num_controls-1] + '1'] norm = r_norm[super_key] p = 0 if norm != 0: p = r_probs[r] / norm theta = 2*np.arcsin(np.sqrt(p)) if r == '1': qc.ry(-theta, num_state_qubits-1) else: controls = [qr[num_state_qubits-1 - i] for i in range(num_controls)] # define a MCRY gate: # this does the same thing as qc.mcry, but is clearer in the circuit printing MCRY = RYGate(-theta).control(num_controls, ctrl_state=r[:-1]) qc.append(MCRY, [*controls, qr[num_state_qubits-1 - num_controls]]) def uniform_prep(qc, qr, num_state_qubits): """ Generates a uniform distribution over all states """ for i in range(num_state_qubits): qc.h(i) def AE_Subroutine(num_state_qubits, num_counting_qubits, A_circuit, method): num_qubits = num_state_qubits + num_counting_qubits qr_state = QuantumRegister(num_state_qubits+1) qr_counting = QuantumRegister(num_counting_qubits) cr = ClassicalRegister(num_counting_qubits) qc = QuantumCircuit(qr_state, qr_counting, cr, name=f"qmc({method})-{num_qubits}-{0}") A = A_circuit cQ, Q = Ctrl_Q(num_state_qubits, A) # save small example subcircuits for visualization global A_, Q_, cQ_, QFTI_ if (cQ_ and Q_) == None or num_state_qubits <= 6: if num_state_qubits < 9: cQ_ = cQ; Q_ = Q if A_ == None or num_state_qubits <= 3: if num_state_qubits < 5: A_ = A if QFTI_ == None or num_counting_qubits <= 3: if num_counting_qubits < 4: QFTI_ = inv_qft_gate(num_counting_qubits) # Prepare state from A, and counting qubits with H transform qc.append(A, qr_state) for i in range(num_counting_qubits): qc.h(qr_counting[i]) repeat = 1 for j in reversed(range(num_counting_qubits)): for _ in range(repeat): qc.append(cQ, [qr_counting[j]] + [qr_state[l] for l in range(num_state_qubits+1)]) repeat *= 2 qc.barrier() # inverse quantum Fourier transform only on counting qubits qc.append(inv_qft_gate(num_counting_qubits), qr_counting) print(inv_qft_gate(num_counting_qubits)) qc.barrier() qc.measure([qr_counting[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits))) return qc ############################### # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qc = QuantumCircuit(num_state_qubits+1, name=f"Q") temp_A = copy.copy(A_circ) A_gate = temp_A.to_gate() A_gate_inv = temp_A.inverse().to_gate() ### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ # -S_chi qc.x(num_state_qubits) qc.z(num_state_qubits) qc.x(num_state_qubits) # A_circ_inverse qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)]) # S_0 for i in range(num_state_qubits+1): qc.x(i) qc.h(num_state_qubits) qc.mcx([x for x in range(num_state_qubits)], num_state_qubits) qc.h(num_state_qubits) for i in range(num_state_qubits+1): qc.x(i) # A_circ qc.append(A_gate, [i for i in range(num_state_qubits+1)]) # Create a gate out of the Q operator qc.to_gate(label='Q') # and also a controlled version of it Ctrl_Q_ = qc.control(1) # and return both return Ctrl_Q_, qc ############### Inverse QFT Circuit def inv_qft_gate(input_size): global QFTI_, num_gates, depth qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="inv_qft") # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.h(qr[hidx]) num_gates += 1 depth += 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1]) num_gates += 1 depth += 1 qc.barrier() if QFTI_ == None or input_size <= 5: if input_size < 9: QFTI_= qc return qc # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def analyzer(num_counting_qubits,num_state_qubits,mu,f_of_X): # generate exact value for the expectation value given our function and dist target_dist = p_distribution(num_state_qubits, mu) f = functools.partial(f_of_X, num_state_qubits=num_state_qubits) if method == 1: exact = mc_utils.estimated_value(target_dist, f) elif method == 2: exact = 0.5 # hard coded exact value from uniform dist and square function # calculate the expected output histogram correct_dist = a_to_bitstring(exact, num_counting_qubits) # generate thermal_dist with amplitudes instead, to be comparable to correct_dist thermal_dist = uniform_dist(num_counting_qubits) # # convert counts, expectation, and thermal_dist to app form for visibility # # app form of correct distribution is measuring the input a 100% of the time # # convert bit_counts into expectation values counts according to Quantum Risk Analysis paper # app_counts = expectation_from_bits(counts, num_counting_qubits, num_shots, method) # app_correct_dist = mc_utils.mc_dist(num_counting_qubits, exact, c_star, method) # app_thermal_dist = expectation_from_bits(thermal_dist, num_counting_qubits, num_shots, method) return correct_dist,thermal_dist def a_to_bitstring(a, num_counting_qubits): m = num_counting_qubits # solution 1 num1 = round(np.arcsin(np.sqrt(a)) / np.pi * 2**m) num2 = round( (np.pi - np.arcsin(np.sqrt(a))) / np.pi * 2**m) if num1 != num2 and num2 < 2**m and num1 < 2**m: counts = {format(num1, "0"+str(m)+"b"): 0.5, format(num2, "0"+str(m)+"b"): 0.5} else: counts = {format(num1, "0"+str(m)+"b"): 1} return counts def expectation_from_bits(bits, num_qubits, num_shots, method): amplitudes = {} for b in bits.keys(): precision = int(num_qubits / (np.log2(10))) + 2 r = bits[b] a_meas = pow(np.sin(np.pi*int(b,2)/pow(2,num_qubits)),2) if method == 1: a = ((a_meas - 0.5)/c_star) + 0.5 if method == 2: a = a_meas a = round(a, precision) if a not in amplitudes.keys(): amplitudes[a] = 0 amplitudes[a] += r return amplitudes if method == 1: MIN_STATE_QUBITS = 2 elif method == 2: MIN_STATE_QUBITS = 1 def run (min_qubits=min_qubits, max_qubits=5, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, epsilon=epsilon, degree=degree, num_state_qubits = MIN_STATE_QUBITS, method=2 #(default) ): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() skip_qubits = max(1, skip_qubits) print(f"min, max qubits = {min_qubits} {max_qubits}") global c_star c_star = (2*epsilon)**(1/(degree+1)) global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # reset random seed np.random.seed(0) input_size = num_qubits - 1 # TODO: keep using inputsize? only used in num_circuits # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (input_size), max_circuits) print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}") numckts.append(num_circuits) # determine range of circuits to loop over for method 1 if 2**(input_size) <= max_circuits: mu_range = [i/2**(input_size) for i in range(num_circuits)] else: mu_range = [i/2**(input_size) for i in np.random.choice(2**(input_size), num_circuits, False)] for mu in mu_range: print("*********************************************") print(f"qc of {num_qubits} qubits for mu value {mu}") target_dist = p_distribution(num_state_qubits, mu) f_to_estimate = functools.partial(f_of_X, num_state_qubits=num_state_qubits) #creation of Quantum Circuit. ts = time.time() qc = MonteCarloSampling(target_dist, f_to_estimate, num_state_qubits, num_counting_qubits, epsilon, degree, method=method) print(qc) #creation time creation_time = time.time() - ts creation_times.append(creation_time) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose().decompose().decompose().decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() #Correct distribution to compare with counts correct_dist,thermal_dist = analyzer(num_counting_qubits,num_state_qubits,mu,f_of_X) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist, thermal_dist) ########################################################################### # NOTE: in this benchmark, we are testing how well the amplitude estimation routine # works according to theory, and we do not measure the difference between # the reported answer and the correct answer; the below code just helps # demonstrate that we do approximate the expectation value accurately. # the max in the counts is what the algorithm would report as the correct answer a, _ = mc_utils.value_and_max_prob_from_dist(counts) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nControlled Quantum Operator 'cQ' ="); print(cQ_ if cQ_ != None else " ... too large!") print("\nQuantum Operator 'Q' ="); print(Q_ if Q_ != None else " ... too large!") print("\nAmplitude Generator 'A' ="); print(A_ if A_ != None else " ... too large!") print("\nDistribution Generator 'R' ="); print(R_ if R_ != None else " ... too large!") print("\nFunction Generator 'F' ="); print(F_ if F_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=2 max_qubits=18 skip_qubits=1 max_circuits=3 num_shots=1000 Noise_Inclusion = False saveplots = False Memory_utilization_plot = True gate_counts_plots = True ype_of_Simulator = "FAKEV2" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np import copy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute import time import matplotlib.pyplot as plt # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) # Benchmark Name benchmark_name = "Phase Estimation" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) num_gates = 0 depth = 0 def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved subcircuits circuits for printing QC_ = None QFTI_ = None U_ = None ############### Circuit Definition def PhaseEstimation(num_qubits, theta): qr = QuantumRegister(num_qubits) num_counting_qubits = num_qubits - 1 # only 1 state qubit cr = ClassicalRegister(num_counting_qubits) qc = QuantumCircuit(qr, cr, name=f"qpe-{num_qubits}-{theta}") # initialize counting qubits in superposition for i in range(num_counting_qubits): qc.h(qr[i]) # change to |1> in state qubit, so phase will be applied by cphase gate qc.x(num_counting_qubits) qc.barrier() repeat = 1 for j in reversed(range(num_counting_qubits)): # controlled operation: adds phase exp(i*2*pi*theta*repeat) to the state |1> # does nothing to state |0> cp, _ = CPhase(2*np.pi*theta, repeat) qc.append(cp, [j, num_counting_qubits]) repeat *= 2 #Define global U operator as the phase operator _, U = CPhase(2*np.pi*theta, 1) qc.barrier() # inverse quantum Fourier transform only on counting qubits qc.append(inv_qft_gate(num_counting_qubits), qr[:num_counting_qubits]) qc.barrier() # measure counting qubits qc.measure([qr[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits))) # save smaller circuit example for display global QC_, U_, QFTI_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc if U_ == None or num_qubits <= 5: if num_qubits < 9: U_ = U if QFTI_ == None or num_qubits <= 5: if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits) return qc #Construct the phase gates and include matching gate representation as readme circuit def CPhase(angle, exponent): qc = QuantumCircuit(1, name=f"U^{exponent}") qc.p(angle*exponent, 0) phase_gate = qc.to_gate().control(1) return phase_gate, qc ############### Inverse QFT Circuit def inv_qft_gate(input_size): global QFTI_, num_gates, depth qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="inv_qft") # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.h(qr[hidx]) num_gates += 1 depth += 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1]) num_gates += 1 depth += 1 qc.barrier() if QFTI_ == None or input_size <= 5: if input_size < 9: QFTI_= qc return qc # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem # Convert theta to a bitstring distribution def theta_to_bitstring(theta, num_counting_qubits): counts = {format( int(theta * (2**num_counting_qubits)), "0"+str(num_counting_qubits)+"b"): 1.0} return counts # Convert bitstring to theta representation, useful for debugging def bitstring_to_theta(counts, num_counting_qubits): theta_counts = {} for key in counts.keys(): r = counts[key] theta = int(key,2) / (2**num_counting_qubits) if theta not in theta_counts.keys(): theta_counts[theta] = 0 theta_counts[theta] += r return theta_counts def analyzer(theta,num_qubits, num_counting_qubits,counts): num_counting_qubits_1 = num_qubits -1 # calculate expected output histogram correct_dist = theta_to_bitstring(theta, num_counting_qubits_1) # generate thermal_dist for polarization calculation thermal_dist = uniform_dist(num_counting_qubits) #print("thermal_dist=",thermal_dist) # convert counts, expectation, and thermal_dist to app form for visibility # app form of correct distribution is measuring amplitude a 100% of the time # app_counts = bitstring_to_a(counts, num_counting_qubits) # app_correct_dist = correct_dist#{a: 1.0} # app_thermal_dist = bitstring_to_a(thermal_dist, num_counting_qubits) return correct_dist,thermal_dist num_state_qubits=1 #(default) not exposed to users def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, num_state_qubits=num_state_qubits): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") # validate parameters (smallest circuit is 3 qubits) num_state_qubits = max(1, num_state_qubits) if max_qubits < num_state_qubits + 2: print(f"ERROR: AE Benchmark needs at least {num_state_qubits + 2} qubits to run") return min_qubits = max(max(3, min_qubits), num_state_qubits + 2) skip_qubits = max(1, skip_qubits) global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() # Execute Benchmark Program N times for multiple circuit sizes for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # reset random seed np.random.seed(0) # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (num_counting_qubits), max_circuits) print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}") numckts.append(num_circuits) # determine range of secret strings to loop over if 2**(num_counting_qubits) <= max_circuits: theta_range = [i/(2**(num_counting_qubits)) for i in list(range(num_circuits))] else: theta_range = [i/(2**(num_counting_qubits)) for i in np.random.choice(2**(num_counting_qubits), num_circuits, False)] for theta in theta_range: print("*********************************************") print(f"qc of {num_qubits} qubits for theta {theta}") #creation of Quantum Circuit. ts = time.time() qc = PhaseEstimation(num_qubits, theta) #creation time creation_time = time.time() - ts creation_times.append(creation_time) #print(qc) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose().decompose().decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() #Correct distribution to compare with counts correct_dist,thermal_dist = analyzer(theta,num_qubits, num_counting_qubits,counts) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist,thermal_dist) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nPhase Operator 'U' = "); print(U_ if U_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) qc.h(2) qc.cp(pi/2, 1, 2) qc.cp(pi/4, 0, 2) qc.h(1) qc.cp(pi/2, 0, 1) qc.h(0) qc.swap(0, 2) qc.draw() def qft_rotations(circuit, n): if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): qft_rotations(circuit, n) swap_registers(circuit, n) return circuit qc = QuantumCircuit(4) qft(qc,4) qc.draw() # Create the circuit qc = QuantumCircuit(3) # Encode the state 5 (101 in binary) qc.x(0) qc.x(2) qc.draw() sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qft(qc, 3) qc.draw() qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector)
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
from qiskit import BasicAer from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import Shor N = 15 shor = Shor(N) backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024) ret = shor.run(quantum_instance) print("The list of factors of {} as computed by the Shor's algorithm is {}.".format(N, ret['factors'][0]))
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=4 max_qubits=15 #reference files are upto 12 Qubits only skip_qubits=2 max_circuits=3 num_shots=4092 gate_counts_plots = True Noise_Inclusion = False saveplots = False Memory_utilization_plot = True Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute from qiskit.opflow import PauliTrotterEvolution, Suzuki from qiskit.opflow.primitive_ops import PauliSumOp import time,os,json import matplotlib.pyplot as plt # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) # Benchmark Name benchmark_name = "VQE Simulation" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved circuits for display QC_ = None Hf_ = None CO_ = None ################### Circuit Definition ####################################### # Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz # param: n_spin_orbs - The number of spin orbitals. # return: return a Qiskit circuit for this VQE ansatz def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1): # number of alpha spin orbitals norb_a = int(n_spin_orbs / 2) # construct the Hamiltonian qubit_op = ReadHamiltonian(n_spin_orbs) # allocate qubits num_qubits = n_spin_orbs qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"vqe-ansatz({method})-{num_qubits}-{circuit_id}") # initialize the HF state Hf = HartreeFock(num_qubits, na, nb) qc.append(Hf, qr) # form the list of single and double excitations excitationList = [] for occ_a in range(na): for vir_a in range(na, norb_a): excitationList.append((occ_a, vir_a)) for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_b, vir_b)) for occ_a in range(na): for vir_a in range(na, norb_a): for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_a, vir_a, occ_b, vir_b)) # get cluster operators in Paulis pauli_list = readPauliExcitation(n_spin_orbs, circuit_id) # loop over the Pauli operators for index, PauliOp in enumerate(pauli_list): # get circuit for exp(-iP) cluster_qc = ClusterOperatorCircuit(PauliOp, excitationList[index]) # add to ansatz qc.append(cluster_qc, [i for i in range(cluster_qc.num_qubits)]) # method 1, only compute the last term in the Hamiltonian if method == 1: # last term in Hamiltonian qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits) # return the circuit return qc_with_mea # now we need to add the measurement parts to the circuit # circuit list qc_list = [] diag = [] off_diag = [] global normalization normalization = 0.0 # add the first non-identity term identity_qc = qc.copy() identity_qc.measure_all() qc_list.append(identity_qc) # add to circuit list diag.append(qubit_op[1]) normalization += abs(qubit_op[1].coeffs[0]) # add to normalization factor diag_coeff = abs(qubit_op[1].coeffs[0]) # add to coefficients of diagonal terms # loop over rest of terms for index, p in enumerate(qubit_op[2:]): # get the circuit with expectation measurements qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits) # accumulate normalization normalization += abs(p.coeffs[0]) # add to circuit list if non-diagonal if not is_diag: qc_list.append(qc_with_mea) else: diag_coeff += abs(p.coeffs[0]) # diagonal term if is_diag: diag.append(p) # off-diagonal term else: off_diag.append(p) # modify the name of diagonal circuit qc_list[0].name = qubit_op[1].primitive.to_list()[0][0] + " " + str(np.real(diag_coeff)) normalization /= len(qc_list) return qc_list # Function that constructs the circuit for a given cluster operator def ClusterOperatorCircuit(pauli_op, excitationIndex): # compute exp(-iP) exp_ip = pauli_op.exp_i() # Trotter approximation qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip) # convert to circuit qc = qc_op.to_circuit(); qc.name = f'Cluster Op {excitationIndex}' global CO_ if CO_ == None or qc.num_qubits <= 4: if qc.num_qubits < 7: CO_ = qc # return this circuit return qc # Function that adds expectation measurements to the raw circuits def ExpectationCircuit(qc, pauli, nqubit, method=2): # copy the unrotated circuit raw_qc = qc.copy() # whether this term is diagonal is_diag = True # primitive Pauli string PauliString = pauli.primitive.to_list()[0][0] # coefficient coeff = pauli.coeffs[0] # basis rotation for i, p in enumerate(PauliString): target_qubit = nqubit - i - 1 if (p == "X"): is_diag = False raw_qc.h(target_qubit) elif (p == "Y"): raw_qc.sdg(target_qubit) raw_qc.h(target_qubit) is_diag = False # perform measurements raw_qc.measure_all() # name of this circuit raw_qc.name = PauliString + " " + str(np.real(coeff)) # save circuit global QC_ if QC_ == None or nqubit <= 4: if nqubit < 7: QC_ = raw_qc return raw_qc, is_diag # Function that implements the Hartree-Fock state def HartreeFock(norb, na, nb): # initialize the quantum circuit qc = QuantumCircuit(norb, name="Hf") # alpha electrons for ia in range(na): qc.x(ia) # beta electrons for ib in range(nb): qc.x(ib+int(norb/2)) # Save smaller circuit global Hf_ if Hf_ == None or norb <= 4: if norb < 7: Hf_ = qc # return the circuit return qc ################ Helper Functions # Function that converts a list of single and double excitation operators to Pauli operators def readPauliExcitation(norb, circuit_id=0): # load pre-computed data filename = os.path.join(f'ansatzes/{norb}_qubit_{circuit_id}.txt') with open(filename) as f: data = f.read() ansatz_dict = json.loads(data) # initialize Pauli list pauli_list = [] # current coefficients cur_coeff = 1e5 # current Pauli list cur_list = [] # loop over excitations for ext in ansatz_dict: if cur_coeff > 1e4: cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4: pauli_list.append(PauliSumOp.from_list(cur_list)) cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] else: cur_list.append((ext, ansatz_dict[ext])) # add the last term pauli_list.append(PauliSumOp.from_list(cur_list)) # return Pauli list return pauli_list # Get the Hamiltonian by reading in pre-computed file def ReadHamiltonian(nqubit): # load pre-computed data filename = os.path.join(f'Hamiltonians/{nqubit}_qubit.txt') with open(filename) as f: data = f.read() ham_dict = json.loads(data) # pauli list pauli_list = [] for p in ham_dict: pauli_list.append( (p, ham_dict[p]) ) # build Hamiltonian ham = PauliSumOp.from_list(pauli_list) # return Hamiltonian return ham # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def analyzer(qc,references,num_qubits): # total circuit name (pauli string + coefficient) total_name = qc.name # pauli string pauli_string = total_name.split()[0] # get the correct measurement if (len(total_name.split()) == 2): correct_dist = references[pauli_string] else: circuit_id = int(total_name.split()[2]) correct_dist = references[f"Qubits - {num_qubits} - {circuit_id}"] return correct_dist,total_name # Max qubits must be 12 since the referenced files only go to 12 qubits MAX_QUBITS = 12 method = 1 def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=2, max_circuits=max_circuits, num_shots=num_shots): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() max_qubits = max(max_qubits, min_qubits) # max must be >= min # validate parameters (smallest circuit is 4 qubits and largest is 10 qubits) max_qubits = min(max_qubits, MAX_QUBITS) min_qubits = min(max(4, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) if method == 2: max_circuits = 1 if max_qubits < 4: print(f"Max number of qubits {max_qubits} is too low to run method {method} of VQE algorithm") return global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for input_size in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # determine the number of circuits to execute for this group num_circuits = min(3, max_circuits) num_qubits = input_size fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # decides number of electrons na = int(num_qubits/4) nb = int(num_qubits/4) # random seed np.random.seed(0) numckts.append(num_circuits) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() # circuit list qc_list = [] # Method 1 (default) if method == 1: # loop over circuits for circuit_id in range(num_circuits): # construct circuit qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method) qc_single.name = qc_single.name + " " + str(circuit_id) # add to list qc_list.append(qc_single) # method 2 elif method == 2: # construct all circuits qc_list = VQEEnergy(num_qubits, na, nb, 0, method) print(qc_list) print(f"************\nExecuting [{len(qc_list)}] circuits with num_qubits = {num_qubits}") for qc in qc_list: print("*********************************************") #print(f"qc of {qc} qubits for qc_list value: {qc_list}") # get circuit id if method == 1: circuit_id = qc.name.split()[2] else: circuit_id = qc.name.split()[0] #creation time creation_time = time.time() - ts creation_times.append(creation_time) #print(qc) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value print("operations: ",operations) algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() # load pre-computed data if len(qc.name.split()) == 2: filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit.json') with open(filename) as f: references = json.load(f) else: filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit_method2.json') with open(filename) as f: references = json.load(f) #Correct distribution to compare with counts correct_dist,total_name = analyzer(qc,references,num_qubits) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist) print(fidelity_dict) # modify fidelity based on the coefficient if (len(total_name.split()) == 2): fidelity_dict *= ( abs(float(total_name.split()[1])) / normalization ) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nHartree Fock Generator 'Hf' ="); print(Hf_ if Hf_ != None else " ... too large!") print("\nCluster Operator Example 'Cluster Op' ="); print(CO_ if CO_ != None else " ... too large!") return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
import sys sys.path[1:1] = ["_common", "_common/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit"] from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import time import math import os import numpy as np np.random.seed(0) import execute as ex import metrics as metrics from collections import defaultdict from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule from qiskit_nature.circuit.library import HartreeFock as HF from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.transformers import ActiveSpaceTransformer from qiskit_nature.operators.second_quantization import FermionicOp from qiskit.opflow import PauliTrotterEvolution, CircuitStateFn, Suzuki from qiskit.opflow.primitive_ops import PauliSumOp # Function that converts a list of single and double excitation operators to Pauli operators def readPauliExcitation(norb, circuit_id=0): # load pre-computed data filename = os.path.join(os.getcwd(), f'../qiskit/ansatzes/{norb}_qubit_{circuit_id}.txt') with open(filename) as f: data = f.read() ansatz_dict = json.loads(data) # initialize Pauli list pauli_list = [] # current coefficients cur_coeff = 1e5 # current Pauli list cur_list = [] # loop over excitations for ext in ansatz_dict: if cur_coeff > 1e4: cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4: pauli_list.append(PauliSumOp.from_list(cur_list)) cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] else: cur_list.append((ext, ansatz_dict[ext])) # add the last term pauli_list.append(PauliSumOp.from_list(cur_list)) # return Pauli list return pauli_list # Get the Hamiltonian by reading in pre-computed file def ReadHamiltonian(nqubit): # load pre-computed data filename = os.path.join(os.getcwd(), f'../qiskit/Hamiltonians/{nqubit}_qubit.txt') with open(filename) as f: data = f.read() ham_dict = json.loads(data) # pauli list pauli_list = [] for p in ham_dict: pauli_list.append( (p, ham_dict[p]) ) # build Hamiltonian ham = PauliSumOp.from_list(pauli_list) # return Hamiltonian return ham def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1): ''' Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz :param n_spin_orbs:The number of spin orbitals :return: return a Qiskit circuit for this VQE ansatz ''' # allocate qubits num_qubits = n_spin_orbs qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name="main") # number of alpha spin orbitals norb_a = int(n_spin_orbs / 2) # number of beta spin orbitals norb_b = norb_a # construct the Hamiltonian qubit_op = ReadHamiltonian(n_spin_orbs) # initialize the HF state qc = HartreeFock(n_spin_orbs, na, nb) # form the list of single and double excitations singles = [] doubles = [] for occ_a in range(na): for vir_a in range(na, norb_a): singles.append((occ_a, vir_a)) for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): singles.append((occ_b, vir_b)) for occ_a in range(na): for vir_a in range(na, norb_a): for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): doubles.append((occ_a, vir_a, occ_b, vir_b)) # get cluster operators in Paulis pauli_list = readPauliExcitation(n_spin_orbs, circuit_id) # loop over the Pauli operators for index, PauliOp in enumerate(pauli_list): # get circuit for exp(-iP) cluster_qc = ClusterOperatorCircuit(PauliOp) # add to ansatz qc.compose(cluster_qc, inplace=True) # method 2, only compute the last term in the Hamiltonian if method == 2: # last term in Hamiltonian qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits) # return the circuit return qc_with_mea # now we need to add the measurement parts to the circuit # circuit list qc_list = [] diag = [] off_diag = [] for p in qubit_op: # get the circuit with expectation measurements qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits) # add to circuit list qc_list.append(qc_with_mea) # diagonal term if is_diag: diag.append(p) # off-diagonal term else: off_diag.append(p) return qc_list def ClusterOperatorCircuit(pauli_op): # compute exp(-iP) exp_ip = pauli_op.exp_i() # Trotter approximation qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip) # convert to circuit qc = qc_op.to_circuit() # return this circuit return qc # Function that adds expectation measurements to the raw circuits def ExpectationCircuit(qc, pauli, nqubit, method=1): # a flag that tells whether we need to perform rotation need_rotate = False # copy the unrotated circuit raw_qc = qc.copy() # whether this term is diagonal is_diag = True # primitive Pauli string PauliString = pauli.primitive.to_list()[0][0] # coefficient coeff = pauli.coeffs[0] # basis rotation for i, p in enumerate(PauliString): target_qubit = nqubit - i - 1 if (p == "X"): need_rotate = True is_diag = False raw_qc.h(target_qubit) elif (p == "Y"): raw_qc.sdg(target_qubit) raw_qc.h(target_qubit) need_rotate = True is_diag = False # perform measurements raw_qc.measure_all() # name of this circuit raw_qc.name = PauliString + " " + str(np.real(coeff)) return raw_qc, is_diag # Function that implements the Hartree-Fock state def HartreeFock(norb, na, nb): # initialize the quantum circuit qc = QuantumCircuit(norb) # alpha electrons for ia in range(na): qc.x(ia) # beta electrons for ib in range(nb): qc.x(ib+int(norb/2)) # return the circuit return qc import json from qiskit import execute, Aer backend = Aer.get_backend("qasm_simulator") precalculated_data = {} def run(min_qubits=4, max_qubits=4, max_circuits=3, num_shots=4092 * 2**8, method=2): print(f"... using circuit method {method}") # validate parameters (smallest circuit is 4 qubits) max_qubits = max(4, max_qubits) min_qubits = min(max(4, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even if method == 1: max_circuits = 1 # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for input_size in range(min_qubits, max_qubits + 1, 2): # determine the number of circuits to execute fo this group num_circuits = max_circuits num_qubits = input_size # decides number of electrons na = int(num_qubits/4) nb = int(num_qubits/4) # decides number of unoccupied orbitals nvira = int(num_qubits/2) - na nvirb = int(num_qubits/2) - nb # determine the size of t1 and t2 amplitudes t1_size = na * nvira + nb * nvirb t2_size = na * nb * nvira * nvirb # random seed np.random.seed(0) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() # circuit list qc_list = [] # method 1 (default) if method == 1: # sample t1 and t2 amplitude t1 = np.random.normal(size=t1_size) t2 = np.random.normal(size=t2_size) # construct all circuits qc_list = VQEEnergy(num_qubits, na, nb, 0, method) else: # loop over circuits for circuit_id in range(num_circuits): # sample t1 and t2 amplitude t1 = np.random.normal(size=t1_size) t2 = np.random.normal(size=t2_size) # construct circuit qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method) qc_single.name = qc_single.name + " " + str(circuit_id) # add to list qc_list.append(qc_single) print(f"************\nExecuting VQE with num_qubits {num_qubits}") for qc in qc_list: # get circuit id if method == 1: circuit_id = qc.name.split()[0] else: circuit_id = qc.name.split()[2] # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) job = execute(qc, backend, shots=num_shots) # executation result result = job.result() # get measurement counts counts = result.get_counts(qc) # initialize empty dictionary dist = {} for key in counts.keys(): prob = counts[key] / num_shots dist[key] = prob # add dist values to precalculated data for use in fidelity calculation precalculated_data[f"{circuit_id}"] = dist with open(f'precalculated_data_qubit_{num_qubits}_method1.json', 'w') as f: f.write(json.dumps( precalculated_data, sort_keys=True, indent=4, separators=(',', ': ') )) run()
https://github.com/xin-0/QC-jupyter
xin-0
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, execute, BasicAer from qiskit.visualization import plot_bloch_multivector, plot_histogram circ = QuantumCircuit(2) circ.x(0) circ.x(1) circ.h(0) circ.cx(0,1) circ.measure_all() circ.draw("mpl") res_sim = BasicAer.get_backend("qasm_simulator") counts = execute(circ,backend=res_sim,shots=1024).result().get_counts() plot_histogram(counts) def state_prepare(qc:QuantumCircuit, reg0, reg1): qc.x(reg0) qc.x(reg1) qc.h(reg0) qc.cx(reg0, reg1) return def AB_gates(qc:QuantumCircuit, a, b): qc.z(a) qc.h(b) return qc = QuantumCircuit(2) state_prepare(qc,0,1) qc.barrier() AB_gates(qc,0,1) qc.measure_all() qc.draw("mpl") from qiskit.aqua.operators import Z, X, H, One, Zero operator = - Z ^ H psi = 1 / np.sqrt(2) * ((Zero ^ One) - (One ^ Zero)) mu = (~psi @ operator @ psi).eval() print(mu.real) operator = - Z ^ (X@H@X) psi = 1 / np.sqrt(2) * ((Zero ^ One) - (One ^ Zero)) mu = (~psi @ operator @ psi).eval() print(mu.real) operator = X psi = Zero mu = (~psi @ operator @ psi).eval() print(mu.real)
https://github.com/xin-0/QC-jupyter
xin-0
import numpy as np from math import pi from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, BasicAer, execute, IBMQ from qiskit.visualization import plot_bloch_multivector, plot_histogram def pe_circ_init(size:int): #quantum register and single state for storing eigen-state qr = QuantumRegister(size) psi = QuantumRegister(1,name="psi") #classical bits for readout cr = ClassicalRegister(size) qc = QuantumCircuit(qr,psi,cr) # apply Hadamards and init the eigenstate as |1> for i in range(size): qc.h(i) qc.x(size) qc.barrier() return qc def C_U(circuit:QuantumCircuit, size:int, phi:float): rep = 1 for counting_qubit in range(size): for i in range(rep): circuit.cu1(2*pi*phi, counting_qubit, size) rep *= 2 circuit.barrier() return def qft_dagger(qc:QuantumCircuit,size:int): for qubit in range(size//2): qc.swap(qubit,size-qubit-1) for j in range(size): for m in range(j): qc.cu1(-pi/float(2**(j-m)), m, j) qc.h(j) qc.barrier() return def readout(qc:QuantumCircuit,size:int): for i in range(size): qc.measure(i,i) return def phaseEstCircuit(size:int, phi:float): qc = pe_circ_init(size) C_U(qc, size, phi) qft_dagger(qc, size) readout(qc,size) return qc def counts_decode(counts): decoded = {} for key in counts: decimal_key = 0.0 i = -1 for c in key: b = int(c) if b: decimal_key += 2**i i -= 1 decoded[decimal_key] = counts[key] return decoded def expectation(decode_counts): res = 0.0 total = 0 for key in decode_counts: total += decode_counts[key] res += key*decode_counts[key] return res/total def choosemax(decode_counts): counts = 0 result = 0.0 for key in decode_counts: if decode_counts[key] > counts: counts = decode_counts[key] result = key return result def getEstPhi(PhaseEstQC:QuantumCircuit, back_end, shots, metric): # get backend result = execute(qc,backend=back_end,shots=shots).result() counts = result.get_counts() plot_histogram(counts) dt = counts_decode(counts) est_val = metric(dt) return est_val qubit = 4 nTrail = 20 back_end = BasicAer.get_backend("qasm_simulator") shots = 4096 Phi = np.random.random((nTrail,)) Phi_est = [] for phi in Phi: qc = phaseEstCircuit(qubit, phi) single_run_res = getEstPhi(qc, back_end,shots,metric=choosemax) Phi_est.append(single_run_res) Phi_est = np.array(Phi_est) error = np.abs(Phi_est-Phi)/Phi print(Phi) print(Phi_est) print(error) qubit = 5 nTrail = 20 back_end = BasicAer.get_backend("qasm_simulator") shots = 4096 Phi_est = [] for phi in Phi: qc = phaseEstCircuit(qubit, phi) single_run_res = getEstPhi(qc, back_end,shots,metric=choosemax) Phi_est.append(single_run_res) Phi_est = np.array(Phi_est) error = np.abs(Phi_est-Phi)/Phi print(Phi) print(Phi_est) print(error) qubit = 6 nTrail = 20 back_end = BasicAer.get_backend("qasm_simulator") shots = 4096 Phi_est = [] for phi in Phi: qc = phaseEstCircuit(qubit, phi) single_run_res = getEstPhi(qc, back_end,shots,metric=choosemax) Phi_est.append(single_run_res) Phi_est = np.array(Phi_est) error = np.abs(Phi_est-Phi)/Phi print(Phi) print(Phi_est) print(error) qubit = 7 nTrail = 20 back_end = BasicAer.get_backend("qasm_simulator") shots = 4096 Phi_est = [] for phi in Phi: qc = phaseEstCircuit(qubit, phi) single_run_res = getEstPhi(qc, back_end,shots,metric=choosemax) Phi_est.append(single_run_res) Phi_est = np.array(Phi_est) error = np.abs(Phi_est-Phi)/Phi print(Phi) print(Phi_est) print(error) qubit = 8 nTrail = 20 back_end = BasicAer.get_backend("qasm_simulator") shots = 4096 Phi_est = [] for phi in Phi: qc = phaseEstCircuit(qubit, phi) single_run_res = getEstPhi(qc, back_end,shots,metric=choosemax) Phi_est.append(single_run_res) Phi_est = np.array(Phi_est) error = np.abs(Phi_est-Phi)/Phi print(Phi) print(Phi_est) print(error) def get_error(size, Phi, back_end, shots, metric): Phi_est = [] for phi in Phi: qc = phaseEstCircuit(qubit, phi) qc.draw() single_run_res = getEstPhi(qc, back_end,shots,metric) Phi_est.append(single_run_res) Phi_est = np.array(Phi_est) return np.abs(Phi_est-Phi)/Phi error_4 = get_error(size=4, Phi=Phi, back_end=back_end,shots=2048,metric=choosemax) error_5 = get_error(size=5, Phi=Phi, back_end=back_end,shots=2048,metric=choosemax) error_6 = get_error(size=6, Phi=Phi, back_end=back_end,shots=2048,metric=choosemax) import matplotlib.pyplot as plt plt.plot(Phi,error_4,'rs',Phi,error_5,'bs',Phi,error_6,'gs') error_4 error_5
https://github.com/xin-0/QC-jupyter
xin-0
import numpy as np from qiskit.tools.jupyter import * from qiskit import IBMQ # ibm account manager # - communicate with online account # - store/delete # - enable/disenable # - communicate with ibmq online devices, quantum computers # - get actual quantum computers as backend IBMQ.load_account() provider = IBMQ.ibmq.get_provider(hub='ibm-q', group='open', project='main') provider.backends() backend = provider.get_backend('ibmq_bogota') back_config = backend.configuration() print("number of qubit: ", back_config.n_qubits) print("support open pulse?: ", back_config.open_pulse) print("basic gate set: ", back_config.basis_gates) dt = back_config.dt print(f"Sampling time: {dt*1e9} ns") back_defualt = backend.defaults() # frequncies for all the 5 qubits back_defualt.qubit_freq_est GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz us = 1.0e-6 # Microsecond ns = 1.0e-9 # Nanosecond # the index of the qubit in backend that we want to find frequency with qubitIdx = 4 mem_slot = 0 # define the search range and get a list of frequencies center_f_Hz = back_defualt.qubit_freq_est[qubitIdx] f_span = 50 * MHz f_step = 1 * MHz f_min = center_f_Hz - f_span/2 f_max = center_f_Hz + f_span/2 frequencies_GHz = np.arange(f_min/GHz, f_max/GHz, f_step/GHz) print(f"We'll measure the {qubitIdx}th qubit in {back_config.backend_name} \n") print(f"sweep from {frequencies_GHz[0]} GHz to {frequencies_GHz[-1]} GHz with approximated frequncy {center_f_Hz/GHz} GHz") # samples need to be multiples of 16 def get_closest_multiple_of_16(num): return int(num + 8 ) - (int(num + 8 ) % 16) from qiskit import pulse from qiskit.circuit import Parameter drive_sigma_sec = 0.075 * us drive_duration_sec = 8 * drive_sigma_sec drive_amp =0.05 freq = Parameter('freq') with pulse.build(backend=backend, default_alignment='sequential', name='freq_sweep') as sweep_plan: drive_duration = get_closest_multiple_of_16(pulse.seconds_to_samples(drive_duration_sec)) drive_sigma = pulse.seconds_to_samples(drive_sigma_sec) drive_chan = pulse.drive_channel(qubitIdx) pulse.set_frequency(freq, drive_chan) pulse.play(pulse.Gaussian( duration=drive_duration, sigma=drive_sigma, amp=drive_amp, name='freq_sweep_excitation_pulse' ),channel=drive_chan) pulse.measure(qubits=[qubitIdx], registers=[pulse.MemorySlot(mem_slot)]) frequencies_Hz = frequencies_GHz * GHz schedules = [sweep_plan.assign_parameters({freq: f}, inplace=False) for f in frequencies_Hz] schedules[0].draw(backend=backend)
https://github.com/xin-0/QC-jupyter
xin-0
# circuit construction and execution: # - circuit, register, classical bit, executor, simulator from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer # Visualization: # - basis amplitudes, bloch vector from qiskit.visualization import plot_histogram, plot_bloch_multivector # Input state initialization: # - initial psi from qiskit.extensions import Initialize # initialized state are numpy complex arrays import numpy as np # state vector presentation from qiskit_textbook.tools import array_to_latex, random_state # construct quantum teleportation circuit def qtel(state): # circuit initialization psi = QuantumRegister(1,name="psi") alice = QuantumRegister(1,name="alice") bob = QuantumRegister(1,name="bob") crx = ClassicalRegister(1, name="crx") crz = ClassicalRegister(1, name="crz") res = ClassicalRegister(1, name="result") qtel_circ = QuantumCircuit(psi,alice,bob,crx,crz,res) #step 0 initialize psi init_gate = Initialize(state) init_gate.label = "init" qtel_circ.append(init_gate, [0]) qtel_circ.barrier() # step 1 prepare bell state between alice and bob qtel_circ.h(alice) qtel_circ.cx(alice,bob) qtel_circ.barrier() # step 2 alice gate qtel_circ.cx(psi,alice) qtel_circ.h(psi) qtel_circ.barrier() #step 3 meaure as classical bits qtel_circ.measure(alice,crx) qtel_circ.measure(psi,crz) qtel_circ.barrier() #step 4 bob gate qtel_circ.x(bob).c_if(crx,1) qtel_circ.z(bob).c_if(crz,1) reverse_init = init_gate.gates_to_uncompute() qtel_circ.append(reverse_init,[2]) qtel_circ.measure(bob,res) return qtel_circ # state initialization psi = random_state(1) #viz array_to_latex(psi, pretext="\\vert\\psi\\rangle =") plot_bloch_multivector(psi) circ = qtel(psi) circ.draw("mpl") # set up simulator state_sim_back = BasicAer.get_backend("statevector_simulator") res_vetor = execute(circ, backend=state_sim_back).result().get_statevector() plot_bloch_multivector(res_vetor) circ_sim_back = BasicAer.get_backend("qasm_simulator") counts = execute(circ, backend=circ_sim_back, shots=1024).result().get_counts() plot_histogram(counts) def modified_qtel(state): qc = QuantumCircuit(3,1) init_gate =Initialize(state) init_gate.label = "init" qc.append(init_gate, [0]) qc.barrier() qc.h(1) qc.cx(1,2) qc.barrier() qc.cx(0,1) qc.h(0) qc.barrier() qc.cx(1,2) qc.cz(0,2) qc.barrier() reverse_init_gate = init_gate.gates_to_uncompute() qc.append(reverse_init_gate,[2]) qc.measure(2,0) return qc circ_hard = modified_qtel(psi) circ_hard.draw("mpl") from qiskit import IBMQ IBMQ.enable_account(token='') IBMQ.save_account(token='',overwrite=True) IBMQ.stored_account() IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') from qiskit.providers.ibmq import least_busy backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and not b.configuration().simulator and b.status().operational==True)) job_exp = execute(circ_hard, backend=backend, shots=8192) from qiskit.tools.monitor import job_monitor job_monitor(job_exp) # displays job status under cell # Get the results and display them exp_result = job_exp.result() exp_measurement_result = exp_result.get_counts(circ_hard) print(exp_measurement_result) plot_histogram(exp_measurement_result)
https://github.com/trevorpiltch/Grovers-Algorithm
trevorpiltch
from qiskit import * from math import pi def amplifier(n): """Creates a general diffuser using V and V-Dagger gates""" circuit = QuantumCircuit(n) circuit.x(range(n)) #V circuit.cu1(pi/4, 0, 3) #V-dagger circuit.cx(0, 1) circuit.cu1(-pi/4, 1, 3) circuit.cx(0, 1) # V circuit.cu1(pi/4, 1, 3) #V-dagger circuit.cx(1, 2) circuit.cu1(-pi/4, 2, 3) # V circuit.cx(0, 2) circuit.cu1(pi/4, 2, 3) #V-dagger circuit.cx(1, 2) circuit.cu1(-pi/4, 2, 3) # V circuit.cx(0, 2) circuit.cu1(pi/4, 2, 3) circuit.x(range(n)) amplification = circuit.to_gate() amplification.name = 'Amplification' return amplification
https://github.com/trevorpiltch/Grovers-Algorithm
trevorpiltch
from qiskit import * def init(qc, n): """Prepares qubits for algorithm""" qc.x(n) qc.barrier() qc.h(range(n+1)) qc.barrier()
https://github.com/trevorpiltch/Grovers-Algorithm
trevorpiltch
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/trevorpiltch/Grovers-Algorithm
trevorpiltch
from qiskit import * def oracle(n, target_binary): """Creates an oracle based on the implementation here: https://github.com/SaashaJoshi/grovers-algorithm""" circuit = QuantumCircuit(n + 1) for index, value in reversed(list(enumerate(target_binary))): if value == '0': circuit.x(n-1-index) cbits = [] for i in range(n): cbits.append(i) circuit.mct(cbits, n, n) for index, value in enumerate(target_binary): if value == '0': circuit.x(n-1-index) gate = circuit.to_gate() gate.name = 'Oracle' return gate
https://github.com/trevorpiltch/Grovers-Algorithm
trevorpiltch
from qiskit import * def get_result(qc, shots=1024): """Runs the circuit on the simulator""" backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend, shots = shots).result() counts = result.get_counts() return counts def parse_result(counts, p=False): """Returns the maximum value found and optionally prints all results""" max = [0, 0] for i in counts: num = int(i, 2) key = str(num) value = str(counts[i]) if (int(counts[i]) > int(max[1])): max[0] = num max[1] = value if p: print(key + ": " + value) return max
https://github.com/Harshithan07/Quantum-Computing-using-Qiskit-SDK
Harshithan07
from qiskit import * from qiskit.tools.visualization import plot_histogram %matplotlib inline secretnumber = '11100011' circuit = QuantumCircuit(len(secretnumber)+1,len(secretnumber)) circuit.h(range(len(secretnumber))) circuit.x(len(secretnumber)) circuit.h(len(secretnumber)) circuit.barrier() for ii, yesno in enumerate(reversed(secretnumber)): if yesno == '1': circuit.cx(ii,len(secretnumber)) circuit.barrier() circuit.h(range(len(secretnumber))) circuit.barrier() circuit.measure(range(len(secretnumber)),range(len(secretnumber))) circuit.draw(output = 'mpl')
https://github.com/Harshithan07/Quantum-Computing-using-Qiskit-SDK
Harshithan07
import qiskit qiskit.__qiskit_version__ from qiskit import IBMQ IBMQ.save_account('46fd3c15ef48cd5f5d6e4a8ae48748af512d2a57b1647282d61d7e98fda97a54d4be4ab8ff433fccd6613f9e30b3819a1aef9d6262f4980804cb2cd3952f7850') IBMQ.load_account() from qiskit import * qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr,cr) %matplotlib inline circuit.draw() circuit.h(qr[0]) #hadamard gate circuit.draw(output = 'mpl') circuit.cx(qr[0],qr[1]) #controlled X gate circuit.draw(output = 'mpl') circuit.measure(qr,cr) circuit.draw(output = 'mpl') #setting up simulator simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend = simulator).result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) provider = IBMQ.get_provider('ibm-q') # Get a list of available backends backends = provider.backends() # Print the names of available backends print("Available Backends:", [backend.name() for backend in backends]) qcomp = provider.get_backend('ibm_osaka') job = execute(circuit, backend = qcomp) from qiskit.tools.monitor import job_monitor job_monitor(job) results = job.result() plot_histogram(results.get_counts(circuit))
https://github.com/Harshithan07/Quantum-Computing-using-Qiskit-SDK
Harshithan07
from qiskit import * IBMQ.load_account() from qiskit.tools.visualization import plot_bloch_multivector circuit = QuantumCircuit(1,1) circuit.x(0) simulator = Aer.get_backend('statevector_simulator') result = execute(circuit, backend = simulator).result() statevector = result.get_statevector() print(statevector) %matplotlib inline circuit.draw(output = 'mpl') plot_bloch_multivector(statevector) circuit.measure([0],[0]) simulator = Aer.get_backend('qasm_simulator') results = execute(circuit, backend = simulator, shots = 1024).result() count = result.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(count) circuit = QuantumCircuit(1,1) circuit.x(0) simulator = Aer.get_backend('unitary_simulator') result = execute(circuit, backend = simulator).result() unitary = result.get_unitary() print(unitary)
https://github.com/Harshithan07/Quantum-Computing-using-Qiskit-SDK
Harshithan07
from qiskit import * circuit = QuantumCircuit(3,3) %matplotlib inline circuit.draw(output='mpl') circuit.x(0) circuit.barrier() circuit.draw(output='mpl') circuit.h(1) circuit.cx(1,2) circuit.draw(output='mpl') circuit.cx(0,1) circuit.h(0) circuit.draw(output='mpl') circuit.barrier() circuit.measure([0,1],[0,1]) circuit.draw(output='mpl') circuit.barrier() circuit.cx(1,2) circuit.cz(0,2) circuit.draw(output='mpl') circuit.measure(2,2) simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator,shots=1024).result() counts = result.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) print(counts)
https://github.com/55blabs/grovers-algothrim
55blabs
#Classical vs Quantum Computer #!/usr/bin/env python # coding: utf-8 # In[2]: #simple unordered list of elements my_list = [1, 3, 5, 2, 4, 9, 5, 8, 0, 7] # In[4]: #defining my varibale #set wining number you would like def the_oracle(my_input): winner=7 if my_input is winner: response = True else: response = False return response # In[25]: #Classical computer enumeration on a winning number for index, trial_number in enumerate(my_list): if the_oracle(trial_number) is True: print('winner winner found at index %i'%index) print('%i calls to the oracle used' % (index+1)) break # In[26]: #Transistion to Qiskit Aer #import dependencies from qiskit import * import matplotlib.pyplot as plt import numpy as np # In[11]: #define the oracle circuit oracle = QuantumCircuit(2, name='oracle') oracle.cz(0,1) oracle.to_gate() oracle.draw() # In[13]: backend = Aer.get_backend('statevector_simulator') grover_circ = QuantumCircuit(2,2) grover_circ.h([0, 1]) grover_circ.append(oracle, [0, 1]) grover_circ.draw() # In[15]: job = execute(grover_circ, backend) result = job.result() # In[16]: sv = result.get_statevector() np.around(sv, 2) # In[18]: #Grovers Diffusion Operator [Operator] + [Reflection] reflection = QuantumCircuit(2, name='reflection') reflection.h([0, 1]) reflection.z([0,1]) reflection.cz(0,1) reflection.h([0,1]) reflection.to_gate() # In[20]: reflection.draw() # In[22]: backend = Aer.get_backend('qasm_simulator') grover_circ = QuantumCircuit(2, 2) grover_circ.h([0,1]) grover_circ.append(oracle, [0, 1]) grover_circ.append(reflection, [0, 1]) grover_circ.measure([0, 1], [0,1]) # In[23]: grover_circ.draw() # In[24]: job=execute(grover_circ,backend,shots=1) result=job.result() result.get_counts() # In[ ]:
https://github.com/theRealNoah/qiskit-grovers-3by3
theRealNoah
# Quantum Computing and Communications Term Project # Spring 2021 by Noah Hamilton # Inspired by https://qiskit.org/textbook/ch-algorithms/grover.html#sudoku # This is the code for the implementation of the Grover's Algorithm solving a # 3x3 Binary Sudoku. # Problem Environment + Rules # Each Column must contain exactly one 1. # Each Row must contain exactly one 1. # ---------------- # | v0 | v1 | v2 | # ---------------- # | v3 | v4 | v5 | # ---------------- # | v6 | v7 | v8 | # ---------------- # For this simulation, we will use the Qiskit library and the IBMQ Simulator. import qiskit as q import matplotlib.pyplot as plt from qiskit import IBMQ import numpy as np from qiskit.quantum_info.operators import Operator plt.close() IBMQ.save_account( 'ab770cdeb560aa1f1dfff99b0076fa95172a84dfaabe83d593e234549f5601d05f921e4c76a38cb4e02951c0a7b137aa30730e739c527cdffbf32495adb77896', overwrite=True) # After defining the problem, the first step is to create an oracle. # Need to create a classical function that checks whether the state of our # variables is a valid solution. # To do this we first need to define the conditions to check: # for each row/column the solutions can boil down to # ((NOT A) AND (B XOR C) OR ((NOT C) AND (A XOR B )) # So, check each row and column for this condition. # List of all rows and Columns # 1st Row - [v0, v1, v2] # 2nd Row - [v3, v4, v5] # 3rd Row - [v6, v7, v8] # 1st Col - [v0, v3, v6] # 2nd Col - [v1, v4, v7] # 3rd Col - [v2, v5, v8] # To make things simpler, I'm creating a compiled list of clauses clause_list = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8]] # Assigning the value of each variable to a bit in our circuit. # We need to define a function that will check if exactly one of these is true. # The final output should be the Quantum Equivalent of Classical: # ((NOT A) AND (B XOR C) OR ((NOT C) AND (A XOR B )) # The NOT Gate in classical can be represented by an X Gate (NOT) # The XOR Gate can be represented by the combination of 2 CX (CNOT) # The AND Gate can be implemented using a Toffoli Gate ccx (CCNOT) # No current quantum gates are explicit creations of an OR Gate because all # operations must be reversible. # To create the OR Logic, we need to use a unitary matrix using the Operator # class and use an Ancilla Bit (extra bit) # Ancilla Bit - https://en.wikipedia.org/wiki/Ancilla_bit # Credit: https://quantumcomputing.stackexchange.com/a/5834 OR_Unitary_Matrix = [[0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1] ] OR_Operator = Operator(OR_Unitary_Matrix) print('The OR Operator Created is a Unitary operator:', OR_Operator.is_unitary()) # Parameters: # qc: Quantum Circuit Element # a: First bit # b: Second bit # c: Third bit # ancilla_1 - ancilla_3 --- extra qubits needed for processing. # out_qubit: Output # def OnlyOneTrue(qc, a, b, c, ancilla_1, ancilla_2, ancilla_3, out_qubit): # # NOT A # qc.x(a) # # B XOR C # # ancilla_1 will be flipped only if b and c are different. # qc.cx(b, ancilla_1) # qc.cx(c, ancilla_1) # # NOT A AND (B XOR C) - stored in ancilla_2 # qc.ccx(a, ancilla_1, ancilla_2) # # RESET ancilla_1 will be flipped back only if b and c are different. # qc.cx(b, ancilla_1) # qc.cx(c, ancilla_1) # # Need to undo NOT A for second half. # qc.x(a) # # NOT C # qc.x(c) # # A XOR B # # ancilla_1 will be flipped only if b and a are different. # qc.cx(a, ancilla_1) # qc.cx(b, ancilla_1) # # NOT C AND (B XOR A) - stored in ancilla_3 # qc.ccx(c, ancilla_1, ancilla_3) # # RESET ancilla_1 will be flipped only if b and a are different. # qc.cx(a, ancilla_1) # qc.cx(b, ancilla_1) # # OR Operation # qc.append(OR_Operator, [ancilla_2, ancilla_3, out_qubit]) # qc.x(c) # Reset Value of C def OnlyOneTrue(qc, a, b, c, ancilla_2, ancilla_3, out_qubit): # NOT A qc.x(a) # B XOR C # ancilla_1 will be flipped only if b and c are different. qc.cx(b, out_qubit) qc.cx(c, out_qubit) # NOT A AND (B XOR C) - stored in ancilla_2 qc.ccx(a, out_qubit, ancilla_2) # RESET ancilla_1 will be flipped back only if b and c are different. qc.cx(b, out_qubit) qc.cx(c, out_qubit) # Need to undo NOT A for second half. qc.x(a) # NOT C qc.x(c) # A XOR B # ancilla_1 will be flipped only if b and a are different. qc.cx(a, out_qubit) qc.cx(b, out_qubit) # NOT C AND (B XOR A) - stored in ancilla_3 qc.ccx(c, out_qubit, ancilla_3) # RESET ancilla_1 will be flipped only if b and a are different. qc.cx(a, out_qubit) qc.cx(b, out_qubit) # OR Operation qc.append(OR_Operator, [ancilla_2, ancilla_3, out_qubit]) qc.x(c) # Reset Value of C # Define a Diffuser to be used with N Qubits def diffuser(nqubits): qc = q.QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "U$_s$" return U_s # # Testing that the OnlyOneTrue function works # # Displays Quantum Equivalent Circuit # in_qubits = q.QuantumRegister(3, name='input') # ancilla_qubits = q.QuantumRegister(4, name='ancilla') # out_qubit = q.QuantumRegister(1, name='output') # qc = q.QuantumCircuit(in_qubits, ancilla_qubits, out_qubit) # OnlyOneTrue(qc, in_qubits[0], in_qubits[1], in_qubits[2], ancilla_qubits[0], # ancilla_qubits[1], ancilla_qubits[2], ancilla_qubits[3], out_qubit) # qc.draw(output='mpl') # plt.title( # 'Quantum Equivalent of Classical: ((NOT A) AND (B XOR C) OR ((NOT C) AND (A XOR B ))') # Create separate registers to name bits var_qubits = q.QuantumRegister(9, name='v') ancilla_qubits = q.QuantumRegister(12, name='ancilla') clause_qubits = q.QuantumRegister(6, name='c') output_qubit = q.QuantumRegister(1, name='out') cbits = q.ClassicalRegister(9, name='cbits') # Create Quantum Circuit qc = q.QuantumCircuit(var_qubits, ancilla_qubits, clause_qubits, output_qubit, cbits) # Initialize 'out0' in state |-> qc.initialize([1, -1]/np.sqrt(2), output_qubit) # Initialize qubits in state |s> qc.h(var_qubits) qc.barrier() # For Visual Separation (may remove later) # Next, create a checking circuit using the Oracle using phase kickback def sudoku_oracle(qc, clause_list, clause_qubits): # Use OnlyOneTrue gate to check each clause i = 0 for clause in clause_list: OnlyOneTrue(qc, clause[0], clause[1], clause[2], ancilla_qubits[2*i], ancilla_qubits[2*i + 1], clause_qubits[i]) i += 1 # Flip 'output' bit if all classes are satisfied qc.mct(clause_qubits, output_qubit) # Uncompute clauses to reset clause-checking bits to 0 i = 0 for clause in clause_list: OnlyOneTrue(qc, clause[0], clause[1], clause[2], ancilla_qubits[2*i], ancilla_qubits[2*i + 1], clause_qubits[i]) i += 1 # First Iteration # Apply our oracle sudoku_oracle(qc, clause_list, clause_qubits) qc.barrier() # For Visual Separation (may remove later) # Apply our diffuser qc.append(diffuser(9), [0, 1, 2, 3, 4, 5, 6, 7, 8]) # Second Iteration sudoku_oracle(qc, clause_list, clause_qubits) qc.barrier() # for visual separation # Apply our diffuser qc.append(diffuser(9), [0, 1, 2, 3, 4, 5, 6, 7, 8]) # Measure the variable qubits qc.measure(var_qubits, cbits) # qc.draw(output='mpl', fold=-1) ############################################################ # # Select the AerSimulator from the Aer provider # backend = q.Aer.get_backend('statevector_simulator') # backend.MAX_QUBIT_MEMORY = 32 # shots = 1024 # job = q.execute(qc, backend) # # try: # # job_status = job.status() # Query the backend server for job status. # # if job_status is q.JobStatus.RUNNING: # # print("The job is still running") # # except IBMQJobApiError as ex: # # print("Something wrong happened!: {}".format(ex)) # result = job.result() # q.visualization.plot_histogram(result.get_counts()) # # Run and get counts, using the matrix_product_state method ############################################################## #tcirc = q.transpile(qc, simulator) # result = simulator.run(qc).result() # Simulate and Plot Results # The QASM_Simulator only supports up to 32 qubits. I currently use 34. qasm_simulator = q.Aer.get_backend('qasm_simulator') transpiled_qc = q.transpile(qc, qasm_simulator) qobj = q.assemble(transpiled_qc) result = qasm_simulator.run(qobj).result() # Simulate the Circuit using the open-source QASM Simulator provided by IBM Q. # simulator = q.Aer.get_backend('qasm_simulator') # results = q.execute(circuit, backend=simulator).result() # q.visualization.plot_histogram(results.get_counts(circuit)) # Used for showing Circuits and Histograms. plt.show()
https://github.com/Yadu9238/Shor-Algo
Yadu9238
from qiskit import BasicAer from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import Shor N = 15 shor = Shor(N) backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024) ret = shor.run(quantum_instance) print("The list of factors of {} as computed by the Shor's algorithm is {}.".format(N, ret['factors'][0]))
https://github.com/darkmatter2000/Quantum_phase_estimation
darkmatter2000
from qiskit import ClassicalRegister , QuantumCircuit, QuantumRegister import numpy as np qr = QuantumRegister(2) cr = ClassicalRegister(3) #For tree classicals bites qc = QuantumCircuit(qr , cr) qc.h(qr[0]) #auxiliary qubit qc.x(qr[1]) # eigenvector #qc.cp((3/2)*np.pi , qr[0] , qr[1]) qc.cp(3*np.pi , qr[0] , qr[1]) qc.h(qr[0]) qc.measure(qr[0] , cr[0]) # this is the controlled-U^(2^n-1) operator for determine phi_n qc.draw("mpl") qc.reset(qr[0]) qc.h(qr[0]) # la valeur du bit du poids le plus faible est dans cr[0]. #Si cr[0] = 1 on enléve le bit de poids le plus faible en fesant la rotation alpha_2 #et on continu le bit n-1 devient le bit le bit de poids le plus faible #si cr[0] est à 0 alors on peut appliquer directement la matrice unitaire associé sans avoir #à faire de rotation inverse alpha_k with qc.if_test((cr[0] , 1)) as else_: qc.p(-np.pi/2 , qr[0]) #qc.cp((3/8)*np.pi , qr[0] ,qr[1]) qc.cp((3/2)*np.pi , qr[0] ,qr[1]) qc.h(qr[0]) # For make measure in X basis {|0> , |1>} qc.measure(qr[0] , cr[1]) qc.draw("mpl") qc.reset(qr[0]) qc.h(qr[0]) # la valeur du bit du poids le plus faible est dans cr[0]. #Si cr[0] = 1 on enléve le bit de poids le plus faible en fesant la rotation alpha_2 #et on continu le bit n-1 devient le bit le bit de poids le plus faible #si cr[0] est à 0 alors on peut appliquer directement la matrice unitaire associé sans avoir #à faire de rotation inverse alpha_k with qc.if_test((cr[1] , 1)) as else_: qc.p(-(3/4)*np.pi , qr[0]) qc.cp((3/4)*np.pi , qr[0] ,qr[1]) qc.h(qr[0]) # For make measure in X basis {|0> , |1>} qc.measure(qr[0] , cr[2]) qc.draw("mpl") from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() counts import qiskit.tools.jupyter %qiskit_version_table
https://github.com/topgun007-oss/Quantum-gates
topgun007-oss
from qiskit import * from qiskit.visualization import plot_bloch_multivector, plot_histogram from qiskit.tools.monitor import job_monitor from matplotlib import style style.use('dark_background') qc = QuantumCircuit(1,1) qc.h(0) qc.measure([0], [0]) qc.draw('mpl') qasm_simulator = Aer.get_backend('qasm_simulator') job = execute(qc, qasm_simulator, shots = 1000) output = job.result() counts = output.get_counts(qc) plot_histogram(counts) qc1 = QuantumCircuit(1,1) qc1.x(0) qc1.measure([0], [0]) display(qc1.draw('mpl')) counts = execute(qc1, qasm_simulator, shots = 10000).result().get_counts(qc1) plot_histogram(counts) qc2 = QuantumCircuit(2, 2) qc2.h(0) qc2.y(1) qc2.measure([0,1], [0,1]) display(qc2.draw('mpl')) counts = execute(qc2, qasm_simulator, shots = 10000).result().get_counts(qc2) plot_histogram(counts) from qiskit import * from qiskit.visualization import plot_bloch_multivector, plot_histogram from qiskit.tools.monitor import job_monitor from matplotlib import style style.use('dark_background') qc3 = QuantumCircuit(2,2) qc3.cx(0,1) qc3.measure([0,1], [0,1]) display(qc3.draw('mpl')) counts = execute(qc3, qasm_simulator, shots = 10).result().get_counts(qc3) plot_histogram(counts) #now applying the X gate first qc3 = QuantumCircuit(2,2) qc3.x(0) qc3.cx(0,1) qc3.measure([0,1], [0,1]) display(qc3.draw('mpl')) counts = execute(qc3, qasm_simulator, shots = 10).result().get_counts(qc3) plot_histogram(counts) from qiskit import * from qiskit.visualization import plot_bloch_multivector, plot_histogram from qiskit.tools.monitor import job_monitor from matplotlib import style style.use('dark_background') qc4 = QuantumCircuit(3,3) qc4.ccx(0,1,2) qc4.measure([0,1,2], [0,1,2]) display(qc4.draw('mpl')) counts = execute(qc4, qasm_simulator, shots = 10).result().get_counts(qc4) plot_histogram(counts) import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import IBMQ, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex,plot_bloch_vector from qiskit.extensions import Initialize qureg = QuantumRegister(3, 'q') cr1 = ClassicalRegister(1, name="cr1") cr2 = ClassicalRegister(1, name="cr2") circuit = QuantumCircuit(qureg, cr1,cr2) circuit.draw('mpl') plot_bloch_multivector([(1/9)**0.5 , (8/9)**0.5]) circuit.initialize([(1/9)**0.5 , (8/9)**0.5],0) #initializing the bloch vector and making the circuit for teleportation circuit.h(qureg[1]) circuit.cx(qureg[1], qureg[2]) circuit.barrier(qureg[1], qureg[0], qureg[2]) circuit.cx(qureg[0], qureg[1]) circuit.h(qureg[0]) circuit.barrier(qureg[1], qureg[0], qureg[2]) circuit.measure(qureg[0], cr1) circuit.measure(qureg[1], cr2) circuit.draw('mpl') circuit.x(qureg[2]).c_if(cr1, 1)#applying the condition to get the info from alice to bob circuit.z(qureg[2]).c_if(cr2, 1) circuit.draw('mpl') sim = Aer.get_backend('aer_simulator') circuit.save_statevector() out_vector = sim.run(circuit).result().get_statevector() plot_bloch_multivector(out_vector) from qiskit import * from qiskit.tools.visualization import plot_histogram import numpy as np from matplotlib import style circuit = QuantumCircuit() classicalRegister = ClassicalRegister(4 , name = 'classicalRegister') data = QuantumRegister(4, name = 'data') circuit.add_register(data) circuit.add_register(classicalRegister) circuit.draw('mpl') circuit.h(data) circuit.draw('mpl') # creating the extra bit or ancilla ancilla = QuantumRegister(1, name = 'ancilla') circuit.add_register(ancilla) circuit.x(ancilla) circuit.h(ancilla) circuit.barrier() circuit.draw('mpl') #oracle part def constant_oracle(circuit): return circuit def balanced_oracle(circuit): circuit.cx(data, ancilla) return circuit circuit = constant_oracle(circuit) circuit.barrier() circuit.draw('mpl') circuit.h(data) circuit.measure(data, classicalRegister) sim = Aer.get_backend('qasm_simulator') result = execute(circuit, sim, shots = 1).result() plot_histogram(result.get_counts(circuit)) from qiskit import QuantumCircuit from qiskit import IBMQ, Aer, transpile, assemble from qiskit.visualization import plot_histogram from matplotlib import style style.use('dark_background') def bell_pair(qC, a, b): qC.h(a) qC.cx(a,b) def encoded_message(qC, qubit, msg): if msg == "00": pass elif msg == "10": qC.x(qubit) elif msg == "01": qC.z(qubit) elif msg == "11": qC.z(qubit) qC.x(qubit) else: print("ERROR: Sending '00'") def decoded_message(qC, a, b): qC.cx(a,b) qC.h(a) qC = QuantumCircuit(2) bell_pair(qC, 0, 1) qC.barrier() message = "00" encoded_message(qC, 0, message) qC.barrier() decoded_message(qC, 0, 1) qC.measure_all() qC.draw('mpl') aer_sim = Aer.get_backend('aer_simulator') job = assemble(qC) result = aer_sim.run(job).result() counts = result.get_counts(qC) print(counts) plot_histogram(counts)
https://github.com/soultanis/Quantum-Database-Search
soultanis
operation DatabaseOracleFromInts( markedElement : Int, markedQubit: Qubit, databaseRegister: Qubit[] ) : Unit { body (...) { (ControlledOnInt(markedElement, X))(databaseRegister, markedQubit); } adjoint auto; controlled auto; adjoint controlled auto; } ControlledOnInt? operation PrepareDatabaseRegister( markedElement : Int, idxMarkedQubit: Int, startQubits: Qubit[] ) : Unit { body (...) { let flagQubit = startQubits[idxMarkedQubit]; let databaseRegister = Exclude([idxMarkedQubit], startQubits); // Apply 𝑈. ApplyToEachCA(H, databaseRegister); // Apply 𝐷. DatabaseOracleFromInts(markedElement, flagQubit, databaseRegister); } adjoint auto; controlled auto; adjoint controlled auto; } function GroverStatePrepOracle(markedElement : Int) : StateOracle { return StateOracle(PrepareDatabaseRegister(markedElement, _, _)); } function GroverSearch( markedElement: Int, nIterations: Int, idxMarkedQubit: Int ) : (Qubit[] => Unit : Adjoint, Controlled) { return AmpAmpByOracle(nIterations, GroverStatePrepOracle(markedElement), idxMarkedQubit); } operation ApplyQuantumSearch() : (Result, Int) { let nIterations = 6; let nDatabaseQubits = 6; let markedElement = 3; // Allocate variables to store measurement results. mutable resultSuccess = Zero; mutable numberElement = 0; using ((markedQubit, databaseRegister) = (Qubit(), Qubit[nDatabaseQubits])) { // Implement the quantum search algorithm. (GroverSearch(markedElement, nIterations, 0))([markedQubit] + databaseRegister); // Measure the marked qubit. On success, this should be One. set resultSuccess = MResetZ(markedQubit); // Measure the state of the database register post-selected on // the state of the marked qubit. let resultElement = MultiM(databaseRegister); set numberElement = PositiveIntFromResultArr(resultElement); // These reset all qubits to the |0〉 state, which is required // before deallocation. ResetAll(databaseRegister); } // Returns the measurement results of the algorithm. return (resultSuccess, numberElement); } %simulate ApplyQuantumSearch %version
https://github.com/soultanis/Quantum-Database-Search
soultanis
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, Aer from qiskit.tools.visualization import plot_histogram, circuit_drawer, plot_state # Create a Quantum Register with 2 qubits. q = QuantumRegister(2) # Create a Classical Register with 2 bits. c = ClassicalRegister(2) # Create a Quantum Circuit qc = QuantumCircuit(q, c) # Add a H gate on qubit 0, putting this qubit in superposition. qc.h(q[0]) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. qc.cx(q[0], q[1]) # Add a Measure gate to see the state. qc.measure(q, c) # See a list of available local simulators print("Aer backends: ", Aer.backends()) backend_sim = Aer.get_backend('qasm_simulator') # Compile and run the Quantum circuit on a simulator backend sim_result1 = execute(qc, backend_sim, shots=2).result() sim_result2 = execute(qc, backend_sim, shots=1000).result() counts1 = sim_result1.get_counts(qc) counts2 = sim_result2.get_counts(qc) # Show the results as text and plot print("First simulation: ", sim_result1) print("Output: ", counts1) print("Second simulation: ", sim_result2) print("Output: ", counts2) legend = ['First execution', 'Second execution'] plot_histogram([counts1,counts2], legend=legend) circuit_drawer(qc) # Import the Qiskit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError from qiskit import execute, IBMQ, Aer from qiskit.backends.ibmq import least_busy from qiskit.tools.visualization import plot_histogram, circuit_drawer, plot_state # Authenticate for access to remote backends try: import Qconfig IBMQ.load_accounts() except: print("""WARNING: There's no connection with the API for remote backends. Have you initialized a file with your personal token? For now, there's only access to local simulator backends...""") try: # Create a Quantum Register with 2 qubits. q = QuantumRegister(2) # Create a Classical Register with 2 bits. c = ClassicalRegister(2) # Create a Quantum Circuit qc = QuantumCircuit(q, c) # Add a H gate on qubit 0, putting this qubit in superposition. qc.h(q[0]) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. qc.cx(q[0], q[1]) # Add a Measure gate to see the state. qc.measure(q, c) # see a list of available remote backends ibmq_backends = IBMQ.backends() print("Remote backends: ", ibmq_backends) # Compile and run the Quantum Program on a real device backend try: least_busy_device = least_busy(IBMQ.backends(simulator=False)) print("Running on current least busy device: ", least_busy_device) #running the job twice and get counts result_exp1 = execute(qc, least_busy_device, shots=1024, max_credits=10).result() result_exp2 = execute(qc, least_busy_device, shots=1024, max_credits=10).result() counts01 = result_exp1.get_counts(qc) counts02 = result_exp2.get_counts(qc) # Show the results print("First experiment: ", result_exp1) print("Output: ", counts01) print("Second experiment: ", result_exp2) print("Output: ", counts02) legend = ['First experiment', 'Second experiment'] plot_histogram([counts01,counts02], legend=legend) except: print("All devices are currently unavailable. Try again later.") except QISKitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex)) # Import the Qiskit SDK. from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, Aer from qiskit.tools.visualization import plot_histogram, circuit_drawer, plot_state # Define the number of n-qbits. n = 2 # Create a Quantum Register with n-qbits. q = QuantumRegister(n) # Create a Classical Register with n-bits. c = ClassicalRegister(n) # Create a Quantum Circuit qc = QuantumCircuit(q, c) # Add H-gate to get superposition. qc.h(q[0]) qc.h(q[1]) # Apply the oracle 11. qc.x(q[0]) qc.h(q[1]) qc.cx(q[0],q[1]) qc.x(q[0]) qc.h(q[1]) for x in range(0, 1): # Apply the grover-algorithm 11 qc.h(q[0]) qc.h(q[1]) qc.x(q[0]) qc.x(q[1]) qc.h(q[1]) qc.cx(q[0],q[1]) qc.h(q[1]) qc.x(q[0]) qc.x(q[1]) qc.h(q[0]) qc.h(q[1]) # Measure qubit to bit. . qc.measure(q, c) # Get Aer backend. backend_sim = Aer.get_backend('qasm_simulator') # Compile and run the Quantum circuit on a simulator backend. sim_result1 = execute(qc, backend_sim, shots=1000).result() counts1 = sim_result1.get_counts(qc) # Show the results as text and plot. print("Simulation: ", sim_result1) print("Output: ", counts1) plot_histogram(counts1) circuit_drawer(qc) from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, Aer, backends from qiskit.tools.visualization import plot_histogram, circuit_drawer, plot_state import math # Authenticate for access to remote backends try: import Qconfig IBMQ.load_accounts() except: print("""WARNING: There's no connection with the API for remote backends. Have you initialized a file with your personal token? For now, there's only access to local simulator backends...""") # decide, on which backend you want to run the grover algorithmus backendIBMQ = True # define the number n-Qbits n = 4 N = 2^n O = math.sqrt(N) pi = math.pi try: # Create a Quantum-Register with n-Qbits. qr = QuantumRegister(n) cr = ClassicalRegister(n) qc = QuantumCircuit(qr, cr) # initialize n-Qbits qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) # Create oracle for 0010 qc.x(qr[0]) qc.x(qr[2]) qc.x(qr[3]) qc.cu1(pi/4, qr[0], qr[3]) qc.cx(qr[0], qr[1]) qc.cu1(-pi/4, qr[1], qr[3]) qc.cx(qr[0], qr[1]) qc.cu1(pi/4, qr[1], qr[3]) qc.cx(qr[1], qr[2]) qc.cu1(-pi/4, qr[2], qr[3]) qc.cx(qr[0], qr[2]) qc.cu1(pi/4, qr[2], qr[3]) qc.cx(qr[1], qr[2]) qc.cu1(-pi/4, qr[2], qr[3]) qc.cx(qr[0], qr[2]) qc.cu1(pi/4, qr[2], qr[3]) qc.x(qr[0]) qc.x(qr[2]) qc.x(qr[3]) # avarage of O(sqrt(N)) repititions for x in range(0, 1): # Amplification qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) qc.x(qr[0]) qc.x(qr[1]) qc.x(qr[2]) qc.x(qr[3]) ######## cccZ ######### qc.cu1(pi/4, qr[0], qr[3]) qc.cx(qr[0], qr[1]) qc.cu1(-pi/4, qr[1], qr[3]) qc.cx(qr[0], qr[1]) qc.cu1(pi/4, qr[1], qr[3]) qc.cx(qr[1], qr[2]) qc.cu1(-pi/4, qr[2], qr[3]) qc.cx(qr[0], qr[2]) qc.cu1(pi/4, qr[2], qr[3]) qc.cx(qr[1], qr[2]) qc.cu1(-pi/4, qr[2], qr[3]) qc.cx(qr[0], qr[2]) qc.cu1(pi/4, qr[2], qr[3]) ####### end cccZ ####### qc.x(qr[0]) qc.x(qr[1]) qc.x(qr[2]) qc.x(qr[3]) qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) # Measure: take state from Qbit to Cbit qc.barrier(qr) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) qc.measure(qr[3], cr[3]) except QISKitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex)) # run the code on a real quantumcomputer from IBM if backendIBMQ: try: # See a list of available local simulators least_busy_device = least_busy(IBMQ.backends(simulator=False)) # IBMQ.get_backend('ibmq_16_melbourne') print("Running on current least busy device: ", least_busy_device) #running the job twice and get counts result_exp1 = execute(qc, least_busy_device, shots = 500, max_credits = 10).result() result_exp2 = execute(qc, least_busy_device, shots = 500, max_credits = 10).result() counts01 = result_exp1.get_counts(qc) counts02 = result_exp2.get_counts(qc) # Show the results print("First experiment: ", result_exp1) print("Output: ", counts01) print("Second experiment: ", result_exp2) print("Output: ", counts02) legend = ['First experiment', 'Second experiment'] plot_histogram([counts01, counts02], legend=legend) circuit_drawer(qc) except: print("All devices are currently unavailable. Try again later.") # or run the code on your own system with the simulation backend Aer else: # See a list of available local simulators print("Aer backends: ", Aer.backends()) backend_sim = Aer.get_backend('qasm_simulator') # Compile and run the Quantum circuit on a simulator backend sim_result1 = execute(qc, backend_sim, shots=1000).result() sim_result2 = execute(qc, backend_sim, shots=1000).result() counts1 = sim_result1.get_counts(qc) counts2 = sim_result2.get_counts(qc) # Show the results as text and plot print("First simulation: ", sim_result1) print("Output: ", counts1) print("Second simulation: ", sim_result2) print("Output: ", counts2) legend = ['First execution', 'Second execution'] plot_histogram([counts1,counts2], legend=legend) circuit_drawer(qc)
https://github.com/soultanis/Quantum-Database-Search
soultanis
from math import sqrt, pi from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import oracle_simple import composed_gates def get_circuit(n, oracles): """ Build the circuit composed by the oracle black box and the other quantum gates. :param n: The number of qubits (not including the ancillas) :param oracles: A list of black box (quantum) oracles; each of them selects a specific state :returns: The proper quantum circuit :rtype: qiskit.QuantumCircuit """ cr = ClassicalRegister(n) ## Testing if n > 3: #anc = QuantumRegister(n - 1, 'anc') # n qubits for the real number # n - 1 qubits for the ancillas qr = QuantumRegister(n + n - 1) qc = QuantumCircuit(qr, cr) else: # We don't need ancillas qr = QuantumRegister(n) qc = QuantumCircuit(qr, cr) ## /Testing print("Number of qubits is {0}".format(len(qr))) print(qr) # Initial superposition for j in range(n): qc.h(qr[j]) # The length of the oracles list, or, in other words, how many roots of the function do we have m = len(oracles) # Grover's algorithm is a repetition of an oracle box and a diffusion box. # The number of repetitions is given by the following formula. print("n is ", n) r = int(round((pi / 2 * sqrt((2**n) / m) - 1) / 2)) print("Repetition of ORACLE+DIFFUSION boxes required: {0}".format(r)) oracle_t1 = oracle_simple.OracleSimple(n, 5) oracle_t2 = oracle_simple.OracleSimple(n, 0) for j in range(r): for i in range(len(oracles)): oracles[i].get_circuit(qr, qc) diffusion(n, qr, qc) for j in range(n): qc.measure(qr[j], cr[j]) return qc, len(qr) def diffusion(n, qr, qc): """ The Grover diffusion operator. Given the arry of qiskit QuantumRegister qr and the qiskit QuantumCircuit qc, it adds the diffusion operator to the appropriate qubits in the circuit. """ for j in range(n): qc.h(qr[j]) # D matrix, flips state |000> only (instead of flipping all the others) for j in range(n): qc.x(qr[j]) # 0..n-2 control bits, n-1 target, n.. if n > 3: composed_gates.n_controlled_Z_circuit( qc, [qr[j] for j in range(n - 1)], qr[n - 1], [qr[j] for j in range(n, n + n - 1)]) else: composed_gates.n_controlled_Z_circuit( qc, [qr[j] for j in range(n - 1)], qr[n - 1], None) for j in range(n): qc.x(qr[j]) for j in range(n): qc.h(qr[j])
https://github.com/soultanis/Quantum-Database-Search
soultanis
circuit = None oracle_simple = None execute = None Aer = None IBMQ = None least_busy = None def _import_modules(): print("Importing modules") global circuit, oracle_simple, execute, least_busy import circuit import oracle_simple from qiskit import execute from qiskit.backends.ibmq import least_busy # To be used from REPL def build_and_infos(n, x_stars, real=False, online=False, backend_name=None): _import_modules() oracles = [] for i in range(len(x_stars)): oracles.append(oracle_simple.OracleSimple(n, x_stars[i])) gc, n_qubits = circuit.get_circuit(n, oracles) if real: online = True backend, max_credits, shots = get_appropriate_backend( n_qubits, real, online, backend_name) res = get_compiled_circuit_infos(gc, backend, max_credits, shots) return res # To be used from REPL def build_and_run(n, x_stars, real=False, online=False, backend_name=None): """ This just build the grover circuit for the specific n and x_star and run them on the selected backend. It may be convenient to use in an interactive shell for quick testing. """ _import_modules() oracles = [] for i in range(len(x_stars)): oracles.append(oracle_simple.OracleSimple(n, x_stars[i])) gc, n_qubits = circuit.get_circuit(n, oracles) if real: online = True backend, max_credits, shots = get_appropriate_backend( n_qubits, real, online, backend_name) return run_grover_algorithm(gc, backend, max_credits, shots) def get_appropriate_backend(n, real, online, backend_name): # Online, real or simuator? if (not online): global Aer from qiskit import Aer max_credits = 10 shots = 4098 print("Local simulator backend") backend = Aer.get_backend('qasm_simulator') # list of online devices: ibmq_qasm_simulator, ibmqx2, ibmqx4, ibmqx5, ibmq_16_melbourne else: global IBMQ from qiskit import IBMQ print("Online {0} backend".format("real" if real else "simulator")) max_credits = 3 shots = 4098 import Qconfig IBMQ.load_accounts() if (backend_name is not None): backend = IBMQ.get_backend(backend_name) else: large_enough_devices = IBMQ.backends( filters=lambda x: x.configuration()['n_qubits'] >= n and x.configuration()[ 'simulator'] == (not real) ) backend = least_busy(large_enough_devices) print("Backend name is {0}; max_credits = {1}, shots = {2}".format( backend, max_credits, shots)) return backend, max_credits, shots def get_compiled_circuit_infos(qc, backend, max_credits, shots): result = {} print("Getting infos ... ") backend_coupling = backend.configuration()['coupling_map'] from qiskit import compile grover_compiled = compile( qc, backend=backend, coupling_map=backend_coupling, shots=shots) grover_compiled_qasm = grover_compiled.experiments[ 0].header.compiled_circuit_qasm result['n_gates'] = len(grover_compiled_qasm.split("\n")) - 4 return result def run_grover_algorithm(qc, backend, max_credits, shots): """ Run the grover algorithm, i.e. the quantum circuit qc. :param qc: The (qiskit) quantum circuit :param real: False (default) to run the circuit on a simulator backend, True to run on a real backend :param backend_name: None (default) to run the circuit on the default backend (local qasm for simulation, least busy IBMQ device for a real backend); otherwise, it should contain the name of the backend you want to use. :returns: Result of the computations, i.e. the dictionary of result counts for an execution. :rtype: dict """ _import_modules() pending_jobs = backend.status()['pending_jobs'] print("Backend has {0} pending jobs".format(pending_jobs)) print("Compiling ... ") job = execute(qc, backend, shots=shots, max_credits=max_credits) print("Job id is {0}".format(job.job_id())) print( "At this point, if any error occurs, you can always retrieve the job results using the backend name and the job id using the utils/retrieve_job_results.py script" ) if pending_jobs > 1: s = input( "Do you want to wait for the job to go up in the queue list or exit the program(q)? If you exit now you can still retrieve the job results later on using the backend name and the job id w/ the utils/retrieve_job_results.py script" ) if (s == "q"): print( "WARNING: Take note of backend name and job id to retrieve the job" ) from sys import exit exit() result = job.result() return result.get_counts(qc) def get_max_key_value(counts): mx = max(counts.keys(), key=(lambda key: counts[key])) total = sum(counts.values()) confidence = counts[mx] / total return mx, confidence def main(): import argparse parser = argparse.ArgumentParser(description="Grover algorithm") parser.add_argument( 'n', metavar='n', type=int, help='the number of bits used to store the oracle data.') parser.add_argument( 'x_stars', metavar='x_star', type=int, nargs='+', help='the number(s) for which the oracle returns 1, in the range [0..2**n-1].' ) parser.add_argument( '-r', '--real', action='store_true', help='Invoke the real device (implies -o). Default is simulator.') parser.add_argument( '-o', '--online', action='store_true', help='Use the online IBMQ devices. Default is local (simulator). This option is automatically set when we want to use a real device (see -r).' ) parser.add_argument( '-i', '--infos', action='store_true', help='Print only infos on the circuit built for the specific backend (such as the number of gates) without executing it.' ) parser.add_argument( '-b', '--backend_name', help="The name of the backend. It makes sense only for online ibmq devices and it's useless otherwise. If not specified, the program automatically choose the least busy ibmq backend." ) parser.add_argument( '--img_dir', help='If you want to store the image of the circuit, you need to specify the directory.' ) parser.add_argument( '--plot', action='store_true', help='Plot the histogram of the results. Default is false') args = parser.parse_args() n = args.n x_stars = args.x_stars print("n: {0}, x_stars: {1}".format(n, x_stars)) real = args.real online = True if real else args.online infos = args.infos backend_name = args.backend_name img_dir = args.img_dir plot = args.plot print("real: {0}, online: {1}, infos: {2}, backend_name: {3}".format( real, online, infos, backend_name)) _import_modules() oracles = [] for i in range(len(x_stars)): oracles.append(oracle_simple.OracleSimple(n, x_stars[i])) gc, n_qubits = circuit.get_circuit(n, oracles) if (img_dir is not None): from qiskit.tools.visualization import circuit_drawer circuit_drawer( gc, filename=img_dir + "grover_{0}_{1}.png".format(n, x_stars[0])) backend, max_credits, shots = get_appropriate_backend( n_qubits, real, online, backend_name) if (infos): res = get_compiled_circuit_infos(gc, backend, max_credits, shots) for k, v in res.items(): print("{0} --> {1}".format(k, v)) else: # execute counts = run_grover_algorithm(gc, backend, max_credits, shots) print(counts) max, confidence = get_max_key_value(counts) print("Max value: {0}, confidence {1}".format(max, confidence)) if (plot): from qiskit.tools.visualization import plot_histogram plot_histogram(counts) print("END") # Assumption: if run from console we're inside src/.. dir if __name__ == "__main__": main()
https://github.com/soultanis/Quantum-Database-Search
soultanis
import grover_test as gt # Simulator-Backend # output = gt.build_and_run(3, [1]) # IBMQ-Backend output = gt.build_and_run(2, [1], real=True, online=True) print(output)
https://github.com/soultanis/Quantum-Database-Search
soultanis
from qiskit import IBMQ import sys def get_job_status(backend, job_id): backend = IBMQ.get_backend(backend) print("Backend {0} is operational? {1}".format( backend.name(), backend.status()['operational'])) print("Backend was last updated in {0}".format( backend.properties()['last_update_date'])) print("Backend has {0} pending jobs".format( backend.status()['pending_jobs'])) ibmq_job = backend.retrieve_job(job_id) status = ibmq_job.status() print(status.name) print(ibmq_job.creation_date()) if (status.name == 'DONE'): print("EUREKA") result = ibmq_job.result() count = result.get_counts() print("Result is: {0}".format()) from qiskit.tools.visualization import plot_histogram plot_histogram(counts) else: print("... Work in progress ...") print("Queue position = {0}".format(ibmq_job.queue_position())) print("Error message = {0}".format(ibmq_job.error_message())) IBMQ.load_accounts() print("Account(s) loaded") if (len(sys.argv) > 2): get_job_status(sys.argv[1], sys.argv[2])
https://github.com/JoelHBierman/SSVQE
JoelHBierman
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import numpy as np import textwrap from typing import Union from functools import partial from qiskit import QuantumCircuit from qiskit.opflow import OperatorBase, ListOp, PrimitiveOp, PauliOp from qiskit.opflow import I, Z from qiskit.circuit.library import TwoLocal from qiskit.algorithms.optimizers import Optimizer from qiskit.utils import QuantumInstance from qiskit.providers import BaseBackend from volta.observables import sample_hamiltonian class SSVQE(object): """Subspace-search variational quantum eigensolver for excited states algorithm class. Based on https://arxiv.org/abs/1810.09434 """ def __init__( self, hamiltonian: Union[OperatorBase, ListOp, PrimitiveOp, PauliOp], ansatz: QuantumCircuit, backend: Union[BaseBackend, QuantumInstance], optimizer: Optimizer, n_excited: int, debug: bool = False, ) -> None: """Initialize the class. Args: hamiltonian (Union[OperatorBase, ListOp, PrimitiveOp, PauliOp]): Hamiltonian constructed using qiskit's aqua operators. ansatz (QuantumCircuit): Anstaz that you want to run VQD. optimizer (qiskit.aqua.components.optimizers.Optimizer): Classical Optimizers from aqua components. backend (Union[BaseBackend, QuantumInstance]): Backend for running the algorithm. """ # Input parameters self.hamiltonian = hamiltonian self.n_qubits = hamiltonian.num_qubits self.optimizer = optimizer self.backend = backend # Helper Parameters self.ansatz = ansatz self.n_parameters = self._get_num_parameters self._debug = debug self._ansatz_1_params = None self._first_optimization = False self._n_excited = n_excited # Running inate functions self._inate_optimizer_run() def _create_blank_circuit(self) -> list: return [QuantumCircuit(self.n_qubits) for _ in range(self._n_excited)] def _copy_unitary(self, list_states: list) -> list: out_states = [] for state in list_states: out_states.append(state.copy()) return out_states def _apply_initialization(self, list_states: list) -> None: for ind, state in enumerate(list_states): b = bin(ind)[2:] if len(b) != self.n_qubits: b = "0" * (self.n_qubits - len(b)) + b spl = textwrap.wrap(b, 1) for qubit, val in enumerate(spl): if val == "1": state.x(qubit) @property def _get_num_parameters(self) -> int: """Get the number of parameters in a given ansatz. Returns: int: Number of parameters of the given ansatz. """ return len(self.ansatz.parameters) def _apply_varform_params(self, ansatz, params: list): """Get an hardware-efficient ansatz for n_qubits given parameters. """ # Define variational Form var_form = ansatz # Get Parameters from the variational form var_form_params = sorted(var_form.parameters, key=lambda p: p.name) # Check if the number of parameters is compatible assert len(var_form_params) == len( params ), "The number of parameters don't match" # Create a dictionary with the parameters and values param_dict = dict(zip(var_form_params, params)) # Assing those values for the ansatz wave_function = var_form.assign_parameters(param_dict) return wave_function def _apply_ansatz(self, list_states: list, name: str = None) -> None: for states in list_states: if name: self.ansatz.name = name states.append(self.ansatz, range(self.n_qubits)) def _construct_states(self): circuit = self._create_blank_circuit() self._apply_initialization(circuit) self._apply_ansatz(circuit) return circuit def _cost_function_1(self, params: list) -> float: """Evaluate the first cost function of SSVQE. Args: params (list): Parameter values for the ansatz. Returns: float: Cost function value. """ # Construct states states = self._construct_states() cost = 0 w = np.arange(len(states), 0, -1) for i, state in enumerate(states): qc = self._apply_varform_params(state, params) # Hamiltonian hamiltonian_eval = sample_hamiltonian( hamiltonian=self.hamiltonian, ansatz=qc, backend=self.backend ) cost += w[i] * hamiltonian_eval return cost def _inate_optimizer_run(self): # Random initialization params = np.random.rand(self.n_parameters) optimal_params, energy, n_iters = self.optimizer.optimize( num_vars=self.n_parameters, objective_function=self._cost_function_1, initial_point=params, ) self._ansatz_1_params = optimal_params self._first_optimization = True def _cost_excited_state(self, ind: int, params: list): cost = 0 # Construct states states = self._construct_states() # Define Ansatz qc = self._apply_varform_params(states[ind], params) # Hamiltonian hamiltonian_eval = sample_hamiltonian( hamiltonian=self.hamiltonian, ansatz=qc, backend=self.backend ) cost += hamiltonian_eval return cost, qc def run(self, index: int) -> (float, QuantumCircuit): """Run SSVQE for a given index. Args: index(int): Index of the given excited state. Returns: Energy: Energy of such excited state. State: State for such energy. """ energy, state = self._cost_excited_state(index, self._ansatz_1_params) return energy, state if __name__ == "__main__": import qiskit from qiskit import BasicAer optimizer = qiskit.algorithms.optimizers.COBYLA(maxiter=100) backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=10000 ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) algo = SSVQE(hamiltonian, ansatz, backend, optimizer) energy, state = algo.run(1) print(energy) print(state)
https://github.com/JoelHBierman/SSVQE
JoelHBierman
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import unittest import qiskit from qiskit.circuit.library import TwoLocal from qiskit import QuantumCircuit, Aer from qiskit.utils import QuantumInstance from qiskit.opflow import Z, I from volta.ssvqe import SSVQE from volta.utils import classical_solver class TestSSVQD(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=Aer.get_backend("qasm_simulator"), shots=10000 ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) self.Algo = SSVQE( hamiltonian=hamiltonian, ansatz=ansatz, optimizer=optimizer, n_excited=2, backend=backend, ) self.energy = [] self.energy.append(self.Algo.run(index=0)[0]) self.energy.append(self.Algo.run(index=1)[0]) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies(self): want = self.eigenvalues[0] got = self.energy[0] decimalPlace = 1 message = "SSVQE not working for the ground state of 1/2*((Z^I) + (Z^Z))" self.assertAlmostEqual(want, got, decimalPlace, message) decimalPlace = 1 want = self.eigenvalues[1] got = self.energy[1] message = "SSVQE not working for the first excited state of 1/2*((Z^I) + (Z^Z))" self.assertAlmostEqual(want, got, decimalPlace, message) if __name__ == "__main__": unittest.main(argv=[""], verbosity=2, exit=False)
https://github.com/osamarais/qiskit_iterative_solver
osamarais
import qiskit from qiskit import QuantumCircuit, QuantumRegister from qiskit.extensions import UnitaryGate import numpy as np from scipy.linalg import fractional_matrix_power from scipy.io import loadmat, savemat from copy import deepcopy # problems = ((1,4),(1,8),(1,16),(2,4),(2,8),(2,16),(3,4),(3,16),(4,4),(4,16),(5,6),(5,20),(6,4),(6,16),(7,6),(7,20)) problems = ((5,6),(5,20),(6,4),(6,16),(7,6),(7,20)) def CR_phi_d(phi, d, register_1, register_2): circuit = QuantumCircuit(register_1,register_2,name = 'CR_( \\phi \\tilde {})'.format(d)) circuit.cnot(register_2,register_1,ctrl_state=0) circuit.rz(phi*2, register_1) circuit.cnot(register_2,register_1,ctrl_state=0) return circuit for problem in problems: problem_number = problem[0] size = problem[1] iterations = int(np.floor(128/size -1)) # iterations = 7 K = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['A'] R = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['R'] B = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['B'] f = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['f'] f = f/np.linalg.norm(f) print('|R|_2 = {}'.format(np.linalg.norm(R,2))) A = np.eye((iterations+1)*size,(iterations+1)*size) for block in range(iterations): A[(block+1)*size:(block+2)*size,(block)*size:(block+1)*size] = -R # A[(block+1)*size:(block+2)*size,(block)*size:(block+1)*size] = -np.eye(size) A_orig = deepcopy(A) # Normalize the matrix using the upper bound A = A/2 np.linalg.norm(A,2) RHS_provided = True A_shape = np.shape(A_orig) # Hermitian Dilation # Only if A is not Hermitian from copy import deepcopy if np.any(A != A.conj().T): A = np.block([ [np.zeros(np.shape(A)),A], [A.conj().T,np.zeros(np.shape(A))] ]) HD = True else: HD = False print(HD) if RHS_provided: b = np.zeros(((iterations+1)*size,1)) for block in range(iterations): b[(block+1)*size:(block+2)*size,:] = f b = b / np.linalg.norm(b,2) b = b.flatten() b_orig = deepcopy(b) if HD: b = np.concatenate([b,np.zeros(b.shape)]) print(b) if np.size(A)>1: A_num_qubits = int(np.ceil(np.log2(np.shape(A)[0]))) padding_size = 2**A_num_qubits - np.shape(A)[0] if padding_size > 0: A = np.block([ [A, np.zeros([np.shape(A)[0],padding_size])], [np.zeros([padding_size,np.shape(A)[0]]), np.zeros([padding_size,padding_size])] ]) else: A_num_qubits = 1 padding_size = 1 A = np.array([[A,0],[0,0]]) print(A_num_qubits) print(padding_size) print(A) # If RHS is given, it also needs to be padded if RHS_provided: b = np.pad(b,(0,padding_size)) O = np.block([ [A , -fractional_matrix_power(np.eye(np.shape(A)[0]) - np.linalg.matrix_power(A,2),0.5)], [fractional_matrix_power(np.eye(np.shape(A)[0]) - np.linalg.matrix_power(A,2),0.5) , A] ]) print(O) # We also need to get the block-encoding size, i.e. m, used to encode A in U_A m = int(np.log2(np.shape(O)[0]) - A_num_qubits) O_A_num_qubits = int(np.log2(np.shape(O)[0])) print('m = {} \nNumber of Qubits for O_A is {}'.format(m,O_A_num_qubits)) blockA = UnitaryGate(O,label='O_A') register_1 = QuantumRegister(size = 1, name = '|0>') register_2 = QuantumRegister(size = m, name = '|0^m>') register_3 = QuantumRegister(size = O_A_num_qubits-m, name = '|\\phi>') from scipy.io import loadmat phi_angles = np.array( loadmat('phi_k_50_14.mat') ).item()['phi'] phi_tilde_angles = np.zeros(np.shape(phi_angles)) temp = np.zeros(np.shape(phi_angles)) # plot QSP angles for d,phi in enumerate(phi_angles): if d==0 or d==np.size(phi_angles)-1: temp[d] = phi_angles[d] - np.pi/4 else: temp[d] = phi_angles[d] phase_angles = phi_angles.reshape(phi_angles.shape[0]) circuit = QuantumCircuit(register_1, register_2, register_3, name = 'QSP') if RHS_provided: circuit.initialize(b,list(reversed(register_3))) # First thing is to Hadamard the ancilla qubit since we want Re(P(A)) circuit.h(register_1) # Note: QSPPACK produces symmetric phase angles, so reversing phase angles is unnecessary # for d, phi in enumerate(reversed(phase_angles)): for d, phi in reversed(list(enumerate(phase_angles))): circuit = circuit.compose(CR_phi_d(phi,d,register_1,register_2)) if d>0: # The endianness of the bits matters. Need to change the order of the bits circuit.append(blockA,list(reversed(register_3[:])) + register_2[:]) # Apply the final Hadamard gate circuit.h(register_1) circuit = circuit.reverse_bits() circuit.size() from qiskit import transpile circuit = transpile(circuit) from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer Aer.backends() # solver = 'unitary' solver = 'statevector' machine = "CPU" # machine = "GPU" # precision = "single" precision = "double" if solver=='unitary': # backend = Aer.get_backend('unitary_simulator',precision = 'double',device="GPU") backend = Aer.get_backend('unitary_simulator',precision = precision,device=machine) job = execute(circuit, backend, shots=0) result = job.result() QSP_unitary = result.get_unitary(circuit,100) QSP_matrix = np.array(QSP_unitary.to_matrix()) print(QSP_matrix) elif solver=='statevector': backend = Aer.get_backend('statevector_simulator',precision = precision,device=machine) # backend = Aer.get_backend('statevector_simulator',precision = 'double',device="GPU") job = execute(circuit, backend, shots=0) result = job.result() QSP_statevector = result.get_statevector() print(QSP_statevector) if solver=='statevector': # We can ignore the padding size and directly use the size of b (considering Hermitian dilation) if HD: P_A_b = np.real(QSP_statevector.data[int(b_orig.shape[0]):(2*b_orig.shape[0])]) else: P_A_b = np.real(QSP_statevector.data[0:b.shape[0]]) P_A_b = P_A_b/np.linalg.norm(P_A_b) if solver=='statevector': expected_P_A_b = np.linalg.solve(A_orig,b_orig) expected_P_A_b = expected_P_A_b/np.linalg.norm(expected_P_A_b) exact_solution = np.linalg.solve(K,f) x_exact_normalized = exact_solution x_exact_normalized = x_exact_normalized/np.linalg.norm(x_exact_normalized) error_actual = [] if solver=='statevector': for iteration_number in range(1,iterations): e = x_exact_normalized - (P_A_b[iteration_number*size:(iteration_number+1)*size]/np.linalg.norm(P_A_b[iteration_number*size:(iteration_number+1)*size])).reshape(np.shape(x_exact_normalized)) error_actual.append(np.linalg.norm(e)) error_expected = [] if solver=='statevector': for iteration_number in range(1,iterations): e = x_exact_normalized - (expected_P_A_b[iteration_number*size:(iteration_number+1)*size]/np.linalg.norm(expected_P_A_b[iteration_number*size:(iteration_number+1)*size])).reshape(np.shape(x_exact_normalized)) error_expected.append(np.linalg.norm(e)) mdic = {"classical":error_expected,"quantum":error_actual,"kappa":np.linalg.cond(A_orig)} savemat("output_N_{}_problem_{}.mat".format(size,problem_number), mdic)
https://github.com/osamarais/qiskit_iterative_solver
osamarais
import qiskit from qiskit import QuantumCircuit, QuantumRegister from qiskit.extensions import UnitaryGate import numpy as np from scipy.linalg import fractional_matrix_power from scipy.io import loadmat from copy import deepcopy # problem = 'lower triangular' # problem = 'lower triangular identities' # problem = 'diagonal' problem = 'laplacian' if 'lower triangular'==problem: N = 16 A = np.eye(N) for i in range(N-1): A[i+1,i] = -1 A_orig = deepcopy(A) A = A/2 RHS_provided = False if 'lower triangular identities'==problem: N = 4 I = 4 A = np.eye(N*I) for i in range(N-1): A[(i+1)*I:(i+2)*I,(i)*I:(i+1)*I] = -np.eye(I) A_orig = deepcopy(A) A = A/2 RHS_provided = False if 'diagonal'==problem: # # A = np.array([[1, 0, 0],[-1, 1, 0],[0, -1, 1]])/2 # step = 0.025 step = 0.05 x = np.diag(np.concatenate( (np.arange(-1,0,step),np.arange(step,1+step,step)) ) ) # x = np.diag(np.concatenate( (np.arange(1,0,-step),-np.arange(-step,-1-step,-step)) ) ) # # x = np.diag(np.arange(step,1+step,step)) # # x = np.diag([1,0.5]) # # x = np.diag(np.arange(1,0,-step)) A = x A = np.array(A) A_orig = deepcopy(A) RHS_provided = False # A = np.eye(8) # # DON'T FORGET TO NORMALIZE A!!!! if 'laplacian'==problem: problem_number = 2 size = 4 iterations = int(np.floor(128/size -1)) # iterations = 7 K = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['A'] R = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['R'] B = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['B'] f = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['f'] f = f/np.linalg.norm(f) print('|R|_2 = {}'.format(np.linalg.norm(R,2))) A = np.eye((iterations+1)*size,(iterations+1)*size) for block in range(iterations): A[(block+1)*size:(block+2)*size,(block)*size:(block+1)*size] = -R # A[(block+1)*size:(block+2)*size,(block)*size:(block+1)*size] = -np.eye(size) A_orig = deepcopy(A) # Normalize the matrix using the upper bound A = A/2 np.linalg.norm(A,2) RHS_provided = True # A_identities = deepcopy(A) # spy(A_identities) A_shape = np.shape(A_orig) # Hermitian Dilation # Only if A is not Hermitian if np.any(A != A.conj().T): A = np.block([ [np.zeros(np.shape(A)),A], [A.conj().T,np.zeros(np.shape(A))] ]) HD = True else: HD = False print(HD) from matplotlib.pyplot import spy spy(A) if RHS_provided: b = np.zeros(((iterations+1)*size,1)) for block in range(iterations): b[(block+1)*size:(block+2)*size,:] = f b = b / np.linalg.norm(b,2) b = b.flatten() b_orig = deepcopy(b) if HD: b = np.concatenate([b,np.zeros(b.shape)]) print(b) # Check the norm and condition number of the matrix if np.size(A)>1: print( '||A||_2 = {} \n cond(A) = {} \n ||A^-1||_2 = {}'.format( np.linalg.norm(A,2), np.linalg.cond(A), np.linalg.norm(np.linalg.inv(A),2) ) ) else: print('||A||_2 = {} \n cond(A) = {}'.format(np.linalg.norm(A),1) ) if np.size(A)>1: A_num_qubits = int(np.ceil(np.log2(np.shape(A)[0]))) padding_size = 2**A_num_qubits - np.shape(A)[0] if padding_size > 0: A = np.block([ [A, np.zeros([np.shape(A)[0],padding_size])], [np.zeros([padding_size,np.shape(A)[0]]), np.zeros([padding_size,padding_size])] ]) else: A_num_qubits = 1 padding_size = 1 A = np.array([[A,0],[0,0]]) print(A_num_qubits) print(padding_size) print(A) # If RHS is given, it also needs to be padded if RHS_provided: b = np.pad(b,(0,padding_size)) # Create block encoding of A by creating a Unitary matrix # Question: does A need to be Hermitian to define this sort of block encoding? # Answer: Yes, A is defined as Hermitian for QET and QSP # But the block encoding U_A does not have to be Hermitian # This block encoding needs to be the REFLECTION operator in order to # stay consistent with the conventions of the QET or QSP # QET uses U_A # QSP uses O_A O = np.block([ [A , -fractional_matrix_power(np.eye(np.shape(A)[0]) - np.linalg.matrix_power(A,2),0.5)], [fractional_matrix_power(np.eye(np.shape(A)[0]) - np.linalg.matrix_power(A,2),0.5) , A] ]) print(O) # We also need to get the block-encoding size, i.e. m, used to encode A in U_A m = int(np.log2(np.shape(O)[0]) - A_num_qubits) O_A_num_qubits = int(np.log2(np.shape(O)[0])) print('m = {} \nNumber of Qubits for O_A is {}'.format(m,O_A_num_qubits)) # Check is still Unitary np.linalg.norm(np.matmul(O,O.T)-np.eye(np.shape(O)[0]),2) blockA = UnitaryGate(O,label='O_A') register_1 = QuantumRegister(size = 1, name = '|0>') register_2 = QuantumRegister(size = m, name = '|0^m>') register_3 = QuantumRegister(size = O_A_num_qubits-m, name = '|\phi>') # Create a rotation circuit in the block-encoding basis def CR_phi_d(phi, d, register_1, register_2): circuit = QuantumCircuit(register_1,register_2,name = 'CR_( \phi \tilde {})'.format(d)) circuit.cnot(register_2,register_1,ctrl_state=0) circuit.rz(phi*2, register_1) circuit.cnot(register_2,register_1,ctrl_state=0) return circuit from scipy.io import loadmat phi_angles = np.array( loadmat('phi_k_50_14.mat') ).item()['phi'] phi_tilde_angles = np.zeros(np.shape(phi_angles)) temp = np.zeros(np.shape(phi_angles)) # plot QSP angles for d,phi in enumerate(phi_angles): if d==0 or d==np.size(phi_angles)-1: temp[d] = phi_angles[d] - np.pi/4 else: temp[d] = phi_angles[d] phase_angles = phi_angles.reshape(phi_angles.shape[0]) from matplotlib import pyplot as plt %matplotlib inline plt.plot(phase_angles) # It seems like using the QSP angles might be more stable numerically.... circuit = QuantumCircuit(register_1, register_2, register_3, name = 'QSP') if RHS_provided: circuit.initialize(b,list(reversed(register_3))) # First thing is to Hadamard the ancilla qubit since we want Re(P(A)) circuit.h(register_1) # Note: QSPPACK produces symmetric phase angles, so reversing phase angles is unnecessary # for d, phi in enumerate(reversed(phase_angles)): for d, phi in reversed(list(enumerate(phase_angles))): circuit = circuit.compose(CR_phi_d(phi,d,register_1,register_2)) if d>0: # The endianness of the bits matters. Need to change the order of the bits circuit.append(blockA,list(reversed(register_3[:])) + register_2[:]) # Apply the final Hadamard gate circuit.h(register_1) circuit = circuit.reverse_bits() circuit.size() # print(circuit) # from qiskit import transpile # circuit = transpile(circuit) from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer Aer.backends() # solver = 'unitary' solver = 'statevector' machine = "CPU" # machine = "GPU" # precision = "single" precision = "double" if solver=='unitary': # backend = Aer.get_backend('unitary_simulator',precision = 'double',device="GPU") backend = Aer.get_backend('unitary_simulator',precision = precision,device=machine) job = execute(circuit, backend, shots=0) result = job.result() QSP_unitary = result.get_unitary(circuit,100) QSP_matrix = np.array(QSP_unitary.to_matrix()) print(QSP_matrix) elif solver=='statevector': backend = Aer.get_backend('statevector_simulator',precision = precision,device=machine) # backend = Aer.get_backend('statevector_simulator',precision = 'double',device="GPU") job = execute(circuit, backend, shots=0) result = job.result() QSP_statevector = result.get_statevector() print(QSP_statevector) if solver=='statevector': # We can ignore the padding size and directly use the size of b (considering Hermitian dilation) if HD: P_A_b = np.real(QSP_statevector.data[int(b_orig.shape[0]):(2*b_orig.shape[0])]) else: P_A_b = np.real(QSP_statevector.data[0:b.shape[0]]) P_A_b = P_A_b/np.linalg.norm(P_A_b) b_orig.shape[0] if solver=='statevector': print(P_A_b) if solver=='statevector': expected_P_A_b = np.linalg.solve(A_orig,b_orig) expected_P_A_b = expected_P_A_b/np.linalg.norm(expected_P_A_b) if solver=='statevector': print(expected_P_A_b) if solver=='statevector': for iteration_number in range(iterations): plt.plot(expected_P_A_b[iteration_number*size:(iteration_number+1)*size]) if solver=='statevector': for iteration_number in range(iterations): plt.plot(P_A_b[iteration_number*size:(iteration_number+1)*size]) exact_solution = np.linalg.solve(K,f) plt.plot(exact_solution/np.linalg.norm(exact_solution)) x_exact_normalized = exact_solution x_exact_normalized = x_exact_normalized/np.linalg.norm(x_exact_normalized) error_actual = [] if solver=='statevector': for iteration_number in range(1,iterations): e = x_exact_normalized - (P_A_b[iteration_number*size:(iteration_number+1)*size]/np.linalg.norm(P_A_b[iteration_number*size:(iteration_number+1)*size])).reshape(np.shape(x_exact_normalized)) error_actual.append(np.linalg.norm(e)) plt.plot(np.log10(error_actual)) error_expected = [] if solver=='statevector': for iteration_number in range(1,iterations): e = x_exact_normalized - (expected_P_A_b[iteration_number*size:(iteration_number+1)*size]/np.linalg.norm(expected_P_A_b[iteration_number*size:(iteration_number+1)*size])).reshape(np.shape(x_exact_normalized)) error_expected.append(np.linalg.norm(e)) plt.plot(np.log10(error_expected),'--') plt.legend(['actual','expected']) plt.xlabel('iterations') plt.ylabel('log10 e') plt.title('N = {}, {} iterations'.format(size,iterations)) error_actual error_expected np.linalg.cond(A_orig) plt.plot(np.log10(np.abs(np.array(error_actual)-error_expected))) if solver=='unitary': A_inv = np.linalg.inv(A_orig) if HD: # Extract the appropriate block N1 = 2**int(O_A_num_qubits-2) # Remove the padding N2 = np.shape(A_orig)[0] P_A = np.real(QSP_matrix[N1:(N1+N2),0:N2]) else: # Extract the appropriate block # Remove the padding N2 = np.shape(A_orig)[0] P_A = np.real(QSP_matrix[0:N2,0:N2]) print(P_A/P_A[0,0]) print("Error: {}".format(np.linalg.norm(P_A/abs(P_A[0,0])-A_inv,2))) if 'unitary'==solver and 'diagonal'==problem: plt.plot(np.arange(-1,0,0.05),np.diag(P_A)[0:20]/abs(P_A[0,0]),'r',linewidth=3) plt.plot(np.arange(0.05,1.05,0.05),np.diag(P_A)[20:40]/abs(P_A[0,0]),'r',linewidth=3) plt.plot(np.arange(-1.25,0,0.01),1/np.arange(-1.25,0,0.01),'k--',) plt.plot(np.arange(0.01,1.25,0.01),1/np.arange(0.01,1.25,0.01),'k--') plt.ylim([-25,25]) if 'unitary'==solver and 'diagonal'==problem: error = np.abs(np.diag(A_inv)-np.diag(P_A / abs(P_A[0,0]))) plt.plot(np.diag(A)[0:int(len(error)/2)],error[0:int(len(error)/2)],np.diag(A)[int(len(error)/2):len(error)],error[int(len(error)/2):len(error)]) plt.xlabel('normalized eigenvalues') plt.ylabel('error') # # np.set_printoptions(threshold=np.inf) # for i in range(P_A.shape[0]): # # print(QSP_matrix[i,i]/0.0062) # print(P_A[i,i]/abs(P_A[0,0])) # # print(QSP_matrix/QSP_matrix[0,0])
https://github.com/Akshara-Bulkapuram/Quantum-Hadamard-Edge-detection
Akshara-Bulkapuram
# Importing standard Qiskit libraries from qiskit import * from qiskit import IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * import numpy as np import matplotlib.pyplot as plt from matplotlib import style style.use('dark_background') # representing a binary image(8x8) in form of a numpy array img = np.array([ [0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0] ]) # plot image function def plot_image(Image, title): plt.title(title) plt.xticks(range(Image.shape[0])) plt.yticks(range(Image.shape[1])) plt.imshow(Image, extent=[ 0,Image.shape[0], Image.shape[1],0,], cmap='hot') plt.show() plot_image(img, 'Initial image') #we encode the intensities of image pixels as probability amplitudes of quantum states #we use normalization for this #we normalize the amplitudes to lie in the range (0,1) # Convert the raw pixel values to probability amplitudes def amplitude_encode(img_data): # Calculate the RMS value rms = np.sqrt(np.sum(np.sum(img_data**2, axis=1))) # Create normalized image image_norm = [] for arr in img_data: for ele in arr: image_norm.append(ele / rms) # Return the normalized image as a numpy array return np.array(image_norm) #we now normalize image and get coefficients in both horizontal and vertical directions # Horizontal: Original image h_norm_image = amplitude_encode(img) print("Horizontal image normalized coefficients",h_norm_image) print() print() # Vertical: Transpose of Original image v_norm_image = amplitude_encode(img.T) print("vertical image normalized coefficients",v_norm_image) print() print("size of 1d array",h_norm_image.shape) print("size of 1d array",v_norm_image.shape) #we require N=log(8*8) qubits #N=6 data_q = 6 ancillary_q = 1 total_q = data_q + ancillary_q # Initialize the amplitude permutation unitary Amp_permutation_unitary = np.identity(2**total_q) print(Amp_permutation_unitary) Amp_permutation_unitary=np.roll(Amp_permutation_unitary,1,axis=1) print() print() print() print("shift Amplitude permutation matrix by 1 unit to the right column wise") print() print(Amp_permutation_unitary) print() print("we will later use this for while applying hadamard operation to image coefficient vectors") print() print(Amp_permutation_unitary.shape) # Creating the circuit for horizontal scan qc_h = QuantumCircuit(total_q) qc_h.initialize(h_norm_image, range(1, total_q)) qc_h.h(0) qc_h.unitary(Amp_permutation_unitary, range(total_q)) qc_h.h(0) display(qc_h.draw('mpl', fold=-1)) # Create the circuit for vertical scan qc_v = QuantumCircuit(total_q) qc_v.initialize(v_norm_image, range(1, total_q)) qc_v.h(0) qc_v.unitary(Amp_permutation_unitary, range(total_q)) qc_v.h(0) display(qc_v.draw('mpl', fold=-1)) # Combine both circuits into a single list circ_list = [qc_h, qc_v] # Simulating cirucits back = Aer.get_backend('statevector_simulator') results = execute(circ_list, backend=back).result() state_vector_h = results.get_statevector(qc_h) state_vector_v = results.get_statevector(qc_v) print("print size is ",state_vector_h.size) from qiskit.visualization import array_to_latex print('Horizontal scan statevector:') display(array_to_latex(state_vector_h, max_size=128)) print() print('Vertical scan statevector:') display(array_to_latex(state_vector_v, max_size=128)) # postprocessing for plotting the output (Classical) # Defining a lambda function for thresholding to binary values # returns true for specified Amplitude values else false threshold = lambda amp: (amp > 1e-15 or amp < -1e-15) # Selecting odd states from the raw statevector and # reshaping column vector of size 64 to an 8x8 matrix h_edge_scan_img = np.abs(np.array([1 if threshold(state_vector_h[(2*i)+1].real) else 0 for i in range(2**data_q)])).reshape(8, 8) v_edge_scan_img= np.abs(np.array([1 if threshold(state_vector_v[(2*i)+1].real) else 0 for i in range(2**data_q)])).reshape(8, 8).T # Plotting the Horizontal and vertical scans plot_image(h_edge_scan_img, 'Horizontal scan output') plot_image(v_edge_scan_img, 'Vertical scan output') # Combining the horizontal and vertical component of the result by or operator edge_scan_image = h_edge_scan_img | v_edge_scan_img # Plotting the original and edge-detected images plot_image(img, 'Original image') plot_image(edge_scan_image, 'Edge-Detected image') from PIL import Image from numpy import asarray image = Image.open('cat.png') image.show() new_image = image.resize((32, 32)).convert('1') new_image.save('IMAGE_32.png') new_image.show() imgg=asarray(new_image) print(imgg.shape) def plot_image(Image, title): plt.title(title) plt.xticks(range(Image.shape[0])) plt.yticks(range(Image.shape[1])) plt.imshow(Image, extent=[ 0,Image.shape[0], Image.shape[1],0,], cmap='hot') plt.show() plot_image(imgg, 'Initial image') print("size=",imgg.shape) #we encode the intensities of image pixels as probability amplitudes of quantum states #we use normalization for this #we normalize the amplitudes to lie in the range (0,1) # Convert the raw pixel values to probability amplitudes def amplitude_encode(img_data): # Calculate the RMS value rms_32 = np.sqrt(np.sum(np.sum(img_data**2, axis=1))) # Create normalized image image_norm = [] for arr in img_data: for ele in arr: image_norm.append(ele / rms_32) # Return the normalized image as a numpy array return np.array(image_norm) #we now normalize image and get coefficients in both horizontal and vertical directions # Horizontal: Original image h_norm_image_32 = amplitude_encode(imgg) print("Horizontal image normalized coefficients",h_norm_image_32) print() print() # Vertical: Transpose of Original image v_norm_image_32 = amplitude_encode(imgg.T) print("vertical image normalized coefficients",v_norm_image_32) print() print("size of 1d array",h_norm_image_32.shape) print("size of 1d array",v_norm_image_32.shape) #we require N=log(32*32) qubits #N=10 data_q_32 = 10 ancillary_q_32 = 1 total_q_32 = data_q_32 + ancillary_q_32 # Initialize the amplitude permutation unitary Amp_permutation_unitary_32 = np.identity(2**total_q_32) print(Amp_permutation_unitary_32) Amp_permutation_unitary_32=np.roll(Amp_permutation_unitary_32,1,axis=1) print() print() print() print("shift Amplitude permutation matrix by 1 unit to the right column wise") print() print(Amp_permutation_unitary_32) print() print("we will later use this for while applying hadamard operation to image coefficient vectors") print() print(Amp_permutation_unitary_32.shape) # Creating the circuit for horizontal scan qc_h_32 = QuantumCircuit(total_q_32) qc_h_32.initialize(h_norm_image_32, range(1, total_q_32)) qc_h_32.h(0) qc_h_32.unitary(Amp_permutation_unitary_32, range(total_q_32)) qc_h_32.h(0) display(qc_h_32.draw('mpl', fold=-1)) # Create the circuit for vertical scan qc_v_32 = QuantumCircuit(total_q_32) qc_v_32.initialize(v_norm_image_32, range(1, total_q_32)) qc_v_32.h(0) qc_v_32.unitary(Amp_permutation_unitary_32, range(total_q_32)) qc_v_32.h(0) display(qc_v_32.draw('mpl', fold=-1)) # Combine both circuits into a single list circ_list_32 = [qc_h_32, qc_v_32] # Simulating cirucits back = Aer.get_backend('statevector_simulator') results = execute(circ_list_32, backend=back).result() state_vector_h_32 = results.get_statevector(qc_h_32) state_vector_v_32 = results.get_statevector(qc_v_32) print("size is ",state_vector_h_32.size) from qiskit.visualization import array_to_latex print('Horizontal scan statevector:') display(array_to_latex(state_vector_h_32, max_size=128)) print() print('Vertical scan statevector:') display(array_to_latex(state_vector_v_32, max_size=128)) # postprocessing for plotting the output (Classical) # Defining a lambda function for thresholding to binary values # returns true for specified Amplitude values else false threshold = lambda amp: (amp > 1e-15 or amp < -1e-15) # Selecting odd states from the raw statevector and # reshaping column vector of size 64 to an 8x8 matrix h_edge_scan_img_32 = np.abs(np.array([1 if threshold(state_vector_h_32[2*(i)+1].real) else 0 for i in range(2**data_q_32)])).reshape(32, 32) v_edge_scan_img_32= np.abs(np.array([1 if threshold(state_vector_v_32[2*(i)+1].real) else 0 for i in range(2**data_q_32)])).reshape(32, 32).T # Plotting the Horizontal and vertical scans plot_image(h_edge_scan_img_32, 'Horizontal scan output') plot_image(v_edge_scan_img_32, 'Vertical scan output') # Combining the horizontal and vertical component of the result by or operator edge_scan_image_32 = h_edge_scan_img_32 | v_edge_scan_img_32 # Plotting the original and edge-detected images plot_image(imgg, 'Original image') plot_image(edge_scan_image_32, 'Edge-Detected image') from qiskit import * from qiskit import IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * import skimage.color import numpy as np import matplotlib.pyplot as plt from matplotlib import style import math from PIL import Image from numpy import asarray image_o = Image.open('Apple1.jpg').convert('1') image_o.show() new_image_o = Image.open('Apple1.jpg') imggg=asarray(image_o) imggg_=asarray(new_image_o) #print(imggg.shape) #for item in imggg: # print(item) plot_image(imggg_, 'Initial image') print("size=",imggg_.shape) #we encode the intensities of image pixels as probability amplitudes of quantum states #we use normalization for this #we normalize the amplitudes to lie in the range (0,1) # Convert the raw pixel values to probability amplitudes def amplitude_encode(img_data): # Calculate the RMS value rms_32_rgb = np.sqrt(np.sum(np.sum(img_data**2, axis=1))) # Create normalized image image_norm = [] for arr in img_data: for ele in arr: image_norm.append(ele / rms_32_rgb) # Return the normalized image as a numpy array return np.array(image_norm) #we now normalize image and get coefficients in both horizontal and vertical directions # Horizontal: Original image h_norm_image_32_rgb = amplitude_encode(imggg) print("Horizontal image normalized coefficients",h_norm_image_32_rgb) print() print() # Vertical: Transpose of Original image v_norm_image_32_rgb = amplitude_encode(imggg.T) print("vertical image normalized coefficients",v_norm_image_32_rgb) print() print("size of 1d array",h_norm_image_32_rgb.shape) print("size of 1d array",v_norm_image_32_rgb.shape) #we require N=log(32*32) qubits #N=10 data_q_32_rgb = 10 ancillary_q_32_rgb = 1 total_q_32_rgb = data_q_32_rgb + ancillary_q_32_rgb # Initialize the amplitude permutation unitary Amp_permutation_unitary_32_rgb = np.identity(2**total_q_32_rgb) print(Amp_permutation_unitary_32_rgb) Amp_permutation_unitary_32_rgb=np.roll(Amp_permutation_unitary_32_rgb,1,axis=1) print() print() print() print("shift Amplitude permutation matrix by 1 unit to the right column wise") print() print(Amp_permutation_unitary_32_rgb) print() print("we will later use this for while applying hadamard operation to image coefficient vectors") print() print(Amp_permutation_unitary_32_rgb.shape) # Creating the circuit for horizontal scan qc_h_32_rgb = QuantumCircuit(total_q_32_rgb) qc_h_32_rgb.initialize(h_norm_image_32_rgb, range(1, total_q_32_rgb)) qc_h_32_rgb.h(0) qc_h_32_rgb.unitary(Amp_permutation_unitary_32_rgb, range(total_q_32_rgb)) qc_h_32_rgb.h(0) display(qc_h_32_rgb.draw('mpl', fold=-1)) # Create the circuit for vertical scan qc_v_32_rgb = QuantumCircuit(total_q_32_rgb) qc_v_32_rgb.initialize(v_norm_image_32_rgb, range(1, total_q_32_rgb)) qc_v_32_rgb.h(0) qc_v_32_rgb.unitary(Amp_permutation_unitary_32_rgb, range(total_q_32_rgb)) qc_v_32_rgb.h(0) display(qc_v_32_rgb.draw('mpl', fold=-1)) # Combine both circuits into a single list circ_list_32_rgb = [qc_h_32_rgb, qc_v_32_rgb] # Simulating cirucits back = Aer.get_backend('statevector_simulator') results = execute(circ_list_32_rgb, backend=back).result() state_vector_h_32_rgb = results.get_statevector(qc_h_32_rgb) state_vector_v_32_rgb = results.get_statevector(qc_v_32_rgb) print("size is ",state_vector_h_32_rgb.size) from qiskit.visualization import array_to_latex print('Horizontal scan statevector:') display(array_to_latex(state_vector_h_32_rgb, max_size=128)) print() print('Vertical scan statevector:') display(array_to_latex(state_vector_v_32_rgb, max_size=128)) # postprocessing for plotting the output (Classical) # Defining a lambda function for thresholding to binary values # returns true for specified Amplitude values else false threshold = lambda amp: (amp > 1e-15 or amp < -1e-15) # Selecting odd states from the raw statevector and # reshaping column vector of size 64 to an 8x8 matrix h_edge_scan_img_32_rgb = np.abs(np.array([1 if threshold(state_vector_h_32_rgb[2*(i)+1].real) else 0 for i in range(2**data_q_32_rgb)])).reshape(32, 32) v_edge_scan_img_32_rgb= np.abs(np.array([1 if threshold(state_vector_v_32_rgb[2*(i)+1].real) else 0 for i in range(2**data_q_32_rgb)])).reshape(32, 32).T # Plotting the Horizontal and vertical scans plot_image(h_edge_scan_img_32_rgb, 'Horizontal scan output') plot_image(v_edge_scan_img_32_rgb, 'Vertical scan output') # Combining the horizontal and vertical component of the result by or operator edge_scan_image_32_rgb = h_edge_scan_img_32_rgb | v_edge_scan_img_32_rgb # Plotting the original and edge-detected images plot_image(imggg_, 'Original image') plot_image(edge_scan_image_32_rgb, 'Edge-Detected image')
https://github.com/m0tela01/GroversAlgorithmQSvsQiskit
m0tela01
%matplotlib inline from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer from qiskit.compiler import transpile, assemble from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator from qiskit.visualization import * from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout from qiskit.tools.jupyter import * from qiskit.tools.visualization import plot_histogram, plot_state_city from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt import numpy as np from math import pi provider = IBMQ.load_account() q = QuantumRegister(5, name='quantumRegister') c = ClassicalRegister(5, name ='qlassicalRegister') qc = QuantumCircuit(q, c) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[4]) qc.barrier() qc.barrier() qc.draw() qc.h(q[2]) qc.cx(q[3],q[2]) qc.tdg(q[2]) qc.cx(q[4],q[2]) qc.t(q[2]) qc.cx(q[3],q[2]) qc.tdg(q[2]) qc.cx(q[4],q[2]) # qc.tdg(q[2]) # qc.cx(q[4],q[2]) qc.barrier() qc.t(q[2]) qc.tdg(q[3]) qc.h(q[2]) qc.barrier() qc.h(q[3]) qc.h(q[4]) qc.cx(q[3],q[4]) qc.h(q[3]) qc.h(q[4]) qc.tdg(q[3]) qc.barrier() qc.draw() qc.h(q[3]) qc.h(q[4]) qc.cx(q[3],q[4]) qc.h(q[3]) qc.h(q[4]) qc.s(q[3]) qc.t(q[4]) qc.barrier() qc.cx(q[2],q[1]) qc.t(q[1]) qc.cx(q[2],q[1]) qc.tdg(q[1]) qc.tdg(q[2]) qc.h(q[2]) qc.cx(q[3],q[2]) qc.tdg(q[2]) qc.cx(q[4],q[2]) qc.t(q[2]) qc.cx(q[3],q[2]) qc.tdg(q[2]) qc.cx(q[4],q[2]) qc.t(q[2]) qc.tdg(q[3]) qc.h(q[2]) qc.barrier() qc.h(q[3]) qc.h(q[4]) qc.cx(q[3],q[4]) qc.h(q[3]) qc.h(q[4]) qc.tdg(q[3]) qc.barrier() qc.h(q[3]) qc.h(q[4]) qc.cx(q[3],q[4]) qc.h(q[3]) qc.h(q[4]) qc.s(q[3]) qc.t(q[4]) qc.barrier() qc.cx(q[2],q[1]) qc.tdg(q[1]) qc.cx(q[2],q[1]) qc.t(q[1]) qc.t(q[2]) qc.barrier() qc.h(q[3]) qc.h(q[4]) qc.cx(q[3],q[4]) qc.h(q[3]) qc.h(q[4]) qc.barrier() qc.draw() qc.cx(q[2],q[1]) qc.h(q[1]) qc.h(q[2]) qc.cx(q[2],q[1]) qc.h(q[1]) qc.h(q[2]) qc.cx(q[2],q[1]) qc.cx(q[3],q[2]) qc.u1(pi/8, q[2]) qc.cx(q[3],q[2]) qc.u1(-pi/8, q[2]) qc.u1(-pi/8,q[3]) qc.barrier() qc.h(q[3]) qc.h(q[4]) qc.cx(q[3],q[4]) qc.h(q[3]) qc.h(q[4]) qc.barrier() qc.cx(q[3],q[2]) qc.u1(-pi/8,q[2]) qc.cx(q[3],q[2]) qc.u1(pi/8,q[2]) qc.u1(pi/8,q[3]) qc.cx(q[4],q[2]) qc.u1(-pi/8,q[2]) qc.cx(q[4],q[2]) qc.u1(pi/8,q[2]) qc.u1(-pi/8,q[4]) qc.barrier() qc.cx(q[2],q[1]) qc.h(q[1]) qc.h(q[2]) qc.cx(q[2],q[1]) qc.h(q[1]) qc.h(q[2]) qc.cx(q[2],q[1]) qc.barrier() qc.barrier() qc.h(q[4]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.barrier() qc.x(q[4]) qc.x(q[1]) qc.x(q[2]) qc.x(q[3]) qc.draw() qc.barrier() qc.barrier() qc.h(q[2]) qc.cx(q[3],q[2]) qc.tdg(q[2]) qc.cx(q[4],q[2]) qc.t(q[2]) qc.cx(q[3],q[2]) qc.tdg(q[2]) qc.cx(q[4],q[2]) # qc.tdg(q[2]) # qc.cx(q[4],q[2]) qc.barrier() qc.t(q[2]) qc.tdg(q[3]) qc.h(q[2]) qc.barrier() qc.h(q[3]) qc.h(q[4]) qc.cx(q[3],q[4]) qc.h(q[3]) qc.h(q[4]) qc.tdg(q[3]) qc.barrier() qc.draw() qc.h(q[3]) qc.h(q[4]) qc.cx(q[3],q[4]) qc.h(q[3]) qc.h(q[4]) qc.s(q[3]) qc.t(q[4]) qc.barrier() qc.cx(q[2],q[1]) qc.t(q[1]) qc.cx(q[2],q[1]) qc.tdg(q[1]) qc.tdg(q[2]) qc.h(q[2]) qc.cx(q[3],q[2]) qc.tdg(q[2]) qc.cx(q[4],q[2]) qc.t(q[2]) qc.cx(q[3],q[2]) qc.tdg(q[2]) qc.cx(q[4],q[2]) qc.t(q[2]) qc.tdg(q[3]) qc.h(q[2]) qc.barrier() qc.h(q[3]) qc.h(q[4]) qc.cx(q[3],q[4]) qc.h(q[3]) qc.h(q[4]) qc.tdg(q[3]) qc.barrier() qc.h(q[3]) qc.h(q[4]) qc.cx(q[3],q[4]) qc.h(q[3]) qc.h(q[4]) qc.s(q[3]) qc.t(q[4]) qc.barrier() qc.cx(q[2],q[1]) qc.tdg(q[1]) qc.cx(q[2],q[1]) qc.t(q[1]) qc.t(q[2]) qc.barrier() qc.h(q[3]) qc.h(q[4]) qc.cx(q[3],q[4]) qc.h(q[3]) qc.h(q[4]) qc.barrier() qc.draw() qc.cx(q[2],q[1]) qc.h(q[1]) qc.h(q[2]) qc.cx(q[2],q[1]) qc.h(q[1]) qc.h(q[2]) qc.cx(q[2],q[1]) qc.cx(q[3],q[2]) qc.u1(pi/8, q[2]) qc.cx(q[3],q[2]) qc.u1(-pi/8, q[2]) qc.u1(-pi/8,q[3]) qc.barrier() qc.h(q[3]) qc.h(q[4]) qc.cx(q[3],q[4]) qc.h(q[3]) qc.h(q[4]) qc.barrier() qc.cx(q[3],q[2]) qc.u1(-pi/8,q[2]) qc.cx(q[3],q[2]) qc.u1(pi/8,q[2]) qc.u1(pi/8,q[3]) qc.cx(q[4],q[2]) qc.u1(-pi/8,q[2]) qc.cx(q[4],q[2]) qc.u1(pi/8,q[2]) qc.u1(-pi/8,q[4]) qc.barrier() qc.cx(q[2],q[1]) qc.h(q[1]) qc.h(q[2]) qc.cx(q[2],q[1]) qc.h(q[1]) qc.h(q[2]) qc.cx(q[2],q[1]) qc.draw() qc.barrier() qc.barrier() qc.x(q[1]) qc.x(q[2]) qc.x(q[3]) qc.x(q[4]) qc.barrier() qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[4]) qc.draw() qc.barrier() qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) qc.measure(q[4], c[4])
https://github.com/pathakis/Introduction-To-Qiskit
pathakis
from collections import namedtuple import matplotlib.pyplot as plt import numpy as np import qutip from qutip import Qobj, Bloch, basis, ket, tensor import seaborn as sns sns.set_theme(style="whitegrid") %matplotlib inline from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram from math import gcd from numpy.random import randint import pandas as pd from fractions import Fraction print("Imports Successful") b = Bloch() up = ket("0") down = ket("1") b.add_states([up, down]) b.show() b = Bloch() b0 = (up+(0+1j)*down)/np.sqrt(2) # (|0> + |1>) / √2 (green) b1 = (up-(0+1j)*down)/np.sqrt(2) # (|0> - |1>) / √2 (orange) b.add_states([b0, b1]) b.show() qc = QuantumCircuit(1) qc.h(0) qc.draw() def c_amod15(a, power): """Controlled multiplication by a mod 15""" if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11 or 13") U = QuantumCircuit(4) for iteration in range(power): if a in [2,13]: U.swap(0,1) U.swap(1,2) U.swap(2,3) if a in [7,8]: U.swap(2,3) U.swap(1,2) U.swap(0,1) if a == 11: U.swap(1,3) U.swap(0,2) if a in [7,11,13]: for q in range(4): U.x(q) U = U.to_gate() U.name = "%i^%i mod 15" % (a, power) c_U = U.control() return c_U # Specify variables n_count = 8 # number of counting qubits a = 7 def qft_dagger(n): """n-qubit QFTdagger the first n qubits in circ""" qc = QuantumCircuit(n) # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc.name = "QFT†" return qc # Create QuantumCircuit with n_count counting qubits # plus 4 qubits for U to act on qc = QuantumCircuit(n_count + 4, n_count) # Initialise counting qubits # in state |+> for q in range(n_count): qc.h(q) # And auxiliary register in state |1> qc.x(3+n_count) # Do controlled-U operations for q in range(n_count): qc.append(c_amod15(a, 2**q), [q] + [i+n_count for i in range(4)]) # Do inverse-QFT qc.append(qft_dagger(n_count), range(n_count)) # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(fold=-1) # -1 means 'do not fold' qasm_sim = Aer.get_backend('qasm_simulator') t_qc = transpile(qc, qasm_sim) qobj = assemble(t_qc) results = qasm_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**n_count) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) Fraction(0.666) # Get fraction that most closely resembles 0.666 # with denominator < 15 Fraction(0.666).limit_denominator(15) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df) N = 15 np.random.seed(1) # This is to make sure we get reproduceable results a = randint(2, 15) print(a) from math import gcd # greatest common divisor gcd(a, N) def qpe_amod15(a): n_count = 8 qc = QuantumCircuit(4+n_count, n_count) for q in range(n_count): qc.h(q) # Initialise counting qubits in state |+> qc.x(3+n_count) # And auxiliary register in state |1> for q in range(n_count): # Do controlled-U operations qc.append(c_amod15(a, 2**q), [q] + [i+n_count for i in range(4)]) qc.append(qft_dagger(n_count), range(n_count)) # Do inverse-QFT qc.measure(range(n_count), range(n_count)) # Simulate Results qasm_sim = Aer.get_backend('qasm_simulator') # Setting memory=True below allows us to see a list of each sequential reading t_qc = transpile(qc, qasm_sim) obj = assemble(t_qc, shots=1) result = qasm_sim.run(qobj, memory=True).result() readings = result.get_memory() print("Register Reading: " + readings[0]) phase = int(readings[0],2)/(2**n_count) print("Corresponding Phase: %f" % phase) return phase phase = qpe_amod15(a) # Phase = s/r Fraction(phase).limit_denominator(15) # Denominator should (hopefully!) tell us r frac = Fraction(phase).limit_denominator(15) s, r = frac.numerator, frac.denominator print(r) guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)] print(guesses) start = time.perf_counter() a = 7 factor_found = False attempt = 0 while not factor_found: attempt += 1 print("\nAttempt %i:" % attempt) phase = qpe_amod15(a) # Phase = s/r frac = Fraction(phase).limit_denominator(N) # Denominator should (hopefully!) tell us r r = frac.denominator print("Result: r = %i" % r) if phase != 0: # Guesses for factors are gcd(x^{r/2} ±1 , 15) guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)] print("Guessed Factors: %i and %i" % (guesses[0], guesses[1])) for guess in guesses: if guess not in [1,N] and (N % guess) == 0: # Check to see if guess is a factor print("*** Non-trivial factor found: %i ***" % guess) factor_found = True elapsed = time.perf_counter() - start print('Elapsed %.3f seconds.' % elapsed) from matplotlib import pyplot import numpy as np import timeit from functools import partial import random def fsquare(N): """ O(n^2) function """ for i in range(N): for j in range(N): x = i*j def flog(N): for i in range(N): np.log(N) def plotTC(fn, nMin, nMax, nInc, nTests): """ Run timer and plot time complexity """ x = [] y = [] for i in range(nMin, nMax, nInc): N = i testNTimer = timeit.Timer(partial(fn, N)) t = testNTimer.timeit(number=nTests) x.append(i) y.append(t) p1 = pyplot.plot(x, y, 'o') # main() function def main(): print('Analyzing Algorithms...') plotTC(fsquare, 10, 1000, 10, 10) plotTC(flog, 10,1000,10,10) pyplot.xlabel('N') pyplot.ylabel('O Complexity') pyplot.show() if __name__ == '__main__': main()
https://github.com/marcoparadina/Qiskit_Hackathon_ETH
marcoparadina
# Write your code here import numpy as np import matplotlib.pyplot as plt #Parameters of the distribution mu = 0.1 sigma = 0.2 S0 = 50 #We want to simulate npaths=10000 paths of the r.v #for tha we discretize the time from t=0 to T=10 in n=100 steps n = 100 npaths=10000 T=10 dt =T/n np.random.seed(1) s = np.exp( (mu - sigma ** 2 / 2) * dt + sigma * np.random.normal(0, np.sqrt(dt), size=(npaths,n)).T ) s = np.vstack([np.ones(npaths), s]) s = S0 * s.cumprod(axis=0) #This is for scaling the x axis correctly to 0 to T=10 in 100 steps time=np.linspace(0,T,n+1) t=np.full(shape=(npaths,n+1),fill_value=time).T #Plot the paths plt.plot(t,s) plt.xlabel("$t$") plt.ylabel("$x$") plt.title( "10000 paths of GBM for $\mu=0.1$ and $\sigma=0.2$" ) plt.show() #We calculate the expectation by averaging over the samples expectation_numerical=sum(s[100])/npaths expectation_numerical # E_ST #We compare with the theoretical result given by the analytical solution #E=S_0*exp(mu*t) expectation_analytical=S0*np.exp(mu*10) expectation_analytical #As we can see we get quite similar results %matplotlib inline from qiskit import QuantumCircuit, IBMQ from qiskit import Aer from qiskit_ibm_runtime import QiskitRuntimeService, Session, Estimator, Options from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem, MaximumLikelihoodAmplitudeEstimation from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # Loading your IBM Q account(s) IBMQ.save_account('a68087d9c262053b5e20eea6f7d5dd9a02252efbc722cc8774bde7a6b69f71b9b077e3cd8541be84c5841c130f3d8f1c4d3940bf42ccbd3f1caae0d843c42976') # Write your code here # number of qubits to represent the uncertainty num_samples_qubits = 4 # parameters for considered random distribution S0 = 50 T = 10 #parameters for log-normal distribution mu = 0.1 sigma = 0.2 mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma*2) - 1) * np.exp(2 * mu + sigma*2) stddev = np.sqrt(variance) #lowest and highest value considered low = np.maximum(0, mean - 3 * stddev) high = mean + 3* stddev #We construct a circuit to load a log-normal random distribution into a quantum state. preparation_model = LogNormalDistribution( num_samples_qubits, mu=mu, sigma=sigma**2, bounds=(low, high) ) preparation_model.num_qubits # plot probability distribution x = preparation_model.values y = preparation_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("$S_T$", size=15) plt.ylabel("Probability", size=15) plt.show() # Write your code here sim=Aer.get_backend('qasm_simulator') num_samples_qubits = 4 #this number should be a power of 2 num_qubits = num_samples_qubits + 1 #add the target qubit that we will measure circuit = QuantumCircuit(num_qubits) circuit.append(preparation_model, range(num_samples_qubits)) def controlled_rotations(num_control_qubits, angle): qc = QuantumCircuit(num_control_qubits+1) #do the controlled rotations for i in range(num_control_qubits-1, -1, -1): qc.cry(2**(num_control_qubits-1-i)*angle, control_qubit=i,target_qubit=num_control_qubits) return qc.to_gate() #The bounds of the support of f(x) x_l = 0.01 x_u = 0.3*sigma num_fourier_terms = 4 P = (x_u-x_l) #period of the periodic function delta = (x_u-x_l)/(2**num_samples_qubits-1) #step in the discretized space #Initialize sampler to run circuits #service = QiskitRuntimeService(channel='ibm_quantum') #backend = service.backend('ibmq_qasm_simulator') #choose the simulator or device sampler = Sampler() #Arrays where fourier terms are stored fourier_terms_cos = [] fourier_terms_sin = [] for n in range(num_fourier_terms): w = 2*np.pi/P #phase of the fourier terms theta = n*w*delta alpha_cos=2*(np.pi)*x_l alpha_sin=2*(np.pi)*x_l+np.pi/2 #circuit must be reinitialized everytime circuit_fourier=circuit.copy() #distinguish two cases: #If we want to estimate the cos term: circuit_sin=circuit_fourier.copy() circuit_sin.ry(alpha_cos,num_samples_qubits) circuit_sin.append(controlled_rotations(num_samples_qubits,theta),range(num_qubits)) #run QAE for the cos term problem = EstimationProblem(circuit_sin, objective_qubits = num_samples_qubits) mlae = MaximumLikelihoodAmplitudeEstimation(evaluation_schedule = 3, sampler = sampler) mlae_result = mlae.estimate(problem) fourier_terms_cos.append(1-2*mlae_result.estimation) print("Estimate of a_",n+1,"is",1-2*mlae_result.estimation) #If we want to estimate the sin term: circuit_cos=circuit_fourier.copy() circuit_cos.ry(alpha_sin,num_samples_qubits) circuit_cos.append(controlled_rotations(num_samples_qubits,theta),range(num_qubits)) #run QAE for the sin term problem = EstimationProblem(circuit_cos, num_samples_qubits) mlae = MaximumLikelihoodAmplitudeEstimation(evaluation_schedule = 3, sampler = sampler) mlae_result = mlae.estimate(problem) fourier_terms_sin.append(1-2*mlae_result.estimation) print("Estimate of b_",n+1,"is",1-2*mlae_result.estimation,"\n") circuit_sin.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'}) #New version to compute coefficients import numpy as np import scipy.integrate as spi import matplotlib.pyplot as plt #x = np.linspace(45, 144, 100) #y = np.piecewise(x, [((x >= 45) & (x <= 100)), ((x >= 100) & (x < 145))], [0, lambda x: x-100]) #plt.plot(x, y) def f(x): return np.piecewise(x, [((x >= 45) & (x <= 100)), ((x >= 100) & (x < 145))], [0, lambda x: x-100]) #t is the independent variable x_l = 50 x_u = 107 P = (x_u-x_l) #period value BT=0. #initian value of t (begin time) ET=10. #final value of t (end time) FS=100 #number of discrete values of t between BT and ET #all discrete values of t in the interval from BT and ET t_range = np.linspace(BT, ET, FS) y_true = f(t_range) #the true f(t) #function that computes the real fourier couples of coefficients (a0, 0), (a1, b1)...(aN, bN) def compute_real_fourier_coeffs(func, N): result = [] for n in range(N+1): an = (2./P) * spi.quad(lambda t: func(t) * np.cos(2 * np.pi * n * t / P), 0, P)[0] bn = (2./P) * spi.quad(lambda t: func(t) * np.sin(2 * np.pi * n * t / P), 0, P)[0] result.append((an, bn)) return np.array(result) def fit_func_by_fourier_series_with_real_coeffs(t, AB): result = 0. A = AB[:,0] B = AB[:,1] for n in range(0, len(AB)): if n > 0: result += A[n] * fourier_terms_cos[n] + B[n]* fourier_terms_sin[n] else: result += A[0] return result def f(t): return max(np.exp(mu*t) - 100, 0) AB = compute_real_fourier_coeffs(f,num_fourier_terms-1 ) est = fit_func_by_fourier_series_with_real_coeffs(0, AB) print(est) #The results for different values of n (precission of Fourier) #44.698394965554456 for n=4 #41.10875168637083 for n=8 #48.88444858978799 for n=12 #37.715743030433934 for n=16 #45.077490680927184 for n=20 #48.90604298278019 for n=32 #We choose the Maximum Likelihood Amplitude estimation because it is one of the fastest ones and it is #also subject to paralelization for a more efficient use # Write your code here # Write your code here # Build your presentation and rehearse your pitch!
https://github.com/AlluSu/Grover-Search
AlluSu
''' Demonstrating Grover's search algorithm. Scenario: We have a phone book containing names and numbers. Because the phone book is sorted alphabetically by names, it is easy to find a persons phone number by persons name. However, a more difficult task would be if we want to find a person by a phone number. Number-wise, if we have a million (1 000 000) entries in a phone book, we would on average have to look up half of it to find the correct entry (500 000 lookups). Worst case complexity is 1 000 000 queries. Grover's algorithm provides a quadratical speed-up to unstructured search probelms. Applying Grover's algorithm to this problem would reduce the needed amount of lookups to only 1000, in the worst case. This program simulates the above scenario on a smaller scale. ''' import json import random from os import getenv from dotenv import load_dotenv import matplotlib.pyplot as plt from qiskit import transpile, assemble, IBMQ from qiskit.quantum_info import Statevector from qiskit.algorithms import AmplificationProblem, Grover from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session from qiskit.tools.visualization import plot_histogram from qiskit.tools.monitor import job_monitor # Loads the API key used to connect to the cloud load_dotenv() # Global variables for easier maintenace of code TOKEN = getenv('IBM_QUANTUM_TOKEN') USED_BACKEND = 'ibm_oslo' FILE_TO_WRITE_NAME ='History.txt' # Function used for printing quantum circuits as matplotlib images def print_quantum_circuits(circuits): #Matplotlib output, freezes the program execution until windows are closed for circuit in circuits: circuit.draw(output = 'mpl') plt.show() # Function used for connecting to the IBM quantum computer # TODO: Remove deprecated components def connect_to_cloud(token, backend): IBMQ.save_account(token, overwrite=True) provider = IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') used_backend = provider.get_backend(backend) # for lower latency choosing the geographically closest one print(f"The used backend is: {used_backend}") return used_backend # Writing the randomized entry to see if the results are correct by the quantum computer. # Results can be obtained from the IBM cloud with the job_id. # TODO: Use a real (cloud) database instead of a .txt-file. def write_to_history(randomized_entry, job_id): results_history = open(FILE_TO_WRITE_NAME, "a") results_history.write("\n" + str(randomized_entry) + " " + str(job_id) + "\n") results_history.close() # Run the Grover search on a simulator backend. # TODO: Refactor logging/printing to separate component. def run_grover_in_simulator(grover_circuits): service = QiskitRuntimeService() backend_simulator = "ibmq_qasm_simulator" with Session(service=service, backend=backend_simulator): sampler = Sampler() job = sampler.run(circuits=grover_circuits, shots=1000) job_monitor(job) result = job.result() print('===================================== RESULTS =====================================') print(f"{result.quasi_dists}") print(f"{result.metadata}") qubits = 3 optimal_amount = Grover.optimal_num_iterations(1, qubits) print(f"The optimal amount of Grover iterations is: {optimal_amount} with {qubits} qubits") return result, job # Run the Grover search on a real quantum computer backend. def run_grover_in_quantum_computer(random_name_formatted, backend, grover_circuits): print(f"The value, which we are looking for is: {random_name_formatted}") mapped_circuit = transpile(grover_circuits, backend=backend) quantum_object = assemble(mapped_circuit, backend=backend, shots=1000) job = backend.run(quantum_object) job_monitor(job) job_id = job.job_id() result = job.result() print(result) return result, job # Visualize the results gotten from the simulator run. # TODO: Refactor logging/printing to separate component. def visualize_simulator_results(result, random_name_formatted): for distribution in range(0, len(result.quasi_dists)): results_dictionary = result.quasi_dists[distribution].binary_probabilities() answer = max(results_dictionary, key=results_dictionary.get) print(f"With {distribution + 1} iterations the following probabilities were returned: \n {result.quasi_dists[distribution]}") print(f"Maximum probability was for the value {answer}") print(f"Correct answer: {random_name_formatted}") print('Correct!' if answer == random_name_formatted else 'Failure!') print('\n') histogram = plot_histogram(result.quasi_dists, legend=['1 iteration', '2 iterations', '3 iterations', '4 iterations', '5 iterations', '6 iterations', '7 iterations', '8 iterations']) plt.xlabel("Which entry in the data [0,..,7]") plt.show() def visualize_existing_simulator_results(): with open('test-results/simulator/cfuq0n7b5be8coe26so0-result.json') as f: measurements = json.load(f) plot_histogram(measurements['quasi_dists'], legend=['1 iteration', '2 iterations', '3 iterations', '4 iterations', '5 iterations', '6 iterations', '7 iterations', '8 iterations']) plt.show() def visualize_existing_qc_results(): with open('test-results/real/63fda07b6d831406fd4b6847-output.json') as f: measurements = json.load(f) measurements_results = measurements.get('results') counts_list = [] for value in measurements_results: counts_list.append(value.get('data').get("counts")) plot_histogram(data=counts_list, legend=['1 iteration', '2 iterations', '3 iterations', '4 iterations', '5 iterations', '6 iterations', '7 iterations', '8 iterations']) plt.show() # The real program execution starts here. def run_grover(): # Commented out, used during the writing of the seminar report to visualize results to use in the report # TODO: Refactor to get results straight from the cloud with job id, or give path as parameter # visualize_existing_simulator_results() # visualize_existing_qc_results() # STEP 1: Construct and define the unstructured search problem. random_name = random.randint(0,7) # This simulates a random person from a phone book containing 8 entries [0,..,7]. As 8 = 2³, we need 3 qubits. random_name_formatted = format(random_name, '03b') # This formats the random person's name to a 3-bit string oracle = Statevector.from_label(random_name_formatted) # Oracle, which is a black-box quantum circuit telling if your guess is right or wrong. We will let the oracle know the owner. unstructured_search = AmplificationProblem(oracle, is_good_state=random_name_formatted) # Grover's algorithm uses a technique for modifying quantum states to raise the probability amplitude of the wanted value # STEP 2: Constructing the adequate quantum circuit for the problem grover_circuits = [] # Grover's algorithm's accuracy to find the right solution increases with the amount of iterations ip to a certain point (in theory). values = [0, 1, 2, 3, 4, 5, 6, 7] for value in range(0, len(values)): grover = Grover(iterations=values[value]) # using Grover's algorithm straight from the Qiskit library quantum_circuit = grover.construct_circuit(unstructured_search) quantum_circuit.measure_all() grover_circuits.append(quantum_circuit) # Commented for now so the program does not freeze # Used for printing the quantum circuits if interested to see them # print_quantum_circuits(grover_circuits) # STEP 3: Submit the circuits to IBM Quantum Computer or run with a simulator # NOTE: Occasionally the simulator is significantly faster than the real computer due to queue try: user_option = int(input( "Press \n 1 for simulator \n 2 for real hardware \n 3 for retrieving an existing job by job_id \n 4 for both simulator and real hardware \n" )) except ValueError: raise ValueError('Please give an integer') # Simulator if user_option == 1: # Result from Grover's algorithm result, job = run_grover_in_simulator(grover_circuits) # Write the randomized entry and job id of the run to a file write_to_history(random_name_formatted, job) # Counting probabilities and doing plotting & visualization with matplotlib visualize_simulator_results(result, random_name_formatted) # Real quantum computer elif user_option == 2: # Connect to IBM cloud and get the backend provider. backend = connect_to_cloud(TOKEN, USED_BACKEND) result = run_grover_in_quantum_computer(random_name_formatted, backend, grover_circuits) # Write the randomized entry and job id of the run to a file write_to_history(random_name_formatted, result.job_id()) # Due to occasional queues (45 minutes to 4 hours) in the free-tier quantum computer, it is easier to investigate and experiment by using previous runs, which can be obtained with the job id. elif user_option == 3: job_id = input("Give job id: ") backend = connect_to_cloud(TOKEN, USED_BACKEND) result = backend.retrieve_job(job_id) print(f"as a dict: {result.result().to_dict()}") all_results_as_dict = result.result().to_dict() print(all_results_as_dict) # This runs the job on a simulator and on the real hardware for the same randomized value. # Decided to create this due to better and transparent comparison for the different systems. elif user_option == 4: result = run_grover_in_simulator(grover_circuits) write_to_history(random_name_formatted, result[1].job_id()) visualize_simulator_results(result[0], random_name_formatted) backend = connect_to_cloud(TOKEN, USED_BACKEND) quantum_job_result_and_id = run_grover_in_quantum_computer(random_name_formatted, backend, grover_circuits) write_to_history(random_name_formatted, quantum_job_result_and_id[1].job_id()) # Undefined input closes the program. else: print("Closing program!") exit() def main(): run_grover() if __name__ == "__main__": main()
https://github.com/NicoGiamm/Quantum_computing
NicoGiamm
import qiskit qiskit.__qiskit_version__ import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import BasicAer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.visualization import plot_histogram q = QuantumRegister(6) qc = QuantumCircuit(q) qc.x(q[2]) qc.cx(q[1], q[5]) qc.cx(q[2], q[5]) qc.cx(q[3], q[5]) qc.ccx(q[1], q[2], q[4]) qc.ccx(q[3], q[4], q[5]) qc.ccx(q[1], q[2], q[4]) qc.x(q[2]) qc.draw(output='mpl') def black_box_u_f(circuit, f_in, f_out, aux, n, exactly_1_3_sat_formula): """Circuit that computes the black-box function from f_in to f_out. Create a circuit that verifies whether a given exactly-1 3-SAT formula is satisfied by the input. The exactly-1 version requires exactly one literal out of every clause to be satisfied. """ num_clauses = len(exactly_1_3_sat_formula) for (k, clause) in enumerate(exactly_1_3_sat_formula): # This loop ensures aux[k] is 1 if an odd number of literals # are true for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) # Flip aux[k] if all literals are true, using auxiliary qubit # (ancilla) aux[num_clauses] circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) # Flip back to reverse state of negative literals and ancilla circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # The formula is satisfied if and only if all auxiliary qubits # except aux[num_clauses] are 1 if (num_clauses == 1): circuit.cx(aux[0], f_out[0]) elif (num_clauses == 2): circuit.ccx(aux[0], aux[1], f_out[0]) elif (num_clauses == 3): circuit.ccx(aux[0], aux[1], aux[num_clauses]) circuit.ccx(aux[2], aux[num_clauses], f_out[0]) circuit.ccx(aux[0], aux[1], aux[num_clauses]) else: raise ValueError('We only allow at most 3 clauses') # Flip back any auxiliary qubits to make sure state is consistent # for future executions of this routine; same loop as above. for (k, clause) in enumerate(exactly_1_3_sat_formula): for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # -- end function def n_controlled_Z(circuit, controls, target): """Implement a Z gate with multiple controls""" if (len(controls) > 2): raise ValueError('The controlled Z with more than 2 ' + 'controls is not implemented') elif (len(controls) == 1): circuit.h(target) circuit.cx(controls[0], target) circuit.h(target) elif (len(controls) == 2): circuit.h(target) circuit.ccx(controls[0], controls[1], target) circuit.h(target) # -- end function def inversion_about_average(circuit, f_in, n): """Apply inversion about the average step of Grover's algorithm.""" # Hadamards everywhere for j in range(n): circuit.h(f_in[j]) # D matrix: flips the sign of the state |000> only for j in range(n): circuit.x(f_in[j]) n_controlled_Z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1]) for j in range(n): circuit.x(f_in[j]) # Hadamards everywhere again for j in range(n): circuit.h(f_in[j]) # -- end function qr = QuantumRegister(3) qInvAvg = QuantumCircuit(qr) inversion_about_average(qInvAvg, qr, 3) qInvAvg.draw(output='mpl') """ Grover search implemented in Qiskit. This module contains the code necessary to run Grover search on 3 qubits, both with a simulator and with a real quantum computing device. This code is the companion for the paper "An introduction to quantum computing, without the physics", Giacomo Nannicini, https://arxiv.org/abs/1708.03684. """ def input_state(circuit, f_in, f_out, n): """(n+1)-qubit input state for Grover search.""" for j in range(n): circuit.h(f_in[j]) circuit.x(f_out) circuit.h(f_out) # -- end function # Make a quantum program for the n-bit Grover search. n = 3 # Exactly-1 3-SAT formula to be satisfied, in conjunctive # normal form. We represent literals with integers, positive or # negative, to indicate a Boolean variable or its negation. exactly_1_3_sat_formula = [[1, 2, -3], [-1, -2, -3], [-1, 2, 3]] # Define three quantum registers: 'f_in' is the search space (input # to the function f), 'f_out' is bit used for the output of function # f, aux are the auxiliary bits used by f to perform its # computation. f_in = QuantumRegister(n) f_out = QuantumRegister(1) aux = QuantumRegister(len(exactly_1_3_sat_formula) + 1) # Define classical register for algorithm result ans = ClassicalRegister(n) # Define quantum circuit with above registers grover = QuantumCircuit() grover.add_register(f_in) grover.add_register(f_out) grover.add_register(aux) grover.add_register(ans) input_state(grover, f_in, f_out, n) T = 2 for t in range(T): # Apply T full iterations black_box_u_f(grover, f_in, f_out, aux, n, exactly_1_3_sat_formula) inversion_about_average(grover, f_in, n) # Measure the output register in the computational basis for j in range(n): grover.measure(f_in[j], ans[j]) # Execute circuit backend = BasicAer.get_backend('qasm_simulator') job = execute([grover], backend=backend, shots=1000) result = job.result() # Get counts and plot histogram counts = result.get_counts(grover) plot_histogram(counts) IBMQ.load_account() # get ibmq_16_melbourne configuration and coupling map backend = IBMQ.get_backend('ibmq_16_melbourne') # compile the circuit for ibmq_16_rueschlikon grover_compiled = transpile(grover, backend=backend, seed_transpiler=1, optimization_level=3) print('gates = ', grover_compiled.count_ops()) print('depth = ', grover_compiled.depth()) grover.draw(output='mpl', scale=0.5)
https://github.com/NicoGiamm/Quantum_computing
NicoGiamm
import cirq import numpy as np from qiskit import QuantumCircuit, execute, Aer import seaborn as sns import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (15,10) q0, q1, q2 = [cirq.LineQubit(i) for i in range(3)] circuit = cirq.Circuit() #entagling the 2 quibits in different laboratories #and preparing the qubit to send circuit.append(cirq.H(q0)) circuit.append(cirq.H(q1)) circuit.append(cirq.CNOT(q1, q2)) #entangling the qubit we want to send to the one in the first laboratory circuit.append(cirq.CNOT(q0, q1)) circuit.append(cirq.H(q0)) #measurements circuit.append(cirq.measure(q0, q1)) #last transformations to obtain the qubit information circuit.append(cirq.CNOT(q1, q2)) circuit.append(cirq.CZ(q0, q2)) #measure of the qubit in the receiving laboratory along z axis circuit.append(cirq.measure(q2, key = 'Z')) circuit #starting simulation sim = cirq.Simulator() results = sim.run(circuit, repetitions=100) sns.histplot(results.measurements['Z'], discrete = True) 100 - np.count_nonzero(results.measurements['Z']), np.count_nonzero(results.measurements['Z']) #in qiskit the qubits are integrated in the circuit qc = QuantumCircuit(3, 1) #entangling qc.h(0) qc.h(1) qc.cx(1, 2) qc.cx(0, 1) #setting for measurment qc.h(0) qc.measure([0,1], [0,0]) #transformation to obtain qubit sent qc.cx(1, 2) qc.cz(0, 2) qc.measure(2, 0) print(qc) #simulation simulator = Aer.get_backend('qasm_simulator') job = execute(qc, simulator, shots=100) res = job.result().get_counts(qc) plt.bar(res.keys(), res.values()) res
https://github.com/RishwiBT/Open-Quantum-Systems-Algorithms
RishwiBT
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile from qiskit.visualization import * from ibm_quantum_widgets import * # qiskit-ibmq-provider has been deprecated. # Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail. from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options # Loading your IBM Quantum account(s) service = QiskitRuntimeService(channel="ibm_quantum") # Invoke a primitive. For more details see https://docs.quantum.ibm.com/run/primitives # result = Sampler().run(circuits).result() from qiskit import quantum_info as qi import numpy as np # Define the probability for the bit-flip error p = 0.5 # Define the Kraus operators for the bit-flip channel I = np.eye(2) # Identity matrix X = np.array([[0, 1], [1, 0]]) # Pauli-X matrix E0 = np.sqrt(1-p) * I E1 = np.sqrt(p) * X # Create the bit-flip channel using Kraus operators bit_flip_channel = qi.Kraus([E0, E1]) # Get the Choi matrix of the channel choi_matrix = qi.Choi(bit_flip_channel) # Alternatively, create the channel as a SuperOp and get the process matrix process_matrix = qi.SuperOp(bit_flip_channel) # Alternatively, create the channel as a SuperOp and get the process matrix chi_matrix = qi.Chi(bit_flip_channel) print("Choi matrix:") print(choi_matrix.data) print("\n(SuperOp representation):") print(process_matrix.data) print("\nProcess matrix ") print(chi_matrix.data) from qiskit import QuantumCircuit from qiskit.quantum_info import Choi, Operator # Create the entanglement circuit qc = QuantumCircuit(2) qc.h(0) # Apply Hadamard gate to the first qubit qc.cx(0, 1) # Apply CNOT gate controlled by the first qubit targeting the second qubit # Convert the circuit into an operator operator = Operator(qc) # Get the Choi matrix of the operator choi_matrix = Choi(operator) # Print the Choi matrix print(choi_matrix) from qiskit import QuantumCircuit from qiskit.quantum_info import Operator # Create the entanglement circuit qc = QuantumCircuit(2) qc.h(0) # Apply Hadamard gate to the first qubit qc.cx(0, 1) # Apply CNOT gate controlled by the first qubit targeting the second qubit # Convert the circuit to a unitary operator unitary = Operator(qc) # The Kraus operator for this unitary process is the unitary itself kraus_op = [unitary.data] # Print out the Kraus operator for i, k in enumerate(kraus_op): print(f"Kraus operator K{i+1}:\n{k}\n")
https://github.com/darkn3to/dinner-problem
darkn3to
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/Jayshah25/Quantum-Algorithms-and-Circuits
Jayshah25
import numpy as np zero_state = np.array([[1],[0]]) one_state = np.array([[0],[1]]) print("The |0> is \n", zero_state) print("The |1> is \n", one_state) print("The shape of the Vector |0> is",zero_state.shape) print("The shape of the Vector |1> is",one_state.shape) !pip install qiskit #Install qiskit on colab !pip install pylatexenc #Required for matplotlib support to render the images of circuit from IPython.display import clear_output #Clear the output after installation clear_output() #QuantumCircuit is the class that we shall use for our circuit #Aer is required to get the required backend support #execute will execute our circuit from qiskit import QuantumCircuit, Aer, execute circuit_es1 = QuantumCircuit(2,2) #initializing our circuit with two qubits and two bits circuit_es1.h(0) #Applying hadamard Gate on the first qubit circuit_es1.cx(0,1) #Applying the CNOT Gate with zeroth qubit as the control qubit #and the first qubit as the target qubit circuit_es1.measure(0,0) #Measuring the zeroth qubit and storing its output to zeroth bit circuit_es1.measure(1,1) #Let's visualize our circuit circuit_es1.draw('mpl') simulator = Aer.get_backend('qasm_simulator') #Using qasm_simulator, we can simulate our circuit on an actual quantum device result = execute(circuit_es1,backend=simulator, shots = 1024).result() #shots = number of time we want to execute the circuit counts = result.get_counts() #Get the results for each simulation from qiskit.visualization import plot_histogram #To visualize our results plot_histogram(counts) circuit_es2 = QuantumCircuit(2,2) circuit_es2.x(0) #Applying the NOT Gate on the first qubit to get the state |01> circuit_es2.h(0) circuit_es2.cx(0,1) circuit_es2.measure(0,0) circuit_es2.measure(1,1) #Let's visualize our circuit circuit_es2.draw('mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit_es2,backend=simulator, shots = 1024).result() counts = result.get_counts() plot_histogram(counts) circuit_es3 = QuantumCircuit(2,2) circuit_es3.x(1) #Applying the NOT Gate on the second qubit to get the state |10> circuit_es3.h(0) circuit_es3.cx(0,1) circuit_es3.measure(0,0) circuit_es3.measure(1,1) #Let's visualize our circuit circuit_es3.draw('mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit_es3,backend=simulator, shots = 1024).result() counts = result.get_counts() plot_histogram(counts) circuit_es4 = QuantumCircuit(2,2) circuit_es4.x(0) circuit_es4.x(1) #Applying the NOT Gates on the two qubits to get the state |11> circuit_es4.h(0) circuit_es4.cx(0,1) circuit_es4.measure(0,0) circuit_es4.measure(1,1) #Let's visualize our circuit circuit_es4.draw('mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit_es4,backend=simulator, shots = 1024).result() counts = result.get_counts() plot_histogram(counts)
https://github.com/Jayshah25/Quantum-Algorithms-and-Circuits
Jayshah25
import numpy as np zero_state = np.array([[1],[0]]) one_state = np.array([[0],[1]]) print("The |0> is \n", zero_state) print("The |1> is \n", one_state) print("The shape of the Vector |0> is",zero_state.shape) print("The shape of the Vector |1> is",one_state.shape) #Getting the user input int values for two numbers num1 = int(input("Enter a value for Number One! \n")) num2 = int(input("Enter a value for Number Two! \n")) num1, num2 = num2, num1 #Swapping print("The value of Number 1 after swapping: ",num1) print("The value of Number 2 after swapping: ",num2) #Getting the user input int values for two numbers num1 = int(input("Enter a value for Number One! \n")) num2 = int(input("Enter a value for Number Two! \n")) def cvtb(num): binnum = [int(i) for i in list('{0:0b}'.format(num))] return binnum '{0:0b}'.format(4) list('{0:0b}'.format(4)) [int(i) for i in list('{0:0b}'.format(4))] #Calling the method "cvtb" and getting the binary equivalents of num1 and num2 num1_b = cvtb(num1) num2_b = cvtb(num2) #Getting the length of each list num1_l = len(num1_b) num2_l = len(num2_b) #Adjusting the length of two lists if num1_l==num2_l: pass elif num1_l < num2_l: diff = num2_l - num1_l #Getting the difference in the lengths for ind in range(diff): num1_b.insert(ind,0)#Adding zeroes to the left elif num2_l < num1_l: diff = num1_l - num2_l for ind in range(diff): num2_b.insert(ind,0) print(num1_b) print(num2_b) #In this block, we check for the indices with the value 1 in the lists num1_b, #num2_b, and store the indices in the corresponding list indices_num1 = [] indices_num2 = [] for i in range(len(num2_b)): if num1_b[i]==1: indices_num1.append(i) if num2_b[i]==1: indices_num2.append(i) #In this block, we check for the indices for which the values #differ in both the lists indices = [] for i in range(len(num2_b)): if num1_b[i]!=num2_b[i]: indices.append(i) !pip install qiskit #Install qiskit on colab !pip install pylatexenc #Required for matplotlib support to render the images of circuit from IPython.display import clear_output #Clear the output after installation clear_output() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute n_qubits = len(num2_b)#Number of required qubits #equals to the length of num2_b or num1_b list n_q1 = QuantumRegister(n_qubits,name='num1') print(n_q1) n_b1 = ClassicalRegister(n_qubits) print(n_b1) qnum1 = QuantumCircuit(n_q1, n_b1) #Initializing the Quantum Circuit #For every index with a value one, we appply a NOT Gate #that transforms state |0> to |1> for i in indices_num1: qnum1.x(i) qnum1.barrier() #We will add a barrier for visual discrimination between the initial #encoding part and the transformation part qnum1.draw('mpl') #Visualizing the Circuit qnum1 n_q2 = QuantumRegister(n_qubits,name='num2') n_b2 = ClassicalRegister(n_qubits) qnum2 = QuantumCircuit(n_q2,n_b2) for i in indices_num2: qnum2.x(i) qnum2.barrier() qnum2.draw('mpl') for i in indices: qnum1.x(i) qnum2.x(i) #Using barriers to distinguish transformation part from output extraction qnum1.barrier() qnum2.barrier() qnum1.draw('mpl') qnum2.draw('mpl') for i in range(3): qnum1.measure(i,i) qnum2.measure(i,i) qnum1.draw('mpl') #Using qasm_simulator, we can simulate our circuit on an actual quantum device simulator = Aer.get_backend('qasm_simulator') #Get the results for each simulation result_num1 = execute(qnum1,backend=simulator).result().get_counts() #Visualizing the results through a histogram from qiskit.visualization import plot_histogram plot_histogram(result_num1) qnum2.draw('mpl') simulator = Aer.get_backend('qasm_simulator') result_num2 = execute(qnum2,backend=simulator).result().get_counts() plot_histogram(result_num2)
https://github.com/Christophe-pere/Deutsch_Jozsa_qiskit
Christophe-pere
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram class DeutschJozsa: ''' Class to generate a DeutschJozsa object containing: - init functions - oracle function - dj function ''' def __init__(self, case, input_str): ''' Initialization of the object: @case: (str) type of oracle balanced or constant @input_str: (str) string input state values ''' self.case = case self.number_qubit = len(input_str) self.str_input = input_str def oracle(self): ''' Will create the oracle needed for the Deutsch-Jozsa algorithm No input, the function will be used in the dj function @return the oracle in form of a gate ''' # Create the QuantumCircuit with n+1 qubits self.oracle_circuit = QuantumCircuit(self.number_qubit+1) # Balanced case if self.case == "balanced": # apply an X-gate to a qubit when its value is 1 for qubit in range(len(self.str_input)): if self.str_input[qubit] == '1': self.oracle_circuit.x(qubit) # Apply CNOT gates on each qubit for qubit in range(self.number_qubit): self.oracle_circuit.cx(qubit, self.number_qubit) # apply another set of X gates when the input qubit == 1 for qubit in range(len(self.str_input)): if self.str_input[qubit] == '1': self.oracle_circuit.x(qubit) # Constant case if self.case == "constant": # Output 0 for a constant oracle self.output = np.random.randint(2) if self.output == 1: self.oracle_circuit.x(self.number_qubit) # convert the quantum circuit into a gate self.oracle_gate = self.oracle_circuit.to_gate() # name of the oracle self.oracle_gate.name = "Oracle" return self.oracle_gate def dj(self): ''' Create the Deutsch-Jozsa algorithm in the general case with n qubit No input @return the quantum circuit of the DJ ''' self.dj_circuit = QuantumCircuit(self.number_qubit+1, self.number_qubit) # Set up the output qubit: self.dj_circuit.x(self.number_qubit) self.dj_circuit.h(self.number_qubit) # Psi_0 for qubit in range(self.number_qubit): self.dj_circuit.h(qubit) # Psi_1 + oracle self.dj_circuit.append(self.oracle(), range(self.number_qubit+1)) # Psi_2 for qubit in range(self.number_qubit): self.dj_circuit.h(qubit) # Psi_3 # Let's put some measurement for i in range(self.number_qubit): self.dj_circuit.measure(i, i) return self.dj_circuit test = DeutschJozsa('constant', '0110') #circuit = test.oracle() dj_circuit = test.dj() dj_circuit.draw('mpl') qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) from qiskit import IBMQ #TOKEN = 'paste your token here' #IBMQ.save_account(TOKEN) IBMQ.load_account() # Load account from disk IBMQ.providers() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() provider.backends(filters=lambda x: x.configuration().n_qubits >= 5 and not x.configuration().simulator and x.status().operational==True) backend = provider.get_backend('ibmq_manila') backend mapped_circuit = transpile(dj_circuit, backend=backend) qobj = assemble(mapped_circuit, backend=backend, shots=1024) job = backend.run(qobj) job.status() # 9:17 pm result = job.result() counts = result.get_counts() print(counts) plot_histogram(counts) plot_histogram(counts,figsize=(10,8), filename='DJ.jpeg')
https://github.com/maximusron/qgss_2021_labs
maximusron
from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=2, reps=1, entanglement='linear') ansatz.draw('mpl', style='iqx') from qiskit.opflow import Z, I hamiltonian = Z ^ Z from qiskit.opflow import StateFn expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) import numpy as np point = np.random.random(ansatz.num_parameters) index = 2 from qiskit import Aer from qiskit.utils import QuantumInstance backend = Aer.get_backend('qasm_simulator') q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 2718, seed_transpiler = 2718) from qiskit.circuit import QuantumCircuit from qiskit.opflow import Z, X H = X ^ X U = QuantumCircuit(2) U.h(0) U.cx(0, 1) # YOUR CODE HERE expectation = StateFn(H, is_measurement=True) @ StateFn(U) matmult_result = expectation.eval() from qc_grader import grade_lab4_ex1 # Note that the grading function is expecting a complex number grade_lab4_ex1(matmult_result) from qiskit.opflow import CircuitSampler, PauliExpectation sampler = CircuitSampler(q_instance) # YOUR CODE HERE expectation = StateFn(H, is_measurement=True) @ StateFn(U) in_pauli_basis = PauliExpectation().convert(expectation) shots_result = sampler.convert(in_pauli_basis).eval() from qc_grader import grade_lab4_ex2 # Note that the grading function is expecting a complex number grade_lab4_ex2(shots_result) from qiskit.opflow import PauliExpectation, CircuitSampler expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) in_pauli_basis = PauliExpectation().convert(expectation) sampler = CircuitSampler(q_instance) def evaluate_expectation(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(in_pauli_basis, params=value_dict).eval() return np.real(result) eps = 0.2 e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0 plus = point + eps * e_i minus = point - eps * e_i finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps) print(finite_difference) from qiskit.opflow import Gradient expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient('fin_diff', analytic=False, epsilon=eps) grad = shifter.convert(expectation, params=ansatz.parameters[index]) print(grad) value_dict = dict(zip(ansatz.parameters, point)) sampler.convert(grad, value_dict).eval().real eps = np.pi / 2 e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0 plus = point + eps * e_i minus = point - eps * e_i finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / 2 print(finite_difference) expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient() # parameter-shift rule is the default grad = shifter.convert(expectation, params=ansatz.parameters[index]) sampler.convert(grad, value_dict).eval().real expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient('lin_comb') # parameter-shift rule is the default grad = shifter.convert(expectation, params=ansatz.parameters[index]) sampler.convert(grad, value_dict).eval().real # initial_point = np.random.random(ansatz.num_parameters) initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341]) expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz)) gradient = Gradient().convert(expectation) gradient_in_pauli_basis = PauliExpectation().convert(gradient) sampler = CircuitSampler(q_instance) def evaluate_gradient(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() # add parameters in here! return np.real(result) # Note: The GradientDescent class will be released with Qiskit 0.28.0 and can then be imported as: # from qiskit.algorithms.optimizers import GradientDescent from qc_grader.gradient_descent import GradientDescent gd_loss = [] def gd_callback(nfevs, x, fx, stepsize): gd_loss.append(fx) gd = GradientDescent(maxiter=300, learning_rate=0.01, callback=gd_callback) x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, # number of parameters evaluate_expectation, # function to minimize gradient_function=evaluate_gradient, # function to evaluate the gradient initial_point=initial_point) # initial point import matplotlib import matplotlib.pyplot as plt matplotlib.rcParams['font.size'] = 14 plt.figure(figsize=(12, 6)) plt.plot(gd_loss, label='vanilla gradient descent') plt.axhline(-1, ls='--', c='tab:red', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend(); from qiskit.opflow import NaturalGradient expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz)) natural_gradient = NaturalGradient(regularization='ridge').convert(expectation) natural_gradient_in_pauli_basis = PauliExpectation().convert(natural_gradient) sampler = CircuitSampler(q_instance, caching="all") def evaluate_natural_gradient(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(natural_gradient, params=value_dict).eval() return np.real(result) print('Vanilla gradient:', evaluate_gradient(initial_point)) print('Natural gradient:', evaluate_natural_gradient(initial_point)) qng_loss = [] def qng_callback(nfevs, x, fx, stepsize): qng_loss.append(fx) qng = GradientDescent(maxiter=300, learning_rate=0.01, callback=qng_callback) x_opt, fx_opt, nfevs = qng.optimize(initial_point.size, evaluate_expectation, gradient_function=evaluate_natural_gradient, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() from qc_grader.spsa import SPSA spsa_loss = [] def spsa_callback(nfev, x, fx, stepsize, accepted): spsa_loss.append(fx) spsa = SPSA(maxiter=300, learning_rate=0.01, perturbation=0.01, callback=spsa_callback) x_opt, fx_opt, nfevs = spsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() # Note: The QNSPSA class will be released with Qiskit 0.28.0 and can then be imported as: # from qiskit.algorithms.optimizers import QNSPSA from qc_grader.qnspsa import QNSPSA qnspsa_loss = [] def qnspsa_callback(nfev, x, fx, stepsize, accepted): qnspsa_loss.append(fx) fidelity = QNSPSA.get_fidelity(ansatz, q_instance, expectation=PauliExpectation()) qnspsa = QNSPSA(fidelity, maxiter=300, learning_rate=0.01, perturbation=0.01, callback=qnspsa_callback) x_opt, fx_opt, nfevs = qnspsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() autospsa_loss = [] def autospsa_callback(nfev, x, fx, stepsize, accepted): autospsa_loss.append(fx) autospsa = SPSA(maxiter=300, learning_rate=None, perturbation=None, callback=autospsa_callback) x_opt, fx_opt, nfevs = autospsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA') plt.plot(autospsa_loss, 'tab:red', label='Powerlaw SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() H_tfi = -(Z^Z^I)-(I^Z^Z)-(X^I^I)-(I^X^I)-(I^I^X) from qc_grader import grade_lab4_ex3 # Note that the grading function is expecting a Hamiltonian grade_lab4_ex3(H_tfi) from qiskit.circuit.library import EfficientSU2 efficient_su2 = EfficientSU2(3, entanglement="linear", reps=2) tfi_sampler = CircuitSampler(q_instance) def evaluate_tfi(parameters): exp = StateFn(H_tfi, is_measurement=True).compose(StateFn(efficient_su2)) value_dict = dict(zip(efficient_su2.parameters, parameters)) result = tfi_sampler.convert(PauliExpectation().convert(exp), params=value_dict).eval() return np.real(result) # target energy tfi_target = -3.4939592074349326 # initial point for reproducibility tfi_init = np.array([0.95667807, 0.06192812, 0.47615196, 0.83809827, 0.89022282, 0.27140831, 0.9540853 , 0.41374024, 0.92595507, 0.76150126, 0.8701938 , 0.05096063, 0.25476016, 0.71807858, 0.85661325, 0.48311132, 0.43623886, 0.6371297 ]) spsa = SPSA(maxiter = 300, learning_rate = None, perturbation = None, callback = None) tfi_result = spsa.optimize(tfi_init.size, evaluate_tfi, initial_point = tfi_init) tfi_minimum = tfi_result[1] print("Error:", np.abs(tfi_result[1] - tfi_target)) from qc_grader import grade_lab4_ex4 # Note that the grading function is expecting a floating point number grade_lab4_ex4(tfi_minimum) from qiskit_machine_learning.datasets import ad_hoc_data training_features, training_labels, test_features, test_labels = ad_hoc_data( training_size=20, test_size=10, n=2, one_hot=False, gap=0.5 ) # the training labels are in {0, 1} but we'll use {-1, 1} as class labels! training_labels = 2 * training_labels - 1 test_labels = 2 * test_labels - 1 def plot_sampled_data(): from matplotlib.patches import Patch from matplotlib.lines import Line2D import matplotlib.pyplot as plt plt.figure(figsize=(12,6)) for feature, label in zip(training_features, training_labels): marker = 'o' color = 'tab:green' if label == -1 else 'tab:blue' plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) for feature, label in zip(test_features, test_labels): marker = 's' plt.scatter(feature[0], feature[1], marker=marker, s=100, facecolor='none', edgecolor='k') legend_elements = [ Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15), Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15), Line2D([0], [0], marker='s', c='w', mfc='none', mec='k', label='test features', ms=10) ] plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.6)) plt.title('Training & test data') plt.xlabel('$x$') plt.ylabel('$y$') plot_sampled_data() from qiskit.circuit.library import ZZFeatureMap dim = 2 feature_map = ZZFeatureMap(dim, reps=1) # let's keep it simple! feature_map.draw('mpl', style='iqx') ansatz = RealAmplitudes(num_qubits=dim, entanglement='linear', reps=1) # also simple here! ansatz.draw('mpl', style='iqx') circuit = feature_map.compose(ansatz) circuit.draw('mpl', style='iqx') hamiltonian = Z ^ Z # global Z operators gd_qnn_loss = [] def gd_qnn_callback(*args): gd_qnn_loss.append(args[2]) gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=gd_qnn_callback) from qiskit_machine_learning.neural_networks import OpflowQNN qnn_expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit) qnn = OpflowQNN(qnn_expectation, input_params=list(feature_map.parameters), weight_params=list(ansatz.parameters), exp_val=PauliExpectation(), gradient=Gradient(), # <-- Parameter-Shift gradients quantum_instance=q_instance) from qiskit_machine_learning.algorithms import NeuralNetworkClassifier #initial_point = np.array([0.2, 0.1, 0.3, 0.4]) classifier = NeuralNetworkClassifier(qnn, optimizer=gd) classifier.fit(training_features, training_labels); predicted = classifier.predict(test_features) def plot_predicted(): from matplotlib.lines import Line2D plt.figure(figsize=(12, 6)) for feature, label in zip(training_features, training_labels): marker = 'o' color = 'tab:green' if label == -1 else 'tab:blue' plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) for feature, label, pred in zip(test_features, test_labels, predicted): marker = 's' color = 'tab:green' if pred == -1 else 'tab:blue' if label != pred: # mark wrongly classified plt.scatter(feature[0], feature[1], marker='o', s=500, linewidths=2.5, facecolor='none', edgecolor='tab:red') plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) legend_elements = [ Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15), Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15), Line2D([0], [0], marker='s', c='w', mfc='tab:green', label='predict A', ms=10), Line2D([0], [0], marker='s', c='w', mfc='tab:blue', label='predict B', ms=10), Line2D([0], [0], marker='o', c='w', mfc='none', mec='tab:red', label='wrongly classified', mew=2, ms=15) ] plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.7)) plt.title('Training & test data') plt.xlabel('$x$') plt.ylabel('$y$') plot_predicted() qng_qnn_loss = [] def qng_qnn_callback(*args): qng_qnn_loss.append(args[2]) gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=qng_qnn_callback) qnn = OpflowQNN(qnn_expectation, input_params=list(feature_map.parameters), weight_params=list(ansatz.parameters), gradient=NaturalGradient(regularization='ridge'), # <-- using Natural Gradients! quantum_instance=q_instance) classifier = NeuralNetworkClassifier(qnn, optimizer=gd)#, initial_point=initial_point) classifier.fit(training_features, training_labels); def plot_losses(): plt.figure(figsize=(12, 6)) plt.plot(gd_qnn_loss, 'tab:blue', marker='o', label='vanilla gradients') plt.plot(qng_qnn_loss, 'tab:green', marker='o', label='natural gradients') plt.xlabel('iterations') plt.ylabel('loss') plt.legend(loc='best') plot_losses() from qiskit.opflow import I def sample_gradients(num_qubits, reps, local=False): """Sample the gradient of our model for ``num_qubits`` qubits and ``reps`` repetitions. We sample 100 times for random parameters and compute the gradient of the first RY rotation gate. """ index = num_qubits - 1 # you can also exchange this for a local operator and observe the same! if local: operator = Z ^ Z ^ (I ^ (num_qubits - 2)) else: operator = Z ^ num_qubits # real amplitudes ansatz ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps) # construct Gradient we want to evaluate for different values expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz)) grad = Gradient().convert(expectation, params=ansatz.parameters[index]) # evaluate for 100 different, random parameter values num_points = 100 grads = [] for _ in range(num_points): # points are uniformly chosen from [0, pi] point = np.random.uniform(0, np.pi, ansatz.num_parameters) value_dict = dict(zip(ansatz.parameters, point)) grads.append(sampler.convert(grad, value_dict).eval()) return grads num_qubits = list(range(2, 13)) reps = num_qubits # number of layers = numbers of qubits gradients = [sample_gradients(n, r) for n, r in zip(num_qubits, reps)] fit = np.polyfit(num_qubits, np.log(np.var(gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='measured variance') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); from qiskit.opflow import NaturalGradient def sample_natural_gradients(num_qubits, reps): index = num_qubits - 1 operator = Z ^ num_qubits ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps) expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz)) grad = # TODO: ``grad`` should be the natural gradient for the parameter at index ``index``. # Hint: Check the ``sample_gradients`` function, this one is almost the same. grad = NaturalGradient().convert(expectation, params=ansatz.parameters[index]) num_points = 100 grads = [] for _ in range(num_points): point = np.random.uniform(0, np.pi, ansatz.num_parameters) value_dict = dict(zip(ansatz.parameters, point)) grads.append(sampler.convert(grad, value_dict).eval()) return grads num_qubits = list(range(2, 13)) reps = num_qubits # number of layers = numbers of qubits natural_gradients = [sample_natural_gradients(n, r) for n, r in zip(num_qubits, reps)] fit = np.polyfit(num_qubits, np.log(np.var(natural_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='vanilla gradients') plt.semilogy(num_qubits, np.var(natural_gradients, axis=1), 's-', label='natural gradients') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {float(fit[0]):.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) fixed_depth_global_gradients = [sample_gradients(n, 1) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_global_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) linear_depth_local_gradients = [sample_gradients(n, n, local=True) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(linear_depth_local_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) fixed_depth_local_gradients = [sample_gradients(n, 1, local=True) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_local_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_local_gradients, axis=1), 'o-', label='local cost, constant depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = 6 operator = Z ^ Z ^ (I ^ (num_qubits - 4)) def minimize(circuit, optimizer): initial_point = np.random.random(circuit.num_parameters) exp = StateFn(operator, is_measurement=True) @ StateFn(circuit) grad = Gradient().convert(exp) # pauli basis exp = PauliExpectation().convert(exp) grad = PauliExpectation().convert(grad) sampler = CircuitSampler(q_instance, caching="all") def loss(x): values_dict = dict(zip(circuit.parameters, x)) return np.real(sampler.convert(exp, values_dict).eval()) def gradient(x): values_dict = dict(zip(circuit.parameters, x)) return np.real(sampler.convert(grad, values_dict).eval()) return optimizer.optimize(circuit.num_parameters, loss, gradient, initial_point=initial_point) circuit = RealAmplitudes(4, reps=1, entanglement='linear') circuit.draw('mpl', style='iqx') circuit.reps = 5 circuit.draw('mpl', style='iqx') def layerwise_training(ansatz, max_num_layers, optimizer): optimal_parameters = [] fopt = None for reps in range(1, max_num_layers): ansatz.reps = reps # bind already optimized parameters values_dict = dict(zip(ansatz.parameters, optimal_parameters)) partially_bound = ansatz.bind_parameters(values_dict) xopt, fopt, _ = minimize(partially_bound, optimizer) print('Circuit depth:', ansatz.depth(), 'best value:', fopt) optimal_parameters += list(xopt) return fopt, optimal_parameters ansatz = RealAmplitudes(4, entanglement='linear') optimizer = GradientDescent(maxiter=50) np.random.seed(12) fopt, optimal_parameters = layerwise_training(ansatz, 4, optimizer)
https://github.com/maximusron/qgss_2021_labs
maximusron
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram from qiskit_textbook.problems import dj_problem_oracle def lab1_ex1(): qc = QuantumCircuit(1) qc.x(0) return qc state = Statevector.from_instruction(lab1_ex1()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex1 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex1(lab1_ex1()) def lab1_ex2(): qc = QuantumCircuit(1) qc.h(0) # # FILL YOUR CODE IN HERE # # return qc state = Statevector.from_instruction(lab1_ex2()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex2 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex2(lab1_ex2()) def lab1_ex3(): qc = QuantumCircuit(1) qc.h(0) qc.z(0) # # FILL YOUR CODE IN HERE # # return qc state = Statevector.from_instruction(lab1_ex3()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex3 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex3(lab1_ex3()) def lab1_ex4(): qc = QuantumCircuit(1) qc.h(0) qc.y(0) qc.sdg(0) qc.sdg(0) qc.sdg(0) return qc state = Statevector.from_instruction(lab1_ex4()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex4 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex4(lab1_ex4()) def lab1_ex5(): qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement qc.h(0) qc.cx(0,1) qc.x(1) return qc qc = lab1_ex5() qc.draw() # we draw the circuit from qc_grader import grade_lab1_ex5 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex5(lab1_ex5()) qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0 qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1 backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities def lab1_ex6(): qc = QuantumCircuit(3,3) # this time, we not only want two qubits, but also two classical bits for the measurement qc.h(0) qc.cx(0,1) qc.x(1) qc.cx(1,2) qc.y(2) return qc qc = lab1_ex6() qc.draw() # we draw the circuit from qc_grader import grade_lab1_ex6 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex6(lab1_ex6()) oraclenr = 4 # determines the oracle (can range from 1 to 5) oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles oracle.name = "DJ-Oracle" def dj_classical(n, input_str): # build a quantum circuit with n qubits and 1 classical readout bit dj_circuit = QuantumCircuit(n+1,1) # Prepare the initial state corresponding to your input bit string for i in range(n): if input_str[i] == '1': dj_circuit.x(i) # append oracle dj_circuit.append(oracle, range(n+1)) # measure the fourth qubit dj_circuit.measure(n,0) return dj_circuit n = 4 # number of qubits input_str = '1111' dj_circuit = dj_classical(n, input_str) dj_circuit.draw() # draw the circuit input_str = '1111' dj_circuit = dj_classical(n, input_str) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit, qasm_sim) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) def lab1_ex7(): min_nr_inputs = 2# put your answer here max_nr_inputs = 9# put your answer here return [min_nr_inputs, max_nr_inputs] from qc_grader import grade_lab1_ex7 # Note that the grading function is expecting a list of two integers grade_lab1_ex7(lab1_ex7()) n=4 def psi_0(n): qc = QuantumCircuit(n+1,n) qc.x(4) # Build the state (|00000> - |10000>)/sqrt(2) # # # FILL YOUR CODE IN HERE # # return qc dj_circuit = psi_0(n) dj_circuit.draw() def psi_1(n): # obtain the |psi_0> = |00001> state qc = psi_0(n) for qubit in range(n+1): qc.h(qubit) # create the superposition state |psi_1> # # # FILL YOUR CODE IN HERE # # return qc dj_circuit = psi_1(n) dj_circuit.draw() def psi_2(oracle,n): # circuit to obtain psi_1 qc = psi_1(n) # append the oracle qc.append(oracle, range(n+1)) return qc dj_circuit = psi_2(oracle, n) dj_circuit.draw() def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25]) qc = psi_2(oracle, n) # apply n-fold hadamard gate for qubit in range(n): qc.h(qubit) # add the measurement by connecting qubits to classical bits for i in range(n): qc.measure(i, i) return qc return qc dj_circuit = lab1_ex8(oracle, n) dj_circuit.draw() from qc_grader import grade_lab1_ex8 # Note that the grading function is expecting a quantum circuit with measurements grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n)) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/maximusron/qgss_2021_labs
maximusron
# General Imports import numpy as np # Visualisation Imports import matplotlib.pyplot as plt # Scikit Imports from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler, MinMaxScaler # Qiskit Imports from qiskit import Aer, execute from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2 from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate from qiskit_machine_learning.kernels import QuantumKernel # Load digits dataset digits = datasets.load_digits(n_class=2) # Plot example '0' and '1' fig, axs = plt.subplots(1, 2, figsize=(6,3)) axs[0].set_axis_off() axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest') axs[1].set_axis_off() axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest') plt.show() # Split dataset sample_train, sample_test, label_train, label_test = train_test_split( digits.data, digits.target, test_size=0.2, random_state=22) # Reduce dimensions n_dim = 4 pca = PCA(n_components=n_dim).fit(sample_train) sample_train = pca.transform(sample_train) sample_test = pca.transform(sample_test) # Normalise std_scale = StandardScaler().fit(sample_train) sample_train = std_scale.transform(sample_train) sample_test = std_scale.transform(sample_test) # Scale samples = np.append(sample_train, sample_test, axis=0) minmax_scale = MinMaxScaler((-1, 1)).fit(samples) sample_train = minmax_scale.transform(sample_train) sample_test = minmax_scale.transform(sample_test) # Select train_size = 100 sample_train = sample_train[:train_size] label_train = label_train[:train_size] test_size = 20 sample_test = sample_test[:test_size] label_test = label_test[:test_size] print(sample_train[0], label_train[0]) print(sample_test[0], label_test[0]) # 3 features, depth 2 map_z = ZFeatureMap(feature_dimension=3, reps=2) map_z.draw('mpl') # 3 features, depth 1 map_zz = ZZFeatureMap(feature_dimension=3, reps=1) map_zz.draw('mpl') # 3 features, depth 1, linear entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear') map_zz.draw('mpl') # 3 features, depth 1, circular entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular') map_zz.draw('mpl') # 3 features, depth 1 map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ']) map_pauli.draw('mpl') def custom_data_map_func(x): coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x)) return coeff map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'], data_map_func=custom_data_map_func) #map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'], entanglement_blocks='cx', entanglement='circular', insert_barriers=True) twolocal.draw('mpl') twolocaln = NLocal(num_qubits=3, reps=2, rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))], entanglement_blocks=CXGate(), entanglement='circular', insert_barriers=True) twolocaln.draw('mpl') # rotation block: rot = QuantumCircuit(2) params = ParameterVector('r', 2) rot.ry(params[0], 0) rot.rz(params[1], 1) # entanglement block: ent = QuantumCircuit(4) params = ParameterVector('e', 3) ent.crx(params[0], 0, 1) ent.crx(params[1], 1, 2) ent.crx(params[2], 2, 3) nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent, entanglement='linear', insert_barriers=True) nlocal.draw('mpl') qubits = 3 repeats = 2 x = ParameterVector('x', length=qubits) var_custom = QuantumCircuit(qubits) for _ in range(repeats): for i in range(qubits): var_custom.rx(x[i], i) for i in range(qubits): for j in range(i + 1, qubits): var_custom.cx(i, j) var_custom.p(x[i] * x[j], j) var_custom.cx(i, j) var_custom.barrier() var_custom.draw('mpl') print(sample_train[0]) encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True) encode_circuit = encode_map.bind_parameters(sample_train[0]) encode_circuit.draw(output='mpl') x = [-0.1,0.2] encode_map = ZZFeatureMap(feature_dimension=2, reps=4, entanglement='linear', insert_barriers=True) ex1_circuit = encode_map.bind_parameters(x) ex1_circuit.draw(output='mpl') # YOUR CODE HERE from qc_grader import grade_lab3_ex1 # Note that the grading function is expecting a quantum circuit grade_lab3_ex1(ex1_circuit) zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True) zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator')) print(sample_train[0]) print(sample_train[1]) zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1]) zz_circuit.decompose().decompose().draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(zz_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(zz_circuit) counts['0000']/sum(counts.values()) matrix_train = zz_kernel.evaluate(x_vec=sample_train) matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(matrix_train), interpolation='nearest', origin='upper', cmap='Blues') axs[0].set_title("training kernel matrix") axs[1].imshow(np.asmatrix(matrix_test), interpolation='nearest', origin='upper', cmap='Reds') axs[1].set_title("testing kernel matrix") plt.show() x = [-0.1,0.2] y = [0.4,-0.6] zz_map = ZZFeatureMap(feature_dimension=2, reps=4, entanglement='linear', insert_barriers=True) zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator')) zz_circuit = zz_kernel.construct_circuit(x,y) zz_circuit.decompose().decompose().draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(zz_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(zz_circuit) amplitude = counts['00']/sum(counts.values()) # YOUR CODE HERE from qc_grader import grade_lab3_ex2 # Note that the grading function is expecting a floating point number grade_lab3_ex2(amplitude) zzpc_svc = SVC(kernel='precomputed') zzpc_svc.fit(matrix_train, label_train) zzpc_score = zzpc_svc.score(matrix_test, label_test) print(f'Precomputed kernel classification test score: {zzpc_score}') zzcb_svc = SVC(kernel=zz_kernel.evaluate) zzcb_svc.fit(sample_train, label_train) zzcb_score = zzcb_svc.score(sample_test, label_test) print(f'Callable kernel classification test score: {zzcb_score}') classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid'] for kernel in classical_kernels: classical_svc = SVC(kernel=kernel) classical_svc.fit(sample_train, label_train) classical_score = classical_svc.score(sample_test, label_test) print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
https://github.com/maximusron/qgss_2021_labs
maximusron
# General tools import numpy as np import matplotlib.pyplot as plt # Qiskit Circuit Functions from qiskit import execute,QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile import qiskit.quantum_info as qi # Tomography functions from qiskit.ignis.verification.tomography import process_tomography_circuits, ProcessTomographyFitter from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter import warnings warnings.filterwarnings('ignore') target = QuantumCircuit(2) target.h(0) target.h(1) target.rx(np.pi/2,0) target.rx(np.pi/2,1) target.cx(0,1) target.p(np.pi,1) target.cx(0,1) target_unitary = qi.Operator(target) from qc_grader import grade_lab5_ex1 # Note that the grading function is expecting a quantum circuit with no measurements grade_lab5_ex1(target) simulator = Aer.get_backend('qasm_simulator') qpt_circs = process_tomography_circuits(target, measured_qubits = [0,1]) qpt_job = execute(qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192) qpt_result = qpt_job.result() # YOUR CODE HERE qpt_tomo = ProcessTomographyFitter(qpt_result, qpt_circs) qpt_lstq = qpt_tomo.fit(method='lstsq') fidelity = qi.average_gate_fidelity(qpt_lstq, target_unitary) print(fidelity) from qc_grader import grade_lab5_ex2 # Note that the grading function is expecting a floating point number grade_lab5_ex2(fidelity) # T1 and T2 values for qubits 0-3 T1s = [15000, 19000, 22000, 14000] T2s = [30000, 25000, 18000, 28000] # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond from qiskit.providers.aer.noise import thermal_relaxation_error from qiskit.providers.aer.noise import NoiseModel # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(4): noise_thermal.add_quantum_error(errors_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(4): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j,k]) noise_thermal # YOUR CODE HERE from qc_grader import grade_lab5_ex3 # Note that the grading function is expecting a NoiseModel grade_lab5_ex3(noise_thermal) np.random.seed(0) # YOUR CODE HERE noisy_qpt_job = execute(qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192, noise_model=noise_thermal) noisy_qpt_result = noisy_qpt_job.result() noisy_qpt_tomo = ProcessTomographyFitter(noisy_qpt_result, qpt_circs) noisy_qpt_lstsq = noisy_qpt_tomo.fit(method='lstsq') noisy_fidelity = qi.average_gate_fidelity(noisy_qpt_lstsq, target_unitary) print(noisy_fidelity) from qc_grader import grade_lab5_ex4 # Note that the grading function is expecting a floating point number grade_lab5_ex4(noisy_fidelity) np.random.seed(0) meas_cal_circs, state_labels = complete_meas_cal(qubit_list = [0,1]) print(state_labels) qpt_ex5 = execute(meas_cal_circs,simulator, seed_simulator=3145, seed_transpiler=3145,shots=8192, noise_model=noise_thermal) nqpt_result = qpt_ex5.result() meas_fitter = CompleteMeasFitter(nqpt_result, state_labels = state_labels) meas_fitter.plot_calibration() meas_fitter = meas_fitter.filter noisy_qpt_result = meas_fitter.apply(noisy_qpt_result) process = ProcessTomographyFitter(noisy_qpt_result, qpt_circs) lstsq = (process.fit(method = 'lstsq')) noisy_fidelity = qi.average_gate_fidelity(lstsq, target_unitary) print(noisy_fidelity) from qc_grader import grade_lab5_ex5 # Note that the grading function is expecting a floating point number grade_lab5_ex5(noisy_fidelity)
https://github.com/maximusron/qgss_2021_labs
maximusron
import networkx as nx import numpy as np import plotly.graph_objects as go import matplotlib as mpl import pandas as pd from IPython.display import clear_output from plotly.subplots import make_subplots from matplotlib import pyplot as plt from qiskit import Aer from qiskit import QuantumCircuit from qiskit.visualization import plot_state_city from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM from time import time from copy import copy from typing import List from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs mpl.rcParams['figure.dpi'] = 300 from qiskit.circuit import Parameter, ParameterVector #Parameters are initialized with a simple string identifier parameter_0 = Parameter('θ[0]') parameter_1 = Parameter('θ[1]') circuit = QuantumCircuit(1) #We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates circuit.ry(theta = parameter_0, qubit = 0) circuit.rx(theta = parameter_1, qubit = 0) circuit.draw('mpl') parameter = Parameter('θ') circuit = QuantumCircuit(1) circuit.ry(theta = parameter, qubit = 0) circuit.rx(theta = parameter, qubit = 0) circuit.draw('mpl') #Set the number of layers and qubits n=3 num_layers = 2 #ParameterVectors are initialized with a string identifier and an integer specifying the vector length parameters = ParameterVector('θ', n*(num_layers+1)) circuit = QuantumCircuit(n, n) for layer in range(num_layers): #Appending the parameterized Ry gates using parameters from the vector constructed above for i in range(n): circuit.ry(parameters[n*layer+i], i) circuit.barrier() #Appending the entangling CNOT gates for i in range(n): for j in range(i): circuit.cx(j,i) circuit.barrier() #Appending one additional layer of parameterized Ry gates for i in range(n): circuit.ry(parameters[n*num_layers+i], i) circuit.barrier() circuit.draw('mpl') print(circuit.parameters) #Create parameter dictionary with random values to bind param_dict = {parameter: np.random.random() for parameter in parameters} print(param_dict) #Assign parameters using the assign_parameters method bound_circuit = circuit.assign_parameters(parameters = param_dict) bound_circuit.draw('mpl') new_parameters = ParameterVector('Ψ',9) new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[k] for k in range(9)]) new_circuit.draw('mpl') #Run the circuit with assigned parameters on Aer's statevector simulator simulator = Aer.get_backend('statevector_simulator') result = simulator.run(bound_circuit).result() statevector = result.get_statevector(bound_circuit) plot_state_city(statevector) #The following line produces an error when run because 'circuit' still contains non-assigned parameters #result = simulator.run(circuit).result() for key in graphs.keys(): print(key) graph = nx.Graph() #Add nodes and edges graph.add_nodes_from(np.arange(0,6,1)) edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)] graph.add_weighted_edges_from(edges) graphs['custom'] = graph #Display widget display_maxcut_widget(graphs['custom']) def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float: """ Computes the maxcut cost function value for a given graph and cut represented by some bitstring Args: graph: The graph to compute cut values for bitstring: A list of integer values '0' or '1' specifying a cut of the graph Returns: The value of the cut """ #Get the weight matrix of the graph weight_matrix = nx.adjacency_matrix(graph).toarray() size = weight_matrix.shape[0] value = 0. x=bitstring for i in range(size): for j in range(size): value = value + (weight_matrix[i,j]*x[i]*(1-x[j])) return value def plot_maxcut_histogram(graph: nx.Graph) -> None: """ Plots a bar diagram with the values for all possible cuts of a given graph. Args: graph: The graph to compute cut values for """ num_vars = graph.number_of_nodes() #Create list of bitstrings and corresponding cut values bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)] values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings] #Sort both lists by largest cut value values, bitstrings = zip(*sorted(zip(values, bitstrings))) #Plot bar diagram bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value'))) fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600)) fig.show() plot_maxcut_histogram(graph = graphs['custom']) from qc_grader import grade_lab2_ex1 bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE # Note that the grading function is expecting a list of integers '0' and '1' grade_lab2_ex1(bitstring) from qiskit_optimization import QuadraticProgram quadratic_program = QuadraticProgram('sample_problem') print(quadratic_program.export_as_lp_string()) quadratic_program.binary_var(name = 'x_0') quadratic_program.integer_var(name = 'x_1') quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8) quadratic = [[0,1,2],[3,4,5],[0,1,2]] linear = [10,20,30] quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5) print(quadratic_program.export_as_lp_string()) def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram: """Constructs a quadratic program from a given graph for a MaxCut problem instance. Args: graph: Underlying graph of the problem. Returns: QuadraticProgram """ #Get weight matrix of graph weight_matrix = nx.adjacency_matrix(graph) shape = weight_matrix.shape size = shape[0] #Build qubo matrix Q from weight matrix W qubo_matrix = np.zeros((size, size)) qubo_vector = np.zeros(size) for i in range(size): for j in range(size): qubo_matrix[i, j] -= weight_matrix[i, j] for i in range(size): for j in range(size): qubo_vector[i] += weight_matrix[i,j] quadratic_program = QuadraticProgram('function') quadratic_program.binary_var(name = 'x_0') quadratic_program.binary_var(name = 'x_1') quadratic_program.binary_var(name = 'x_2') quadratic_program.binary_var(name = 'x_3') quadratic_program.binary_var(name = 'x_4') quadratic_program.binary_var(name = 'x_5') print(quadratic_program.export_as_lp_string()) quadratic = [[0,-4,-6,-4,-8,-2],[0,0,-8,-2,-2,-6], [0,0,0,0,-4,-6],[0,0,0,0,-10,-2], [0,0,0,0,0,0],[0,0,0,0,0,0]] linear = [12,11,12,9,12,8] quadratic_program.maximize(quadratic = quadratic, linear = linear, constant = 0) return quadratic_program quadratic_program = quadratic_program_from_graph(graphs['custom']) print(quadratic_program.export_as_lp_string()) from qc_grader import grade_lab2_ex2 # Note that the grading function is expecting a quadratic program grade_lab2_ex2(quadratic_program) def qaoa_circuit(qubo: QuadraticProgram, p: int = 1): """ Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers. Args: qubo: The quadratic program instance p: The number of layers in the QAOA circuit Returns: The parameterized QAOA circuit """ size = len(qubo.variables) qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True) qubo_linearity = qubo.objective.linear.to_array() #Prepare the quantum and classical registers qaoa_circuit = QuantumCircuit(size,size) #Apply the initial layer of Hadamard gates to all qubits qaoa_circuit.h(range(size)) #Create the parameters to be used in the circuit gammas = ParameterVector('gamma', p) betas = ParameterVector('beta', p) #Outer loop to create each layer for i in range(p): #Apply R_Z rotational gates from cost layer #INSERT YOUR CODE HERE for j in range(size): angle = qubo_linearity[j] for k in range(size): angle += qubo_matrix[j,k] qaoa_circuit.rz(gammas[i]*angle,qubit = j) qaoa_circuit.rz(0, range(size)) #Apply R_ZZ rotational gates for entangled qubit rotations from cost layer #INSERT YOUR CODE HERE for j in range(size): for k in range(size): if k!=j: qaoa_circuit.rzz(qubo_matrix[j,k]*gammas[i]/2,j,k) # Apply single qubit X - rotations with angle 2beta_i to all qubits #INSERT YOUR CODE HERE for j in range(size): qaoa_circuit.rx(2.*betas[i],j) circuit.barrier() return qaoa_circuit quadratic_program = quadratic_program_from_graph(graphs['custom']) custom_circuit = qaoa_circuit(qubo = quadratic_program) test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters)) from qc_grader import grade_lab2_ex3 # Note that the grading function is expecting a quantum circuit grade_lab2_ex3(test) from qiskit.algorithms import QAOA from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = Aer.get_backend('statevector_simulator') qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1]) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) quadratic_program = quadratic_program_from_graph(graphs['custom']) result = eigen_optimizer.solve(quadratic_program) print(result) def plot_samples(samples): """ Plots a bar diagram for the samples of a quantum algorithm Args: samples """ #Sort samples by probability samples = sorted(samples, key = lambda x: x.probability) #Get list of probabilities, function values and bitstrings probabilities = [sample.probability for sample in samples] values = [sample.fval for sample in samples] bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples] #Plot bar diagram sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value'))) fig = go.Figure( data=sample_plot, layout = dict( xaxis=dict( type = 'category' ) ) ) fig.show() plot_samples(result.samples) graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name]) trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]} offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum() def callback(eval_count, params, mean, std_dev): trajectory['beta_0'].append(params[1]) trajectory['gamma_0'].append(params[0]) trajectory['energy'].append(-mean + offset) optimizers = { 'cobyla': COBYLA(), 'slsqp': SLSQP(), 'adam': ADAM() } qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) result = eigen_optimizer.solve(quadratic_program) fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples) fig.show() graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graphs[graph_name]) #Create callback to record total number of evaluations max_evals = 0 def callback(eval_count, params, mean, std_dev): global max_evals max_evals = eval_count #Create empty lists to track values energies = [] runtimes = [] num_evals=[] #Run QAOA for different values of p for p in range(1,10): print(f'Evaluating for p = {p}...') qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) start = time() result = eigen_optimizer.solve(quadratic_program) runtimes.append(time()-start) num_evals.append(max_evals) #Calculate energy of final state from samples avg_value = 0. for sample in result.samples: avg_value += sample.probability*sample.fval energies.append(avg_value) #Create and display plots energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma')) runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma')) num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma')) fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations']) fig.update_layout(width=1800,height=600, showlegend=False) fig.add_trace(energy_plot, row=1, col=1) fig.add_trace(runtime_plot, row=1, col=2) fig.add_trace(num_evals_plot, row=1, col=3) clear_output() fig.show() def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None): num_shots = 1000 seed = 42 simulator = Aer.get_backend('qasm_simulator') simulator.set_options(seed_simulator = 42) #Generate circuit circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1) circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes())) #Create dictionary with precomputed cut values for all bitstrings cut_values = {} size = graph.number_of_nodes() for i in range(2**size): bitstr = '{:b}'.format(i).rjust(size, '0')[::-1] x = [int(bit) for bit in bitstr] cut_values[bitstr] = maxcut_cost_fn(graph, x) #Perform grid search over all parameters data_points = [] max_energy = None for beta in np.linspace(0,np.pi, 50): for gamma in np.linspace(0, 4*np.pi, 50): bound_circuit = circuit.assign_parameters([beta, gamma]) result = simulator.run(bound_circuit, shots = num_shots).result() statevector = result.get_counts(bound_circuit) energy = 0 measured_cuts = [] for bitstring, count in statevector.items(): measured_cuts = measured_cuts + [cut_values[bitstring]]*count if cvar is None: #Calculate the mean of all cut values energy = sum(measured_cuts)/num_shots else: measured_cuts.sort(reverse = True) alphan = np.math.ceil(cvar*num_shots) energy = sum(measured_cuts[:alphan])/alphan #Update optimal parameters if max_energy is None or energy > max_energy: max_energy = energy optimum = {'beta': beta, 'gamma': gamma, 'energy': energy} #Update data data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy}) #Create and display surface plot from data_points df = pd.DataFrame(data_points) df = df.pivot(index='beta', columns='gamma', values='energy') matrix = df.to_numpy() beta_values = df.index.tolist() gamma_values = df.columns.tolist() surface_plot = go.Surface( x=gamma_values, y=beta_values, z=matrix, coloraxis = 'coloraxis' ) fig = go.Figure(data = surface_plot) fig.show() #Return optimum return optimum graph = graphs['custom'] optimal_parameters = plot_qaoa_energy_landscape(graph = graph) print('Optimal parameters:') print(optimal_parameters) optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2) print(optimal_parameters) from qc_grader import grade_lab2_ex4 # Note that the grading function is expecting a python dictionary # with the entries 'beta', 'gamma' and 'energy' grade_lab2_ex4(optimal_parameters)
https://github.com/jacobwatkins1/rodeo-algorithm
jacobwatkins1
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.quantum_info import Kraus, SuperOp from qiskit.providers.aer import AerSimulator from qiskit.tools.visualization import plot_histogram # Import from Qiskit Aer noise module from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise import QuantumError, ReadoutError from qiskit.providers.aer.noise import pauli_error from qiskit.providers.aer.noise import depolarizing_error from qiskit.providers.aer.noise import thermal_relaxation_error # Error probabilities prob_1 = 0.01 # 1-qubit gate prob_2 = 0.3 # 2-qubit gate prob_b = 0.05 # 1-qubit gate for phase damping error. # Depolarizing quantum errors error_1 = noise.depolarizing_error(prob_1, 1) error_2 = noise.depolarizing_error(prob_2, 2) error_b = noise.phase_damping_error(prob_b) # Add errors to noise model noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3']) #noise_model.add_all_qubit_quantum_error(error_b, ['u1', 'u2', 'u3']) noise_model.add_all_qubit_quantum_error(error_2, ['cx']) # Get basis gates from noise model basis_gates = noise_model.basis_gates print(basis_gates) # Make a circuit circ = QuantumCircuit(3, 3) circ.h(0) circ.cx(0, 1) circ.cx(1, 2) circ.measure([0, 1, 2], [0, 1, 2]) # Perform a noise simulation result = execute(circ, Aer.get_backend('qasm_simulator'), basis_gates=basis_gates, noise_model=noise_model).result() counts = result.get_counts(0) plot_histogram(counts)
https://github.com/jacobwatkins1/rodeo-algorithm
jacobwatkins1
import numpy as np from sympy import * from sympy.solvers import solve import random from qiskit import * import scipy as sp from numpy import linalg as la from scipy import linalg as sla from IPython.display import clear_output from numpy import linalg as la from qiskit.tools.visualization import plot_histogram from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.compiler import transpile, assemble from qiskit.providers.ibmq.managed import IBMQJobManager from qiskit.visualization import * from operator import itemgetter from functools import reduce # Pauli Matrices Id = np.matrix([[1,0],[0,1]],dtype=complex) X = np.matrix([[0,1],[1,0]],dtype=complex) Y = np.matrix([[0,-1j],[1j,0]],dtype=complex) Z = np.matrix([[1,0],[0,-1]],dtype=complex) # Generate random values. a,b,c,d = [random.uniform(-1,1) for n in range(4)] print('a=',a,',b=',b,',c=',c,',d=',d) # The values used in our paper. a= -0.08496099317164885 b= -0.8913449722923625 c= 0.2653567873681286 d= 0.5720506205204723 a = 2.0641811586466403 b = -0.8795521785527299 c = 0.2618460278326864 d = 0.5644821984323585 # Generate random values. c_i,c_x,c_y,c_z = [random.uniform(-1,1) for n in range(4)] print('c_i=', c_i,',c_x=',c_x,',c_y=',c_y,',c_z=',c_z) # The values used in our paper. c_i= -0.8453688208879107 c_x= 0.006726766902514836 c_y= -0.29354208134440296 c_z= 0.18477436355081123 # The Hamiltonian. H = a*Id+b*X+c*Y+d*Z print(H) # Find the exact eigenstates and eigenvalues. Awh, Avh = la.eig(H) Aeval0h = float(re(Awh[0])) Aeval1h = float(re(Awh[1])) Aevec0h = Avh[:,0] Aevec1h = Avh[:,1] print('The energy eigenvalues of H are:',Aeval0h, 'and', Aeval1h) print('The corresponding eigenvectors are:', '\n', Aevec0h,'\n', 'and','\n', Aevec1h) O = c_i*Id+c_x*X+c_y*Y+c_z*Z print(O) Aw, Av = la.eig(O) Aeval0 = float(re(Aw[0])) Aeval1 = float(re(Aw[1])) Aevec0 = Av[:,0] Aevec1 = Av[:,1] print('The energy eigenvalues are:',Aeval0, 'and', Aeval1) print('The corresponding eigenvectors are:', '\n', Aevec0,'\n', 'and','\n', Aevec1) Zero = np.matrix([[1],[0]],dtype=complex) One = np.matrix([[0],[1]],dtype=complex) Ze = np.squeeze(np.asarray(Zero)) On = np.squeeze(np.asarray(One)) def H_obj(phi): # All the information needed for H_obj. # Hamiltonian. Hobj = H + phi*O wo, vo = la.eig(Hobj) # Eigenvalues. eval0o = float(re(wo[0])) eval1o = float(re(wo[1])) # Eigenvectors. evec0o = vo[:,0] evec1o = vo[:,1] # Direct calculation of the expectation value. Expe0 = evec0o.getH() @ O @ evec0o Expe1 = evec1o.getH() @ O @ evec1o return eval0o, eval1o, evec0o, evec1o, Expe0, Expe1 def GH(phimax,num,sigma): plt.figure(figsize=(16.18,10)) philist = np.linspace(-phimax,phimax,num) # epslist = np.concatenate((epslist[epslist<0], [0], epslist[epslist>0])) x = np.arange(-1.5,1.5,0.005) cm = LinearSegmentedColormap.from_list('defcol', ["#979A9A", "#17F514"]) trace_color = cm(np.linspace(0,1,len(philist))) evalf = [] evals = [] expfi = [] expse = [] PS0 = [] PS1 = [] VEC0 = [] VEC1 = [] for phi, color in zip(philist, trace_color): val0,val1,vec0,vec1,expe0,expe1 = H_obj(phi) evalf.append(val0) evals.append(val1) expfi.append(expe0) expse.append(expe1) EV0 = np.squeeze(np.asarray(vec0)) EV1 = np.squeeze(np.asarray(vec1)) Pini0 = simplify(np.inner(Ze,EV0)*conjugate(np.inner(Ze,EV0))) Pini1 = simplify(np.inner(Ze,EV1)*conjugate(np.inner(Ze,EV1))) PS0.append(Pini0) PS1.append(Pini1) Probs = [Pini0,Pini1] Evals = [val0,val1] VEC0.append(vec0) VEC1.append(vec1) Yt = 0 for k in range (2): y = Probs[k] for i in range (3): y *= 0.5*(1+np.exp((-0.5)*(x-Evals[k])**2*sigma**2)) Yt += y if phi == 0: expc = plt.plot(x,Yt,color = 'red',linewidth=3.6) else: expc = plt.plot(x,Yt,color = color) plt.xlabel(r'$E_{target}$',fontsize = 25) plt.ylabel(r'$P_{success}$',fontsize = 25) plt.grid() plt.show() dx = 4*phimax/(num-1) drf = [(evalf[i+1]-evalf[i-1])/dx for i in range(1,num-1)] drs = [(evals[i+1]-evals[i-1])/dx for i in range(1,num-1)] Df = dict(zip(philist[1:-1],drf)) Ds = dict(zip(philist[1:-1],drs)) Expf = dict(zip(philist[1:-1],expfi[1:-1])) Exps = dict(zip(philist[1:-1],expse[1:-1])) Energy1 = dict(zip(philist[1:-1],evalf[1:-1])) # Energy Eigenvalues Energy2 = dict(zip(philist[1:-1],evals[1:-1])) Pros0 = dict(zip(philist[1:-1],PS0[1:-1])) # Energy Eigenvalues Pros1 = dict(zip(philist[1:-1],PS1[1:-1])) return Df, Ds, Expf, Exps, Energy1, Energy2,Pros0,Pros1,VEC0,VEC1 Dc01, Dc02, Dc03, Dc04, Espec1, Espec2, PR0,PR1,VL0,VL1 = GH(0.1,21,12) N = 3 # Number of cycles. obj = 3 # Numbering of the physical (object) qubit on quantum device. arena = 1 # Numbering of the physical (arena) qubit on quantum device. def qc1(E_targ,tstep,phi): ao = a + phi*c_i bo = b + phi*c_x co = c + phi*c_y do = d + phi*c_z sigo = Matrix([[bo],[co],[do]]) n_hato = np.dot(1/sqrt(bo**2+co**2+do**2),sigo) nxo, nyo, nzo = [float(i.item()) for i in n_hato] theta = 2*tstep*sqrt(bo**2+co**2+do**2) % (4*pi) delta = float(re(atan(nzo*tan(theta/2))+atan(nxo/nyo))) beta = float(re(atan(nzo*tan(theta/2))-atan(nxo/nyo))) gamma = float(2*re(acos(cos(theta/2)/cos((delta+beta)/2)))) if nyo > 0 and theta > 2*pi: gamma *= (-1) elif nyo < 0 and theta <= 2*pi: gamma *= (-1) quanc1t = QuantumCircuit(2) quanc1t.h(1) quanc1t.cu(gamma,beta,delta,0,1,0) quanc1t.p(tstep*(E_targ-ao)-0.5*(delta+beta),1) # The Energy Sensor. quanc1t.h(1) quanc1t.barrier() return quanc1t def qct(E_targ,sigma,phi): qrz = QuantumRegister(2,'q') crz = ClassicalRegister(N,'c') qc = QuantumCircuit(qrz,crz) t = np.random.normal(0, sigma, N).tolist() init_gate = Initialize([i.item() for i in Aevec0h]) qc.append(init_gate, [1]) # qc.initialize([i.item() for i in Aevec0h],1) # qc.append(init_gate, [1]) for i in range (N): # sub_inst = qc1(E_targ,t[i],epsilon).to_instruction() # qc.append(sub_inst,[obj,arena]) qc.append(qc1(E_targ,t[i],phi),[0,1]) # 0:Obj, 1:Arena. qc.measure(1,i) # Mid-circuit measurement, arena is measured. qc.barrier() qc = transpile(qc,backend=backend,optimization_level=2,initial_layout = [obj,arena]) # qc = transpile(qc,backend=backend,optimization_level=2,layout_method = "noise_adaptive") # qc.barrier() return qc def numsli_expc (L,rang1,rang2,nuni,nshots,sigma,k,phi): val0, val1,_,_,_,_ = H_obj(phi) EW = np.linspace(rang1,rang2,L) # The energy spectrum we're interested in. circuits = [] # The 'circuit matrix'. for i in range(L): circuitsi = [] for j in range (nuni): circuit = qct(EW[i],sigma,phi) circuitsi.append(circuit) circuits.append(circuitsi) all_circuits = [] for i in range(L): all_circuits += circuits[i][:] MExperiments = job_manager.run(all_circuits, backend=backend, shots = nshots) results = MExperiments.results() # cresults = results.combine_results() # We are not doing read-out error mitigation here. # mitigated_results = meas_filter.apply(cresults) probsu = [] succs = '0'*N for i in range (L): probsui = [] for j in range (nuni): # counts = mitigated_results.get_counts((nuni*i)+j) counts = results.get_counts((nuni*i)+j) if succs in counts: prob = counts[succs]/sum(counts.values()) else: prob = 0 probsui.append(prob) probsu.append(np.average(probsui)) spec = dict(zip(EW,probsu)) plt.figure(figsize=(16.18,10)) plt.xlabel(r'$Energy\ Spectrum\ (E_{target})$',fontsize = 15) plt.ylabel('Probability to measure the success state',fontsize = 15) hist = plt.bar(spec.keys(), spec.values(), width=np.abs((rang2-rang1)/L), color='lightseagreen',alpha = 0.7) plt.legend([hist],['Results from qasm']) plt.grid() plt.show() # Weighted avg based on the highest bins. #Larg = dict(sorted(spec.items(), key = itemgetter(1), reverse = True)[:Hisk]) #Wavg = np.average(list(Larg.keys()), weights=list(Larg.values())) # Weighted avg of the highest consecutive bins. keys = np.fromiter(spec.keys(), float, count=len(spec)) vals = np.fromiter(spec.values(), float, count=len(spec)) idx = np.convolve(vals, np.ones(k), 'valid').argmax() Wavg = np.average(keys[idx:idx + k], weights=vals[idx:idx + k]) print('Range for the next scan', keys[idx:idx + k]) print('The estimated Eigenvalue is', Wavg) print('The precise values are',val0,'and',val1) return spec # (L,rang1,rang2,nuni,nshots,sigma,k,phi) 9/26 qasm firstscan = numsli_expc (18,0,np.pi+1,25,2500,2,6,0) print(firstscan) firstscan = numsli_expc (18,0,np.pi+1,15,2500,2,6,0) print(firstscan) # (L,rang1,rang2,nuni,nshots,sigma,k,phi) 7/22 firstscan = numsli_expc (18,-1-np.sqrt(3),1+np.sqrt(3),25,2500,2,6,0) print(firstscan) #7/22 secondscan_a = numsli_expc (18, -1.768, -0.161 ,25,2500,7,6,0) # Small Peak. 7/22 print(secondscan_a) secondscan_b = numsli_expc (18, 0.161, 1.768 ,25,2500,7,6,0) # Large Peak. print(secondscan_b) thirdscan_a = numsli_expc (18, -1.390, -0.917 ,25,2500,12,6,0) # Small Peak. print(thirdscan_a) thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,0) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,0) # Large Peak. print(thirdscan_b) firstscan_722 = {-2.732050807568877: 0.11027200000000001, -2.4106330655019503: 0.118928, -2.089215323435024: 0.12784, -1.767797581368097: 0.184432, -1.4463798393011702: 0.264032, -1.1249620972342433: 0.300608, -0.8035443551673167: 0.254656, -0.48212661310039007: 0.200192, -0.1607088710334632: 0.14988800000000002, 0.16070887103346365: 0.19345600000000002, 0.4821266131003905: 0.37512, 0.8035443551673169: 0.5875360000000001, 1.1249620972342438: 0.6517439999999999, 1.4463798393011706: 0.499424, 1.767797581368097: 0.22110400000000002, 2.0892153234350244: 0.101648, 2.410633065501951: 0.11871999999999998, 2.732050807568877: 0.17247999999999997} secondscan_722a = {-1.768: 0.131792, -1.673470588235294: 0.115936, -1.5789411764705883: 0.122, -1.4844117647058823: 0.09486399999999998, -1.3898823529411766: 0.14913600000000002, -1.2953529411764706: 0.22596799999999997, -1.2008235294117648: 0.239616, -1.1062941176470589: 0.247136, -1.011764705882353: 0.223568, -0.9172352941176471: 0.16216, -0.8227058823529413: 0.08616000000000001, -0.7281764705882354: 0.09582399999999999, -0.6336470588235295: 0.10512, -0.5391176470588237: 0.10432000000000001, -0.44458823529411773: 0.09491199999999997, -0.350058823529412: 0.08795199999999999, -0.255529411764706: 0.08761599999999997, -0.161: 0.07192} secondscan_722b = {0.161: 0.182816, 0.2555294117647059: 0.15763200000000002, 0.35005882352941176: 0.10408, 0.4445882352941176: 0.13350399999999998, 0.5391176470588235: 0.08361600000000001, 0.6336470588235293: 0.12872, 0.7281764705882353: 0.15812800000000002, 0.8227058823529412: 0.24163199999999999, 0.917235294117647: 0.554208, 1.011764705882353: 0.695728, 1.1062941176470587: 0.509696, 1.2008235294117646: 0.296912, 1.2953529411764706: 0.184352, 1.3898823529411763: 0.116848, 1.4844117647058823: 0.10819200000000001, 1.578941176470588: 0.145056, 1.673470588235294: 0.09142399999999999, 1.768: 0.09601599999999999} thirdscan_722a = {-1.39: 0.105148, -1.362176470588235: 0.132608, -1.3343529411764705: 0.163096, -1.3065294117647057: 0.18905999999999998, -1.2787058823529411: 0.188512, -1.2508823529411763: 0.227852, -1.2230588235294118: 0.238048, -1.195235294117647: 0.311544, -1.1674117647058824: 0.288476, -1.1395882352941176: 0.27693999999999996, -1.111764705882353: 0.22833199999999998, -1.0839411764705882: 0.21373999999999999, -1.0561176470588234: 0.20185599999999998, -1.0282941176470588: 0.18544799999999997, -1.0004705882352942: 0.1288, -0.9726470588235294: 0.14307599999999998, -0.9448235294117647: 0.12436799999999998, -0.917: 0.121528} thirdscan_722b = {0.823: 0.221904, 0.8507647058823529: 0.16145600000000002, 0.8785294117647058: 0.23401600000000003, 0.9062941176470588: 0.307184, 0.9340588235294117: 0.42928000000000005, 0.9618235294117646: 0.533504, 0.9895882352941177: 0.6538719999999999, 1.0173529411764706: 0.6308799999999999, 1.0451176470588235: 0.577024, 1.0728823529411764: 0.438288, 1.1006470588235293: 0.30886399999999997, 1.1284117647058824: 0.261488, 1.1561764705882354: 0.21272, 1.1839411764705883: 0.207696, 1.2117058823529412: 0.144432, 1.239470588235294: 0.117392, 1.267235294117647: 0.12107200000000003, 1.295: 0.13726400000000002} firstscan_926qasm = {-2.732050807568877: 0.095152, -2.4106330655019503: 0.109664, -2.089215323435024: 0.147952, -1.767797581368097: 0.19204800000000002, -1.4463798393011702: 0.315872, -1.1249620972342433: 0.33392000000000005, -0.8035443551673167: 0.301248, -0.48212661310039007: 0.22039999999999998, -0.1607088710334632: 0.14299199999999998, 0.16070887103346365: 0.27012800000000003, 0.4821266131003905: 0.41830399999999995, 0.8035443551673169: 0.6923039999999999, 1.1249620972342438: 0.7712320000000001, 1.4463798393011706: 0.47627200000000003, 1.767797581368097: 0.21656000000000003, 2.0892153234350244: 0.157872, 2.410633065501951: 0.134464, 2.732050807568877: 0.154464} #plt.figure(figsize=(5*(1+np.sqrt(5)),10)) plt.figure(figsize=(14*1.2,12)) hist1 = plt.bar(firstscan_722.keys(), firstscan_722.values(), width = 2*(1+sqrt(3))/18 , color='limegreen',alpha = 0.32) plt.bar(secondscan_722a.keys(), secondscan_722a.values(), width= 1.608/18, color='deepskyblue',alpha = 0.49) hist2 = plt.bar(secondscan_722b.keys(), secondscan_722b.values(), width= 1.607/18, color='deepskyblue',alpha = 0.49) plt.bar(thirdscan_722a.keys(), thirdscan_722a.values(), width=0.5/18, color='darkorchid',alpha = 0.65) hist3 = plt.bar(thirdscan_722b.keys(), thirdscan_722b.values(), width=0.5/18, color='darkorchid',alpha = 0.65) hist_ref = plt.bar(firstscan_926qasm.keys(), firstscan_926qasm.values(),width = 2*(1+sqrt(3))/18,fill = False , color='grey',alpha = 0.49) Zero = np.matrix([[1],[0]],dtype=complex) One = np.matrix([[0],[1]],dtype=complex) Ze = np.squeeze(np.asarray(Zero)) On = np.squeeze(np.asarray(One)) x = np.arange(-1-np.sqrt(3),1+np.sqrt(3),0.005) EV0 = np.squeeze(np.asarray(Aevec0h)) EV1 = np.squeeze(np.asarray(Aevec1h)) Pini0 = np.inner(Ze,EV0)*conjugate(np.inner(Ze,EV0)) Pini1 = np.inner(Ze,EV1)*conjugate(np.inner(Ze,EV1)) Probs = [Pini0,Pini1] Evals = [Aeval0h,Aeval1h] Yt = 0 for k in range (2): y = Probs[k] for i in range (N): y *= 0.5*(1+np.exp((-0.5)*(x-Evals[k])**2*2**2)) Yt += y Ytl = 0 for k in range (2): yl = Probs[k] for i in range (N): yl *= 0.5*(1+np.exp((-0.5)*(x-Evals[k])**2*7**2)) Ytl += yl Yt2 = 0 for k in range (2): y2 = Probs[k] for i in range (N): y2 *= 0.5*(1+np.exp((-0.5)*(x-Evals[k])**2*12**2)) Yt2 += y2 expc, = plt.plot(x,Yt,color = 'royalblue',linewidth=2.7,linestyle='--',alpha=1) expc1, = plt.plot(x,Ytl,color = 'red',linewidth=2.7,linestyle='--',alpha=1) expc2, = plt.plot(x,Yt2,color = 'black',linewidth=2.7,linestyle='--',alpha=1) #plt.xlabel(r'$E$',fontsize = 35) #plt.ylabel(r'$P_{0^N}$',fontsize = 35) plt.legend([hist1,hist2,hist3,hist_ref,expc,expc1,expc2], ['$\sigma=2$ (1st scan)','$\sigma=7$ (2nd scan)','$\sigma=12$ (3rd scan)','Noiseless simulation (1st scan)','$\sigma=2$ (expected)','$\sigma=7$ (expected)','$\sigma=12$ (expected)'], ncol = 2,loc="upper left",fontsize=20,columnspacing = -4.5) #plt.grid(alpha = 0.6) plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.text(0.087, 0.9, r'$P_{0^N}$', fontsize=35, transform=plt.gcf().transFigure) plt.text(0.9, 0.087, r'$E$', fontsize=35, transform=plt.gcf().transFigure) plt.savefig("SeqScan430_0610.png",dpi=430,bbox_inches='tight',pad_inches = 0) plt.show() thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,0.01) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,0.01) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.01) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.01) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,0.02) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,0.02) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.02) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.02) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,0.03) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,0.03) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.03) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.03) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.04) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.04) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.490, -1.017 ,50,5000,12,6,0.04) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.723, 1.195 ,25,2500,12,6,0.04) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.490, -1.017 ,50,5000,12,6,0.05) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.723, 1.195 ,25,2500,12,6,0.05) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.05) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.05) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.490, -1.017 ,50,5000,12,6,0.06) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.723, 1.195 ,25,2500,12,6,0.06) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.06) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.06) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.490, -1.017 ,50,5000,12,6,0.07) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.723, 1.195 ,25,2500,12,6,0.07) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.07) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.07) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.490, -1.017 ,50,5000,12,6,0.08) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.723, 1.195 ,25,2500,12,6,0.08) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.08) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.08) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.490, -1.017 ,50,5000,12,6,0.09) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.723, 1.195 ,25,2500,12,6,0.09) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.290, -0.817 ,50,5000,12,6,-0.09) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.09) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.490, -1.017 ,50,5000,12,6,0.1) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.723, 1.195 ,25,2500,12,6,0.1) # Large Peak. print(thirdscan_b) thirdscan_a = numsli_expc (18, -1.290, -0.817 ,50,5000,12,6,-0.1) # Small Peak. print(thirdscan_a) thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.1) # Large Peak. print(thirdscan_b)
https://github.com/jacobwatkins1/rodeo-algorithm
jacobwatkins1
import numpy as np from sympy import * from qiskit import * from qiskit.quantum_info import Kraus, SuperOp from qiskit.providers.aer import AerSimulator from qiskit.tools.visualization import plot_histogram # Import from Qiskit Aer noise module from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise import QuantumError, ReadoutError from qiskit.providers.aer.noise import pauli_error from qiskit.providers.aer.noise import depolarizing_error from qiskit.providers.aer.noise import thermal_relaxation_error from numpy import linalg as la Id = np.matrix([[1,0],[0,1]],dtype=complex) X = np.matrix([[0,1],[1,0]],dtype=complex) Y = np.matrix([[0,-1j],[1j,0]],dtype=complex) Z = np.matrix([[1,0],[0,-1]],dtype=complex) # The values used in our paper. a= -0.08496099317164885 b= -0.8913449722923625 c= 0.2653567873681286 d= 0.5720506205204723 # The values used in our paper. c_i= -0.8453688208879107 c_x= 0.006726766902514836 c_y= -0.29354208134440296 c_z= 0.18477436355081123 # The Hamiltonian. H = a*Id+b*X+c*Y+d*Z print(H) # Find the exact eigenstates and eigenvalues. Awh, Avh = la.eig(H) Aeval0h = float(re(Awh[0])) Aeval1h = float(re(Awh[1])) Aevec0h = Avh[:,0] Aevec1h = Avh[:,1] print('The energy eigenvalues of H are:',Aeval0h, 'and', Aeval1h) print('The corresponding eigenvectors are:', '\n', Aevec0h,'\n', 'and','\n', Aevec1h) N = 3 Aevec0h1 = [0.8729044694074841+0j, -0.4676094626792474+0.13920911500783384j] def qc1(E_targ,tstep,phi): ao = a + phi*c_i bo = b + phi*c_x co = c + phi*c_y do = d + phi*c_z sigo = Matrix([[bo],[co],[do]]) n_hato = np.dot(1/sqrt(bo**2+co**2+do**2),sigo) nxo, nyo, nzo = [float(i.item()) for i in n_hato] theta = 2*tstep*sqrt(bo**2+co**2+do**2) % (4*pi) delta = float(re(atan(nzo*tan(theta/2))+atan(nxo/nyo))) beta = float(re(atan(nzo*tan(theta/2))-atan(nxo/nyo))) gamma = float(2*re(acos(cos(theta/2)/cos((delta+beta)/2)))) if nyo > 0 and theta > 2*pi: gamma *= (-1) elif nyo < 0 and theta <= 2*pi: gamma *= (-1) quanc1t = QuantumCircuit(2) quanc1t.h(1) quanc1t.cu(gamma,beta,delta,0,1,0) quanc1t.p(tstep*(E_targ-ao)-0.5*(delta+beta),1) # The Energy Sensor. quanc1t.h(1) quanc1t.barrier() return quanc1t def qct(E_targ,sigma,phi): qrz = QuantumRegister(2,'q') crz = ClassicalRegister(N,'c') qc = QuantumCircuit(qrz,crz) t = np.random.normal(0, sigma, N).tolist() qc.initialize(Aevec0h1, 0) for i in range (N): # sub_inst = qc1(E_targ,t[i],epsilon).to_instruction() # qc.append(sub_inst,[obj,arena]) qc.append(qc1(E_targ,t[i],phi),[0,1]) # 0:Obj, 1:Arena. qc.measure(1,i) # Mid-circuit measurement, arena is measured. qc.barrier() # qc = transpile(qc,backend=backend,optimization_level=2,initial_layout = [obj,arena]) # qc = transpile(qc,backend=backend,optimization_level=2,layout_method = "noise_adaptive") # qc.barrier() return qc def depolarizing_noise(one_qubit_noise, two_qubit_noise): depolarizing_model = NoiseModel() error_1 = depolarizing_error(one_qubit_noise, 1) error_2 = depolarizing_error(two_qubit_noise, 2) depolarizing_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3']) depolarizing_model.add_all_qubit_quantum_error(error_2, ['cx']) print(depolarizing_model) return depolarizing_model test_circuit = qct(Aeval0h,3,0) test_circuit.draw('mpl') # Create noisy simulator backend sim_noise = AerSimulator(noise_model = depolarizing_noise(0.9,0.9)) # Transpile circuit for noisy basis gates circ_tnoise = transpile(test_circuit, sim_noise) # Run and get counts result_bit_flip = sim_noise.run(circ_tnoise).result() counts_bit_flip = result_bit_flip.get_counts(0) # Plot noisy output plot_histogram(counts_bit_flip) def numsli_expc (L,rang1,rang2,nuni,nshots,sigma,k,phi): val0, val1,_,_,_,_ = H_obj(phi) EW = np.linspace(rang1,rang2,L) # The energy spectrum we're interested in. circuits = [] # The 'circuit matrix'. for i in range(L): circuitsi = [] for j in range (nuni): circuit = qct(EW[i],sigma,phi) circuitsi.append(circuit) circuits.append(circuitsi) all_circuits = [] for i in range(L): all_circuits += circuits[i][:] MExperiments = job_manager.run(all_circuits, backend=backend, shots = nshots) results = MExperiments.results() # cresults = results.combine_results() # We are not doing read-out error mitigation here. # mitigated_results = meas_filter.apply(cresults) probsu = [] succs = '0'*N for i in range (L): probsui = [] for j in range (nuni): # counts = mitigated_results.get_counts((nuni*i)+j) counts = results.get_counts((nuni*i)+j) if succs in counts: prob = counts[succs]/sum(counts.values()) else: prob = 0 probsui.append(prob) probsu.append(np.average(probsui)) spec = dict(zip(EW,probsu)) plt.figure(figsize=(16.18,10)) plt.xlabel(r'$Energy\ Spectrum\ (E_{target})$',fontsize = 15) plt.ylabel('Probability to measure the success state',fontsize = 15) hist = plt.bar(spec.keys(), spec.values(), width=np.abs((rang2-rang1)/L), color='lightseagreen',alpha = 0.7) plt.legend([hist],['Results from qasm']) plt.grid() plt.show() # Weighted avg based on the highest bins. #Larg = dict(sorted(spec.items(), key = itemgetter(1), reverse = True)[:Hisk]) #Wavg = np.average(list(Larg.keys()), weights=list(Larg.values())) # Weighted avg of the highest consecutive bins. keys = np.fromiter(spec.keys(), float, count=len(spec)) vals = np.fromiter(spec.values(), float, count=len(spec)) idx = np.convolve(vals, np.ones(k), 'valid').argmax() Wavg = np.average(keys[idx:idx + k], weights=vals[idx:idx + k]) print('Range for the next scan', keys[idx:idx + k]) print('The estimated Eigenvalue is', Wavg) print('The precise values are',val0,'and',val1) return spec
https://github.com/jacobwatkins1/rodeo-algorithm
jacobwatkins1
# Import statements import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit import Parameter, Gate import matplotlib.pyplot as plt #from qiskit.opflow import I, X, Y, Z, PauliOp, MatrixEvolution, MatrixOp #from qiskit.quantum_info import Operator def zsum(t: Parameter, nqubits, coeffs): """ Creates time evolution operator for non-interacting qubits. Default is Z. """ circ = QuantumCircuit(nqubits) for q in range(nqubits): circ.rz(2 * t*coeffs[q], q) return circ.to_gate(label = r'$\otimes R_z$') def rodeo_cycle(U, t:Parameter, targ:Parameter, sysqubits:int, coeffs): """Prepares a unitary quantum gate for a single cycle of the rodeo algorithm without measurements. Contains the parameters t and targ. """ # Prepare registers aux = QuantumRegister(1,'a') sys = QuantumRegister(sysqubits, 's') circuit = QuantumCircuit(aux, sys) # Add Hadamard test gates circuit.h(aux) circuit.append(U(t, sysqubits, coeffs).control(1), range(1+sysqubits)) circuit.p(targ * t,aux) circuit.h(aux) return circuit.to_gate(label=r'$RA_{cyc}$') def extract_rodeo_success(probs): """Given a dictionary of distributions, extracts the values of the distributions at zero counts""" zero_probs = len(probs)*[0] for i, dist in enumerate(probs): try: zero_probs[i] = dist[0] except Exception: pass return zero_probs # General parameters cycles = 6 sys_size = 3 # Circuit parameters targ = Parameter(r'$E_\odot$') t = [Parameter(fr'$t_{i}$') for i in range(cycles)] # Hamiltonian parameters ham_params = [1]*sys_size # Create registers and initialize circuit cbits = ClassicalRegister(cycles, 'c') aux = QuantumRegister(1, 'a') sys = QuantumRegister(sys_size, 's') circ = QuantumCircuit(cbits, aux, sys) # State prep circ.h(sys) # Iteratively construct full rodeo circuit for cyc in range(cycles): circ.append(rodeo_cycle(zsum, t[cyc], targ, sys_size, ham_params), range(1 + sys_size)) circ.measure(aux, cbits[cyc]) circ.draw(output= 'mpl') # Import noise model from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError, pauli_error, depolarizing_error, thermal_relaxation_error) from qiskit_ibm_runtime import Sampler, QiskitRuntimeService, Session, Options # Construct Sampler service = QiskitRuntimeService(channel="ibm_quantum") backend = "ibmq_qasm_simulator" session = Session(service = service, backend = backend) # Enumerate scan energies energymin = -5 energymax = 5 stepsize = .1 targetenergies = np.linspace(energymin, energymax, int((energymax-energymin)/stepsize)) targetenergynum = len(targetenergies) print("Number of target energies:", targetenergynum) # Energy window, which should to be slightly larger than stepsize in scan # Is inverse of sigma parameter gamma = 10 * stepsize # Amount of "scrambling" of t per target energy. The more random the t the better. timeresamples = 10 # Resampling of times for given target energy shots_per_same_time = 100 # Package parameters into runs of rodeo circuit params = [] for i, energy in enumerate(targetenergies): for j in range(timeresamples): tsamples = (1/gamma * np.random.randn(cycles)).tolist() # Choose random t samples params = params + [[targetenergies[i]] + tsamples] # Append parameters to params list runs = len(params) print("Parameter list generated! Number of unique circuits:", runs) # List of noise model parameters depolarize_probs = [0.0, 0.01, 0.02, 0.03, 0.04, 0.05] data = [] for p in depolarize_probs: # Initialize noise model noise_model = NoiseModel() error = depolarizing_error(p, 1) noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3']) options = Options() options.simulator = {"noise_model": noise_model} sampler = Sampler(session=session, options = options) # Execute circuit with bound parameters print("Executing with noise parameter ", p) job = sampler.run([circ]*runs, params, shots = shots_per_same_time) result = job.result() probs = result.quasi_dists allzeroprob = extract_rodeo_success(probs) allzeroprob = np.array(allzeroprob).reshape((targetenergynum, timeresamples)).sum(axis=1)/timeresamples data += [allzeroprob] print("Data acquired!") # Plot results for i, p in enumerate(depolarize_probs): plt.plot(targetenergies, data[i], linestyle = 'None', marker = 'o') plt.plot([-3,-1,1,3],[.125,.375,.375,.125],linestyle = 'None', marker = 'x') plt.ylabel("Normalized counts") plt.xlabel(r"Energy ($\hbar = 1$)") plt.legend([0.0, 0.01, 0.02, 0.03, 0.04, 0.05, "Exact"]) plt.title("Depolarization Noise on Rodeo Algorithm") fig = plt.gcf() plt.show() fig.savefig("RodeoScanDepolarization.png") noise_model = NoiseModel() error = depolarizing_error(p, 1) noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3']) sampler.options.simulator = {"noise_model": noise_model} sampler.options.optimization_level = 2 sampler.options.optimization_level
https://github.com/AislingHeanue/Quantum-Computing-Circuits
AislingHeanue
import matplotlib.pyplot as plt import numpy as np from qiskit import QuantumCircuit, Aer, execute, transpile, assemble, QuantumRegister, ClassicalRegister from qiskit.visualization import plot_histogram def binary(num,length): #converts an integer to a binary number with defined length b = bin(num)[2:] return "0"*(length-len(b))+str(b) ncon = 4 controlreg = QuantumRegister(ncon,"control") hreg = QuantumRegister(1,"y") cc = ClassicalRegister(ncon,"cc") #xi = np.random.randint(0,2**ncon-1) #xi as in the greek letter xi = 7 R = int(np.pi/4*np.sqrt(2**ncon)) qc = QuantumCircuit(controlreg,hreg,cc) def Uf(controlreg,hreg,xi,ncon): #the oracle gate, a multi=controlled x gate which is one iff the input = xi hcirc = QuantumCircuit(hreg) circ = QuantumCircuit(controlreg,hreg) xiBin = binary(xi,ncon) zerolist = [i for i in range(ncon) if (xiBin[i] == "0")] circ.x(zerolist) circ.mct(list(range(ncon)),ncon) circ.x(zerolist) circ.name = "Uf" return circ def ccz(controls=2): #multi controlled Z gate (decomposed here as a multi controlled X with H gates placed either side) circ = QuantumCircuit(controls+1) circ.h(controls) circ.mct(list(range(controls)),[controls]) circ.h(controls) circ.name = "c"*controls+"z" return circ def diffusion(ncon): #https://rdcu.be/cLzsq circ = QuantumCircuit(ncon) circ.h(range(ncon)) circ.x(range(ncon)) circ.append(ccz(ncon-1),list(range(ncon))) circ.barrier() circ.x(range(ncon)) circ.h(range(ncon)) circ.name = "Diffusion" return circ Ufgate = Uf(controlreg,hreg,xi,ncon) qc.x(hreg[0]) qc.h(hreg[0]) qc.h(range(ncon)) for e in range(R): qc.barrier() qc.append(Ufgate,controlreg[:]+hreg[:]) qc.barrier() qc.append(diffusion(ncon).decompose(),controlreg[:ncon]) qc.barrier() qc.measure([controlreg[i] for i in range(ncon-1,-1,-1)],cc,) print(xi) qc.draw(plot_barriers=False,fold = -1,output = "latex") ?aersim aersim = Aer.get_backend('aer_simulator') #set memory=True to see measurements tqc = transpile(qc,aersim) results = aersim.run(tqc,shots=10000).result() plot_histogram(results.get_counts()) aersim = Aer.get_backend('aer_simulator') #set memory=True to see measurements tqc = transpile(qc,aersim) results = aersim.run(tqc,shots=10000).result() d = results.get_counts() oldkeys = list(d.keys()) for key in oldkeys: d[str(int(key,2))] = d[key] del d[key] x = np.arange(0,2**ncon-1,1) y = np.zeros(len(x)) for i,xi in enumerate(x): if str(xi) in d.keys(): y[i] = d[str(xi)] plt.xlim(-1,2**ncon) plt.bar(x,y,color=(0.4,0.6,1)) controlreg,hreg = QuantumRegister(4,"control"),QuantumRegister(1,"y") xi = 7 hcirc = QuantumCircuit(hreg) circ = QuantumCircuit(controlreg,hreg) xiBin = binary(xi,ncon) zerolist = [i for i in range(ncon) if (xiBin[i] == "0")] circ.x(zerolist) circ.mct(list(range(ncon)),ncon) circ.x(zerolist) circ.name = "Uf" circ.draw(output="latex") circ = QuantumCircuit(ncon) circ.h(range(ncon)) circ.x(range(ncon)) circ.h(ncon-1) circ.mct(list(range(ncon-1)),[ncon-1]) circ.h(ncon-1) circ.barrier() circ.x(range(ncon)) circ.h(range(ncon)) circ.name = "Diffusion" circ.draw(output="latex",plot_barriers=False) from qiskit import IBMQ IBMQ.enable_account("") provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = provider.get_backend("ibmq_quito") res = backend.retrieve_job("622a012c9e029c54a90deedc").result() plot_histogram(res.get_counts()) nbits = 4 d = res.get_counts() oldkeys = list(d.keys()) for key in oldkeys: d[str(int(key,2))] = d[key] del d[key] x = list(range(0,7))+list(range(8,16)) xi, yi = 7,d["7"]/10000 del d["7"] y = [d[str(xi)]/10000 for xi in x] plt.xlim(-1,15.9) plt.bar(x,y,color=(0.4,0.6,1)) plt.bar(xi,yi,color=(1,0,0)) plt.ylabel("Probability") plt.xlabel("x")
https://github.com/AislingHeanue/Quantum-Computing-Circuits
AislingHeanue
from scipy.fft import fft import matplotlib.pyplot as plt import numpy as np from tqdm import tqdm from fractions import Fraction from numpy.random import choice import warnings warnings.filterwarnings("ignore", category=RuntimeWarning) #some Runtime Warnings occur when graph is set to true delta = lambda x,y: int(x==y) shorbox = lambda a,x,nbits,N: (abs(fft([delta(x, a**k % N) for k in range(2**nbits)]))/(2**nbits))**2 # Chooses smallest nbits > log2(N) so code is fast as possible # Picks some a coprime with N # Takes the Fourier transform of the periodic equation a^k mod N = x with respect to k, and sums all these for every a. # Measures the location of one of the spikes of the probability graph about 1000 times # And uses fractions.Fraction to guess r # If r is odd the code is thrown out and we start again for a new a. # If we have the correct r, p1 = gcd(a^(r/2) - 1,N), p2 = gcd(a^(r/2) + 1,N) def Factorise(N,tests = 8000,a = 2,nbits = 0,loop = True,graph = False,timer = False): #loop = False if we know it only works for a certain seed loop2 = True if nbits == 0: nbits = max(7,int(1+np.log2(N+4))) while a < N and loop2 == True: loop2 = loop while np.gcd(a,N) != 1: a += 1 if timer: probabilities = [0]*2**nbits for i in tqdm(range(2**nbits)): probabilities += shorbox(a,i,nbits,N)# else: #the following line does the same as above but is less likely to give divide by zero errors probabilities = sum([shorbox(a,x,nbits,N) for x in range(2**nbits)]) #probabilites is a list length 2**nbits if graph: plt.bar(range(len(probabilities)),probabilities,width=.6,color=(0.4,0.6,1)) checkedlist = [] for i in range(tests): phase = choice(range(2**nbits),p=probabilities)/2**nbits r = Fraction(phase).limit_denominator(int(N/2)).denominator if r not in checkedlist: checkedlist.append(r) #print(r) if r > 1 and r % 2 == 0: if int(a**(r/2)) <= 2**62: #gcd requires numbers below 2^64 p1 = np.gcd(int(a**(r/2)-1),N) p2 = np.gcd(int(a**(r/2)+1),N) plist = [p1,p2] if p1 <= p2 else [p2,p1] if p1 * p2 == N and p1 != 1 and p2 != 1: return f"{plist[0]:<2d}* {plist[1]:<3d} = {N:<3d}, r = {r:<3d}, a = {a:<3d}, nbits = {nbits:<2d}" a += 1 return "I can't do "+str(N) print(Factorise(15,nbits=4,a=2,graph=True,loop=False,timer = True)) def primes(N): primel = [2] endindex = 0 for i in range(3,N+1,2): for j in primel[endindex:-1]: if j > np.sqrt(i): endindex = primel.index(j) break prime = True for k in primel[0:endindex]: if i%k == 0: prime = False break if prime: primel.append(i) return primel def Semiprimes(N): semiprimel = [] primelist = primes(N//2)[1:] #2 does not behave well with Shor's algorithm for i in enumerate(primelist): for j in primelist[i[0]:]: if j > i[1]: #square numbers also dont work since the algorithm finds 2 different factors if i[1]*j <= N: semiprimel.append(i[1]*j) semiprimel.sort() return semiprimel for N in Semiprimes(292): print(Factorise(N,100))
https://github.com/AislingHeanue/Quantum-Computing-Circuits
AislingHeanue
import matplotlib.pyplot as plt import numpy as np from fractions import Fraction from qiskit import QuantumCircuit, Aer, execute, transpile, assemble, QuantumRegister, ClassicalRegister from qiskit.visualization import plot_histogram from qiskit.circuit.library import DraperQFTAdder as draper # functions # Draper QFT adder, in gate form # https://arxiv.org/pdf/quant-ph/0008033.pdf def add(qc, a, b, n): drapergate = draper(n,kind = "half").decompose().decompose().to_gate() qc.append(drapergate,list(a[:]) + list(b[:])) #a,b -> a,b+a or a,b-a def makeAdder(nbits,adding = True): qc = QuantumCircuit(2*nbits+1) #a is size N, b is N + 1 add(qc, range(nbits), range(nbits,2*nbits+1),nbits) addergate = qc.to_gate() addergate.name = "adder" iaddergate = addergate.inverse() iaddergate.name = "inverse adder" if adding: return addergate else: return iaddergate def binary(num,length): b = bin(num)[2:] return "0"*(length-len(b))+str(b) def x(number,length,controls = 0): #this changes a decimal number to a series of x gates, not to be confused with qc.x circ = QuantumCircuit(length) for i,num in enumerate(binary(number,length)): if num == "1": circ.x(length - 1 - i) xgate = circ.to_gate() xgate.name = str(number) if controls != 0: cxgate = xgate.control(controls) return cxgate #num bitts will be controls + length else: return xgate def makeAdderMod(a,b,t1,t2,n,nbits,N,control = False): #a,b,n quantum registers, output a,a+bmodN, N. t and aux both start and end zero qc = QuantumCircuit(a, b, t1, t2, n) qc.append(makeAdder(nbits,True),range(2*nbits+1)) qc.swap(a,n) qc.append(makeAdder(nbits, False),range(2*nbits+1)) qc.x(t1) qc.cx(t1,t2) qc.x(t1) #set top register to zero by bitwise adding N qc.append(x(N,nbits,1),t2[:] + a[:]) qc.append(makeAdder(nbits,True),range(2*nbits+1)) #adds nothing if b is already positive #turn it back into N qc.append(x(N,nbits,1),t2[:] + a[:]) qc.swap(a,n) qc.append(makeAdder(nbits, False),range(2*nbits+1)) qc.cx(t1,t2) #t2 reset to zero qc.append(makeAdder(nbits, True),range(2*nbits+1)) addmod = qc.to_gate() addmod.name = "a + b mod "+str(N) if control: caddmod = addmod.control(1) return caddmod else: return addmod def makecmult(c, xreg, tempa, y, t1, t2, n, numa, nbits, N,inv = False): qc = QuantumCircuit(c,xreg,tempa,y,t1,t2,n) for p in range(nbits): qc.append(x((2**p*numa)%N,nbits,2),c[:] + xreg[p:p+1] + tempa[:]) qc.append(makeAdderMod(tempa,y,t1,t2,n,nbits,N),tempa[:] + y[:] + t1[:] + t2[:] + n[:]) qc.append(x((2**p*numa)%N,nbits,2),c[:] + xreg[p:p+1] + tempa[:]) qc.x(c) for q in range(nbits): qc.ccx(c,xreg[q],y[q]) qc.x(c) cmult = qc.to_gate() iqc = qc.inverse() icmult = iqc.to_gate() cmult.name = "times "+str(numa)+" mod "+str(N) icmult.name = "inverse of (times "+str(numa)+" mod "+str(N)+")" return icmult if inv else cmult def fakecmult(c, xreg, tempa, y, t1, t2, n, numa, nbits, N,inv = False): qc = QuantumCircuit(c,xreg,tempa,y,t1,t2,n) cmult = qc.to_gate() iqc = qc.inverse() icmult = iqc.to_gate() cmult.name = "times "+str(numa)+" mod "+str(N) icmult.name = "divided by "+str(modinv(numa,N))+" mod "+str(N) return icmult if inv else cmult def makea2pmod(out1, tempa, out2, t1, t2, n, numa,p,nbits,N): c = QuantumRegister(1) qc = QuantumCircuit(c, out1, tempa, out2, t1, t2, n) #print(l,(numa**(2**l))%N) #it's the iversion that's wrong qc.append(makecmult(c, out1, tempa, out2, t1, t2, n, (numa**(2**p))%N, nbits, N),list(range(0,4*nbits+3))) qc.swap(out1,out2) qc.append(makecmult(c, out1, tempa, out2, t1, t2, n, modinv((numa**(2**p))%N,N), nbits, N, True),list(range(0,4*nbits+3))) #qc = qc.to_gate() qc.name = str(numa)+"^"+str(2**p)+" mod "+str(N) return qc def makeAXmod(xreg, out1, tempa, out2, t1, t2, n,numa,mbits,nbits,N,control = False): qc = QuantumCircuit(xreg, out1, tempa, out2, t1, t2, n) #x starts and finishes as NOT ZERO c = QuantumRegister(1) for l in range(mbits): #print(l,(numa**(2**l))%N) #it's the iversion that's wrong qc.append(makecmult(c, out1, tempa, out2, t1, t2, n, (numa**(2**l))%N, nbits, N),[l] + list(range(mbits,mbits+(4*nbits+2)))) qc.swap(out1,out2) qc.append(makecmult(c, out1, tempa, out2, t1, t2, n, modinv((numa**(2**l))%N,N), nbits, N, True),[l] + list(range(mbits,mbits+(4*nbits+2)))) #qc.append(x(numx,mbits),xreg[:]) #reset x to zero if control: qc = qc.control(1) AXmod = qc#.to_gate() AXmod.name = str(numa)+"^x mod "+str(N) return AXmod #Euclidean gcd method source: Wikibooks #https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m #source: Qiskit textbook def QFT(n): circuit = QuantumCircuit(n) for bit in range(n//2): circuit.swap(bit,n-bit-1) for j in range(n): for m in range(j): circuit.cp(np.pi/(2**(j-m)), m, j) circuit.h(j) circuit.name = "QFT" return circuit def makeSum(inverse = False): qc = QuantumCircuit(3) qc.cx(1,2) qc.cx(0,2) return qc.inverse() if inverse else qc def carry(inverse = False): qc = QuantumCircuit(4) qc.ccx(1,2,3) qc.cx(1,2) qc.ccx(0,2,3) return qc.inverse() if inverse else qc def sim(qc): #prints simulated results of 2 classical registers backend_sim = Aer.get_backend('aer_simulator') job_sim = execute(qc, backend_sim,shots = 100) result_sim = job_sim.result() results = str(list(result_sim.get_counts().keys())[0]).split(" ") #result of add is b+a a resultsint = [int(res,2) for res in results] print(resultsint[1],resultsint[0]) # test code to make sure the adder gate works A = 5 B = 7 ca,cb = ClassicalRegister(4),ClassicalRegister(5) q = QuantumRegister(9) qc = QuantumCircuit(q,ca,cb) qc.append(x(A,4),range(4)) qc.append(x(B,4),range(4,8)) qc.append(makeAdder(4,True),range(9)) qc.barrier() qc.measure(range(4),ca) qc.measure(range(4,9),cb) sim(qc) print(A,A+B) qc.draw(output="text",plot_barriers=False,fold = -1) #modular addition N = 33 numa = 15 numb = 12 #works as long as a+b < 2N nbits = 6 a = QuantumRegister(nbits,"a") b = QuantumRegister(nbits,"b") t1 = QuantumRegister(1,"temp1") n = QuantumRegister(nbits,"n") t2 = QuantumRegister(1,"temp2") ca = ClassicalRegister(nbits,"ca") cb = ClassicalRegister(nbits,"cb") qc = QuantumCircuit(a, b, t1, t2, n, ca, cb) #initialise qubits qc.append(x(numa,nbits),a[:]) qc.append(x(numb,nbits),b) qc.append(x(N,nbits),n) #draw the circuit qc.append(makeAdder(nbits,True),range(2*nbits+1)) qc.swap(a,n) qc.append(makeAdder(nbits, False),range(2*nbits+1)) qc.x(t1) qc.cx(t1,t2) qc.x(t1) #set top register to zero by bitwise adding N qc.append(x(N,nbits,1),t2[:] + a[:]) qc.append(makeAdder(nbits,True),range(2*nbits+1)) #turn it back into N qc.append(x(N,nbits,1),t2[:] + a[:]) qc.swap(a,n) qc.append(makeAdder(nbits, False),range(2*nbits+1)) qc.cx(t1,t2) #t2 reset to zero qc.append(makeAdder(nbits, True),range(2*nbits+1)) qc.measure(a,ca) qc.measure(b,cb) sim(qc) print(numa,(numa+numb)%N) #check against correct value qc.draw(output = "latex",fold = -1,plot_barriers = False) #result is a, a+b mod N #controlled mult N = 15 numx = 6 numa = 5 nbits = 4 #goal = c,x,0 -> c,x,ax mod N on = True c = QuantumRegister(1,"c") #control for next step xreg = QuantumRegister(nbits,"x") #output 1 tempa = QuantumRegister(nbits,"a") #temp from adder (nbits) y = QuantumRegister(nbits,"b") #output 2 t1 = QuantumRegister(1,"temp1") #temp from adder (1) t2 = QuantumRegister(1,"temp2") #temp from adder (1) n = QuantumRegister(nbits,"n") #N (nbits) cx = ClassicalRegister(nbits,"cx") #answer cy = ClassicalRegister(nbits,"cy") #answer qc = QuantumCircuit(c, xreg, tempa, y, t1, t2, n, cx, cy) #initialise qubits qc.append(x(numx,nbits),xreg) qc.append(x(N,nbits),n) if on: qc.append(x(1,1),c) for p in range(nbits): qc.append(x((2**p*numa)%N,nbits,2),c[:] + xreg[p:p+1] + tempa[:]) qc.append(makeAdderMod(tempa,y,t1,t2,n,nbits,N),tempa[:] + y[:] + t1[:] + t2[:] + n[:]) qc.append(x((2**p*numa)%N,nbits,2),c[:] + xreg[p:p+1] + tempa[:]) qc.x(c) for q in range(nbits): qc.ccx(c,xreg[q],y[q]) qc.x(c) qc.barrier() qc.measure(xreg,cx) qc.measure(y,cy) sim(qc) print(numx,(numa*numx)%N) qc.draw(output= "latex",fold = -1,plot_barriers=False) N = 15 numa = 2 nbits = 4 p = 1 #power of 2 #result = a^2^p mod n #xreg = QuantumRegister(mbits,"x") #control, max x is 2^nbits for now but we can define mbits instead c = QuantumRegister(1,"c") out1 = QuantumRegister(nbits,"x") #output 1 tempa = QuantumRegister(nbits,"a") #temp from adder (nbits) out2 = QuantumRegister(nbits,"b") #temp from cmult t1 = QuantumRegister(1,"temp1") #temp from adder (1) t2 = QuantumRegister(1,"temp2") #temp from adder (1) n = QuantumRegister(nbits,"n") #N (nbits) cx = ClassicalRegister(nbits,"cx") #answer (same size as xreg) cy = ClassicalRegister(nbits,"cy") #answer qc = QuantumCircuit(c, out1, tempa, out2, t1, t2, n, cx, cy) qc.x(c) qc.append(x(1,nbits),out1) qc.append(x(N,nbits),n) qc.append(makecmult(c, out1, tempa, out2, t1, t2, n, (numa**(2**p))%N, nbits, N),list(range(0,4*nbits+3))) qc.swap(out1,out2) qc.append(makecmult(c, out1, tempa, out2, t1, t2, n, modinv((numa**(2**p))%N,N), nbits, N, True),list(range(0,4*nbits+3))) qc.barrier() qc.measure(out1,cx) qc.measure(out2,cy) sim(qc) print((numa**(2**p)) % N,0) qc.draw(output= "latex",fold = -1,plot_barriers=False) N = 15 numa = 2 nbits = 4 mbits = nbits period = QuantumRegister(mbits,"period") out1 = QuantumRegister(nbits,"x") #output 1 tempa = QuantumRegister(nbits,"a") #temp from adder (nbits) out2 = QuantumRegister(nbits,"b") #temp from cmult t1 = QuantumRegister(1,"temp1") #temp from adder (1) t2 = QuantumRegister(1,"temp2") #temp from adder (1) n = QuantumRegister(nbits,"n") #N (nbits) cx = ClassicalRegister(mbits,"cx") #answer (same size as xreg) qc = QuantumCircuit(period, out1, tempa, out2, t1, t2, n, cx) #qc.append(x(14,mbits),period[:]) qc.h(period[:]) qc.append(x(1,nbits),out1[:]) qc.append(x(N,nbits),n[:]) for p in range(mbits): qc.append(makea2pmod(out1, tempa, out2, t1, t2, n, numa,p,nbits,N),[p] + list(range(mbits,mbits+4*nbits+2))) qc.append(QFT(nbits),range(nbits)) qc.measure(period,cx) qc.draw(fold=-1,output = "latex") aersim = Aer.get_backend('aer_simulator') tqc = transpile(qc,aersim) results = aersim.run(tqc,shots=5000).result() plot_histogram(results.get_counts()) checkedlist = [] factorfound = False for output in results.get_counts(): if results.get_counts()[output] > 30: #filtering any measurements from random noise phase = int(output,base=2)/(2**nbits) r = Fraction(phase).limit_denominator(int(N/2)).denominator if r not in checkedlist: checkedlist.append(r) if r > 1 and r % 2 == 0: if int(numa**(r/2)) <= 2**62: #gcd requires numbers below 2^64 p1 = np.gcd(int(numa**(r/2)-1),N) p2 = np.gcd(int(numa**(r/2)+1),N) plist = [p1,p2] if p1 <= p2 else [p2,p1] if p1 * p2 == N and p1 != 1 and p2 != 1: print( f"{plist[0]:<2d}* {plist[1]:<3d} = {N:<3d}, r = {r:<3d}, a = {numa:<3d}, nbits = {nbits:<2d}") factorfound = True if not factorfound: print(f"{N} is prime or cannot be found with a = {numa}") #Altenative gate construction for x = 2 and N = 2^n - 1 power2 = 4 N = 2**power2 - 1 def powermodp2(power,power2): #multiply by 2^p (mod 2^n-1) U = QuantumCircuit(power2) for i in range(power): for j in range(power2-1): U.swap(j,j+1) U = U.to_gate() U.name = f"2^{power} mod {N}" c_U = U.control() return c_U nbits = power2 - 1 #edit this line to change the size of the input regiter (eg: nbits = power2 + 1) xreg = QuantumRegister(nbits,"input") y = QuantumRegister(power2,"y") cx = ClassicalRegister(nbits) qc = QuantumCircuit(xreg,y,cx) qc.h(xreg[:]) qc.x(nbits + power2 - 1) for k in range(nbits): qc.append(powermodp2(2**k,power2),[k] + y[:]) qc.append(QFT(nbits),range(nbits)) qc.measure(range(nbits),range(nbits)) qc.draw(fold=-1,output="latex") aersim = Aer.get_backend('aer_simulator') #set memory=True to see measurements tqc = transpile(qc,aersim) results = aersim.run(tqc,shots=10000).result() nbits = 3 d = results.get_counts() oldkeys = list(d.keys()) xblue = [1,3,5,7] xred = [0,2,4,6] for key in xblue+xred: d[str(key)] = 0 for key in oldkeys: d[str(int(key,2))] = d[key] del d[key] yred = [d[str(xi)]/10000 for xi in xred] yblue = [d[str(xi)]/10000 for xi in xblue] plt.xlim(-0.9,7.9) plt.bar(xred,yred,color=(1,0,0)) plt.bar(xblue,yblue,color=(0.4,0.6,1)) plt.ylabel("Probability") plt.xlabel("x") newd = {"0x0": 2919, "0x1": 2298, "0x2": 2249, "0x3": 1850, "0x4": 3353, "0x5": 2431, "0x6": 2704, "0x7": 2196} nbits = 3 oldkeys = list(newd.keys()) xblue = [1,3,5,7] xred = [0,2,4,6] for key in xblue+xred: newd[str(key)] = 0 for key in oldkeys: newd[str(key[2:])] = newd[key] del newd[key] print(newd) yred = [newd[str(xi)]/20000 for xi in xred] yblue = [newd[str(xi)]/20000 for xi in xblue] plt.xlim(-1,7.9) plt.bar(xred,yred,color=(1,0,0)) plt.bar(xblue,yblue,color=(0.4,0.6,1)) plt.ylabel("Probability") plt.xlabel("x") print(yred[1]+yred[3])
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
min_qubits=2 max_qubits=8 skip_qubits=1 max_circuits=3 num_shots=1000 backend_id="dm_simulator" #backend_id="statevector_simulator" #hub="ibm-q"; group="open"; project="main" provider_backend = None exec_options = {} # # ========================== # # *** If using IBMQ hardware, run this once to authenticate # from qiskit import IBMQ # IBMQ.save_account('YOUR_API_TOKEN_HERE') # # *** If you are part of an IBMQ group, set hub, group, and project name here # hub="YOUR_HUB_NAME"; group="YOUR_GROUP_NAME"; project="YOUR_PROJECT_NAME" # # *** This example shows how to specify an IBMQ backend using a known "backend_id" # exec_options = { "optimization_level":3, "use_sessions":True, "resilience_level":1} # backend_id="ibmq_belem" # # ========================== # # *** If using Azure Quantum, use this hub identifier and specify the desired backend_id # # Identify your resources with env variables AZURE_QUANTUM_RESOURCE_ID and AZURE_QUANTUM_LOCATION # hub="azure-quantum"; group="open"; project="QED-C App-Oriented Benchmarks - Qiskit Version" # backend_id="<YOUR_BACKEND_NAME_HERE>" # # ========================== # The remaining examples illustrate other backend execution options # # An example using IonQ provider # from qiskit_ionq import IonQProvider # provider = IonQProvider() # Be sure to set the QISKIT_IONQ_API_TOKEN environment variable # provider_backend = provider.get_backend("ionq_qpu") # backend_id="ionq_qpu" # # An example using BlueQubit provider # import os, bluequbit, _common.executors.bluequbit_executor as bluequbit_executor # provider_backend = bluequbit.init() # backend_id="BlueQubit-CPU" # # An example using a typical custom provider backend (e.g. AQT simulator) # import os # from qiskit_aqt_provider import AQTProvider # provider = AQTProvider(os.environ.get('AQT_ACCESS_KEY')) # get your key from environment # provider_backend = provider.backends.aqt_qasm_simulator_noise_1 # backend_id="aqt_qasm_simulator_noise_1" # # Fire Opal can be used to manage executions on other backends, as illustrated here # import _common.executors.fire_opal_executor as fire_opal_executor # from _common.executors.fire_opal_executor import FireOpalBackend # ibm_backend_id = "ibmq_jakarta" # backend_id = f"fire_opal_{ibm_backend_id}" # provider_backend = FireOpalBackend(ibm_backend_id=ibm_backend_id, hub=hub, group=group, project=project, token=token) # exec_options = {"executor": fire_opal_executor.run} import sys sys.path[1:1] = [ "_common", "_common/qsim" ] import execute as ex # noise parameters for dm-simulator (introduce noise by changing the values) options_noise = { 'plot': False, "thermal_factor": 0.9, 'show_partition': False, "decoherence_factor": 1.0, "depolarization_factor": 0.9, "bell_depolarization_factor": 1.0, "decay_factor": 1.0, "rotation_error": {'rx': [1.0, 0.0], 'ry': [1.0, 0.0], 'rz': [1.0, 0.0]}, # Default values [1.0, 0.0] "tsp_model_error": [1.0, 0.0], } ex.options_noise = options_noise # Custom optimization options can be specified in this cell (below is an example) # # Example of pytket Transformer # import _common.transformers.tket_optimiser as tket_optimiser # exec_options.update({ "optimization_level": 0, "layout_method":'sabre', "routing_method":'sabre', "transformer": tket_optimiser.high_optimisation }) # # Define a custom noise model to be used during execution # import _common.custom.custom_qiskit_noise_model as custom_qiskit_noise_model # exec_options.update({ "noise_model": custom_qiskit_noise_model.my_noise_model() }) # # Example of mthree error mitigation # import _common.postprocessors.mthree.mthree_em as mthree_em # exec_options.update({ "postprocessor": mthree_em.get_mthree_handlers(backend_id, provider_backend) }) # pip uninstall qiskit-aer -y # pip install qiskit-aer import sys sys.path.insert(1, "deutsch-jozsa/qsim") import dj_benchmark dj_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "bernstein-vazirani/qsim") import bv_benchmark bv_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, method=1, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "bernstein-vazirani/qsim") import bv_benchmark bv_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "hidden-shift/qsim") import hs_benchmark hs_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, #hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "quantum-fourier-transform/qsim") import qft_benchmark qft_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, method=1, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "quantum-fourier-transform/qsim") import qft_benchmark qft_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "grovers/qsim") import grovers_benchmark grovers_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "phase-estimation/qsim") import pe_benchmark pe_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "hhl/qsim") import hhl_benchmark hhl_benchmark.verbose=False hhl_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, method=1, use_best_widths=True, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "amplitude-estimation/qsim") import ae_benchmark ae_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "monte-carlo/qsim") import mc_benchmark mc_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "hamiltonian-simulation/qsim") import hamiltonian_simulation_benchmark hamiltonian_simulation_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "vqe/qsim") import vqe_benchmark vqe_num_shots=4098 vqe_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=vqe_num_shots, method=1, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "shors/qsim") import shors_benchmark shors_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=1, num_shots=num_shots, method=1, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "shors/qsim") import shors_benchmark shors_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=1, num_shots=num_shots, method=2, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "_common") import metrics # metrics.depth_base = 2 # metrics.QV = 0 # apps = [ "Hidden Shift", "Grover's Search", "Quantum Fourier Transform (1)", "Hamiltonian Simulation" ] # backend_id='qasm_simulator' metrics.plot_all_app_metrics(backend_id, do_all_plots=False, include_apps=None)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Amplitude Estimation Benchmark Program via Phase Estimation - QSim """ import copy import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = ["_common", "_common/qsim", "quantum-fourier-transform/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../quantum-fourier-transform/qsim"] import execute as ex import metrics as metrics from execute import BenchmarkResult from qft_benchmark import inv_qft_gate # Benchmark Name benchmark_name = "Amplitude Estimation" np.random.seed(0) verbose = False # saved subcircuits circuits for printing A_ = None Q_ = None cQ_ = None QC_ = None QFTI_ = None ############### Circuit Definition def AmplitudeEstimation(num_state_qubits, num_counting_qubits, a, psi_zero=None, psi_one=None): num_qubits = num_state_qubits + 1 + num_counting_qubits qr_state = QuantumRegister(num_state_qubits+1) qr_counting = QuantumRegister(num_counting_qubits) cr = ClassicalRegister(num_counting_qubits) qc = QuantumCircuit(qr_counting, qr_state, cr, name=f"qae-{num_qubits}-{a}") # create the Amplitude Generator circuit A = A_gen(num_state_qubits, a, psi_zero, psi_one) # create the Quantum Operator circuit and a controlled version of it cQ, Q = Ctrl_Q(num_state_qubits, A) # save small example subcircuits for visualization global A_, Q_, cQ_, QFTI_ if (cQ_ and Q_) == None or num_state_qubits <= 6: if num_state_qubits < 9: cQ_ = cQ; Q_ = Q; A_ = A if QFTI_ == None or num_qubits <= 5: if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits) # Prepare state from A, and counting qubits with H transform qc.append(A, [qr_state[i] for i in range(num_state_qubits+1)]) for i in range(num_counting_qubits): qc.h(qr_counting[i]) repeat = 1 for j in reversed(range(num_counting_qubits)): for _ in range(repeat): qc.append(cQ, [qr_counting[j]] + [qr_state[l] for l in range(num_state_qubits+1)]) repeat *= 2 qc.barrier() # inverse quantum Fourier transform only on counting qubits qc.append(inv_qft_gate(num_counting_qubits), qr_counting) qc.barrier() # measure counting qubits qc.measure([qr_counting[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits))) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc return qc # Construct A operator that takes |0>_{n+1} to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> def A_gen(num_state_qubits, a, psi_zero=None, psi_one=None): if psi_zero==None: psi_zero = '0'*num_state_qubits if psi_one==None: psi_one = '1'*num_state_qubits theta = 2 * np.arcsin(np.sqrt(a)) # Let the objective be qubit index n; state is on qubits 0 through n-1 qc_A = QuantumCircuit(num_state_qubits+1, name=f"A") # takes state to |0>_{n} (sqrt(1-a) |0> + sqrt(a) |1>) qc_A.ry(theta, num_state_qubits) # takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |0>_{n}|1> qc_A.x(num_state_qubits) for i in range(num_state_qubits): if psi_zero[i]=='1': qc_A.cnot(num_state_qubits,i) qc_A.x(num_state_qubits) # takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> for i in range(num_state_qubits): if psi_one[i]=='1': qc_A.cnot(num_state_qubits,i) return qc_A # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qc = QuantumCircuit(num_state_qubits+1, name=f"Q") temp_A = copy.copy(A_circ) A_gate = temp_A.to_gate() A_gate_inv = temp_A.inverse().to_gate() ### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ # -S_chi qc.x(num_state_qubits) qc.z(num_state_qubits) qc.x(num_state_qubits) # A_circ_inverse qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)]) # S_0 for i in range(num_state_qubits+1): qc.x(i) qc.h(num_state_qubits) qc.mcx([x for x in range(num_state_qubits)], num_state_qubits) qc.h(num_state_qubits) for i in range(num_state_qubits+1): qc.x(i) # A_circ qc.append(A_gate, [i for i in range(num_state_qubits+1)]) # Create a gate out of the Q operator qc.to_gate(label='Q') # and also a controlled version of it Ctrl_Q_ = qc.control(1) # and return both return Ctrl_Q_, qc # Analyze and print measured results # Expected result is always the secret_int (which encodes alpha), so fidelity calc is simple def analyze_and_print_result(qc, result, num_counting_qubits, s_int, num_shots): if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts # calculate expected output histogram a = a_from_s_int(s_int, num_counting_qubits) correct_dist = a_to_bitstring(a, num_counting_qubits) # print("correct_dist ====== ", correct_dist) # generate thermal_dist for polarization calculation thermal_dist = metrics.uniform_dist(num_counting_qubits) # print("thermal_dist ====== ", thermal_dist) # convert probs, expectation, and thermal_dist to app form for visibility # app form of correct distribution is measuring amplitude a 100% of the time app_counts = bitstring_to_a(probs, num_counting_qubits) app_correct_dist = {a: 1.0} app_thermal_dist = bitstring_to_a(thermal_dist, num_counting_qubits) # print("app_counts ====== ", app_counts) # print("app_correct_dist ====== ", app_correct_dist) # print("app_thermal_dist ====== ", app_thermal_dist) if verbose: print(f"For amplitude {a}, expected: {correct_dist} measured: {probs}") print(f" ... For amplitude {a} thermal_dist: {thermal_dist}") print(f"For amplitude {a}, app expected: {app_correct_dist} measured: {app_counts}") print(f" ... For amplitude {a} app_thermal_dist: {app_thermal_dist}") # use polarization fidelity with rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist, thermal_dist) #fidelity = metrics.polarization_fidelity(app_counts, app_correct_dist, app_thermal_dist) # print("fidelity ====== ", fidelity) hf_fidelity = metrics.hellinger_fidelity_with_expected(probs, correct_dist) if verbose: print(f" ... fidelity: {fidelity} hf_fidelity: {hf_fidelity}") return probs, fidelity def a_to_bitstring(a, num_counting_qubits): m = num_counting_qubits # solution 1 num1 = round(np.arcsin(np.sqrt(a)) / np.pi * 2**m) num2 = round( (np.pi - np.arcsin(np.sqrt(a))) / np.pi * 2**m) if num1 != num2 and num2 < 2**m and num1 < 2**m: counts = {format(num1, "0"+str(m)+"b"): 0.5, format(num2, "0"+str(m)+"b"): 0.5} else: counts = {format(num1, "0"+str(m)+"b"): 1} return counts def bitstring_to_a(counts, num_counting_qubits): est_counts = {} m = num_counting_qubits precision = int(num_counting_qubits / (np.log2(10))) + 2 for key in counts.keys(): r = counts[key] num = int(key,2) / (2**m) a_est = round((np.sin(np.pi * num) )** 2, precision) if a_est not in est_counts.keys(): est_counts[a_est] = 0 est_counts[a_est] += r return est_counts def a_from_s_int(s_int, num_counting_qubits): theta = s_int * np.pi / (2**num_counting_qubits) precision = int(num_counting_qubits / (np.log2(10))) + 2 a = round(np.sin(theta)**2, precision) return a ################ Benchmark Loop # Because circuit size grows significantly with num_qubits # limit the max_qubits here ... MAX_QUBITS=8 # Execute program with default parameters def run(min_qubits=4, max_qubits=8, skip_qubits=1, max_circuits=3, num_shots=100, #for dm-simulator min_qubits=4 because it requires to measure atleast 2 qubits num_state_qubits=1, # default, not exposed to users backend_id='dm_simulator', provider_backend=None, # hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # Clamp the maximum number of qubits if max_qubits > MAX_QUBITS: print(f"INFO: {benchmark_name} benchmark is limited to a maximum of {MAX_QUBITS} qubits.") max_qubits = MAX_QUBITS # validate parameters (smallest circuit is 3 qubits) num_state_qubits = max(1, num_state_qubits) if max_qubits < num_state_qubits + 2: print(f"ERROR: AE Benchmark needs at least {num_state_qubits + 2} qubits to run") return min_qubits = max(max(4, min_qubits), num_state_qubits + 2) # min_qubit=4 for AE using dm-simulator skip_qubits = max(1, skip_qubits) #print(f"min, max, state = {min_qubits} {max_qubits} {num_state_qubits}") # create context identifier if context is None: context = f"{benchmark_name} Benchmark" ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_counting_qubits = int(num_qubits) - num_state_qubits - 1 counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, #hub=hub, group=group, project=project, exec_options=exec_options, context=context) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (num_counting_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") if verbose: print(f" with num_state_qubits = {num_state_qubits} num_counting_qubits = {num_counting_qubits}") # determine range of secret strings to loop over if 2**(num_counting_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_counting_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() a_ = a_from_s_int(s_int, num_counting_qubits) qc = AmplitudeEstimation(num_state_qubits, num_counting_qubits, a_).reverse_bits() #applying reverse_bits() due to change in endianness metrics.store_metric(num_qubits, s_int, 'create_time', time.time() - ts) # collapse the 3 sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose().decompose().decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, s_int, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nControlled Quantum Operator 'cQ' ="); print(cQ_ if cQ_ != None else " ... too large!") print("\nQuantum Operator 'Q' ="); print(Q_ if Q_ != None else " ... too large!") print("\nAmplitude Generator 'A' ="); print(A_ if A_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QC_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks) run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Amplitude Estimation Benchmark Program via Phase Estimation - QSim """ import copy import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = ["_common", "_common/qsim", "quantum-fourier-transform/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../quantum-fourier-transform/qsim"] import execute as ex import metrics as metrics from qft_benchmark import inv_qft_gate from execute import BenchmarkResult # Benchmark Name benchmark_name = "Amplitude Estimation" np.random.seed(0) verbose = False # saved subcircuits circuits for printing A_ = None Q_ = None cQ_ = None QC_ = None QFTI_ = None ############### Circuit Definition def AmplitudeEstimation(num_state_qubits, num_counting_qubits, a, psi_zero=None, psi_one=None): num_qubits = num_state_qubits + 1 + num_counting_qubits qr_state = QuantumRegister(num_state_qubits+1) qr_counting = QuantumRegister(num_counting_qubits) cr = ClassicalRegister(num_counting_qubits) qc = QuantumCircuit(qr_counting, qr_state, cr, name=f"qae-{num_qubits}-{a}") # create the Amplitude Generator circuit A = A_gen(num_state_qubits, a, psi_zero, psi_one) # create the Quantum Operator circuit and a controlled version of it cQ, Q = Ctrl_Q(num_state_qubits, A) # save small example subcircuits for visualization global A_, Q_, cQ_, QFTI_ if (cQ_ and Q_) == None or num_state_qubits <= 6: if num_state_qubits < 9: cQ_ = cQ; Q_ = Q; A_ = A if QFTI_ == None or num_qubits <= 5: if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits) # Prepare state from A, and counting qubits with H transform qc.append(A, [qr_state[i] for i in range(num_state_qubits+1)]) for i in range(num_counting_qubits): qc.h(qr_counting[i]) repeat = 1 for j in reversed(range(num_counting_qubits)): for _ in range(repeat): qc.append(cQ, [qr_counting[j]] + [qr_state[l] for l in range(num_state_qubits+1)]) repeat *= 2 qc.barrier() # inverse quantum Fourier transform only on counting qubits qc.append(inv_qft_gate(num_counting_qubits), qr_counting) qc.barrier() # measure counting qubits qc.measure([qr_counting[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits))) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc return qc # Construct A operator that takes |0>_{n+1} to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> def A_gen(num_state_qubits, a, psi_zero=None, psi_one=None): if psi_zero==None: psi_zero = '0'*num_state_qubits if psi_one==None: psi_one = '1'*num_state_qubits theta = 2 * np.arcsin(np.sqrt(a)) # Let the objective be qubit index n; state is on qubits 0 through n-1 qc_A = QuantumCircuit(num_state_qubits+1, name=f"A") # takes state to |0>_{n} (sqrt(1-a) |0> + sqrt(a) |1>) qc_A.ry(theta, num_state_qubits) # takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |0>_{n}|1> qc_A.x(num_state_qubits) for i in range(num_state_qubits): if psi_zero[i]=='1': qc_A.cnot(num_state_qubits,i) qc_A.x(num_state_qubits) # takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> for i in range(num_state_qubits): if psi_one[i]=='1': qc_A.cnot(num_state_qubits,i) return qc_A # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qc = QuantumCircuit(num_state_qubits+1, name=f"Q") temp_A = copy.copy(A_circ) A_gate = temp_A.to_gate() A_gate_inv = temp_A.inverse().to_gate() ### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ # -S_chi qc.x(num_state_qubits) qc.z(num_state_qubits) qc.x(num_state_qubits) # A_circ_inverse qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)]) # S_0 for i in range(num_state_qubits+1): qc.x(i) qc.h(num_state_qubits) qc.mcx([x for x in range(num_state_qubits)], num_state_qubits) qc.h(num_state_qubits) for i in range(num_state_qubits+1): qc.x(i) # A_circ qc.append(A_gate, [i for i in range(num_state_qubits+1)]) # Create a gate out of the Q operator qc.to_gate(label='Q') # and also a controlled version of it Ctrl_Q_ = qc.control(1) # and return both return Ctrl_Q_, qc # Analyze and print measured results # Expected result is always the secret_int (which encodes alpha), so fidelity calc is simple def analyze_and_print_result(qc, result, num_counting_qubits, s_int, num_shots): if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts # calculate expected output histogram a = a_from_s_int(s_int, num_counting_qubits) correct_dist = a_to_bitstring(a, num_counting_qubits) # print("correct_dist ====== ", correct_dist) # generate thermal_dist for polarization calculation thermal_dist = metrics.uniform_dist(num_counting_qubits) # print("thermal_dist ====== ", thermal_dist) # convert probs, expectation, and thermal_dist to app form for visibility # app form of correct distribution is measuring amplitude a 100% of the time app_counts = bitstring_to_a(probs, num_counting_qubits) app_correct_dist = {a: 1.0} app_thermal_dist = bitstring_to_a(thermal_dist, num_counting_qubits) # print("app_counts ====== ", app_counts) # print("app_correct_dist ====== ", app_correct_dist) # print("app_thermal_dist ====== ", app_thermal_dist) if verbose: print(f"For amplitude {a}, expected: {correct_dist} measured: {probs}") print(f" ... For amplitude {a} thermal_dist: {thermal_dist}") print(f"For amplitude {a}, app expected: {app_correct_dist} measured: {app_counts}") print(f" ... For amplitude {a} app_thermal_dist: {app_thermal_dist}") # use polarization fidelity with rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist, thermal_dist) #fidelity = metrics.polarization_fidelity(app_counts, app_correct_dist, app_thermal_dist) # print("fidelity ====== ", fidelity) hf_fidelity = metrics.hellinger_fidelity_with_expected(probs, correct_dist) if verbose: print(f" ... fidelity: {fidelity} hf_fidelity: {hf_fidelity}") return probs, fidelity def a_to_bitstring(a, num_counting_qubits): m = num_counting_qubits # solution 1 num1 = round(np.arcsin(np.sqrt(a)) / np.pi * 2**m) num2 = round((np.pi - np.arcsin(np.sqrt(a))) / np.pi * 2**m) if num1 != num2 and num2 < 2**m and num1 < 2**m: counts = {format(num1, "0"+str(m)+"b"): 0.5, format(num2, "0"+str(m)+"b"): 0.5} else: counts = {format(num1, "0"+str(m)+"b"): 1} return counts def bitstring_to_a(counts, num_counting_qubits): est_counts = {} m = num_counting_qubits precision = int(num_counting_qubits / (np.log2(10))) + 2 for key in counts.keys(): r = counts[key] num = int(key,2) / (2**m) a_est = round((np.sin(np.pi * num) )** 2, precision) if a_est not in est_counts.keys(): est_counts[a_est] = 0 est_counts[a_est] += r return est_counts def a_from_s_int(s_int, num_counting_qubits): theta = s_int * np.pi / (2**num_counting_qubits) precision = int(num_counting_qubits / (np.log2(10))) + 2 a = round(np.sin(theta)**2, precision) return a ################ Benchmark Loop # Because circuit size grows significantly with num_qubits # limit the max_qubits here ... MAX_QUBITS=8 # Execute program with default parameters def run(min_qubits=4, max_qubits=7, skip_qubits=1, max_circuits=3, num_shots=100, #for dm-simulator min_qubits=4 because it requires to measure atleast 2 qubits num_state_qubits=1, # default, not exposed to users backend_id='dm_simulator', provider_backend=None, #hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # Clamp the maximum number of qubits if max_qubits > MAX_QUBITS: print(f"INFO: {benchmark_name} benchmark is limited to a maximum of {MAX_QUBITS} qubits.") max_qubits = MAX_QUBITS # validate parameters (smallest circuit is 3 qubits) num_state_qubits = max(1, num_state_qubits) if max_qubits < num_state_qubits + 2: print(f"ERROR: AE Benchmark needs at least {num_state_qubits + 2} qubits to run") return min_qubits = max(max(4, min_qubits), num_state_qubits + 2) # min_qubit=4 for AE using dm-simulator skip_qubits = max(1, skip_qubits) #print(f"min, max, state = {min_qubits} {max_qubits} {num_state_qubits}") # create context identifier if context is None: context = f"{benchmark_name} Benchmark" ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_counting_qubits = int(num_qubits) - num_state_qubits - 1 counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options, context=context) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (num_counting_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") if verbose: print(f" with num_state_qubits = {num_state_qubits} num_counting_qubits = {num_counting_qubits}") # determine range of secret strings to loop over if 2**(num_counting_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_counting_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() a_ = a_from_s_int(s_int, num_counting_qubits) # print("a_ ===== ", int(a_)) qc = AmplitudeEstimation(num_state_qubits, num_counting_qubits, a_).reverse_bits() print(qc) metrics.store_metric(num_qubits, s_int, 'create_time', time.time() - ts) # collapse the 3 sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose().decompose().decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, s_int, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nControlled Quantum Operator 'cQ' ="); print(cQ_ if cQ_ != None else " ... too large!") print("\nQuantum Operator 'Q' ="); print(Q_ if Q_ != None else " ... too large!") print("\nAmplitude Generator 'A' ="); print(A_ if A_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QC_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
import matplotlib.pyplot as plt import numpy as np import copy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, assemble from collections.abc import Iterable # Construct A operator that takes |0>_{n+1} to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> def A_gen(num_state_qubits, a, psi_zero=None, psi_one=None): if psi_zero==None: psi_zero = '0'*num_state_qubits if psi_one==None: psi_one = '1'*num_state_qubits theta = 2 * np.arcsin(np.sqrt(a)) # Let the objective be qubit index n; state is on qubits 0 through n-1 qc_A = QuantumCircuit(num_state_qubits+1, name=f"A") # qc_A.ry(theta, num_state_qubits) #ry is not present in the list of basis_gates (qiskit-aakash/qiskit/providers/basicaer/unitary_simulator.py) qc_A.x(num_state_qubits) for i in range(num_state_qubits): if psi_zero[i]=='1': qc_A.cnot(num_state_qubits,i) qc_A.x(num_state_qubits) for i in range(num_state_qubits): if psi_one[i]=='1': qc_A.cnot(num_state_qubits,i) return qc_A # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qc = QuantumCircuit(num_state_qubits+1, name=f"Q") temp_A = copy.copy(A_circ) A_gate = temp_A.to_gate() A_gate_inv = temp_A.inverse().to_gate() ### Each cycle in Q applies in order: S_chi, A_circ_inverse, S_0, A_circ # S_chi qc.z(num_state_qubits) # A_circ_inverse qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)]) # S_0 for i in range(num_state_qubits+1): qc.x(i) qc.h(num_state_qubits) qc.mcx([x for x in range(num_state_qubits)], num_state_qubits) qc.h(num_state_qubits) for i in range(num_state_qubits+1): qc.x(i) # A_circ qc.append(A_gate, [i for i in range(num_state_qubits+1)]) # add "global" phase qc.x(num_state_qubits) qc.z(num_state_qubits) qc.x(num_state_qubits) qc.z(num_state_qubits) # Create a gate out of the Q operator qc.to_gate(label='Q') # and also a controlled version of it Ctrl_Q_ = qc.control(1) # and return both return Ctrl_Q_, qc num_q = 3 qr_ = QuantumRegister(num_q+1) cr_ = ClassicalRegister(num_q+1) qc_ = QuantumCircuit(qr_, cr_) a = 1/8 A = A_gen(num_q, a) _, Q = Ctrl_Q(num_q, A) qc_.append(A, qr_) # qc_.append(Q, qr_) qc_.measure(qr_, cr_) from qiskit import execute, BasicAer backend = BasicAer.get_backend("dm_simulator") job = execute(qc_, backend, shots=1000) result = job.result() counts = result.get_counts() print(counts) num_q = 1 qr_ = QuantumRegister(num_q+1) cr_ = ClassicalRegister(num_q+1) qc_ = QuantumCircuit(qr_, cr_) a = 1/5 A = A_gen(num_q, a) _, Q = Ctrl_Q(num_q, A) qc_.append(Q, qr_) display(qc_.draw()) qc_ = qc_.decompose().decompose() usim = BasicAer.get_backend('unitary_simulator') qobj = assemble(qc_) unitary = usim.run(qobj).result().get_unitary() print(np.round(unitary, 6))
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Bernstein-Vazirani Benchmark Program - QSim """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = [ "_common", "_common/qsim" ] sys.path[1:1] = [ "../../_common", "../../_common/qsim" ] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "Bernstein-Vazirani" np.random.seed(0) verbose = False # Variable for number of resets to perform after mid circuit measurements num_resets = 1 # saved circuits for display QC_ = None Uf_ = None ############### Circuit Definition def create_oracle(num_qubits, input_size, secret_int): # Initialize first n qubits and single ancilla qubit qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"Uf") # perform CX for each qubit that matches a bit in secret string s = ('{0:0' + str(input_size) + 'b}').format(secret_int) for i_qubit in range(input_size): if s[input_size - 1 - i_qubit] == '1': qc.cx(qr[i_qubit], qr[input_size]) return qc def BersteinVazirani (num_qubits, secret_int, method = 1): # size of input is one less than available qubits input_size = num_qubits - 1 if method == 1: # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name=f"bv({method})-{num_qubits}-{secret_int}") # put ancilla in |1> state qc.x(qr[input_size]) # start with Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() #generate Uf oracle Uf = create_oracle(num_qubits, input_size, secret_int) qc.append(Uf,qr) qc.barrier() # start with Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) # uncompute ancilla qubit, not necessary for algorithm qc.x(qr[input_size]) qc.barrier() # measure all data qubits for i in range(input_size): qc.measure(i, i) global Uf_ if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf elif method == 2: # allocate qubits qr = QuantumRegister(2); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name="main") # put ancilla in |-> state qc.x(qr[1]) qc.h(qr[1]) qc.barrier() # perform CX for each qubit that matches a bit in secret string s = ('{0:0' + str(input_size) + 'b}').format(secret_int) for i in range(input_size): if s[input_size - 1 - i] == '1': qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.measure(qr[0], cr[i]) # Perform num_resets reset operations qc.reset([0]*num_resets) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots): # size of input is one less than available qubits input_size = num_qubits - 1 if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts if verbose: print(f"For secret int {secret_int} measured: {counts}") # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{input_size}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) return probs, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=3, max_qubits=8, skip_qubits=1, max_circuits=3, num_shots=100, backend_id='dm_simulator', method = 1, provider_backend=None, #hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} ({method}) Benchmark Program - QSim") # validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # create context identifier if context is None: context = f"{benchmark_name} ({method}) Benchmark" ########## # Variable for new qubit group ordering if using mid_circuit measurements mid_circuit_qubit_group = [] # If using mid_circuit measurements, set transform qubit group to true transform_qubit_group = True if method ==2 else False # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options, context=context) # for noiseless simulation, set noise model to be None # ex.set_noise_model(None) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): input_size = num_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2**(input_size), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(input_size) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(input_size), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # If mid circuit, then add 2 to new qubit group since the circuit only uses 2 qubits if method == 2: mid_circuit_qubit_group.append(2) # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = BersteinVazirani(num_qubits, s_int, method).reverse_bits() #reverse_bits() is to change endianness metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, s_int, shots=num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim", transform_qubit_group = transform_qubit_group, new_qubit_group = mid_circuit_qubit_group) # if main, execute method if __name__ == '__main__': ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks) run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Bernstein-Vazirani Benchmark Program - QSim """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = [ "_common", "_common/qsim" ] sys.path[1:1] = [ "../../_common", "../../_common/qsim" ] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "Bernstein-Vazirani" np.random.seed(0) verbose = False # Variable for number of resets to perform after mid circuit measurements num_resets = 1 # saved circuits for display QC_ = None Uf_ = None ############### Circuit Definition def create_oracle(num_qubits, input_size, secret_int): # Initialize first n qubits and single ancilla qubit qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"Uf") # perform CX for each qubit that matches a bit in secret string s = ('{0:0' + str(input_size) + 'b}').format(secret_int) for i_qubit in range(input_size): if s[input_size - 1 - i_qubit] == '1': qc.cx(qr[i_qubit], qr[input_size]) return qc def BersteinVazirani (num_qubits, secret_int, method = 1): # size of input is one less than available qubits input_size = num_qubits - 1 if method == 1: # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name=f"bv({method})-{num_qubits}-{secret_int}") # put ancilla in |1> state qc.x(qr[input_size]) # start with Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() #generate Uf oracle Uf = create_oracle(num_qubits, input_size, secret_int) qc.append(Uf,qr) qc.barrier() # start with Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) # uncompute ancilla qubit, not necessary for algorithm qc.x(qr[input_size]) qc.barrier() # measure all data qubits for i in range(input_size): qc.measure(i, i) global Uf_ if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf elif method == 2: # allocate qubits qr = QuantumRegister(2); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name="main") # put ancilla in |-> state qc.x(qr[1]) qc.h(qr[1]) qc.barrier() # perform CX for each qubit that matches a bit in secret string s = ('{0:0' + str(input_size) + 'b}').format(secret_int) for i in range(input_size): if s[input_size - 1 - i] == '1': qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.measure(qr[0], cr[i]) # Perform num_resets reset operations qc.reset([0]*num_resets) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots): # size of input is one less than available qubits input_size = num_qubits - 1 if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts if verbose: print(f"For secret int {secret_int} measured: {probs}") # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{input_size}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) return probs, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=3, max_qubits=8, skip_qubits=1, max_circuits=3, num_shots=100, backend_id='dm_simulator', method = 1, provider_backend=None, # hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} ({method}) Benchmark Program - QSim") # validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # create context identifier if context is None: context = f"{benchmark_name} ({method}) Benchmark" ########## # Variable for new qubit group ordering if using mid_circuit measurements mid_circuit_qubit_group = [] # If using mid_circuit measurements, set transform qubit group to true transform_qubit_group = True if method ==2 else False # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options, context=context) # for noiseless simulation, set noise model to be None # ex.set_noise_model(None) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): input_size = num_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2**(input_size), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(input_size) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(input_size), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # If mid circuit, then add 2 to new qubit group since the circuit only uses 2 qubits if method == 2: mid_circuit_qubit_group.append(2) # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = BersteinVazirani(num_qubits, s_int, method).reverse_bits() # reverse_bits() is to change the endianness print(qc) metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, s_int, shots=num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim", transform_qubit_group = transform_qubit_group, new_qubit_group = mid_circuit_qubit_group) # if main, execute method if __name__ == '__main__': run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Bernstein-Vazirani Benchmark Program - QSim """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = [ "_common", "_common/qsim" ] sys.path[1:1] = [ "../../_common", "../../_common/qsim" ] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "Bernstein-Vazirani" np.random.seed(0) verbose = False # Variable for number of resets to perform after mid circuit measurements num_resets = 1 # saved circuits for display QC_ = None Uf_ = None ############### Circuit Definition def create_oracle(num_qubits, input_size, secret_int): # Initialize first n qubits and single ancilla qubit qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"Uf") # perform CX for each qubit that matches a bit in secret string s = ('{0:0' + str(input_size) + 'b}').format(secret_int) for i_qubit in range(input_size): if s[input_size - 1 - i_qubit] == '1': qc.cx(qr[i_qubit], qr[input_size]) return qc def BersteinVazirani (num_qubits, secret_int, method = 1): # size of input is one less than available qubits input_size = num_qubits - 1 if method == 1: # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name=f"bv({method})-{num_qubits}-{secret_int}") # put ancilla in |1> state qc.x(qr[input_size]) # start with Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() #generate Uf oracle Uf = create_oracle(num_qubits, input_size, secret_int) qc.append(Uf,qr) qc.barrier() # start with Hadamard on all qubits, including ancilla for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) # uncompute ancilla qubit, not necessary for algorithm qc.x(qr[input_size]) qc.barrier() # measure all data qubits for i in range(input_size): qc.measure(i, i) global Uf_ if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf elif method == 2: # allocate qubits qr = QuantumRegister(2); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name="main") # put ancilla in |-> state qc.x(qr[1]) qc.h(qr[1]) qc.barrier() # perform CX for each qubit that matches a bit in secret string s = ('{0:0' + str(input_size) + 'b}').format(secret_int) for i in range(input_size): if s[input_size - 1 - i] == '1': qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.measure(qr[0], cr[i]) # Perform num_resets reset operations qc.reset([0]*num_resets) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 15: if num_qubits < 15: QC_ = qc # return a handle on the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots): # size of input is one less than available qubits input_size = num_qubits - 1 if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts if verbose: print(f"For secret int {secret_int} measured: {probs}") # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{input_size}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) return probs, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=3, max_qubits=14, skip_qubits=1, max_circuits=3, num_shots=100, backend_id='dm_simulator', method = 1, provider_backend=None, # hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} ({method}) Benchmark Program - QSim") # validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # create context identifier if context is None: context = f"{benchmark_name} ({method}) Benchmark" ########## # Variable for new qubit group ordering if using mid_circuit measurements mid_circuit_qubit_group = [] # If using mid_circuit measurements, set transform qubit group to true transform_qubit_group = True if method ==2 else False # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options, context=context) # for noiseless simulation, set noise model to be None # ex.set_noise_model(None) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): input_size = num_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2**(input_size), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(input_size) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(input_size), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # If mid circuit, then add 2 to new qubit group since the circuit only uses 2 qubits if method == 2: mid_circuit_qubit_group.append(2) # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = BersteinVazirani(num_qubits, s_int, method).reverse_bits() # reverse_bits() is to change the endianness print(qc) metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, s_int, shots=num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim", transform_qubit_group = transform_qubit_group, new_qubit_group = mid_circuit_qubit_group) # if main, execute method if __name__ == '__main__': run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Deutsch-Jozsa Benchmark Program - QSim """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = [ "_common", "_common/qsim" ] sys.path[1:1] = [ "../../_common", "../../_common/qsim" ] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "Deutsch-Jozsa" np.random.seed(0) verbose = False # saved circuits for display QC_ = None C_ORACLE_ = None B_ORACLE_ = None ############### Circuit Definition # Create a constant oracle, appending gates to given circuit def constant_oracle (input_size, num_qubits): #Initialize first n qubits and single ancilla qubit qc = QuantumCircuit(num_qubits, name=f"Uf") output = np.random.randint(2) if output == 1: qc.x(input_size) global C_ORACLE_ if C_ORACLE_ == None or num_qubits <= 6: if num_qubits < 9: C_ORACLE_ = qc return qc # Create a balanced oracle. # Perform CNOTs with each input qubit as a control and the output bit as the target. # Vary the input states that give 0 or 1 by wrapping some of the controls in X-gates. def balanced_oracle (input_size, num_qubits): #Initialize first n qubits and single ancilla qubit qc = QuantumCircuit(num_qubits, name=f"Uf") b_str = "10101010101010101010" # permit input_string up to 20 chars for qubit in range(input_size): if b_str[qubit] == '1': qc.x(qubit) qc.barrier() for qubit in range(input_size): qc.cx(qubit, input_size) qc.barrier() for qubit in range(input_size): if b_str[qubit] == '1': qc.x(qubit) global B_ORACLE_ if B_ORACLE_ == None or num_qubits <= 6: if num_qubits < 9: B_ORACLE_ = qc return qc # Create benchmark circuit def DeutschJozsa (num_qubits, type): # Size of input is one less than available qubits input_size = num_qubits - 1 # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name=f"dj-{num_qubits}-{type}") for qubit in range(input_size): qc.h(qubit) qc.x(input_size) qc.h(input_size) qc.barrier() # Add a constant or balanced oracle function if type == 0: Uf = constant_oracle(input_size, num_qubits) else: Uf = balanced_oracle(input_size, num_qubits) qc.append(Uf, qr) qc.barrier() for qubit in range(num_qubits): qc.h(qubit) # uncompute ancilla qubit, not necessary for algorithm qc.x(input_size) qc.barrier() for i in range(input_size): qc.measure(i, i) # to get the partial_probability # save smaller circuit and oracle subcircuit example for display global QC_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc # return a handle to the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the type, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, type, num_shots): # Size of input is one less than available qubits input_size = num_qubits - 1 if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts if verbose: print(f"For type {type} measured: {probs}") # create the key that is expected to have all the measurements (for this circuit) if type == 0: key = '0'*input_size else: key = '1'*input_size # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) return probs, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=3, max_qubits=8, skip_qubits=1, max_circuits=3, num_shots=100, backend_id='dm_simulator', provider_backend=None, #hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # create context identifier if context is None: context = f"{benchmark_name} Benchmark" ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) probs, fidelity = analyze_and_print_result(qc, result, num_qubits, int(type), num_shots) metrics.store_metric(num_qubits, type, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, #hub=hub, group=group, project=project, exec_options=exec_options, context=context) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): input_size = num_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2, max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # loop over only 2 circuits for type in range( num_circuits ): # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = DeutschJozsa(num_qubits, type).reverse_bits() # reverse_bits() is applying to handle the change in endianness metrics.store_metric(num_qubits, type, 'create_time', time.time()-ts) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, type, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nConstant Oracle 'Uf' ="); print(C_ORACLE_ if C_ORACLE_ != None else " ... too large or not used!") print("\nBalanced Oracle 'Uf' ="); print(B_ORACLE_ if B_ORACLE_ != None else " ... too large or not used!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks) run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Deutsch-Jozsa Benchmark Program - QSim """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = [ "_common", "_common/qsim" ] sys.path[1:1] = [ "../../_common", "../../_common/qsim" ] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "Deutsch-Jozsa" np.random.seed(0) verbose = False # saved circuits for display QC_ = None C_ORACLE_ = None B_ORACLE_ = None ############### Circuit Definition # Create a constant oracle, appending gates to given circuit def constant_oracle (input_size, num_qubits): #Initialize first n qubits and single ancilla qubit qc = QuantumCircuit(num_qubits, name=f"Uf") output = np.random.randint(2) if output == 1: qc.x(input_size) global C_ORACLE_ if C_ORACLE_ == None or num_qubits <= 6: if num_qubits < 9: C_ORACLE_ = qc return qc # Create a balanced oracle. # Perform CNOTs with each input qubit as a control and the output bit as the target. # Vary the input states that give 0 or 1 by wrapping some of the controls in X-gates. def balanced_oracle (input_size, num_qubits): #Initialize first n qubits and single ancilla qubit qc = QuantumCircuit(num_qubits, name=f"Uf") b_str = "10101010101010101010" # permit input_string up to 20 chars for qubit in range(input_size): if b_str[qubit] == '1': qc.x(qubit) qc.barrier() for qubit in range(input_size): qc.cx(qubit, input_size) qc.barrier() for qubit in range(input_size): if b_str[qubit] == '1': qc.x(qubit) global B_ORACLE_ if B_ORACLE_ == None or num_qubits <= 6: if num_qubits < 9: B_ORACLE_ = qc return qc # Create benchmark circuit def DeutschJozsa (num_qubits, type): # Size of input is one less than available qubits input_size = num_qubits - 1 # allocate qubits qr = QuantumRegister(num_qubits) cr = ClassicalRegister(input_size) qc = QuantumCircuit(qr, cr, name=f"dj-{num_qubits}-{type}") for qubit in range(input_size): qc.h(qubit) qc.x(input_size) qc.h(input_size) qc.barrier() # Add a constant or balanced oracle function if type == 0: Uf = constant_oracle(input_size, num_qubits) else: Uf = balanced_oracle(input_size, num_qubits) qc.append(Uf, qr) qc.barrier() for qubit in range(num_qubits): qc.h(qubit) # uncompute ancilla qubit, not necessary for algorithm qc.x(input_size) qc.barrier() for i in range(input_size): qc.measure(i, i) # save smaller circuit and oracle subcircuit example for display global QC_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc # return a handle to the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the type, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, type, num_shots): # Size of input is one less than available qubits input_size = num_qubits - 1 if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts if verbose: print(f"For type {type} measured: {probs}") # create the key that is expected to have all the measurements (for this circuit) if type == 0: key = '0'*input_size else: key = '1'*input_size # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) return probs, fidelity def run(min_qubits=3, max_qubits=8, skip_qubits=1, max_circuits=3, num_shots=1000, backend_id='dm_simulator', provider_backend=None, exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # Validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # Create context identifier if context is None: context = f"{benchmark_name} Benchmark" # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(type), num_shots) metrics.store_metric(num_qubits, type, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, exec_options=exec_options, context=context) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): input_size = num_qubits - 1 # Determine number of circuits to execute for this group num_circuits = min(2, max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # Loop over only 2 circuits for type in range(num_circuits): # Create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = DeutschJozsa(num_qubits, type).reverse_bits() # reverse_bits() is applying to handle the change in endianness print(f"DJ Circuit for qubit size of {num_qubits} and type {type} : \n{qc} ") metrics.store_metric(num_qubits, type, 'create_time', time.time() - ts) # Collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # Submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, type, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # Print a sample circuit # print("Sample Circuit:"); print(QC_ if QC_ is not None else " ... too large!") print("\nConstant Oracle 'Uf' ="); print(C_ORACLE_ if C_ORACLE_ is not None else " ... too large or not used!") print("\nBalanced Oracle 'Uf' ="); print(B_ORACLE_ if B_ORACLE_ is not None else " ... too large or not used!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Deutsch-Jozsa Benchmark Program - QSim """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = [ "_common", "_common/qsim" ] sys.path[1:1] = [ "../../_common", "../../_common/qsim" ] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "Deutsch-Jozsa" np.random.seed(0) verbose = False # saved circuits for display QC_ = None C_ORACLE_ = None B_ORACLE_ = None ############### Circuit Definition # Create a constant oracle, appending gates to given circuit def constant_oracle (input_size, num_qubits): #Initialize first n qubits and single ancilla qubit qc = QuantumCircuit(num_qubits, name=f"Uf") output = np.random.randint(2) if output == 1: qc.x(input_size) global C_ORACLE_ if C_ORACLE_ == None or num_qubits <= 21: if num_qubits < 21: C_ORACLE_ = qc return qc # Create a balanced oracle. # Perform CNOTs with each input qubit as a control and the output bit as the target. # Vary the input states that give 0 or 1 by wrapping some of the controls in X-gates. def balanced_oracle (input_size, num_qubits): #Initialize first n qubits and single ancilla qubit qc = QuantumCircuit(num_qubits, name=f"Uf") b_str = "10101010101010101010" # permit input_string up to 20 chars for qubit in range(input_size): if b_str[qubit] == '1': qc.x(qubit) qc.barrier() for qubit in range(input_size): qc.cx(qubit, input_size) qc.barrier() for qubit in range(input_size): if b_str[qubit] == '1': qc.x(qubit) global B_ORACLE_ if B_ORACLE_ == None or num_qubits <= 21: if num_qubits < 21: B_ORACLE_ = qc return qc # Create benchmark circuit def DeutschJozsa (num_qubits, type): # Size of input is one less than available qubits input_size = num_qubits - 1 # allocate qubits qr = QuantumRegister(num_qubits) cr = ClassicalRegister(input_size) qc = QuantumCircuit(qr, cr, name=f"dj-{num_qubits}-{type}") for qubit in range(input_size): qc.h(qubit) qc.x(input_size) qc.h(input_size) qc.barrier() # Add a constant or balanced oracle function if type == 0: Uf = constant_oracle(input_size, num_qubits) else: Uf = balanced_oracle(input_size, num_qubits) qc.append(Uf, qr) qc.barrier() for qubit in range(num_qubits): qc.h(qubit) # uncompute ancilla qubit, not necessary for algorithm qc.x(input_size) qc.barrier() for i in range(input_size): qc.measure(i, i) # save smaller circuit and oracle subcircuit example for display global QC_ if QC_ == None or num_qubits <= 21: if num_qubits < 21: QC_ = qc # return a handle to the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the type, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, type, num_shots): # Size of input is one less than available qubits input_size = num_qubits - 1 if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts if verbose: print(f"For type {type} measured: {probs}") # create the key that is expected to have all the measurements (for this circuit) if type == 0: key = '0'*input_size else: key = '1'*input_size # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) return probs, fidelity def run(min_qubits=3, max_qubits=14, skip_qubits=1, max_circuits=3, num_shots=1000, backend_id='dm_simulator', provider_backend=None, exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # Validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # Create context identifier if context is None: context = f"{benchmark_name} Benchmark" # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) print("num_qubits ===== ", num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(type), num_shots) metrics.store_metric(num_qubits, type, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, exec_options=exec_options, context=context) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): input_size = num_qubits - 1 # Determine number of circuits to execute for this group num_circuits = min(2, max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # Loop over only 2 circuits for type in range(num_circuits): # Create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = DeutschJozsa(num_qubits, type).reverse_bits() # reverse_bits() is applying to handle the change in endianness print(f"DJ Circuit for qubit size of {num_qubits} and type {type} : \n{qc} ") metrics.store_metric(num_qubits, type, 'create_time', time.time() - ts) # Collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # Submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, type, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # Print a sample circuit # print("Sample Circuit:"); print(QC_ if QC_ is not None else " ... too large!") print("\nConstant Oracle 'Uf' ="); print(C_ORACLE_ if C_ORACLE_ is not None else " ... too large or not used!") print("\nBalanced Oracle 'Uf' ="); print(B_ORACLE_ if B_ORACLE_ is not None else " ... too large or not used!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
import numpy as np def grovers_dist(num_qubits, marked_item, n_iterations): dist = {} for i in range(2**num_qubits): key = bin(i)[2:].zfill(num_qubits) theta = np.arcsin(1/np.sqrt(2 ** num_qubits)) if i == marked_item: dist[key] = np.sin((2*n_iterations+1)*theta)**2 else: dist[key] = (np.cos((2*n_iterations+1)*theta)/(np.sqrt(2 ** num_qubits - 1)))**2 return dist num_qubits = 4 marked_item = 6 n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4) grovers_dist(num_qubits, marked_item, n_iterations)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Grover's Search Benchmark Program - QSim """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = ["_common", "_common/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim"] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "Grover's Search" np.random.seed(0) verbose = False # saved circuits for display QC_ = None grover_oracle = None diffusion_operator = None # for validating the implementation of an mcx shim _use_mcx_shim = False ############### Circuit Definition def GroversSearch(num_qubits, marked_item, n_iterations): # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name=f"grovers-{num_qubits}-{marked_item}") # Start with Hadamard on all qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) # loop over the estimated number of iterations for _ in range(n_iterations): qc.barrier() # add the grover oracle qc.append(add_grover_oracle(num_qubits, marked_item).to_instruction(), qr) # add the diffusion operator qc.append(add_diffusion_operator(num_qubits).to_instruction(), qr) qc.barrier() # measure all qubits qc.measure(qr, cr) # to get the partial_probability # qc.measure(qr, cr, basis='Ensemble', add_param='Z') # to get the ensemble_probability # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc ############## Grover Oracle def add_grover_oracle(num_qubits, marked_item): global grover_oracle marked_item_bits = format(marked_item, f"0{num_qubits}b")[::-1] qr = QuantumRegister(num_qubits); qc = QuantumCircuit(qr, name="oracle") for (q, bit) in enumerate(marked_item_bits): if not int(bit): qc.x(q) qc.h(num_qubits - 1) if _use_mcx_shim: add_mcx(qc, [x for x in range(num_qubits - 1)], num_qubits - 1) else: qc.mcx([x for x in range(num_qubits - 1)], num_qubits - 1) qc.h(num_qubits - 1) qc.barrier() for (q, bit) in enumerate(marked_item_bits): if not int(bit): qc.x(q) if grover_oracle == None or num_qubits <= 5: if num_qubits < 9: grover_oracle = qc return qc ############## Grover Diffusion Operator def add_diffusion_operator(num_qubits): global diffusion_operator qr = QuantumRegister(num_qubits); qc = QuantumCircuit(qr, name="diffuser") for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) for i_qubit in range(num_qubits): qc.x(qr[i_qubit]) qc.h(num_qubits - 1) if _use_mcx_shim: add_mcx(qc, [x for x in range(num_qubits - 1)], num_qubits - 1) else: qc.mcx([x for x in range(num_qubits - 1)], num_qubits - 1) qc.h(num_qubits - 1) qc.barrier() for i_qubit in range(num_qubits): qc.x(qr[i_qubit]) for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) if diffusion_operator == None or num_qubits <= 5: if num_qubits < 9: diffusion_operator = qc return qc ############### MCX shim # single cx / cu1 unit for mcx implementation def add_cx_unit(qc, cxcu1_unit, controls, target): num_controls = len(controls) i_qubit = cxcu1_unit[1] j_qubit = cxcu1_unit[0] theta = cxcu1_unit[2] if j_qubit != None: qc.cx(controls[j_qubit], controls[i_qubit]) qc.cu1(theta, controls[i_qubit], target) i_qubit = i_qubit - 1 if j_qubit == None: j_qubit = i_qubit + 1 else: j_qubit = j_qubit - 1 if theta < 0: theta = -theta new_units = [] if i_qubit >= 0: new_units += [ [ j_qubit, i_qubit, -theta ] ] new_units += [ [ num_controls - 1, i_qubit, theta ] ] return new_units # mcx recursion loop def add_cxcu1_units(qc, cxcu1_units, controls, target): new_units = [] for cxcu1_unit in cxcu1_units: new_units += add_cx_unit(qc, cxcu1_unit, controls, target) cxcu1_units.clear() return new_units # mcx gate implementation: brute force and inefficent # start with a single CU1 on last control and target # and recursively expand for each additional control def add_mcx(qc, controls, target): num_controls = len(controls) theta = np.pi / 2**num_controls qc.h(target) cxcu1_units = [ [ None, num_controls - 1, theta] ] while len(cxcu1_units) > 0: cxcu1_units += add_cxcu1_units(qc, cxcu1_units, controls, target) qc.h(target) ################ Analysis # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, marked_item, num_shots): if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts # # setting the threhold value to avoid getting exponential values which leads to nan values # threshold = 3e-3 # probs = {key: value if value > threshold else 0.0 for key, value in probs.items()} if verbose: print(f"For type {marked_item} measured: {probs}") # we compare counts to analytical correct distribution correct_dist = grovers_dist(num_qubits, marked_item) if verbose: print(f"Marked item: {marked_item}, Correct dist: {correct_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) return probs, fidelity def grovers_dist(num_qubits, marked_item): n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4) dist = {} for i in range(2**num_qubits): key = bin(i)[2:].zfill(num_qubits)[::-1] theta = np.arcsin(1/np.sqrt(2 ** num_qubits)) if i == int(marked_item): dist[key] = np.sin((2*n_iterations+1)*theta)**2 else: dist[key] = (np.cos((2*n_iterations+1)*theta)/(np.sqrt(2 ** num_qubits - 1)))**2 return dist ################ Benchmark Loop # Because this circuit size grows significantly with num_qubits (due to the mcx gate) # limit the max_qubits here ... MAX_QUBITS=8 # Execute program with default parameters def run(min_qubits=2, max_qubits=6, skip_qubits=1, max_circuits=3, num_shots=100, use_mcx_shim=False, backend_id='dm_simulator', provider_backend=None, # hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # Clamp the maximum number of qubits if max_qubits > MAX_QUBITS: print(f"INFO: {benchmark_name} benchmark is limited to a maximum of {MAX_QUBITS} qubits.") max_qubits = MAX_QUBITS # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # create context identifier if context is None: context = f"{benchmark_name} Benchmark" # set the flag to use an mcx shim if given global _use_mcx_shim _use_mcx_shim = use_mcx_shim if _use_mcx_shim: print("... using MCX shim") ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) probs, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options, context=context) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): # determine number of circuits to execute for this group num_circuits = min(2 ** (num_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4) qc = GroversSearch(num_qubits, s_int, n_iterations) metrics.store_metric(num_qubits, s_int, 'create_time', time.time() - ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, s_int, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit created (if not too large) print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nOracle ="); print(grover_oracle if grover_oracle!= None else " ... too large!") print("\nDiffuser ="); print(diffusion_operator ) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks) run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Grover's Search Benchmark Program - QSim """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = ["_common", "_common/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim"] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "Grover's Search" np.random.seed(0) verbose = False # saved circuits for display QC_ = None grover_oracle = None diffusion_operator = None # for validating the implementation of an mcx shim _use_mcx_shim = False ############### Circuit Definition def GroversSearch(num_qubits, marked_item, n_iterations): # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name=f"grovers-{num_qubits}-{marked_item}") # Start with Hadamard on all qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) # loop over the estimated number of iterations for _ in range(n_iterations): qc.barrier() # add the grover oracle qc.append(add_grover_oracle(num_qubits, marked_item).to_instruction(), qr) # add the diffusion operator qc.append(add_diffusion_operator(num_qubits).to_instruction(), qr) qc.barrier() # measure all qubits qc.measure(qr, cr) # to get the partial_probability # qc.measure(qr, cr, basis='Ensemble', add_param='Z') # to get the ensemble_probability # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc ############## Grover Oracle def add_grover_oracle(num_qubits, marked_item): global grover_oracle marked_item_bits = format(marked_item, f"0{num_qubits}b")[::-1] qr = QuantumRegister(num_qubits); qc = QuantumCircuit(qr, name="oracle") for (q, bit) in enumerate(marked_item_bits): if not int(bit): qc.x(q) qc.h(num_qubits - 1) if _use_mcx_shim: add_mcx(qc, [x for x in range(num_qubits - 1)], num_qubits - 1) else: qc.mcx([x for x in range(num_qubits - 1)], num_qubits - 1) qc.h(num_qubits - 1) qc.barrier() for (q, bit) in enumerate(marked_item_bits): if not int(bit): qc.x(q) if grover_oracle == None or num_qubits <= 5: if num_qubits < 9: grover_oracle = qc return qc ############## Grover Diffusion Operator def add_diffusion_operator(num_qubits): global diffusion_operator qr = QuantumRegister(num_qubits); qc = QuantumCircuit(qr, name="diffuser") for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) for i_qubit in range(num_qubits): qc.x(qr[i_qubit]) qc.h(num_qubits - 1) if _use_mcx_shim: add_mcx(qc, [x for x in range(num_qubits - 1)], num_qubits - 1) else: qc.mcx([x for x in range(num_qubits - 1)], num_qubits - 1) qc.h(num_qubits - 1) qc.barrier() for i_qubit in range(num_qubits): qc.x(qr[i_qubit]) for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) if diffusion_operator == None or num_qubits <= 5: if num_qubits < 9: diffusion_operator = qc return qc ############### MCX shim # single cx / cu1 unit for mcx implementation def add_cx_unit(qc, cxcu1_unit, controls, target): num_controls = len(controls) i_qubit = cxcu1_unit[1] j_qubit = cxcu1_unit[0] theta = cxcu1_unit[2] if j_qubit != None: qc.cx(controls[j_qubit], controls[i_qubit]) qc.cu1(theta, controls[i_qubit], target) i_qubit = i_qubit - 1 if j_qubit == None: j_qubit = i_qubit + 1 else: j_qubit = j_qubit - 1 if theta < 0: theta = -theta new_units = [] if i_qubit >= 0: new_units += [ [ j_qubit, i_qubit, -theta ] ] new_units += [ [ num_controls - 1, i_qubit, theta ] ] return new_units # mcx recursion loop def add_cxcu1_units(qc, cxcu1_units, controls, target): new_units = [] for cxcu1_unit in cxcu1_units: new_units += add_cx_unit(qc, cxcu1_unit, controls, target) cxcu1_units.clear() return new_units # mcx gate implementation: brute force and inefficent # start with a single CU1 on last control and target # and recursively expand for each additional control def add_mcx(qc, controls, target): num_controls = len(controls) theta = np.pi / 2**num_controls qc.h(target) cxcu1_units = [ [ None, num_controls - 1, theta] ] while len(cxcu1_units) > 0: cxcu1_units += add_cxcu1_units(qc, cxcu1_units, controls, target) qc.h(target) ################ Analysis # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, marked_item, num_shots): if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts # # setting the threhold value to avoid getting exponential values which leads to nan values # threshold = 3e-3 # probs = {key: value if value > threshold else 0.0 for key, value in probs.items()} # print(f"\nprobs ===== {probs}") if verbose: print(f"For type {marked_item} measured: {probs}") # we compare counts to analytical correct distribution correct_dist = grovers_dist(num_qubits, marked_item) # print(f"\ncorrect_dist ===== {correct_dist}") if verbose: print(f"Marked item: {marked_item}, Correct dist: {correct_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) print(f"\nfidelity ===== {fidelity}") return probs, fidelity def grovers_dist(num_qubits, marked_item): n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4) dist = {} for i in range(2**num_qubits): # key = bin(i)[2:].zfill(num_qubits) #reverse the key's bits (or) import QFT (reverse_bit()) to get the correct Probability States (in case of dm-simulator) # check the reason --- qiskit-aakash/releasenotes/notes/0.17/qft-little-endian-d232c93e044f0063.yaml key = bin(i)[2:].zfill(num_qubits)[::-1] theta = np.arcsin(1/np.sqrt(2 ** num_qubits)) if i == int(marked_item): dist[key] = np.sin((2*n_iterations+1)*theta)**2 else: dist[key] = (np.cos((2*n_iterations+1)*theta)/(np.sqrt(2 ** num_qubits - 1)))**2 return dist ################ Benchmark Loop # from qiskit.circuit.library import QFT # Because this circuit size grows significantly with num_qubits (due to the mcx gate) # limit the max_qubits here ... MAX_QUBITS=8 # Execute program with default parameters def run(min_qubits=2, max_qubits=6, skip_qubits=1, max_circuits=3, num_shots=1000, use_mcx_shim=False, backend_id='dm_simulator', provider_backend=None, #hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # Clamp the maximum number of qubits if max_qubits > MAX_QUBITS: print(f"INFO: {benchmark_name} benchmark is limited to a maximum of {MAX_QUBITS} qubits.") max_qubits = MAX_QUBITS # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # create context identifier if context is None: context = f"{benchmark_name} Benchmark" # set the flag to use an mcx shim if given global _use_mcx_shim _use_mcx_shim = use_mcx_shim if _use_mcx_shim: print("... using MCX shim") ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) probs, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, #hub=hub, group=group, project=project, exec_options=exec_options, context=context) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): # determine number of circuits to execute for this group num_circuits = min(2 ** (num_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4) qc = GroversSearch(num_qubits, s_int, n_iterations) # qc = GroversSearch(num_qubits, s_int, n_iterations).reverse_bits() print(qc) metrics.store_metric(num_qubits, s_int, 'create_time', time.time() - ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, s_int, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit created (if not too large) print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nOracle ="); print(grover_oracle if grover_oracle!= None else " ... too large!") print("\nDiffuser ="); print(diffusion_operator ) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
import numpy as np def grovers_dist(num_qubits, marked_item, n_iterations): dist = {} for i in range(2**num_qubits): key = bin(i)[2:].zfill(num_qubits) theta = np.arcsin(1/np.sqrt(2 ** num_qubits)) if i == marked_item: dist[key] = np.sin((2*n_iterations+1)*theta)**2 else: dist[key] = (np.cos((2*n_iterations+1)*theta)/(np.sqrt(2 ** num_qubits - 1)))**2 return dist num_qubits = 4 marked_item = 6 n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4) grovers_dist(num_qubits, marked_item, n_iterations)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Hamiltonian-Simulation Benchmark Program - QSim """ import json import os import sys import time import numpy as np from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister sys.path[1:1] = ["_common", "_common/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim"] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "Hamiltonian Simulation" np.random.seed(0) verbose = False # saved circuits and subcircuits for display QC_ = None XX_ = None YY_ = None ZZ_ = None XXYYZZ_ = None # for validating the implementation of XXYYZZ operation _use_XX_YY_ZZ_gates = False # import precalculated data to compare against # filename = os.path.join(os.path.dirname(__file__), os.path.pardir, "_common", "precalculated_data.json") filename = os.path.join(os.path.pardir, "_common", "precalculated_data.json") with open(filename, 'r') as file: data = file.read() precalculated_data = json.loads(data) ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z): ''' Construct a Qiskit circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :return: return a Qiskit circuit for this Hamiltonian ''' num_qubits = n_spins secret_int = f"{K}-{t}" # allocate qubits qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins); qc = QuantumCircuit(qr, cr, name=f"hamsim-{num_qubits}-{secret_int}") tau = t / K # start with initial state of 1010101... for k in range(0, n_spins, 2): qc.x(qr[k]) qc.barrier() # loop over each trotter step, adding gates to the circuit defining the hamiltonian for k in range(K): # the Pauli spin vector product [qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)] [qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)] qc.barrier() # Basic implementation of exp(i * t * (XX + YY + ZZ)) if _use_XX_YY_ZZ_gates: # XX operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # YY operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # Use an optimal XXYYZZ combined operator # See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf else: # optimized XX + YY + ZZ operator on each pair of qubits in linear chain for j in range(2): for i in range(j % 2, n_spins - 1, 2): qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) qc.barrier() # measure all the qubits used in the circuit for i_qubit in range(n_spins): qc.measure(qr[i_qubit], cr[i_qubit]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 6: if n_spins < 9: QC_ = qc return qc ############### XX, YY, ZZ Gate Implementations # Simple XX gate on q0 and q1 with angle 'tau' def xx_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate") qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) # save circuit example for display global XX_ XX_ = qc return qc # Simple YY gate on q0 and q1 with angle 'tau' def yy_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate") qc.s(qr[0]) qc.s(qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.sdg(qr[0]) qc.sdg(qr[1]) # save circuit example for display global YY_ YY_ = qc return qc # Simple ZZ gate on q0 and q1 with angle 'tau' def zz_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate") qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) # save circuit example for display global ZZ_ ZZ_ = qc return qc # Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau' def xxyyzz_opt_gate(tau): alpha = tau; beta = tau; gamma = tau qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt") qc.rz(3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(3.1416*gamma - 3.1416/2, qr[0]) qc.ry(3.1416/2 - 3.1416*alpha, qr[1]) qc.cx(qr[0], qr[1]) qc.ry(3.1416*beta - 3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(-3.1416/2, qr[0]) # save circuit example for display global XXYYZZ_ XXYYZZ_ = qc return qc ############### Result Data Analysis # Analyze and print measured results # Compute the quality of the result based on operator expectation for each state def analyze_and_print_result(qc, result, num_qubits, type, num_shots): if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts # print(f"probs ===== {probs}") if verbose: print(f"For type {type} measured: {probs}") # we have precalculated the correct distribution that a perfect quantum computer will return # it is stored in the json file we import at the top of the code correct_dist = precalculated_data[f"Qubits - {num_qubits}"] if verbose: print(f"\nCorrect dist: {correct_dist}") correct_dist_reversed = {key[::-1]: value for key, value in correct_dist.items()} # print(f"correct_dist_reversed ===== {correct_dist_reversed}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist_reversed) # print(f"fidelity ===== {fidelity}") return probs, fidelity ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=2, max_qubits=8, max_circuits=3, skip_qubits=1, num_shots=100, use_XX_YY_ZZ_gates = False, backend_id='dm_simulator', provider_backend=None, #hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # create context identifier #if context is None: context = f"{benchmark_name} ({method}) Benchmark" if context is None: context = f"{benchmark_name} Benchmark" # set the flag to use an XX YY ZZ shim if given global _use_XX_YY_ZZ_gates _use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates if _use_XX_YY_ZZ_gates: print("... using unoptimized XX YY ZZ gates") ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) probs, expectation_a = analyze_and_print_result(qc, result, num_qubits, type, num_shots) metrics.store_metric(num_qubits, type, 'fidelity', expectation_a) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options, context=context) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # determine number of circuits to execute for this group num_circuits = max(1, max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # parameters of simulation #### CANNOT BE MODIFIED W/O ALSO MODIFYING PRECALCULATED DATA ######### w = precalculated_data['w'] # strength of disorder k = precalculated_data['k'] # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. t = precalculated_data['t'] # time of simulation ####################################################################### # loop over only 1 circuit for circuit_id in range(num_circuits): #print(circuit_id) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() h_x = precalculated_data['h_x'][:num_qubits] # precalculated random numbers between [-1, 1] h_z = precalculated_data['h_z'][:num_qubits] qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z) print(qc) metrics.store_metric(num_qubits, circuit_id, 'create_time', time.time() - ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, circuit_id, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if _use_XX_YY_ZZ_gates: print("\nXX, YY, ZZ =") print(XX_); print(YY_); print(ZZ_) else: print("\nXXYYZZ_opt =") print(XXYYZZ_) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Hamiltonian-Simulation Benchmark Program - QSim """ import json import os import sys import time import numpy as np from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister sys.path[1:1] = ["_common", "_common/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim"] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "Hamiltonian Simulation" np.random.seed(0) verbose = False # saved circuits and subcircuits for display QC_ = None XX_ = None YY_ = None ZZ_ = None XXYYZZ_ = None # for validating the implementation of XXYYZZ operation _use_XX_YY_ZZ_gates = False # import precalculated data to compare against filename = os.path.join(os.path.dirname(__file__), os.path.pardir, "_common", "precalculated_data.json") # filename = os.path.join(os.path.pardir, "_common", "precalculated_data.json") with open(filename, 'r') as file: data = file.read() precalculated_data = json.loads(data) ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z): ''' Construct a Qiskit circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :return: return a Qiskit circuit for this Hamiltonian ''' num_qubits = n_spins secret_int = f"{K}-{t}" # allocate qubits qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins); qc = QuantumCircuit(qr, cr, name=f"hamsim-{num_qubits}-{secret_int}") tau = t / K # start with initial state of 1010101... for k in range(0, n_spins, 2): qc.x(qr[k]) qc.barrier() # loop over each trotter step, adding gates to the circuit defining the hamiltonian for k in range(K): # the Pauli spin vector product [qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)] [qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)] qc.barrier() # Basic implementation of exp(i * t * (XX + YY + ZZ)) if _use_XX_YY_ZZ_gates: # XX operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # YY operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # Use an optimal XXYYZZ combined operator # See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf else: # optimized XX + YY + ZZ operator on each pair of qubits in linear chain for j in range(2): for i in range(j % 2, n_spins - 1, 2): qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) qc.barrier() # measure all the qubits used in the circuit for i_qubit in range(n_spins): qc.measure(qr[i_qubit], cr[i_qubit]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 6: if n_spins < 9: QC_ = qc return qc ############### XX, YY, ZZ Gate Implementations # Simple XX gate on q0 and q1 with angle 'tau' def xx_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate") qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) # save circuit example for display global XX_ XX_ = qc return qc # Simple YY gate on q0 and q1 with angle 'tau' def yy_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate") qc.s(qr[0]) qc.s(qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.sdg(qr[0]) qc.sdg(qr[1]) # save circuit example for display global YY_ YY_ = qc return qc # Simple ZZ gate on q0 and q1 with angle 'tau' def zz_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate") qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) # save circuit example for display global ZZ_ ZZ_ = qc return qc # Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau' def xxyyzz_opt_gate(tau): alpha = tau; beta = tau; gamma = tau qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt") qc.rz(3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(3.1416*gamma - 3.1416/2, qr[0]) qc.ry(3.1416/2 - 3.1416*alpha, qr[1]) qc.cx(qr[0], qr[1]) qc.ry(3.1416*beta - 3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(-3.1416/2, qr[0]) # save circuit example for display global XXYYZZ_ XXYYZZ_ = qc return qc ############### Result Data Analysis # Analyze and print measured results # Compute the quality of the result based on operator expectation for each state def analyze_and_print_result(qc, result, num_qubits, type, num_shots): if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts if verbose: print(f"For type {type} measured: {probs}") # we have precalculated the correct distribution that a perfect quantum computer will return # it is stored in the json file we import at the top of the code correct_dist = precalculated_data[f"Qubits - {num_qubits}"] if verbose: print(f"Correct dist: {correct_dist}") correct_dist_reversed = {key[::-1]: value for key, value in correct_dist.items()} # print(f"correct_dist_reversed ===== {correct_dist_reversed}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist_reversed) # print(f"fidelity ===== {fidelity}") # # use our polarization fidelity rescaling # fidelity = metrics.polarization_fidelity(counts, correct_dist) return probs, fidelity ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=2, max_qubits=6, max_circuits=3, skip_qubits=1, num_shots=100, use_XX_YY_ZZ_gates = False, backend_id='dm_simulator', provider_backend=None, #hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # create context identifier #if context is None: context = f"{benchmark_name} ({method}) Benchmark" if context is None: context = f"{benchmark_name} Benchmark" # set the flag to use an XX YY ZZ shim if given global _use_XX_YY_ZZ_gates _use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates if _use_XX_YY_ZZ_gates: print("... using unoptimized XX YY ZZ gates") ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, expectation_a = analyze_and_print_result(qc, result, num_qubits, type, num_shots) metrics.store_metric(num_qubits, type, 'fidelity', expectation_a) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options, context=context) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # determine number of circuits to execute for this group num_circuits = max(1, max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # parameters of simulation #### CANNOT BE MODIFIED W/O ALSO MODIFYING PRECALCULATED DATA ######### w = precalculated_data['w'] # strength of disorder k = precalculated_data['k'] # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. t = precalculated_data['t'] # time of simulation ####################################################################### # loop over only 1 circuit for circuit_id in range(num_circuits): #print(circuit_id) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() h_x = precalculated_data['h_x'][:num_qubits] # precalculated random numbers between [-1, 1] h_z = precalculated_data['h_z'][:num_qubits] qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z) metrics.store_metric(num_qubits, circuit_id, 'create_time', time.time() - ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, circuit_id, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if _use_XX_YY_ZZ_gates: print("\nXX, YY, ZZ =") print(XX_); print(YY_); print(ZZ_) else: print("\nXXYYZZ_opt =") print(XXYYZZ_) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks) run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Many Body Localization Benchmark Program - Qiskit """ import sys sys.path[1:1] = ["_common", "_common/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit"] from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import time import math import numpy as np np.random.seed(0) import execute as ex import metrics as metrics from collections import defaultdict verbose = False # saved circuits and subcircuits for display QC_ = None XX_ = None YY_ = None ZZ_ = None XXYYZZ_ = None ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z, method=2): ''' Construct a Qiskit circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :param method: the method used to generate hamiltonian circuit :return: return a Qiskit circuit for this Hamiltonian ''' # allocate qubits qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins); qc = QuantumCircuit(qr, cr, name="main") tau = t / K # start with initial state of 1010101... for k in range(0, n_spins, 2): qc.x(qr[k]) # loop over each trotter step, adding gates to the circuit defining the hamiltonian for k in range(K): # the Pauli spin vector product [qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)] [qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)] qc.barrier() ''' Method 1: Basic implementation of exp(i * t * (XX + YY + ZZ)) ''' if method == 1: # XX operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # YY operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) ''' Method 2: Use an optimal XXYYZZ combined operator See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf ''' if method == 2: # optimized XX + YY + ZZ operator on each pair of qubits in linear chain for j in range(2): for i in range(j % 2, n_spins, 2): qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) qc.barrier() # measure all the qubits used in the circuit for i_qubit in range(n_spins): qc.measure(qr[i_qubit], cr[i_qubit]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 6: if n_spins < 9: QC_ = qc return qc ############### XX, YY, ZZ Gate Implementations # Simple XX gate on q0 and q1 with angle 'tau' def xx_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate") qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) # save circuit example for display global XX_ XX_ = qc return qc # Simple YY gate on q0 and q1 with angle 'tau' def yy_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate") qc.s(qr[0]) qc.s(qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.sdg(qr[0]) qc.sdg(qr[1]) # save circuit example for display global YY_ YY_ = qc return qc # Simple ZZ gate on q0 and q1 with angle 'tau' def zz_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate") qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) # save circuit example for display global ZZ_ ZZ_ = qc return qc # Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau' def xxyyzz_opt_gate(tau): alpha = tau; beta = tau; gamma = tau qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt") qc.rz(3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(3.1416*gamma - 3.1416/2, qr[0]) qc.ry(3.1416/2 - 3.1416*alpha, qr[1]) qc.cx(qr[0], qr[1]) qc.ry(3.1416*beta - 3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(-3.1416/2, qr[0]) # save circuit example for display global XXYYZZ_ XXYYZZ_ = qc return qc ############### Result Data Analysis # Analyze and print measured results # Compute the quality of the result based on operator expectation for each state def analyze_and_print_result(qc, result, num_qubits, type, num_shots): counts = result.get_counts(qc) if verbose: print(f"For type {type} measured: {counts}") ################### IMBALANCE CALCULATION ONE ####################### expectation_a = 0 for key in counts.keys(): # compute the operator expectation for this state lambda_a = sum([((-1) ** i) * ((-1) ** int(bit)) for i, bit in enumerate(key)])/num_qubits prob = counts[key] / num_shots # probability of this state expectation_a += lambda_a * prob ##################################################################### ################### IMBALANCE CALCULATION TWO ####################### # this is the imbalance calculation explicitely defined in Sonika's notes prob_one = {} for i in range(num_qubits): prob_one[i] = 0 for key in counts.keys(): for i in range(num_qubits): if key[::-1][i] == '1': prob_one[i] += counts[key] / num_shots I_numer = 0 I_denom = 0 for i in prob_one.keys(): I_numer += (-1)**i * prob_one[i] I_denom += prob_one[i] I = I_numer/I_denom ##################################################################### if verbose: print(f"\tMeasured Imbalance: {I}, measured expectation_a: {expectation_a}") # rescaled fideltiy fidelity = I/0.4 # rescaled expectation_a expectation_a = expectation_a/0.4 # We expect expecation_a to give 1. We would like to plot the deviation from the true expectation. return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=2, max_qubits=8, max_circuits=300, num_shots=100, method=2, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main"): print("Many Body Localization Benchmark Program - Qiskit") print(f"... using circuit method {method}") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, expectation_a = analyze_and_print_result(qc, result, num_qubits, type, num_shots) metrics.store_metric(num_qubits, type, 'fidelity', expectation_a) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project) ex.set_noise_model() # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for input_size in range(min_qubits, max_qubits + 1, 2): # determine number of circuits to execute for this group num_circuits = max_circuits num_qubits = input_size print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # parameters of simulation w = 20 # strength of disorder k = 100 # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. t = 1.2 # time of simulation for circuit_id in range(num_circuits): # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() h_x = 2 * np.random.random(num_qubits) - 1 # random numbers between [-1, 1] h_z = 2 * np.random.random(num_qubits) - 1 qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z, method=method) metrics.store_metric(num_qubits, circuit_id, 'create_time', time.time() - ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, circuit_id, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if method == 1: print("\n********\nXX, YY, ZZ =") print(XX_); print(YY_); print(ZZ_) else: print("\n********\nXXYYZZ =") print(XXYYZZ_) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Hamiltonian Simulation ({method}) - Qiskit") # if main, execute method if __name__ == '__main__': run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Hamiltonian-Simulation (Transverse Field Ising Model) Benchmark Program - Qiskit """ import sys sys.path[1:1] = ["_common", "_common/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit"] from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import time import math import numpy as np np.random.seed(0) import execute as ex import metrics as metrics from collections import defaultdict verbose = False # saved circuits and subcircuits for display QC_ = None ZZ_ = None ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, method): ''' Construct a Qiskit circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :param method: whether the circuit simulates the TFIM in paramagnetic or ferromagnetic phase :return: return a Qiskit circuit for this Hamiltonian ''' # strength of transverse field if method == 1: g = 20.0 # g >> 1 -> paramagnetic phase else: g = 0.1 # g << 1 -> ferromagnetic phase # allocate qubits qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins); qc = QuantumCircuit(qr, cr, name="main") # define timestep based on total runtime and number of Trotter steps tau = t / K # initialize state to approximate eigenstate when deep into phases of TFIM if abs(g) > 1: # paramagnetic phase # start with initial state of |++...> (eigenstate in x-basis) for k in range(n_spins): qc.h(qr[k]) if abs(g) < 1: # ferromagnetic phase # state with initial state of GHZ state: 1/sqrt(2) ( |00...> + |11...> ) qc.h(qr[0]) for k in range(1, n_spins): qc.cnot(qr[k-1], qr[k]) qc.barrier() # loop over each trotter step, adding gates to the circuit defining the Hamiltonian for k in range(K): # the Pauli spin vector product for i in range(n_spins): qc.rx(2 * tau * g, qr[i]) qc.barrier() # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins, 2): qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) qc.barrier() # transform state back to computational basis |00000> if abs(g) > 1: # paramagnetic phase # reverse transformation from |++...> (eigenstate in x-basis) for k in range(n_spins): qc.h(qr[k]) if abs(g) < 1: # ferromagnetic phase # reversed tranformation from GHZ state for k in reversed(range(1, n_spins)): qc.cnot(qr[k-1], qr[k]) qc.h(qr[0]) qc.barrier() # measure all the qubits used in the circuit for i_qubit in range(n_spins): qc.measure(qr[i_qubit], cr[i_qubit]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 4: if n_spins < 9: QC_ = qc return qc ############### exp(ZZ) Gate Implementations # Simple exp(ZZ) gate on q0 and q1 with angle 'tau' def zz_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate") qc.cx(qr[0], qr[1]) qc.rz(np.pi*tau, qr[1]) qc.cx(qr[0], qr[1]) # save circuit example for display global ZZ_ ZZ_ = qc return qc ############### Result Data Analysis # Analyze and print measured results # Compute the quality of the result based on operator expectation for each state def analyze_and_print_result(qc, result, num_qubits, type, num_shots): counts = result.get_counts(qc) if verbose: print(f"For type {type} measured: {counts}") correct_state = '0'*num_qubits fidelity = 0 if correct_state in counts.keys(): fidelity = counts[correct_state] / num_shots return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=2, max_qubits=8, max_circuits=3, num_shots=100, method=1, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main"): print("Hamiltonian-Simulation (Transverse Field Ising Model) Benchmark Program - Qiskit") print(f"... using circuit method {method}") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, expectation_a = analyze_and_print_result(qc, result, num_qubits, type, num_shots) metrics.store_metric(num_qubits, type, 'fidelity', expectation_a) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for input_size in range(min_qubits, max_qubits + 1, 2): # determine number of circuits to execute for this group num_circuits = max_circuits num_qubits = input_size print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # parameters of simulation t = 1 # time of simulation, 1 is chosen so that the dynamics are not completely trivial k = int(5*num_qubits*t) # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. for circuit_id in range(num_circuits): # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() h_x = 2 * np.random.random(num_qubits) - 1 # random numbers between [-1, 1] h_z = 2 * np.random.random(num_qubits) - 1 qc = HamiltonianSimulation(num_qubits, K=k, t=t, method=method) metrics.store_metric(num_qubits, circuit_id, 'create_time', time.time() - ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, circuit_id, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\n********\nZZ ="); print(ZZ_) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Hamiltonian Simulation ({method}) - Qiskit") # if main, execute method if __name__ == '__main__': run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
import sys sys.path[1:1] = ["_common", "_common/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit"] from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import time import math import os import numpy as np np.random.seed(0) import execute as ex import metrics as metrics from collections import defaultdict from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule from qiskit_nature.circuit.library import HartreeFock as HF from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.transformers import ActiveSpaceTransformer from qiskit_nature.operators.second_quantization import FermionicOp from qiskit.opflow import PauliTrotterEvolution, CircuitStateFn, Suzuki from qiskit.opflow.primitive_ops import PauliSumOp # Function that converts a list of single and double excitation operators to Pauli operators def readPauliExcitation(norb, circuit_id=0): # load pre-computed data filename = os.path.join(os.getcwd(), f'../qiskit/ansatzes/{norb}_qubit_{circuit_id}.txt') with open(filename) as f: data = f.read() ansatz_dict = json.loads(data) # initialize Pauli list pauli_list = [] # current coefficients cur_coeff = 1e5 # current Pauli list cur_list = [] # loop over excitations for ext in ansatz_dict: if cur_coeff > 1e4: cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4: pauli_list.append(PauliSumOp.from_list(cur_list)) cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] else: cur_list.append((ext, ansatz_dict[ext])) # add the last term pauli_list.append(PauliSumOp.from_list(cur_list)) # return Pauli list return pauli_list # Get the Hamiltonian by reading in pre-computed file def ReadHamiltonian(nqubit): # load pre-computed data filename = os.path.join(os.getcwd(), f'../qiskit/Hamiltonians/{nqubit}_qubit.txt') with open(filename) as f: data = f.read() ham_dict = json.loads(data) # pauli list pauli_list = [] for p in ham_dict: pauli_list.append( (p, ham_dict[p]) ) # build Hamiltonian ham = PauliSumOp.from_list(pauli_list) # return Hamiltonian return ham def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1): ''' Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz :param n_spin_orbs:The number of spin orbitals :return: return a Qiskit circuit for this VQE ansatz ''' # allocate qubits num_qubits = n_spin_orbs qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name="main") # number of alpha spin orbitals norb_a = int(n_spin_orbs / 2) # number of beta spin orbitals norb_b = norb_a # construct the Hamiltonian qubit_op = ReadHamiltonian(n_spin_orbs) # initialize the HF state qc = HartreeFock(n_spin_orbs, na, nb) # form the list of single and double excitations singles = [] doubles = [] for occ_a in range(na): for vir_a in range(na, norb_a): singles.append((occ_a, vir_a)) for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): singles.append((occ_b, vir_b)) for occ_a in range(na): for vir_a in range(na, norb_a): for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): doubles.append((occ_a, vir_a, occ_b, vir_b)) # get cluster operators in Paulis pauli_list = readPauliExcitation(n_spin_orbs, circuit_id) # loop over the Pauli operators for index, PauliOp in enumerate(pauli_list): # get circuit for exp(-iP) cluster_qc = ClusterOperatorCircuit(PauliOp) # add to ansatz qc.compose(cluster_qc, inplace=True) # method 2, only compute the last term in the Hamiltonian if method == 2: # last term in Hamiltonian qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits) # return the circuit return qc_with_mea # now we need to add the measurement parts to the circuit # circuit list qc_list = [] diag = [] off_diag = [] for p in qubit_op: # get the circuit with expectation measurements qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits) # add to circuit list qc_list.append(qc_with_mea) # diagonal term if is_diag: diag.append(p) # off-diagonal term else: off_diag.append(p) return qc_list def ClusterOperatorCircuit(pauli_op): # compute exp(-iP) exp_ip = pauli_op.exp_i() # Trotter approximation qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip) # convert to circuit qc = qc_op.to_circuit() # return this circuit return qc # Function that adds expectation measurements to the raw circuits def ExpectationCircuit(qc, pauli, nqubit, method=1): # a flag that tells whether we need to perform rotation need_rotate = False # copy the unrotated circuit raw_qc = qc.copy() # whether this term is diagonal is_diag = True # primitive Pauli string PauliString = pauli.primitive.to_list()[0][0] # coefficient coeff = pauli.coeffs[0] # basis rotation for i, p in enumerate(PauliString): target_qubit = nqubit - i - 1 if (p == "X"): need_rotate = True is_diag = False raw_qc.h(target_qubit) elif (p == "Y"): raw_qc.sdg(target_qubit) raw_qc.h(target_qubit) need_rotate = True is_diag = False # perform measurements raw_qc.measure_all() # name of this circuit raw_qc.name = PauliString + " " + str(np.real(coeff)) return raw_qc, is_diag # Function that implements the Hartree-Fock state def HartreeFock(norb, na, nb): # initialize the quantum circuit qc = QuantumCircuit(norb) # alpha electrons for ia in range(na): qc.x(ia) # beta electrons for ib in range(nb): qc.x(ib+int(norb/2)) # return the circuit return qc import json from qiskit import execute, Aer backend = Aer.get_backend("qasm_simulator") precalculated_data = {} def run(min_qubits=4, max_qubits=4, max_circuits=3, num_shots=4092 * 2**8, method=2): print(f"... using circuit method {method}") # validate parameters (smallest circuit is 4 qubits) max_qubits = max(4, max_qubits) min_qubits = min(max(4, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even if method == 1: max_circuits = 1 # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for input_size in range(min_qubits, max_qubits + 1, 2): # determine the number of circuits to execute fo this group num_circuits = max_circuits num_qubits = input_size # decides number of electrons na = int(num_qubits/4) nb = int(num_qubits/4) # decides number of unoccupied orbitals nvira = int(num_qubits/2) - na nvirb = int(num_qubits/2) - nb # determine the size of t1 and t2 amplitudes t1_size = na * nvira + nb * nvirb t2_size = na * nb * nvira * nvirb # random seed np.random.seed(0) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() # circuit list qc_list = [] # method 1 (default) if method == 1: # sample t1 and t2 amplitude t1 = np.random.normal(size=t1_size) t2 = np.random.normal(size=t2_size) # construct all circuits qc_list = VQEEnergy(num_qubits, na, nb, 0, method) else: # loop over circuits for circuit_id in range(num_circuits): # sample t1 and t2 amplitude t1 = np.random.normal(size=t1_size) t2 = np.random.normal(size=t2_size) # construct circuit qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method) qc_single.name = qc_single.name + " " + str(circuit_id) # add to list qc_list.append(qc_single) print(f"************\nExecuting VQE with num_qubits {num_qubits}") for qc in qc_list: # get circuit id if method == 1: circuit_id = qc.name.split()[0] else: circuit_id = qc.name.split()[2] # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) job = execute(qc, backend, shots=num_shots) # executation result result = job.result() # get measurement counts counts = result.get_counts(qc) # initialize empty dictionary dist = {} for key in counts.keys(): prob = counts[key] / num_shots dist[key] = prob # add dist values to precalculated data for use in fidelity calculation precalculated_data[f"{circuit_id}"] = dist with open(f'precalculated_data_qubit_{num_qubits}_method1.json', 'w') as f: f.write(json.dumps( precalculated_data, sort_keys=True, indent=4, separators=(',', ': ') )) run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
#pip install qiskit-ibmq-provider min_qubits=4 max_qubits=12 max_circuits=3 num_shots=1000 backend_id="dm_simulator" #hub="ibm-q"; group="open"; project="main" provider_backend = None exec_options = None # # ========================== # # *** If using IBMQ hardware, run this once to authenticate # from qiskit import IBMQ # IBMQ.save_account('MY_API_TOKEN') # from qiskit_ibm_provider import IBMProvider # IBMProvider.save_account(token='9f77e2cae821d2b8fbb8aa9555078ce6ae3a9dd373c58b42cdf3faf267e64ae96bdbc3afcf9549fee34e78fb737b35410c1707d5cc0c582be44e8b36801d6dab', overwrite=True) # # *** If you are part of an IBMQ group, set hub, group, and project name here # hub="YOUR_HUB_NAME"; group="YOUR_GROUP_NAME"; project="YOUR_PROJECT_NAME" # # *** This example shows how to specify an IBMQ backend using a known "backend_id" # exec_options = { "optimization_level":3, "use_sessions":True, "resilience_level":1} # backend_id="ibmq_belem" # # ========================== # # *** If using Azure Quantum, use this hub identifier and specify the desired backend_id # # Identify your resources with env variables AZURE_QUANTUM_RESOURCE_ID and AZURE_QUANTUM_LOCATION # hub="azure-quantum"; group="open"; project="QED-C App-Oriented Benchmarks - Qiskit Version" # backend_id="<YOUR_BACKEND_NAME_HERE>" # # ========================== # The remaining examples create a provider instance and get a backend from it # # An example using IonQ provider # from qiskit_ionq import IonQProvider # provider = IonQProvider() # Be sure to set the QISKIT_IONQ_API_TOKEN environment variable # provider_backend = provider.get_backend("ionq_qpu") # backend_id="ionq_qpu" # # An example using BlueQubit provider # import sys # sys.path.insert(1, "../..") # import os, bluequbit, _common.executors.bluequbit_executor as bluequbit_executor # provider_backend = bluequbit.init() # backend_id="BlueQubit-CPU" # exec_options = { "executor": bluequbit_executor.run, "device":'cpu' } # # *** Here's an example of using a typical custom provider backend (e.g. AQT simulator) # import os # from qiskit_aqt_provider import AQTProvider # provider = AQTProvider(os.environ.get('AQT_ACCESS_KEY')) # get your key from environment # provider_backend = provider.backends.aqt_qasm_simulator_noise_1 # backend_id="aqt_qasm_simulator_noise_1" # Need this path set for imports used below import sys sys.path[1:1] = [ "../..", "../../_common" ] # Custom optimization options can be specified in this cell (below is an example) # # Example of pytket Transformer # import _common.transformers.tket_optimiser as tket_optimiser # exec_options.update({ "optimization_level": 0, "layout_method":'sabre', "routing_method":'sabre', "transformer": tket_optimiser.high_optimisation }) # # Define a custom noise model to be used during execution # import _common.custom.custom_qiskit_noise_model as custom_qiskit_noise_model # exec_options.update({ "noise_model": custom_qiskit_noise_model.my_noise_model() }) # # Example of mthree error mitigation # import _common.postprocessors.mthree.mthree_em as mthree_em # exec_options.update({ "postprocessor": mthree_em.get_mthree_handlers(backend_id, provider_backend) }) import sys sys.path.insert(1, "hhl/qsim") import hhl_benchmark hhl_benchmark.verbose=False hhl_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=1, use_best_widths=True, backend_id=backend_id, provider_backend=provider_backend, #hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "hhl/qsim") import hhl_benchmark hhl_benchmark.verbose=False # This run2 method allows you to specify an arbitrary range of input and clock qubit sizes min_input_qubits=1 max_input_qubits=3 min_clock_qubits=2 max_clock_qubits=3 hhl_benchmark.run2(min_input_qubits=min_input_qubits, max_input_qubits=max_input_qubits, min_clock_qubits=min_clock_qubits, max_clock_qubits=max_clock_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) # from qiskit.visualization import plot_histogram # # Get the counts, the frequency of each answer # counts = hhl_benchmark.saved_result.get_counts() # # Display the results # plot_histogram(counts) hhl_benchmark.QC_.draw('mpl',scale=1) #print(circuit)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" HHL Benchmark Program - QSim """ import sys import time import numpy as np pi = np.pi from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute import sparse_Ham_sim as shs import uniform_controlled_rotation as ucr from qiskit.circuit.library import QFT # include QFT in this list, so we can refer to the QFT sub-circuit definition #sys.path[1:1] = ["_common", "_common/qiskit", "quantum-fourier-transform/qiskit"] #sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../quantum-fourier-transform/qiskit"] # cannot use the QFT common yet, as HHL seems to use reverse bit order sys.path[1:1] = ["_common", "_common/qsim", "quantum-fourier-transform/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../quantum-fourier-transform/qsim"] #from qft_benchmark import qft_gate, inv_qft_gate import execute as ex import metrics as metrics # Benchmark Name benchmark_name = "HHL" np.random.seed(0) verbose = False # Variable for number of resets to perform after mid circuit measurements num_resets = 1 # saved circuits for display QC_ = None U_ = None UI_ = None QFT_ = None QFTI_ = None HP_ = None INVROT_ = None ############### Circuit Definitions ''' replaced with code below ... def qft_dagger(qc, clock, n): qc.h(clock[1]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): qc.cu1(-np.pi/float(2**(k-j)), clock[k], clock[j]); qc.h(clock[0]); def qft(qc, clock, n): qc.h(clock[0]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): qc.cu1(np.pi/float(2**(k-j)), clock[k], clock[j]); qc.h(clock[1]); ''' ''' DEVNOTE: the QFT and IQFT are defined here as they are in the QFT benchmark - almost; Here, the sign of the angles is reversed and the QFT is actually used as the inverse QFT. This is an inconsistency that needs to be resolved later. The QPE part of the algorithm should be using the inverse QFT, but the qubit order is not correct. The QFT as defined in the QFT benchmark operates on qubits in the opposite order from the HHL pattern. ''' def initialize_state(qc, qreg, b): """ b (int): initial basis state |b> """ n = qreg.size b_bin = np.binary_repr(b, width=n) if verbose: print(f"... initializing |b> to {b}, binary repr = {b_bin}") for q in range(n): if b_bin[n-1-q] == '1': qc.x(qreg[q]) return qc def IQFT(qc, qreg): """ inverse QFT qc : QuantumCircuit qreg : QuantumRegister belonging to qc does not include SWAP at end of the circuit """ n = int(qreg.size) for i in reversed(range(n)): for j in range(i+1,n): phase = -pi/2**(j-i) qc.cp(phase, qreg[i], qreg[j]) qc.h(qreg[i]) return qc def QFT(qc, qreg): """ QFT qc : QuantumCircuit qreg : QuantumRegister belonging to qc does not include SWAP at end of circuit """ n = int(qreg.size) for i in range(n): qc.h(qreg[i]) for j in reversed(range(i+1,n)): phase = pi/2**(j-i) qc.cp(phase, qreg[i], qreg[j]) return qc def inv_qft_gate(input_size, method=1): #def qft_gate(input_size): #global QFT_ qr = QuantumRegister(input_size); #qc = QuantumCircuit(qr, name="qft") qc = QuantumCircuit(qr, name="IQFT") if method == 1: # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in range(0, input_size): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in range(0, num_crzs): divisor = 2 ** (num_crzs - j) #qc.crz( math.pi / divisor , qr[hidx], qr[input_size - j - 1]) ##qc.crz( -np.pi / divisor , qr[hidx], qr[input_size - j - 1]) qc.cp(-np.pi / divisor, qr[hidx], qr[input_size - j - 1]); # followed by an H gate (applied to all qubits) qc.h(qr[hidx]) elif method == 2: # apply IQFT to register for i in range(input_size)[::-1]: for j in range(i+1,input_size): phase = -np.pi/2**(j-i) qc.cp(phase, qr[i], qr[j]) qc.h(qr[i]) qc.barrier() return qc ############### Inverse QFT Circuit def qft_gate(input_size, method=1): #def inv_qft_gate(input_size): #global QFTI_ qr = QuantumRegister(input_size); #qc = QuantumCircuit(qr, name="inv_qft") qc = QuantumCircuit(qr, name="QFT") if method == 1: # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.h(qr[hidx]) # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) #qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1]) ##qc.crz( np.pi / divisor , qr[hidx], qr[input_size - j - 1]) qc.cp( np.pi / divisor , qr[hidx], qr[input_size - j - 1]) elif method == 2: # apply QFT to register for i in range(input_size): qc.h(qr[i]) for j in range(i+1, input_size): phase = np.pi/2**(j-i) qc.cp(phase, qr[i], qr[j]) qc.barrier() return qc ############# Controlled U Gate #Construct the U gates for A def ctrl_u(exponent): qc = QuantumCircuit(1, name=f"U^{exponent}") for i in range(exponent): #qc.u(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, target); #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, control, target); qc.u(np.pi/2, -np.pi/2, np.pi/2, 0); cu_gate = qc.to_gate().control(1) return cu_gate, qc #Construct the U^-1 gates for reversing A def ctrl_ui(exponent): qc = QuantumCircuit(1, name=f"U^-{exponent}") for i in range(exponent): #qc.u(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, target); #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, control, target); qc.u(np.pi/2, np.pi/2, -np.pi/2, 0); cu_gate = qc.to_gate().control(1) return cu_gate, qc ####### DEVNOTE: The following functions (up until the make_circuit) are from the first inccarnation # of this benchmark and are not used here. Should be removed, but kept here for reference for now ############# Quantum Phase Estimation # DEVNOTE: The QPE and IQPE methods below mirror the mechanism in Hector_Wong # Need to investigate whether the clock qubits are in the correct, as this implementation # seems to require the QFT be implemented in reverse also. TODO # Append a series of Quantum Phase Estimation gates to the circuit def qpe(qc, clock, target, extra_qubits=None, ancilla=None, A=None, method=1): qc.barrier() ''' original code from Hector_Wong # e^{i*A*t} #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], target, label='U'); # The CU gate is equivalent to a CU1 on the control bit followed by a CU3 qc.u1(3*np.pi/4, clock[0]); qc.cu3(np.pi/2, -np.pi/2, np.pi/2, clock[0], target); # e^{i*A*t*2} #qc.cu(np.pi, np.pi, 0, 0, clock[1], target, label='U2'); qc.cu3(np.pi, np.pi, 0, clock[1], target); qc.barrier(); ''' # apply series of controlled U operations to the state |1> # does nothing to state |0> # DEVNOTE: have not found a way to create a controlled operation that contains a U gate # with the global phase; instead do it piecemeal for now if method == 1: repeat = 1 #for j in reversed(range(len(clock))): for j in (range(len(clock))): # create U with exponent of 1, but in a loop repeating N times for k in range(repeat): # this global phase is applied to clock qubit qc.u1(3*np.pi/4, clock[j]); # apply the rest of U controlled by clock qubit #cp, _ = ctrl_u(repeat) cp, _ = ctrl_u(1) qc.append(cp, [clock[j], target]) repeat *= 2 qc.barrier(); #Define global U operator as the phase operator (for printing later) _, U_ = ctrl_u(1) if method == 2: for j in range(len(clock)): control = clock[j] phase = -(2*np.pi)*2**j con_H_sim = shs.control_Ham_sim(A, phase) qubits = [control] + [q for q in target] + [q for q in extra_qubits] + [ancilla[0]] qc.append(con_H_sim, qubits) # Perform an inverse QFT on the register holding the eigenvalues qc.append(inv_qft_gate(len(clock), method), clock) # Append a series of Inverse Quantum Phase Estimation gates to the circuit def inv_qpe(qc, clock, target, extra_qubits=None, ancilla=None, A=None, method=1): # Perform a QFT on the register holding the eigenvalues qc.append(qft_gate(len(clock), method), clock) qc.barrier() if method == 1: ''' original code from Hector_Wong # e^{i*A*t*2} #qc.cu(np.pi, np.pi, 0, 0, clock[1], target, label='U2'); qc.cu3(np.pi, np.pi, 0, clock[1], target); # e^{i*A*t} #qc.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, clock[0], target, label='U'); # The CU gate is equivalent to a CU1 on the control bit followed by a CU3 qc.u1(-3*np.pi/4, clock[0]); qc.cu3(np.pi/2, np.pi/2, -np.pi/2, clock[0], target); qc.barrier() ''' # apply inverse series of controlled U operations to the state |1> # does nothing to state |0> # DEVNOTE: have not found a way to create a controlled operation that contains a U gate # with the global phase; instead do it piecemeal for now repeat = 2 ** (len(clock) - 1) for j in reversed(range(len(clock))): #for j in (range(len(clock))): # create U with exponent of 1, but in a loop repeating N times for k in range(repeat): # this global phase is applied to clock qubit qc.u1(-3*np.pi/4, clock[j]); # apply the rest of U controlled by clock qubit #cp, _ = ctrl_u(repeat) cp, _ = ctrl_ui(1) qc.append(cp, [clock[j], target]) repeat = int(repeat / 2) qc.barrier(); #Define global U operator as the phase operator (for printing later) _, UI_ = ctrl_ui(1) if method == 2: for j in reversed(range(len(clock))): control = clock[j] phase = (2*np.pi)*2**j con_H_sim = shs.control_Ham_sim(A, phase) qubits = [control] + [q for q in target] + [q for q in extra_qubits] + [ancilla[0]] qc.append(con_H_sim, qubits) ############### Make HHL Circuit # Make the HHL circuit def make_circuit(A, b, num_clock_qubits): """ Generate top-level circuit for HHL algo A|x>=|b> A : sparse Hermitian matrix b (int): between 0,...,2^n-1. Initial basis state |b> """ # save smaller circuit example for display global QC_, U_, UI_, QFT_, QFTI_, HP_, INVROT_ # read in number of qubits N = len(A) n = int(np.log2(N)) n_t = num_clock_qubits # number of qubits in clock register num_qubits = 2*n + n_t + 1 # lower bound on eigenvalues of A. Fixed for now C = 1/4 ''' Define sets of qubits for this algorithm ''' # create 'input' quantum and classical measurement register qr = QuantumRegister(n, name='input') qr_b = QuantumRegister(n, name='in_anc') # ancillas for Hamiltonian simulation (?) cr = ClassicalRegister(n) # create 'clock' quantum register qr_t = QuantumRegister(n_t, name='clock') # for phase estimation # create 'ancilla' quantum and classical measurement register qr_a = QuantumRegister(1, name='ancilla') # ancilla qubit cr_a = ClassicalRegister(1) # create the top-level HHL circuit, with all the registers qc = QuantumCircuit(qr, qr_b, qr_t, qr_a, cr, cr_a, name=f"hhl-{num_qubits}-{b}") ''' Initialize the input and clock qubits ''' # initialize the |b> state - the 'input' qc = initialize_state(qc, qr, b) #qc.barrier() # Hadamard the phase estimation register - the 'clock' for q in range(n_t): qc.h(qr_t[q]) qc.barrier() ''' Perform Quantum Phase Estimation on input (b), clock, and ancilla ''' # perform controlled e^(i*A*t) for q in range(n_t): control = qr_t[q] anc = qr_a[0] phase = -(2*pi)*2**q qc_u = shs.control_Ham_sim(n, A, phase) if phase <= 0: qc_u.name = "e^{" + str(q) + "iAt}" else: qc_u.name = "e^{-" + str(q) + "iAt}" if U_ == None: U_ = qc_u qc.append(qc_u, qr[0:len(qr)] + qr_b[0:len(qr_b)] + [control] + [anc]) qc.barrier() ''' Perform Inverse Quantum Fourier Transform on clock qubits ''' #qc = IQFT(qc, qr_t) qc_qfti = inv_qft_gate(n_t, method=2) qc.append(qc_qfti, qr_t) if QFTI_ == None: QFTI_ = qc_qfti qc.barrier() ''' Perform inverse rotation with ancilla ''' # reset ancilla qc.reset(qr_a[0]) # compute angles for inversion rotations alpha = [2*np.arcsin(C)] for x in range(1,2**n_t): x_bin_rev = np.binary_repr(x, width=n_t)[::-1] lam = int(x_bin_rev,2)/(2**n_t) if lam < C: alpha.append(0) elif lam >= C: alpha.append(2*np.arcsin(C/lam)) theta = ucr.alpha2theta(alpha) # do inversion step qc_invrot = ucr.uniformly_controlled_rot(n_t, theta) qc.append(qc_invrot, qr_t[0:len(qr_t)] + [qr_a[0]]) if INVROT_ == None: INVROT_ = qc_invrot # and measure ancilla qc.measure(qr_a[0], cr_a[0], basis = "Ensemble", add_param = "Z") qc.reset(qr_a[0]) qc.barrier() ''' Perform Quantum Fourier Transform on clock qubits ''' #qc = QFT(qc, qr_t) qc_qft = qft_gate(n_t, method=2) qc.append(qc_qft, qr_t) if QFT_ == None: QFT_ = qc_qft qc.barrier() ''' Perform Inverse Quantum Phase Estimation on input (b), clock, and ancilla ''' # uncompute phase estimation # perform controlled e^(-i*A*t) for q in reversed(range(n_t)): control = qr_t[q] phase = (2*pi)*2**q qc_ui = shs.control_Ham_sim(n, A, phase) if phase <= 0: qc_ui.name = "e^{" + str(q) + "iAt}" else: qc_ui.name = "e^{-" + str(q) + "iAt}" if UI_ == None: UI_ = qc_ui qc.append(qc_ui, qr[0:len(qr)] + qr_b[0:len(qr_b)] + [control] + [anc]) qc.barrier() # Hadamard (again) the phase estimation register - the 'clock' for q in range(n_t): qc.h(qr_t[q]) qc.barrier() ''' Perform final measurements ''' # measure ancilla and main register qc.measure(qr[0:], cr[0:], basis = "Ensemble", add_param = "Z") if QC_ == None: QC_ = qc #print(f"... made circuit = \n{QC_}") return qc ############### Result Data Analysis saved_result = None # Compute the expected distribution, given the matrix A and input value b def true_distr(A, b=0): N = len(A) n = int(np.log2(N)) b_vec = np.zeros(N); b_vec[b] = 1.0 #b = np.array([1,1])/np.sqrt(2) x = np.linalg.inv(A) @ b_vec # normalize x x_n = x/np.linalg.norm(x) probs = np.array([np.abs(xj)**2 for xj in x_n]) distr = {} for j, prob in enumerate(probs): if prob > 1e-8: j_bin = np.binary_repr(j, width=n) distr[j_bin] = prob distr = {out:distr[out]/sum(distr.values()) for out in distr} return distr # post-select counts where ancilla was measured as |1> def postselect(outcomes, return_probs=True): mar_out = {} for b_str in outcomes: if b_str[0] == '1': counts = outcomes[b_str] mar_out[b_str[2:]] = counts # print(f"mar_out[b_str[2:]] ===== {mar_out[b_str[2:]]}") # compute postselection rate ps_shots = sum(mar_out.values()) # print(f"ps_shots ===== {ps_shots}") shots = sum(outcomes.values()) rate = ps_shots/shots # convert to probability distribution if return_probs == True: mar_out = {b_str:round(mar_out[b_str]/ps_shots, 4) for b_str in mar_out} return mar_out, rate # Analyze the quality of the result obtained from executing circuit qc def analyze_and_print_result (qc, result, num_qubits, s_int, num_shots): global saved_result saved_result = result # obtain counts from the result object counts = result.get_counts(qc) # print(f"counts ===== {counts}") if verbose: print(f"... for circuit = {num_qubits} {s_int}, counts = {counts}") # post-select counts where ancilla was measured as |1> post_counts, rate = postselect(counts) # print(f"post_counts ===== {post_counts}") num_input_qubits = len(list(post_counts.keys())[0]) if verbose: print(f'... ratio of counts with ancilla measured |1> : {round(rate, 4)}') # compute true distribution from secret int off_diag_index = 0 b = 0 # remove instance index from s_int s_int = s_int - 1000 * int(s_int/1000) # get off_diag_index and b s_int_o = int(s_int) s_int_b = int(s_int) while (s_int_o % 2) == 0: s_int_o = int(s_int_o/2) off_diag_index += 1 while (s_int_b % 3) == 0: s_int_b = int(s_int_b/3) b += 1 if verbose: print(f"... rem(s_int) = {s_int}, b = {b}, odi = {off_diag_index}") # temporarily fix diag and off-diag matrix elements diag_el = 0.5 off_diag_el = -0.25 A = shs.generate_sparse_H(num_input_qubits, off_diag_index, diag_el=diag_el, off_diag_el=off_diag_el) ideal_distr = true_distr(A, b) # # compute total variation distance # tvd = TVD(ideal_distr, post_counts) # # use TVD as infidelity # fidelity = 1 - tvd # #fidelity = metrics.polarization_fidelity(post_counts, ideal_distr) fidelity = metrics.polarization_fidelity(post_counts, ideal_distr) # print(f"fidelity ===== {fidelity}") return post_counts, fidelity ################ Benchmark Loop # Execute program with default parameters (based on min and max_qubits) # This routine computes a reasonable min and max input and clock qubit range to sweep # from the given min and max qubit sizes using the formula below and making the # assumption that num_input_qubits ~= num_clock_qubits and num_input_qubits < num_clock_qubits: # num_qubits = 2 * num_input_qubits + num_clock_qubits + 1 (the ancilla) def run (min_qubits=3, max_qubits=8, skip_qubits=1, max_circuits=3, num_shots=100, method = 1, use_best_widths=True, backend_id='dm_simulator', provider_backend=None, #hub="ibm-q", group="open", project="main", exec_options=None, context=None): # we must have at least 4 qubits and min must be less than max max_qubits = max(4, max_qubits) min_qubits = min(max(4, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) #print(f"... using min_qubits = {min_qubits} and max_qubits = {max_qubits}") # create context identifier if context is None: context = f"{benchmark_name} Benchmark" ''' first attempt .. min_input_qubits = min_qubits//2 if min_qubits%2 == 1: min_clock_qubits = min_qubits//2 + 1 else: min_clock_qubits = min_qubits//2 max_input_qubits = max_qubits//2 if max_qubits%2 == 1: max_clock_qubits = max_qubits//2 + 1 else: max_clock_qubits = max_qubits//2 ''' # the calculation below is based on the formula described above, where I = input, C = clock: # I = int((N - 1) / 3) min_input_qubits = int((min_qubits - 1) / 3) max_input_qubits = int((max_qubits - 1) / 3) # C = N - 1 - 2 * I min_clock_qubits = min_qubits - 1 - 2 * min_input_qubits max_clock_qubits = max_qubits - 1 - 2 * max_input_qubits #print(f"... input, clock qubit width range: {min_input_qubits} : {max_input_qubits}, {min_clock_qubits} : {max_clock_qubits}") return run2(min_input_qubits=min_input_qubits,max_input_qubits= max_input_qubits, min_clock_qubits=min_clock_qubits, max_clock_qubits=max_clock_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, method=method, use_best_widths=use_best_widths, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options, context=context) # Execute program with default parameters and permitting the user to specify an # arbitrary range of input and clock qubit widths # The benchmark sweeps over all input widths and clock widths in the range specified def run2 (min_input_qubits=1, max_input_qubits=5, skip_qubits=1, min_clock_qubits=1, max_clock_qubits=5, max_circuits=3, num_shots=100, method=2, use_best_widths=False, backend_id='dm_simulator', provider_backend=None, # hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - Qiskit") # ensure valid input an clock qubit widths min_input_qubits = min(max(1, min_input_qubits), max_input_qubits) max_input_qubits = max(min_input_qubits, max_input_qubits) min_clock_qubits = min(max(1, min_clock_qubits), max_clock_qubits) max_clock_qubits = max(min_clock_qubits, max_clock_qubits) #print(f"... in, clock: {min_input_qubits}, {max_input_qubits}, {min_clock_qubits}, {max_clock_qubits}") # initialize saved circuits for display global QC_, U_, UI_, QFT_, QFTI_, HP_, INVROT_ QC_ = None U_ = None UI_ = None QFT_ = None QFTI_ = None HP_ = None INVROT_ = None ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) #counts, fidelity = analyze_and_print_result(qc, result, num_qubits, ideal_distr) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Variable for new qubit group ordering if using mid_circuit measurements mid_circuit_qubit_group = [] # If using mid_circuit measurements, set transform qubit group to true transform_qubit_group = False # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options, context=context) # for noiseless simulation, set noise model to be None #ex.set_noise_model(None) # temporarily fix diag and off-diag matrix elements diag_el = 0.5 off_diag_el = -0.25 ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete #for num_input_qubits in range(min_input_qubits, max_input_qubits+1): for num_input_qubits in range(min_input_qubits, max_input_qubits + 1, skip_qubits): N = 2**num_input_qubits # matrix size for num_clock_qubits in range(min_clock_qubits, max_clock_qubits+1, skip_qubits): num_qubits = 2*num_input_qubits + num_clock_qubits + 1 # determine number of circuits to execute for this group num_circuits = max_circuits # if flagged to use best input and clock for specific num_qubits, check against formula if use_best_widths: if num_input_qubits != int((num_qubits - 1) / 3) or num_clock_qubits != (num_qubits - 1 - 2 * num_input_qubits): if verbose: print(f"... SKIPPING {num_circuits} circuits with {num_qubits} qubits, using {num_input_qubits} input qubits and {num_clock_qubits} clock qubits") continue print(f"************\nExecuting {num_circuits} circuits with {num_qubits} qubits, using {num_input_qubits} input qubits and {num_clock_qubits} clock qubits") # loop over randomly generated problem instances for i in range(num_circuits): # generate a non-zero value < N #b = np.random.choice(range(N)) # orig code, gens 0 sometimes b = np.random.choice(range(1, N)) # and a non-zero index off_diag_index = np.random.choice(range(1, N)) # define secret_int (include 'i' since b and off_diag_index don't need to be unique) s_int = 1000 * (i+1) + (2**off_diag_index)*(3**b) #s_int = (2**off_diag_index)*(3**b) if verbose: print(f"... create A for b = {b}, off_diag_index = {off_diag_index}, s_int = {s_int}") A = shs.generate_sparse_H(num_input_qubits, off_diag_index, diag_el=diag_el, off_diag_el=off_diag_el) # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = make_circuit(A, b, num_clock_qubits) metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) #print(qc) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, s_int, shots=num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") #if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") print("\nU Circuit ="); print(U_ if U_ != None else " ... too large!") print("\nU^-1 Circuit ="); print(UI_ if UI_ != None else " ... too large!") print("\nQFT Circuit ="); print(QFT_ if QFT_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") print("\nHamiltonian Phase Estimation Circuit ="); print(HP_ if HP_ != None else " ... too large!") print("\nControlled Rotation Circuit ="); print(INVROT_ if INVROT_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim", transform_qubit_group = transform_qubit_group, new_qubit_group = mid_circuit_qubit_group) # if main, execute method if __name__ == '__main__': run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" HHL Benchmark Program - QSim """ import sys import time import numpy as np pi = np.pi from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute import sparse_Ham_sim as shs import uniform_controlled_rotation as ucr # include QFT in this list, so we can refer to the QFT sub-circuit definition #sys.path[1:1] = ["_common", "_common/qiskit", "quantum-fourier-transform/qiskit"] #sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../quantum-fourier-transform/qiskit"] # cannot use the QFT common yet, as HHL seems to use reverse bit order sys.path[1:1] = ["_common", "_common/qsim", "quantum-fourier-transform/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../quantum-fourier-transform/qsim"] #from qft_benchmark import qft_gate, inv_qft_gate import execute as ex import metrics as metrics # Benchmark Name benchmark_name = "HHL" np.random.seed(0) verbose = False # Variable for number of resets to perform after mid circuit measurements num_resets = 1 # saved circuits for display QC_ = None U_ = None UI_ = None QFT_ = None QFTI_ = None HP_ = None INVROT_ = None ############### Circuit Definitions ''' replaced with code below ... def qft_dagger(qc, clock, n): qc.h(clock[1]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): qc.cu1(-np.pi/float(2**(k-j)), clock[k], clock[j]); qc.h(clock[0]); def qft(qc, clock, n): qc.h(clock[0]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): qc.cu1(np.pi/float(2**(k-j)), clock[k], clock[j]); qc.h(clock[1]); ''' ''' DEVNOTE: the QFT and IQFT are defined here as they are in the QFT benchmark - almost; Here, the sign of the angles is reversed and the QFT is actually used as the inverse QFT. This is an inconsistency that needs to be resolved later. The QPE part of the algorithm should be using the inverse QFT, but the qubit order is not correct. The QFT as defined in the QFT benchmark operates on qubits in the opposite order from the HHL pattern. ''' def initialize_state(qc, qreg, b): """ b (int): initial basis state |b> """ n = qreg.size b_bin = np.binary_repr(b, width=n) if verbose: print(f"... initializing |b> to {b}, binary repr = {b_bin}") for q in range(n): if b_bin[n-1-q] == '1': qc.x(qreg[q]) return qc def IQFT(qc, qreg): """ inverse QFT qc : QuantumCircuit qreg : QuantumRegister belonging to qc does not include SWAP at end of the circuit """ n = int(qreg.size) for i in reversed(range(n)): for j in range(i+1,n): phase = -pi/2**(j-i) qc.cp(phase, qreg[i], qreg[j]) qc.h(qreg[i]) return qc def QFT(qc, qreg): """ QFT qc : QuantumCircuit qreg : QuantumRegister belonging to qc does not include SWAP at end of circuit """ n = int(qreg.size) for i in range(n): qc.h(qreg[i]) for j in reversed(range(i+1,n)): phase = pi/2**(j-i) qc.cp(phase, qreg[i], qreg[j]) return qc def inv_qft_gate(input_size, method=1): #def qft_gate(input_size): #global QFT_ qr = QuantumRegister(input_size); #qc = QuantumCircuit(qr, name="qft") qc = QuantumCircuit(qr, name="IQFT") if method == 1: # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in range(0, input_size): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in range(0, num_crzs): divisor = 2 ** (num_crzs - j) #qc.crz( math.pi / divisor , qr[hidx], qr[input_size - j - 1]) ##qc.crz( -np.pi / divisor , qr[hidx], qr[input_size - j - 1]) qc.cp(-np.pi / divisor, qr[hidx], qr[input_size - j - 1]); # followed by an H gate (applied to all qubits) qc.h(qr[hidx]) elif method == 2: # apply IQFT to register for i in range(input_size)[::-1]: for j in range(i+1,input_size): phase = -np.pi/2**(j-i) qc.cp(phase, qr[i], qr[j]) qc.h(qr[i]) qc.barrier() return qc ############### Inverse QFT Circuit def qft_gate(input_size, method=1): #def inv_qft_gate(input_size): #global QFTI_ qr = QuantumRegister(input_size); #qc = QuantumCircuit(qr, name="inv_qft") qc = QuantumCircuit(qr, name="QFT") if method == 1: # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.h(qr[hidx]) # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) #qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1]) ##qc.crz( np.pi / divisor , qr[hidx], qr[input_size - j - 1]) qc.cp( np.pi / divisor , qr[hidx], qr[input_size - j - 1]) elif method == 2: # apply QFT to register for i in range(input_size): qc.h(qr[i]) for j in range(i+1, input_size): phase = np.pi/2**(j-i) qc.cp(phase, qr[i], qr[j]) qc.barrier() return qc ############# Controlled U Gate #Construct the U gates for A def ctrl_u(exponent): qc = QuantumCircuit(1, name=f"U^{exponent}") for i in range(exponent): #qc.u(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, target); #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, control, target); qc.u(np.pi/2, -np.pi/2, np.pi/2, 0); cu_gate = qc.to_gate().control(1) return cu_gate, qc #Construct the U^-1 gates for reversing A def ctrl_ui(exponent): qc = QuantumCircuit(1, name=f"U^-{exponent}") for i in range(exponent): #qc.u(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, target); #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, control, target); qc.u(np.pi/2, np.pi/2, -np.pi/2, 0); cu_gate = qc.to_gate().control(1) return cu_gate, qc ####### DEVNOTE: The following functions (up until the make_circuit) are from the first inccarnation # of this benchmark and are not used here. Should be removed, but kept here for reference for now ############# Quantum Phase Estimation # DEVNOTE: The QPE and IQPE methods below mirror the mechanism in Hector_Wong # Need to investigate whether the clock qubits are in the correct, as this implementation # seems to require the QFT be implemented in reverse also. TODO # Append a series of Quantum Phase Estimation gates to the circuit def qpe(qc, clock, target, extra_qubits=None, ancilla=None, A=None, method=1): qc.barrier() ''' original code from Hector_Wong # e^{i*A*t} #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], target, label='U'); # The CU gate is equivalent to a CU1 on the control bit followed by a CU3 qc.u1(3*np.pi/4, clock[0]); qc.cu3(np.pi/2, -np.pi/2, np.pi/2, clock[0], target); # e^{i*A*t*2} #qc.cu(np.pi, np.pi, 0, 0, clock[1], target, label='U2'); qc.cu3(np.pi, np.pi, 0, clock[1], target); qc.barrier(); ''' # apply series of controlled U operations to the state |1> # does nothing to state |0> # DEVNOTE: have not found a way to create a controlled operation that contains a U gate # with the global phase; instead do it piecemeal for now if method == 1: repeat = 1 #for j in reversed(range(len(clock))): for j in (range(len(clock))): # create U with exponent of 1, but in a loop repeating N times for k in range(repeat): # this global phase is applied to clock qubit qc.u1(3*np.pi/4, clock[j]); # apply the rest of U controlled by clock qubit #cp, _ = ctrl_u(repeat) cp, _ = ctrl_u(1) qc.append(cp, [clock[j], target]) repeat *= 2 qc.barrier(); #Define global U operator as the phase operator (for printing later) _, U_ = ctrl_u(1) if method == 2: for j in range(len(clock)): control = clock[j] phase = -(2*np.pi)*2**j con_H_sim = shs.control_Ham_sim(A, phase) qubits = [control] + [q for q in target] + [q for q in extra_qubits] + [ancilla[0]] qc.append(con_H_sim, qubits) # Perform an inverse QFT on the register holding the eigenvalues qc.append(inv_qft_gate(len(clock), method), clock) # Append a series of Inverse Quantum Phase Estimation gates to the circuit def inv_qpe(qc, clock, target, extra_qubits=None, ancilla=None, A=None, method=1): # Perform a QFT on the register holding the eigenvalues qc.append(qft_gate(len(clock), method), clock) qc.barrier() if method == 1: ''' original code from Hector_Wong # e^{i*A*t*2} #qc.cu(np.pi, np.pi, 0, 0, clock[1], target, label='U2'); qc.cu3(np.pi, np.pi, 0, clock[1], target); # e^{i*A*t} #qc.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, clock[0], target, label='U'); # The CU gate is equivalent to a CU1 on the control bit followed by a CU3 qc.u1(-3*np.pi/4, clock[0]); qc.cu3(np.pi/2, np.pi/2, -np.pi/2, clock[0], target); qc.barrier() ''' # apply inverse series of controlled U operations to the state |1> # does nothing to state |0> # DEVNOTE: have not found a way to create a controlled operation that contains a U gate # with the global phase; instead do it piecemeal for now repeat = 2 ** (len(clock) - 1) for j in reversed(range(len(clock))): #for j in (range(len(clock))): # create U with exponent of 1, but in a loop repeating N times for k in range(repeat): # this global phase is applied to clock qubit qc.u1(-3*np.pi/4, clock[j]); # apply the rest of U controlled by clock qubit #cp, _ = ctrl_u(repeat) cp, _ = ctrl_ui(1) qc.append(cp, [clock[j], target]) repeat = int(repeat / 2) qc.barrier(); #Define global U operator as the phase operator (for printing later) _, UI_ = ctrl_ui(1) if method == 2: for j in reversed(range(len(clock))): control = clock[j] phase = (2*np.pi)*2**j con_H_sim = shs.control_Ham_sim(A, phase) qubits = [control] + [q for q in target] + [q for q in extra_qubits] + [ancilla[0]] qc.append(con_H_sim, qubits) ############### Make HHL Circuit # Make the HHL circuit def make_circuit(A, b, num_clock_qubits): """ Generate top-level circuit for HHL algo A|x>=|b> A : sparse Hermitian matrix b (int): between 0,...,2^n-1. Initial basis state |b> """ # save smaller circuit example for display global QC_, U_, UI_, QFT_, QFTI_, HP_, INVROT_ # read in number of qubits N = len(A) n = int(np.log2(N)) n_t = num_clock_qubits # number of qubits in clock register num_qubits = 2*n + n_t + 1 # lower bound on eigenvalues of A. Fixed for now C = 1/4 ''' Define sets of qubits for this algorithm ''' # create 'input' quantum and classical measurement register qr = QuantumRegister(n, name='input') qr_b = QuantumRegister(n, name='in_anc') # ancillas for Hamiltonian simulation (?) cr = ClassicalRegister(n) # create 'clock' quantum register qr_t = QuantumRegister(n_t, name='clock') # for phase estimation # create 'ancilla' quantum and classical measurement register qr_a = QuantumRegister(1, name='ancilla') # ancilla qubit cr_a = ClassicalRegister(1) # create the top-level HHL circuit, with all the registers qc = QuantumCircuit(qr, qr_b, qr_t, qr_a, cr, cr_a, name=f"hhl-{num_qubits}-{b}") ''' Initialize the input and clock qubits ''' # initialize the |b> state - the 'input' qc = initialize_state(qc, qr, b) #qc.barrier() # Hadamard the phase estimation register - the 'clock' for q in range(n_t): qc.h(qr_t[q]) qc.barrier() ''' Perform Quantum Phase Estimation on input (b), clock, and ancilla ''' # perform controlled e^(i*A*t) for q in range(n_t): control = qr_t[q] anc = qr_a[0] phase = -(2*pi)*2**q qc_u = shs.control_Ham_sim(n, A, phase) if phase <= 0: qc_u.name = "e^{" + str(q) + "iAt}" else: qc_u.name = "e^{-" + str(q) + "iAt}" if U_ == None: U_ = qc_u qc.append(qc_u, qr[0:len(qr)] + qr_b[0:len(qr_b)] + [control] + [anc]) qc.barrier() ''' Perform Inverse Quantum Fourier Transform on clock qubits ''' #qc = IQFT(qc, qr_t) qc_qfti = inv_qft_gate(n_t, method=2) qc.append(qc_qfti, qr_t) if QFTI_ == None: QFTI_ = qc_qfti qc.barrier() ''' Perform inverse rotation with ancilla ''' # reset ancilla qc.reset(qr_a[0]) # compute angles for inversion rotations alpha = [2*np.arcsin(C)] for x in range(1,2**n_t): x_bin_rev = np.binary_repr(x, width=n_t)[::-1] lam = int(x_bin_rev,2)/(2**n_t) if lam < C: alpha.append(0) elif lam >= C: alpha.append(2*np.arcsin(C/lam)) theta = ucr.alpha2theta(alpha) # do inversion step qc_invrot = ucr.uniformly_controlled_rot(n_t, theta) qc.append(qc_invrot, qr_t[0:len(qr_t)] + [qr_a[0]]) if INVROT_ == None: INVROT_ = qc_invrot # and measure ancilla qc.measure(qr_a[0], cr_a[0], basis = "Ensemble", add_param = "Z") qc.reset(qr_a[0]) qc.barrier() ''' Perform Quantum Fourier Transform on clock qubits ''' #qc = QFT(qc, qr_t) qc_qft = qft_gate(n_t, method=2) qc.append(qc_qft, qr_t) if QFT_ == None: QFT_ = qc_qft qc.barrier() ''' Perform Inverse Quantum Phase Estimation on input (b), clock, and ancilla ''' # uncompute phase estimation # perform controlled e^(-i*A*t) for q in reversed(range(n_t)): control = qr_t[q] phase = (2*pi)*2**q qc_ui = shs.control_Ham_sim(n, A, phase) if phase <= 0: qc_ui.name = "e^{" + str(q) + "iAt}" else: qc_ui.name = "e^{-" + str(q) + "iAt}" if UI_ == None: UI_ = qc_ui qc.append(qc_ui, qr[0:len(qr)] + qr_b[0:len(qr_b)] + [control] + [anc]) qc.barrier() # Hadamard (again) the phase estimation register - the 'clock' for q in range(n_t): qc.h(qr_t[q]) qc.barrier() ''' Perform final measurements ''' # measure ancilla and main register qc.measure(qr[0:], cr[0:], basis = "Ensemble", add_param = "Z") if QC_ == None: QC_ = qc #print(f"... made circuit = \n{QC_}") return qc ############### Result Data Analysis saved_result = None # Compute the expected distribution, given the matrix A and input value b def true_distr(A, b=0): N = len(A) n = int(np.log2(N)) b_vec = np.zeros(N); b_vec[b] = 1.0 #b = np.array([1,1])/np.sqrt(2) x = np.linalg.inv(A) @ b_vec # normalize x x_n = x/np.linalg.norm(x) probs = np.array([np.abs(xj)**2 for xj in x_n]) distr = {} for j, prob in enumerate(probs): if prob > 1e-8: j_bin = np.binary_repr(j, width=n) distr[j_bin] = prob distr = {out:distr[out]/sum(distr.values()) for out in distr} return distr # post-select counts where ancilla was measured as |1> def postselect(outcomes, return_probs=True): mar_out = {} for b_str in outcomes: if b_str[0] == '1': counts = outcomes[b_str] mar_out[b_str[2:]] = counts # compute postselection rate ps_shots = sum(mar_out.values()) shots = sum(outcomes.values()) rate = ps_shots/shots # convert to probability distribution if return_probs == True: mar_out = {b_str:round(mar_out[b_str]/ps_shots, 4) for b_str in mar_out} return mar_out, rate # Analyze the quality of the result obtained from executing circuit qc def analyze_and_print_result (qc, result, num_qubits, s_int, num_shots): global saved_result saved_result = result # obtain counts from the result object counts = result.get_counts(qc) #probabilities if verbose: print(f"... for circuit = {num_qubits} {s_int}, counts = {counts}") # post-select counts where ancilla was measured as |1> post_counts, rate = postselect(counts) num_input_qubits = len(list(post_counts.keys())[0]) if verbose: print(f'... ratio of counts with ancilla measured |1> : {round(rate, 4)}') # compute true distribution from secret int off_diag_index = 0 b = 0 # remove instance index from s_int s_int = s_int - 1000 * int(s_int/1000) # get off_diag_index and b s_int_o = int(s_int) s_int_b = int(s_int) while (s_int_o % 2) == 0: s_int_o = int(s_int_o/2) off_diag_index += 1 while (s_int_b % 3) == 0: s_int_b = int(s_int_b/3) b += 1 if verbose: print(f"... rem(s_int) = {s_int}, b = {b}, odi = {off_diag_index}") # temporarily fix diag and off-diag matrix elements diag_el = 0.5 off_diag_el = -0.25 A = shs.generate_sparse_H(num_input_qubits, off_diag_index, diag_el=diag_el, off_diag_el=off_diag_el) ideal_distr = true_distr(A, b) # # compute total variation distance # tvd = TVD(ideal_distr, post_counts) # # use TVD as infidelity # fidelity = 1 - tvd # #fidelity = metrics.polarization_fidelity(post_counts, ideal_distr) fidelity = metrics.polarization_fidelity(post_counts, ideal_distr) return post_counts, fidelity ################ Benchmark Loop # Execute program with default parameters (based on min and max_qubits) # This routine computes a reasonable min and max input and clock qubit range to sweep # from the given min and max qubit sizes using the formula below and making the # assumption that num_input_qubits ~= num_clock_qubits and num_input_qubits < num_clock_qubits: # num_qubits = 2 * num_input_qubits + num_clock_qubits + 1 (the ancilla) def run (min_qubits=3, max_qubits=6, skip_qubits=1, max_circuits=3, num_shots=100, method = 1, use_best_widths=True, backend_id='dm_simulator', provider_backend=None, #hub="ibm-q", group="open", project="main", exec_options=None, context=None): # we must have at least 4 qubits and min must be less than max max_qubits = max(4, max_qubits) min_qubits = min(max(4, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) #print(f"... using min_qubits = {min_qubits} and max_qubits = {max_qubits}") # create context identifier if context is None: context = f"{benchmark_name} Benchmark" ''' first attempt .. min_input_qubits = min_qubits//2 if min_qubits%2 == 1: min_clock_qubits = min_qubits//2 + 1 else: min_clock_qubits = min_qubits//2 max_input_qubits = max_qubits//2 if max_qubits%2 == 1: max_clock_qubits = max_qubits//2 + 1 else: max_clock_qubits = max_qubits//2 ''' # the calculation below is based on the formula described above, where I = input, C = clock: # I = int((N - 1) / 3) min_input_qubits = int((min_qubits - 1) / 3) max_input_qubits = int((max_qubits - 1) / 3) # C = N - 1 - 2 * I min_clock_qubits = min_qubits - 1 - 2 * min_input_qubits max_clock_qubits = max_qubits - 1 - 2 * max_input_qubits #print(f"... input, clock qubit width range: {min_input_qubits} : {max_input_qubits}, {min_clock_qubits} : {max_clock_qubits}") return run2(min_input_qubits=min_input_qubits,max_input_qubits= max_input_qubits, min_clock_qubits=min_clock_qubits, max_clock_qubits=max_clock_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, method=method, use_best_widths=use_best_widths, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options, context=context) # Execute program with default parameters and permitting the user to specify an # arbitrary range of input and clock qubit widths # The benchmark sweeps over all input widths and clock widths in the range specified def run2 (min_input_qubits=1, max_input_qubits=3, skip_qubits=1, min_clock_qubits=1, max_clock_qubits=3, max_circuits=3, num_shots=100, method=2, use_best_widths=False, backend_id='dm_simulator', provider_backend=None, # hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - Qiskit") # ensure valid input an clock qubit widths min_input_qubits = min(max(1, min_input_qubits), max_input_qubits) max_input_qubits = max(min_input_qubits, max_input_qubits) min_clock_qubits = min(max(1, min_clock_qubits), max_clock_qubits) max_clock_qubits = max(min_clock_qubits, max_clock_qubits) #print(f"... in, clock: {min_input_qubits}, {max_input_qubits}, {min_clock_qubits}, {max_clock_qubits}") # initialize saved circuits for display global QC_, U_, UI_, QFT_, QFTI_, HP_, INVROT_ QC_ = None U_ = None UI_ = None QFT_ = None QFTI_ = None HP_ = None INVROT_ = None ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) #counts, fidelity = analyze_and_print_result(qc, result, num_qubits, ideal_distr) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Variable for new qubit group ordering if using mid_circuit measurements mid_circuit_qubit_group = [] # If using mid_circuit measurements, set transform qubit group to true transform_qubit_group = False # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options, context=context) # for noiseless simulation, set noise model to be None #ex.set_noise_model(None) # temporarily fix diag and off-diag matrix elements diag_el = 0.5 off_diag_el = -0.25 ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete #for num_input_qubits in range(min_input_qubits, max_input_qubits+1): for num_input_qubits in range(min_input_qubits, max_input_qubits + 1, skip_qubits): N = 2**num_input_qubits # matrix size for num_clock_qubits in range(min_clock_qubits, max_clock_qubits+1, skip_qubits): num_qubits = 2*num_input_qubits + num_clock_qubits + 1 # determine number of circuits to execute for this group num_circuits = max_circuits # if flagged to use best input and clock for specific num_qubits, check against formula if use_best_widths: if num_input_qubits != int((num_qubits - 1) / 3) or num_clock_qubits != (num_qubits - 1 - 2 * num_input_qubits): if verbose: print(f"... SKIPPING {num_circuits} circuits with {num_qubits} qubits, using {num_input_qubits} input qubits and {num_clock_qubits} clock qubits") continue print(f"************\nExecuting {num_circuits} circuits with {num_qubits} qubits, using {num_input_qubits} input qubits and {num_clock_qubits} clock qubits") # loop over randomly generated problem instances for i in range(num_circuits): # generate a non-zero value < N #b = np.random.choice(range(N)) # orig code, gens 0 sometimes b = np.random.choice(range(1, N)) # and a non-zero index off_diag_index = np.random.choice(range(1, N)) # define secret_int (include 'i' since b and off_diag_index don't need to be unique) s_int = 1000 * (i+1) + (2**off_diag_index)*(3**b) #s_int = (2**off_diag_index)*(3**b) if verbose: print(f"... create A for b = {b}, off_diag_index = {off_diag_index}, s_int = {s_int}") A = shs.generate_sparse_H(num_input_qubits, off_diag_index, diag_el=diag_el, off_diag_el=off_diag_el) # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = make_circuit(A, b, num_clock_qubits) metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) #print(qc) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, s_int, shots=num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") #if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") print("\nU Circuit ="); print(U_ if U_ != None else " ... too large!") print("\nU^-1 Circuit ="); print(UI_ if UI_ != None else " ... too large!") print("\nQFT Circuit ="); print(QFT_ if QFT_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") print("\nHamiltonian Phase Estimation Circuit ="); print(HP_ if HP_ != None else " ... too large!") print("\nControlled Rotation Circuit ="); print(INVROT_ if INVROT_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim", transform_qubit_group = transform_qubit_group, new_qubit_group = mid_circuit_qubit_group) # if main, execute method if __name__ == '__main__': run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" HHL Benchmark Program - Qiskit (KM initial version 220402) TODO: - switch from total variation distance to Hellinger fidelity """ import sys import time import numpy as np pi = np.pi from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute import sparse_Ham_sim as shs import uniform_controlled_rotation as ucr # include QFT in this list, so we can refer to the QFT sub-circuit definition #sys.path[1:1] = ["_common", "_common/qiskit", "quantum-fourier-transform/qiskit"] #sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../quantum-fourier-transform/qiskit"] # cannot use the QFT common yet, as HHL seems to use reverse bit order sys.path[1:1] = ["_common", "_common/qiskit", "quantum-fourier-transform/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../quantum-fourier-transform/qiskit"] #from qft_benchmark import qft_gate, inv_qft_gate import execute as ex import metrics as metrics np.random.seed(0) verbose = False # Variable for number of resets to perform after mid circuit measurements num_resets = 1 # saved circuits for display QC_ = None U_ = None UI_ = None QFT_ = None QFTI_ = None ############### Circuit Definitions ''' replaced with code below ... def qft_dagger(qc, clock, n): qc.h(clock[1]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): qc.cu1(-np.pi/float(2**(k-j)), clock[k], clock[j]); qc.h(clock[0]); def qft(qc, clock, n): qc.h(clock[0]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): qc.cu1(np.pi/float(2**(k-j)), clock[k], clock[j]); qc.h(clock[1]); ''' ''' DEVNOTE: the QFT and IQFT are defined here as they are in the QFT benchmark - almost; Here, the sign of the angles is reversed and the QFT is actually used as the inverse QFT. This is an inconsistency that needs to be resolved later. The QPE part of the algorithm should be using the inverse QFT, but the qubit order is not correct. The QFT as defined in the QFT benchmark operates on qubits in the opposite order from the HHL pattern. ''' def initialize_state(qc, qreg, b): """ b (int): initial basis state |b> """ n = qreg.size b_bin = np.binary_repr(b, width=n) for q in range(n): if b_bin[n-1-q] == '1': qc.x(qreg[q]) return qc def IQFT(qc, qreg): """ inverse QFT qc : QuantumCircuit qreg : QuantumRegister belonging to qc does not include SWAP at end of the circuit """ n = int(qreg.size) for i in reversed(range(n)): for j in range(i+1,n): phase = -pi/2**(j-i) qc.cp(phase, qreg[i], qreg[j]) qc.h(qreg[i]) return qc def QFT(qc, qreg): """ QFT qc : QuantumCircuit qreg : QuantumRegister belonging to qc does not include SWAP at end of circuit """ n = int(qreg.size) for i in range(n): qc.h(qreg[i]) for j in reversed(range(i+1,n)): phase = pi/2**(j-i) qc.cp(phase, qreg[i], qreg[j]) return qc def inv_qft_gate(input_size, method=1): #def qft_gate(input_size): #global QFT_ qr = QuantumRegister(input_size); #qc = QuantumCircuit(qr, name="qft") qc = QuantumCircuit(qr, name="QFT†") if method == 1: # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in range(0, input_size): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in range(0, num_crzs): divisor = 2 ** (num_crzs - j) #qc.crz( math.pi / divisor , qr[hidx], qr[input_size - j - 1]) ##qc.crz( -np.pi / divisor , qr[hidx], qr[input_size - j - 1]) qc.cu1(-np.pi / divisor, qr[hidx], qr[input_size - j - 1]); # followed by an H gate (applied to all qubits) qc.h(qr[hidx]) elif method == 2: # apply IQFT to register for i in range(input_size)[::-1]: for j in range(i+1,input_size): phase = -np.pi/2**(j-i) qc.cp(phase, qr[i], qr[j]) qc.h(qr[i]) qc.barrier() return qc ############### Inverse QFT Circuit def qft_gate(input_size, method=1): #def inv_qft_gate(input_size): #global QFTI_ qr = QuantumRegister(input_size); #qc = QuantumCircuit(qr, name="inv_qft") qc = QuantumCircuit(qr, name="QFT") if method == 1: # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.h(qr[hidx]) # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) #qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1]) ##qc.crz( np.pi / divisor , qr[hidx], qr[input_size - j - 1]) qc.cu1( np.pi / divisor , qr[hidx], qr[input_size - j - 1]) elif method == 2: # apply QFT to register for i in range(input_size): qc.h(qr[i]) for j in range(i+1, input_size): phase = np.pi/2**(j-i) qc.cp(phase, qr[i], qr[j]) qc.barrier() return qc ############# Controlled U Gate #Construct the U gates for A def ctrl_u(exponent): qc = QuantumCircuit(1, name=f"U^{exponent}") for i in range(exponent): #qc.u(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, target); #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, control, target); qc.u(np.pi/2, -np.pi/2, np.pi/2, 0); cu_gate = qc.to_gate().control(1) return cu_gate, qc #Construct the U^-1 gates for reversing A def ctrl_ui(exponent): qc = QuantumCircuit(1, name=f"U^-{exponent}") for i in range(exponent): #qc.u(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, target); #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, control, target); qc.u(np.pi/2, np.pi/2, -np.pi/2, 0); cu_gate = qc.to_gate().control(1) return cu_gate, qc ############# Quantum Phase Estimation # DEVNOTE: The QPE and IQPE methods below mirror the mechanism in Hector_Wong # Need to investigate whether the clock qubits are in the correct, as this implementation # seems to require the QFT be implemented in reverse also. TODO # Append a series of Quantum Phase Estimation gates to the circuit def qpe(qc, clock, target, extra_qubits=None, ancilla=None, A=None, method=1): qc.barrier() ''' original code from Hector_Wong # e^{i*A*t} #qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], target, label='U'); # The CU gate is equivalent to a CU1 on the control bit followed by a CU3 qc.u1(3*np.pi/4, clock[0]); qc.cu3(np.pi/2, -np.pi/2, np.pi/2, clock[0], target); # e^{i*A*t*2} #qc.cu(np.pi, np.pi, 0, 0, clock[1], target, label='U2'); qc.cu3(np.pi, np.pi, 0, clock[1], target); qc.barrier(); ''' # apply series of controlled U operations to the state |1> # does nothing to state |0> # DEVNOTE: have not found a way to create a controlled operation that contains a U gate # with the global phase; instead do it piecemeal for now if method == 1: repeat = 1 #for j in reversed(range(len(clock))): for j in (range(len(clock))): # create U with exponent of 1, but in a loop repeating N times for k in range(repeat): # this global phase is applied to clock qubit qc.u1(3*np.pi/4, clock[j]); # apply the rest of U controlled by clock qubit #cp, _ = ctrl_u(repeat) cp, _ = ctrl_u(1) qc.append(cp, [clock[j], target]) repeat *= 2 qc.barrier(); #Define global U operator as the phase operator (for printing later) _, U_ = ctrl_u(1) if method == 2: for j in range(len(clock)): control = clock[j] phase = -(2*np.pi)*2**j con_H_sim = shs.control_Ham_sim(A, phase) qubits = [control] + [q for q in target] + [q for q in extra_qubits] + [ancilla[0]] qc.append(con_H_sim, qubits) # Perform an inverse QFT on the register holding the eigenvalues qc.append(inv_qft_gate(len(clock), method), clock) # Append a series of Inverse Quantum Phase Estimation gates to the circuit def inv_qpe(qc, clock, target, extra_qubits=None, ancilla=None, A=None, method=1): # Perform a QFT on the register holding the eigenvalues qc.append(qft_gate(len(clock), method), clock) qc.barrier() if method == 1: ''' original code from Hector_Wong # e^{i*A*t*2} #qc.cu(np.pi, np.pi, 0, 0, clock[1], target, label='U2'); qc.cu3(np.pi, np.pi, 0, clock[1], target); # e^{i*A*t} #qc.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, clock[0], target, label='U'); # The CU gate is equivalent to a CU1 on the control bit followed by a CU3 qc.u1(-3*np.pi/4, clock[0]); qc.cu3(np.pi/2, np.pi/2, -np.pi/2, clock[0], target); qc.barrier() ''' # apply inverse series of controlled U operations to the state |1> # does nothing to state |0> # DEVNOTE: have not found a way to create a controlled operation that contains a U gate # with the global phase; instead do it piecemeal for now repeat = 2 ** (len(clock) - 1) for j in reversed(range(len(clock))): #for j in (range(len(clock))): # create U with exponent of 1, but in a loop repeating N times for k in range(repeat): # this global phase is applied to clock qubit qc.u1(-3*np.pi/4, clock[j]); # apply the rest of U controlled by clock qubit #cp, _ = ctrl_u(repeat) cp, _ = ctrl_ui(1) qc.append(cp, [clock[j], target]) repeat = int(repeat / 2) qc.barrier(); #Define global U operator as the phase operator (for printing later) _, UI_ = ctrl_ui(1) if method == 2: for j in reversed(range(len(clock))): control = clock[j] phase = (2*np.pi)*2**j con_H_sim = shs.control_Ham_sim(A, phase) qubits = [control] + [q for q in target] + [q for q in extra_qubits] + [ancilla[0]] qc.append(con_H_sim, qubits) def hhl_routine(qc, ancilla, clock, input_qubits, measurement, extra_qubits=None, A=None, method=1): qpe(qc, clock, input_qubits, extra_qubits, ancilla, A, method) qc.reset(ancilla) qc.barrier() if method == 1: # This section is to test and implement C = 1 # since we are not swapping after the QFT, reverse order of qubits from what is in papers qc.cry(np.pi, clock[1], ancilla) qc.cry(np.pi/3, clock[0], ancilla) # uniformly-controlled rotation elif method == 2: n_clock = clock.size C = 1/2**n_clock # constant in rotation (lower bound on eigenvalues A) # compute angles for inversion rotations alpha = [2*np.arcsin(C)] for x in range(1,2**n_clock): x_bin_rev = np.binary_repr(x, width=n_clock)[::-1] lam = int(x_bin_rev,2)/(2**n_clock) alpha.append(2*np.arcsin(C/lam)) theta = ucr.alpha2theta(alpha) # do inversion step qc = ucr.uniformly_controlled_rot(qc, clock, ancilla, theta) qc.barrier() qc.measure(ancilla, measurement[0]) qc.reset(ancilla) qc.barrier() inv_qpe(qc, clock, input_qubits, extra_qubits, ancilla, A, method) def HHL(num_qubits, num_input_qubits, num_clock_qubits, beta, A=None, method=1): if method == 1: # Create the various registers needed clock = QuantumRegister(num_clock_qubits, name='clock') input_qubits = QuantumRegister(num_input_qubits, name='b') ancilla = QuantumRegister(1, name='ancilla') measurement = ClassicalRegister(2, name='c') # Create an empty circuit with the specified registers qc = QuantumCircuit(ancilla, clock, input_qubits, measurement) # State preparation. (various initial values, done with initialize method) # intial_state = [0,1] # intial_state = [1,0] # intial_state = [1/np.sqrt(2),1/np.sqrt(2)] # intial_state = [np.sqrt(0.9),np.sqrt(0.1)] ##intial_state = [np.sqrt(1 - beta), np.sqrt(beta)] ##qc.initialize(intial_state, 3) # use an RY rotation to initialize the input state between 0 and 1 qc.ry(2 * np.arcsin(beta), input_qubits) # Put clock qubits into uniform superposition qc.h(clock) # Perform the HHL routine hhl_routine(qc, ancilla, clock, input_qubits, measurement) # Perform a Hadamard Transform on the clock qubits qc.h(clock) qc.barrier() # measure the input, which now contains the answer qc.measure(input_qubits, measurement[1]) # return a handle on the circuit return qc # Make the HHL circuit (this is the one aactually used right now) def make_circuit(A, b, num_clock_qubits): """ circuit for HHL algo A|x>=|b> A : sparse Hermitian matrix b (int): between 0,...,2^n-1. Initial basis state |b> """ # read in number of qubits N = len(A) n = int(np.log2(N)) n_t = num_clock_qubits # number of qubits in clock register # lower bound on eigenvalues of A. Fixed for now C = 1/4 # create quantum registers qr = QuantumRegister(n) qr_b = QuantumRegister(n) # ancillas for Hamiltonian simulation cr = ClassicalRegister(n) qr_t = QuantumRegister(n_t) # for phase estimation qr_a = QuantumRegister(1) # ancilla qubit cr_a = ClassicalRegister(1) qc = QuantumCircuit(qr, qr_b, qr_t, qr_a, cr, cr_a) # initialize the |b> state qc = initialize_state(qc, qr, b) # Hadamard phase estimation register for q in range(n_t): qc.h(qr_t[q]) # perform controlled e^(i*A*t) for q in range(n_t): control = qr_t[q] phase = -(2*pi)*2**q qc = shs.control_Ham_sim(qc, A, phase, control, qr, qr_b, qr_a[0]) # inverse QFT qc = IQFT(qc, qr_t) # reset ancilla qc.reset(qr_a[0]) # compute angles for inversion rotations alpha = [2*np.arcsin(C)] for x in range(1,2**n_t): x_bin_rev = np.binary_repr(x, width=n_t)[::-1] lam = int(x_bin_rev,2)/(2**n_t) if lam < C: alpha.append(0) elif lam >= C: alpha.append(2*np.arcsin(C/lam)) theta = ucr.alpha2theta(alpha) # do inversion step and measure ancilla qc = ucr.uniformly_controlled_rot(qc, qr_t, qr_a, theta) qc.measure(qr_a[0], cr_a[0]) qc.reset(qr_a[0]) # QFT qc = QFT(qc, qr_t) # uncompute phase estimation # perform controlled e^(-i*A*t) for q in reversed(range(n_t)): control = qr_t[q] phase = (2*pi)*2**q qc = shs.control_Ham_sim(qc, A, phase, control, qr, qr_b, qr_a[0]) # Hadamard phase estimation register for q in range(n_t): qc.h(qr_t[q]) # measure ancilla and main register qc.barrier() qc.measure(qr[0:], cr[0:]) return qc def sim_circuit(qc, shots): simulator = Aer.get_backend('qasm_simulator') result = execute(qc, simulator, shots=shots).result() outcomes = result.get_counts(qc) return outcomes def postselect(outcomes, return_probs=True): mar_out = {} for b_str in outcomes: if b_str[0] == '1': counts = outcomes[b_str] mar_out[b_str[2:]] = counts # compute postselection rate ps_shots = sum(mar_out.values()) shots = sum(outcomes.values()) rate = ps_shots/shots # convert to probability distribution if return_probs == True: mar_out = {b_str:round(mar_out[b_str]/ps_shots, 4) for b_str in mar_out} return mar_out, rate ############### Result Data Analysis saved_result = None def true_distr(A, b=0): N = len(A) n = int(np.log2(N)) b_vec = np.zeros(N); b_vec[b] = 1.0 #b = np.array([1,1])/np.sqrt(2) x = np.linalg.inv(A) @ b_vec # normalize x x_n = x/np.linalg.norm(x) probs = np.array([np.abs(xj)**2 for xj in x_n]) distr = {} for j, prob in enumerate(probs): if prob > 1e-8: j_bin = np.binary_repr(j, width=n) distr[j_bin] = prob distr = {out:distr[out]/sum(distr.values()) for out in distr} return distr def TVD(distr1, distr2): """ compute total variation distance between distr1 and distr2 which are represented as dictionaries of bitstrings and probabilities """ tvd = 0.0 for out1 in distr1: if out1 in distr2: p1, p2 = distr1[out1], distr2[out1] tvd += np.abs(p1-p2)/2 else: p1 = distr1[out1] tvd += p1/2 for out2 in distr2: if out2 not in distr1: p2 = distr2[out2] tvd += p2/2 return tvd def analyze_and_print_result (qc, result, num_qubits, s_int, num_shots): global saved_result saved_result = result # obtain counts from the result object counts = result.get_counts(qc) # post-select counts where ancilla was measured as |1> post_counts, rate = postselect(counts) num_input_qubits = len(list(post_counts.keys())[0]) if verbose: print(f'Ratio of counts with ancilla measured |1> : {round(rate, 4)}') # compute true distribution from secret int off_diag_index = 0 b = 0 s_int_o = int(s_int) s_int_b = int(s_int) while (s_int_o % 2) == 0: s_int_o = int(s_int_o/2) off_diag_index += 1 while (s_int_b % 3) == 0: s_int_b = int(s_int_b/3) b += 1 # temporarily fix diag and off-diag matrix elements diag_el = 0.5 off_diag_el = -0.25 A = shs.generate_sparse_H(num_input_qubits, off_diag_index, diag_el=diag_el, off_diag_el=off_diag_el) ideal_distr = true_distr(A, b) # compute total variation distance tvd = TVD(ideal_distr, post_counts) # use TVD as infidelity fidelity = 1 - tvd return post_counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_input_qubits=1, max_input_qubits=3, min_clock_qubits=2, max_clock_qubits=3, max_circuits=3, num_shots=100, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None): print("HHL Benchmark Program - Qiskit") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) #counts, fidelity = analyze_and_print_result(qc, result, num_qubits, ideal_distr) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Variable for new qubit group ordering if using mid_circuit measurements mid_circuit_qubit_group = [] # If using mid_circuit measurements, set transform qubit group to true transform_qubit_group = False # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # for noiseless simulation, set noise model to be None #ex.set_noise_model(None) # temporarily fix diag and off-diag matrix elements diag_el = 0.5 off_diag_el = -0.25 # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete #for num_input_qubits in range(min_input_qubits, max_input_qubits+1): for num_input_qubits in range(min_input_qubits, max_input_qubits+1): N = 2**num_input_qubits # matrix size for num_clock_qubits in range(min_clock_qubits, max_clock_qubits+1): num_qubits = 2*num_input_qubits + num_clock_qubits + 1 # determine number of circuits to execute for this group num_circuits = max_circuits print(f"************\nExecuting {num_circuits} circuits with {num_input_qubits} input qubits and {num_clock_qubits} clock qubits") # loop over randomly generated problem instances for i in range(num_circuits): b = np.random.choice(range(N)) off_diag_index = np.random.choice(range(1,N)) A = shs.generate_sparse_H(num_input_qubits, off_diag_index, diag_el=diag_el, off_diag_el=off_diag_el) # define secret_int s_int = (2**off_diag_index)*(3**b) # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = make_circuit(A, b, num_clock_qubits) metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, s_int, shots=num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit #print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") #if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") #print("\nU Circuit ="); print(U_ if U_ != None else " ... too large!") #print("\nU^-1 Circuit ="); print(UI_ if UI_ != None else " ... too large!") #print("\nQFT Circuit ="); print(QFT_ if QFT_ != None else " ... too large!") #print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - HHL - Qiskit", transform_qubit_group = transform_qubit_group, new_qubit_group = mid_circuit_qubit_group) # if main, execute method if __name__ == '__main__': run()