repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/abbarreto/qiskit3
abbarreto
%run init.ipynb def pf(t,r): f = (1-r**t)/(1-r) - t return f from mpl_toolkits import mplot3d def pf_3d(th,ph): import matplotlib matplotlib.rcParams.update({'font.size':12}); #plt.figure(figsize = (6,4,4), dpi = 100) x = np.linspace(0, 1, 20) y = np.linspace(0, 1, 20) X, Y = np.meshgrid(x, y) Z = pf(X,Y) fig = plt.figure(); ax = plt.axes(projection="3d") ax.plot_wireframe(X, Y, Z, color='blue') ax.set_xlabel(r'$\lambda$') ax.set_ylabel(r'$t$'); ax.set_zlabel(r'$r$') ax.view_init(th, ph) fig.tight_layout() plt.show() interactive(pf_3d, th = (0,90,10), ph = (0,360,10)) import numpy as np import math from matplotlib import pyplot as plt x = np.arange(0.1,5,0.1) # d tau/dt y = np.log(np.sinh(x/2)/math.sinh(1/2)) #faz beta*hbat*omega/2 = 1 plt.plot(x,y) plt.show() x = np.arange(0,10,0.1) # x = hb*omega, kT=1 y1 = np.exp(-x) # dtau/dt = 1 y2 = np.exp(-0.5*x) # dtau/dt = 0.5 y3 = np.exp(-1.5*x) # dtau/dt = 1.5 plt.plot(x,y1,label='1') plt.plot(x,y2,label='0.5') plt.plot(x,y3,label='1.5') plt.legend() plt.show()
https://github.com/abbarreto/qiskit3
abbarreto
from qiskit.circuit import Parameter from qiskit import QuantumCircuit theta = Parameter('$\\theta$') chsh_circuits_no_meas = QuantumCircuit(2) chsh_circuits_no_meas.h(0) chsh_circuits_no_meas.cx(0, 1) chsh_circuits_no_meas.ry(theta, 0) chsh_circuits_no_meas.draw('mpl') import numpy as np number_of_phases = 21 phases = np.linspace(0, 2*np.pi, number_of_phases) # Phases need to be expressed as list of lists in order to work individual_phases = [[ph] for ph in phases] individual_phases from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" from qiskit_ibm_runtime import Estimator, Session from qiskit.quantum_info import SparsePauliOp ZZ = SparsePauliOp.from_list([("ZZ", 1)]) ZX = SparsePauliOp.from_list([("ZX", 1)]) XZ = SparsePauliOp.from_list([("XZ", 1)]) XX = SparsePauliOp.from_list([("XX", 1)]) ops = [ZZ, ZX, XZ, XX] chsh_est_sim = [] # Simulator with Session(service=service, backend=backend): estimator = Estimator() for op in ops: job = estimator.run( circuits=[chsh_circuits_no_meas]*len(individual_phases), observables=[op]*len(individual_phases), parameter_values=individual_phases) est_result = job.result() chsh_est_sim.append(est_result) # <CHSH1> = <AB> - <Ab> + <aB> + <ab> chsh1_est_sim = chsh_est_sim[0].values - chsh_est_sim[1].values + chsh_est_sim[2].values + chsh_est_sim[3].values # <CHSH2> = <AB> + <Ab> - <aB> + <ab> chsh2_est_sim = chsh_est_sim[0].values + chsh_est_sim[1].values - chsh_est_sim[2].values + chsh_est_sim[3].values import matplotlib.pyplot as plt import matplotlib.ticker as tck fig, ax = plt.subplots(figsize=(10, 6)) # results from a simulator ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Simulation') ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Simulation') # classical bound +-2 ax.axhline(y=2, color='r', linestyle='--') ax.axhline(y=-2, color='r', linestyle='--') # quantum bound, +-2√2 ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.') ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.') # set x tick labels to the unit of pi ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$')) ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5)) # set title, labels, and legend plt.title('Violation of CHSH Inequality') plt.xlabel('Theta') plt.ylabel('CHSH witness') plt.legend() from qiskit_ibm_runtime import Estimator, Session from qiskit.quantum_info import SparsePauliOp backend = service.get_backend("ibmq_belem") ZZ = SparsePauliOp.from_list([("ZZ", 1)]) ZX = SparsePauliOp.from_list([("ZX", 1)]) XZ = SparsePauliOp.from_list([("XZ", 1)]) XX = SparsePauliOp.from_list([("XX", 1)]) ops = [ZZ, ZX, XZ, XX] chsh_est_sim = [] with Session(service=service, backend=backend): estimator = Estimator() for op in ops: job = estimator.run( circuits=[chsh_circuits_no_meas]*len(individual_phases), observables=[op]*len(individual_phases), parameter_values=individual_phases) print(job.job_id()) est_result = job.result() chsh_est_sim.append(est_result) from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_quito" from qiskit_ibm_runtime import Estimator, Session from qiskit.quantum_info import SparsePauliOp #from qiskit.tools.monitor import job_monitor ZZ = SparsePauliOp.from_list([("ZZ", 1)]) ZX = SparsePauliOp.from_list([("ZX", 1)]) XZ = SparsePauliOp.from_list([("XZ", 1)]) XX = SparsePauliOp.from_list([("XX", 1)]) ops = [ZZ, ZX, XZ, XX] chsh_est_sim = [] with Session(service=service, backend=backend): estimator = Estimator() for op in ops: job = estimator.run( circuits=[chsh_circuits_no_meas]*len(individual_phases), observables=[op]*len(individual_phases), parameter_values=individual_phases) print(job.job_id()) #job_monitor(job) # deu erro est_result = job.result() chsh_est_sim.append(est_result) import matplotlib.pyplot as plt import matplotlib.ticker as tck fig, ax = plt.subplots(figsize=(10, 6)) # results from a simulator ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Simulation') ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Simulation') # classical bound +-2 ax.axhline(y=2, color='r', linestyle='--') ax.axhline(y=-2, color='r', linestyle='--') # quantum bound, +-2√2 ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.') ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.') # set x tick labels to the unit of pi ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$')) ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5)) # set title, labels, and legend plt.title('Violation of CHSH Inequality') plt.xlabel('Theta') plt.ylabel('CHSH witness') plt.legend()
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
import sympy from sympy import * import numpy as np from numpy import random import math import scipy init_printing(use_unicode=True) from matplotlib import pyplot as plt %matplotlib inline from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum import TensorProduct as tp from mpmath import factorial as fact import io import base64 #from IPython.core.display import display, HTML, clear_output from IPython import * from ipywidgets import interactive, interact, fixed, interact_manual, widgets import csv import importlib import scipy.interpolate from mpl_toolkits.mplot3d import Axes3D, proj3d from itertools import product, combinations from matplotlib.patches import FancyArrowPatch from matplotlib import cm, colors from sympy.functions.special.tensor_functions import KroneckerDelta from scipy.linalg import polar, lapack import mpmath # constantes físicas e = 1.60217662*10**-19 # C (carga elementar) k = 8.9875517923*10**9 # Nm^2/C^2 (constante de Coulomb) eps0 = 8.8541878128*10**-12 #F/m (permissividade do vácuo) mu0 = 1.25663706212*10**-6 # N/A^2 (permeabilidade do vácuo) h = 6.626069*10**-34 # Js (constante de Planck) heV = h/e # em eV hb = h/(2*math.pi) # hbar hbeV = hb/e # em eV c = 2.99792458*10**8 # m/s (velocidade da luz no vácuo) G = 6.6742*10**-11 # Nm^2/kg^2 (constante gravitacional) kB = 1.38065*10**-23 # J/K (constante de Boltzmann) me = 9.109382*10**-31 # kg (massa do elétron) mp = 1.6726219*10**-27 # kg (massa do próton) mn = 1.67492749804*10**-27 # kg (massa do nêutron) mT = 5.9722*10**24 # kg (massa da Terra) mS = 1.98847*10**30 # kg (massa do Sol) u = 1.660538921*10**-27 # kg (unidade de massa atômica) dTS = 1.496*10**11 # m (distância Terra-Sol) rT = 6.3781*10**6 # m (raio da Terra) sSB = 5.670374419*10**-8 # W⋅m−2⋅K−4 (constante de Stefan-Boltzmann) Ri = 10973734.848575922 # m^-1 (constante de Rydberg) al = (k*e**2)/(hb*c) # ~1/137.035999084 (constante de estrutura fina) a0=(hb**2)/(me*k*e**2) # ~ 0.52917710^-10 m (raio de Bohr) ge = 2 # (fator giromagnetico do eletron) gp = 5.58 # (fator giromagnetico do proton) def id(n): '''retorna a matriz identidade nxn''' id = zeros(n,n) for j in range(0,n): id[j,j] = 1 return id #id(2) def pauli(j): '''retorna as matrizes de Pauli''' if j == 1: return Matrix([[0,1],[1,0]]) elif j == 2: return Matrix([[0,-1j],[1j,0]]) elif j == 3: return Matrix([[1,0],[0,-1]]) #pauli(1), pauli(2), pauli(3) def tr(A): '''retorna o traço de uma matriz''' d = A.shape[0] tr = 0 for j in range(0,d): tr += A[j,j] return tr #tr(pauli(1)) def comm(A,B): '''retorna a função comutador''' return A*B-B*A #comm(pauli(1),pauli(2)) def acomm(A,B): '''retorna a função anti-comutador''' return A*B+B*A #acomm(pauli(1),pauli(2)) def cb(n,j): '''retorna um vetor da base padrão de C^n''' vec = zeros(n,1) vec[j] = 1 return vec #cb(2,0) def proj(psi): '''retorna o projeto no vetor psi''' d = psi.shape[0] P = zeros(d,d) for j in range(0,d): for k in range(0,d): P[j,k] = psi[j]*conjugate(psi[k]) return P #proj(cb(2,0)) def bell(j,k): if j == 0 and k == 0: return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))+tp(cb(2,1),cb(2,1))) elif j == 0 and k == 1: return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))+tp(cb(2,1),cb(2,0))) elif j == 1 and k == 0: return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))-tp(cb(2,1),cb(2,0))) elif j == 1 and k == 1: return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))-tp(cb(2,1),cb(2,1))) #bell(0,0), bell(0,1), bell(1,0), bell(1,1) def inner_product(v,w): d = len(v); ip = 0 for j in range(0,d): ip += conjugate(v[j])*w[j] return ip #a,b,c,d = symbols("a b c d"); v = [b,a]; w = [c,d]; inner_product(v,w) def norm(v): d = len(v) return sqrt(inner_product(v,v)) #v = [2,2]; norm(v) def tp(x,y): return tensorproduct(x,y) A = tp(pauli(3),pauli(1)); A
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
%run init.ipynb from qiskit import * nshots = 8192 IBMQ.load_account() provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main') device = provider.get_backend('ibmq_bogota') simulator = Aer.get_backend('qasm_simulator') from qiskit.visualization import plot_histogram from qiskit.tools.monitor import job_monitor from qiskit.quantum_info import state_fidelity
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/miamico/Quantum_Generative_Adversarial_Networks
miamico
"""Simple example on how to log scalars and images to tensorboard without tensor ops. License: Copyleft """ __author__ = "Michael Gygli" import tensorflow as tf # from StringIO import StringIO import matplotlib.pyplot as plt import numpy as np class Logger(object): """Logging in tensorboard without tensorflow ops.""" def __init__(self, log_dir): """Creates a summary writer logging to log_dir.""" self.writer = tf.summary.FileWriter(log_dir) def log_scalar(self, tag, value, step): """Log a scalar variable. Parameter ---------- tag : basestring Name of the scalar value step : int training iteration """ summary = tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=value)]) self.writer.add_summary(summary, step) def log_images(self, tag, images, step): """Logs a list of images.""" im_summaries = [] for nr, img in enumerate(images): # Write the image to a string s = StringIO() plt.imsave(s, img, format='png') # Create an Image object img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(), height=img.shape[0], width=img.shape[1]) # Create a Summary value im_summaries.append(tf.Summary.Value(tag='%s/%d' % (tag, nr), image=img_sum)) # Create and write Summary summary = tf.Summary(value=im_summaries) self.writer.add_summary(summary, step) def log_histogram(self, tag, values, step, bins=1000): """Logs the histogram of a list/vector of values.""" # Convert to a numpy array values = np.array(values) # Create histogram using numpy counts, bin_edges = np.histogram(values, bins=bins) # Fill fields of histogram proto hist = tf.HistogramProto() hist.min = float(np.min(values)) hist.max = float(np.max(values)) hist.num = int(np.prod(values.shape)) hist.sum = float(np.sum(values)) hist.sum_squares = float(np.sum(values ** 2)) # Requires equal number as bins, where the first goes from -DBL_MAX to bin_edges[1] # See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/summary.proto#L30 # Thus, we drop the start of the first bin bin_edges = bin_edges[1:] # Add bin edges and counts for edge in bin_edges: hist.bucket_limit.append(edge) for c in counts: hist.bucket.append(c) # Create and write Summary summary = tf.Summary(value=[tf.Summary.Value(tag=tag, histo=hist)]) self.writer.add_summary(summary, step) self.writer.flush()
https://github.com/miamico/Quantum_Generative_Adversarial_Networks
miamico
%%capture %pip install qiskit %pip install qiskit_ibm_provider %pip install qiskit-aer # Importing standard Qiskit libraries from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer from qiskit_ibm_provider import IBMProvider from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.circuit.library import C3XGate # Importing matplotlib import matplotlib.pyplot as plt # Importing Numpy, Cmath and math import numpy as np import os, math, cmath from numpy import pi # Other imports from IPython.display import display, Math, Latex # Specify the path to your env file env_file_path = 'config.env' # Load environment variables from the file os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#')) # Load IBM Provider API KEY IBMP_API_KEY = os.environ.get('IBMP_API_KEY') # Loading your IBM Quantum account(s) IBMProvider.save_account(IBMP_API_KEY, overwrite=True) # Run the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') qc_b1 = QuantumCircuit(2, 2) qc_b1.h(0) qc_b1.cx(0, 1) qc_b1.draw(output='mpl', style="iqp") sv = backend.run(qc_b1).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ") qc_b2 = QuantumCircuit(2, 2) qc_b2.x(0) qc_b2.h(0) qc_b2.cx(0, 1) qc_b2.draw(output='mpl', style="iqp") sv = backend.run(qc_b2).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ") qc_b2 = QuantumCircuit(2, 2) qc_b2.h(0) qc_b2.cx(0, 1) qc_b2.z(0) qc_b2.draw(output='mpl', style="iqp") sv = backend.run(qc_b2).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ") qc_b3 = QuantumCircuit(2, 2) qc_b3.x(1) qc_b3.h(0) qc_b3.cx(0, 1) qc_b3.draw(output='mpl', style="iqp") sv = backend.run(qc_b3).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ") qc_b3 = QuantumCircuit(2, 2) qc_b3.h(0) qc_b3.cx(0, 1) qc_b3.x(0) qc_b3.draw(output='mpl', style="iqp") sv = backend.run(qc_b3).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ") qc_b4 = QuantumCircuit(2, 2) qc_b4.x(0) qc_b4.h(0) qc_b4.x(1) qc_b4.cx(0, 1) qc_b4.draw(output='mpl', style="iqp") sv = backend.run(qc_b4).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ") qc_b4 = QuantumCircuit(2, 2) qc_b4.h(0) qc_b4.cx(0, 1) qc_b4.x(0) qc_b4.z(1) qc_b4.draw(output='mpl', style="iqp") sv = backend.run(qc_b4).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ") def sv_latex_from_qc(qc, backend): sv = backend.run(qc).result().get_statevector() return sv.draw(output='latex') qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(1) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(1) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(1) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(3) sv_latex_from_qc(qc_ej2, backend) def circuit_adder (num): if num<1 or num>8: raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricción sería directo. # Definición del circuito base que vamos a construir qreg_q = QuantumRegister(4, 'q') creg_c = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qreg_q, creg_c) qbit_position = 0 for element in reversed(np.binary_repr(num)): if (element=='1'): circuit.barrier() match qbit_position: case 0: # +1 circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]]) circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) circuit.x(qreg_q[0]) case 1: # +2 circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3]) circuit.cx(qreg_q[1], qreg_q[2]) circuit.x(qreg_q[1]) case 2: # +4 circuit.cx(qreg_q[2], qreg_q[3]) circuit.x(qreg_q[2]) case 3: # +8 circuit.x(qreg_q[3]) qbit_position+=1 return circuit add_3 = circuit_adder(3) add_3.draw(output='mpl', style="iqp") qc_test_2 = QuantumCircuit(4, 4) qc_test_2.x(1) qc_test_2_plus_3 = qc_test_2.compose(add_3) qc_test_2_plus_3.draw(output='mpl', style="iqp") sv_latex_from_qc(qc_test_2_plus_3, backend) qc_test_7 = QuantumCircuit(4, 4) qc_test_7.x(0) qc_test_7.x(1) qc_test_7.x(2) qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8)) sv_latex_from_qc(qc_test_7_plus_8, backend) #qc_test_7_plus_8.draw() theta = 6.544985 phi = 2.338741 lmbda = 0 alice_1 = 0 alice_2 = 1 bob_1 = 2 qr_alice = QuantumRegister(2, 'Alice') qr_bob = QuantumRegister(1, 'Bob') cr = ClassicalRegister(3, 'c') qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr) qc_ej3.barrier(label='1') qc_ej3.u(theta, phi, lmbda, alice_1); qc_ej3.barrier(label='2') qc_ej3.h(alice_2) qc_ej3.cx(alice_2, bob_1); qc_ej3.barrier(label='3') qc_ej3.cx(alice_1, alice_2) qc_ej3.h(alice_1); qc_ej3.barrier(label='4') qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]); qc_ej3.barrier(label='5') qc_ej3.x(bob_1).c_if(alice_2, 1) qc_ej3.z(bob_1).c_if(alice_1, 1) qc_ej3.measure(bob_1, bob_1); qc_ej3.draw(output='mpl', style="iqp") result = backend.run(qc_ej3, shots=1024).result() counts = result.get_counts() plot_histogram(counts) sv_0 = np.array([1, 0]) sv_1 = np.array([0, 1]) def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/√2'}, tolerance=1e-10): """ Check if the given numerical value corresponds to a symbolic constant within a specified tolerance. Parameters: - value (float): The numerical value to check. - symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations. Defaults to {1/np.sqrt(2): '1/√2'}. - tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10. Returns: str or float: If a match is found, returns the symbolic representation as a string (prefixed with '-' if the value is negative); otherwise, returns the original value. """ for constant, symbol in symbolic_constants.items(): if np.isclose(abs(value), constant, atol=tolerance): return symbol if value >= 0 else '-' + symbol return value def array_to_dirac_notation(array, tolerance=1e-10): """ Convert a complex-valued array representing a quantum state in superposition to Dirac notation. Parameters: - array (numpy.ndarray): The complex-valued array representing the quantum state in superposition. - tolerance (float): Tolerance for considering amplitudes as negligible. Returns: str: The Dirac notation representation of the quantum state. """ # Ensure the statevector is normalized array = array / np.linalg.norm(array) # Get the number of qubits num_qubits = int(np.log2(len(array))) # Find indices where amplitude is not negligible non_zero_indices = np.where(np.abs(array) > tolerance)[0] # Generate Dirac notation terms terms = [ (find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b")) for i in non_zero_indices ] # Format Dirac notation dirac_notation = " + ".join([f"{amplitude}|{binary_rep}⟩" for amplitude, binary_rep in terms]) return dirac_notation def array_to_matrix_representation(array): """ Convert a one-dimensional array to a column matrix representation. Parameters: - array (numpy.ndarray): The one-dimensional array to be converted. Returns: numpy.ndarray: The column matrix representation of the input array. """ # Replace symbolic constants with their representations matrix_representation = np.array([find_symbolic_representation(value) or value for value in array]) # Return the column matrix representation return matrix_representation.reshape((len(matrix_representation), 1)) def array_to_dirac_and_matrix_latex(array): """ Generate LaTeX code for displaying both the matrix representation and Dirac notation of a quantum state. Parameters: - array (numpy.ndarray): The complex-valued array representing the quantum state. Returns: Latex: A Latex object containing LaTeX code for displaying both representations. """ matrix_representation = array_to_matrix_representation(array) latex = "Matrix representation\n\\begin{bmatrix}\n" + \ "\\\\\n".join(map(str, matrix_representation.flatten())) + \ "\n\\end{bmatrix}\n" latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}' return Latex(latex) sv_b1 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b1) sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b1) sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b1) sv_b2 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b3 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = np.kron(sv_0, sv_1) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b4 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = np.kron(sv_0, sv_1) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b4)
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, QuantumRegister from qiskit.extensions import HamiltonianGate from qiskit.circuit.library.standard_gates import CRYGate def quantum_fourier_transform(t, vis=False): reg = QuantumRegister(t, name='c') circ = QuantumCircuit(reg, name='$Q.F.T.$') for i in range(t // 2): circ.swap(i, t - 1 - i) for i in range(t): circ.h(i) for j in range(i + 1, t): circ.cu1(np.pi / (2 ** (j - i)), i, j) if vis: circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\ .suptitle("Quantum Fourier Transform", fontsize=16) return circ.to_gate() def quantum_phase_estimation(n, t, unitary, vis=False): reg_b = QuantumRegister(n, name='b') reg_c = QuantumRegister(t, name='c') circ = QuantumCircuit(reg_b, reg_c, name='$Q.P.E.$') circ.h(range(n, n + t)) for i in range(t): circ.append(unitary.control(1).power(2**i), [n + i] + list(range(n))) circ.append(quantum_fourier_transform(t, vis=vis).inverse(), range(n, n + t)) if vis: circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\ .suptitle("Quantum Phase Estimation", fontsize=16) return circ.to_gate() def subroutine_a(t, m, l, k, t0, vis=False): reg_c = QuantumRegister(t, name='c') reg_m = QuantumRegister(m, name='m') reg_l = QuantumRegister(l, name='l') circ = QuantumCircuit(reg_c, reg_m, reg_l, name='$Sub_A$') vis_temp = vis for i in range(t): gate = subroutine_c(m, t - i, l - k, t0, vis=vis_temp) circ.append(gate.control(2), [reg_l[k], reg_c[i]] + [reg_m[j] for j in range(m)]) vis_temp = False if vis: circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\ .suptitle("Subroutine A", fontsize=16) return circ.to_gate() def subroutine_b(t, m, l, t0, vis=False): reg_c = QuantumRegister(t, name='c') reg_m = QuantumRegister(m, name='m') reg_l = QuantumRegister(l, name='l') circ = QuantumCircuit(reg_c, reg_m, reg_l, name='$Sub_B$') vis_temp = vis for i in range(l): gate = subroutine_a(t, m, l, i, t0, vis=vis_temp) circ.append(gate, range(t + m + l)) vis_temp = False if vis: circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\ .suptitle("Subroutine B", fontsize=16) return circ.to_gate() def subroutine_c(m, u, v, t0, vis=False): reg = QuantumRegister(m, name='m') circ = QuantumCircuit(reg, name='$Sub_C$') t = -t0 / (2 ** (u + v - m)) for i in range(m): circ.rz(t / (2 ** (i + 1)), i) if vis: circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\ .suptitle("Subroutine C", fontsize=16) return circ.to_gate() def hhl_forward_ckt(n, t, m, l, A, t0, vis=False): reg_b = QuantumRegister(n, name='b') reg_c = QuantumRegister(t, name='c') reg_m = QuantumRegister(m, name='m') reg_l = QuantumRegister(l, name='l') temp = QuantumCircuit(reg_b, name='$U$') temp.append(HamiltonianGate(A, t0 / (2 ** t)), reg_b) circ = QuantumCircuit(reg_b, reg_c, reg_m, reg_l, name='$Fwd$') circ.append(quantum_phase_estimation(n, t, temp.to_gate(), vis=vis), range(n + t)) circ.h(reg_m) circ.h(reg_l) for i in range(m): circ.rz(t0 / (2 ** (m - i)), reg_m[i]) circ.append(subroutine_b(t, m, l, t0, vis=vis), range(n, n + t + m + l)) if vis: circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\ .suptitle('HHL Forward Computation', fontsize=16) return circ.to_gate() def hhl_circuit(A, t0, theta, size, vis=False): n, t, m, l = size reg_b = QuantumRegister(n, name='b') reg_c = QuantumRegister(t, name='c') reg_m = QuantumRegister(m, name='m') reg_l = QuantumRegister(l, name='l') ancil = QuantumRegister(1, name='anc') circ = QuantumCircuit(reg_b, reg_c, reg_m, reg_l, ancil, name='$HHL$') circ.append(hhl_forward_ckt(n, t, m, l, A, t0, vis=vis), range(sum(size))) for i in range(l): circ.append(CRYGate(theta).power(2**i), [reg_l[i], ancil]) circ.append(hhl_forward_ckt(n, t, m, l, A, t0).inverse(), range(sum(size))) if vis: circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\ .suptitle('HHL Circuit', fontsize=16) return circ def ad_hoc_hhl(A, t0, r): reg_b = QuantumRegister(2) reg_c = QuantumRegister(4) ancil = QuantumRegister(1) circ = QuantumCircuit(reg_b, reg_c, ancil) circ.append(quantum_phase_estimation(2, 4, HamiltonianGate(A, t0/16)), range(6)) circ.swap(reg_c[1], reg_c[3]) for i in range(4): circ.cry(np.pi * (2 ** (4-i-r)), reg_c[i], ancil[0]) circ.barrier() circ.swap(reg_c[1], reg_c[3]) circ.append(quantum_phase_estimation(2, 4, HamiltonianGate(A, t0 / 16)).inverse(), range(6)) return circ if __name__ == '__main__': size = [3, 4, 4, 4] theta = np.pi/12 t0 = 2 * np.pi A = [[0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0]] circ = hhl_circuit(A, t0, theta, size, vis=True) plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np import hhl_components as cmp import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit import Aer, execute from qiskit.visualization import plot_histogram # Initialize parameters t0 = 2 * np.pi r = 6 A = [[3.75, 2.25, 1.25, -0.75], [2.25, 3.75, 0.75, -1.25], [1.25, 0.75, 3.75, -2.25], [-0.75, -1.25, -2.25, 3.75]] b = [0.5, 0.5, 0.5, 0.5] x = [-0.0312, 0.2188, 0.3437, 0.4062] p = [i ** 2 for i in x] basis = ['00', '01', '10', '11'] # Build circuit circ = QuantumCircuit(7, 3) circ.initialize(b, range(2)) circ.append(cmp.ad_hoc_hhl(A, t0, r), range(7)) circ.measure(6, 2) circ.measure([0, 1], [0, 1]) # Get simulators qasm = Aer.get_backend('qasm_simulator') svsm = Aer.get_backend('statevector_simulator') # QASM simulation job = execute(circ, qasm, shots=1024) counts = job.result().get_counts() measured_data = {} expected_data = {basis[i]: np.floor(p[i] * 1024) for i in range(4)} for key in counts.keys(): if key[0] == '1': measured_data[key[1::]] = counts[key] plot_histogram([expected_data, measured_data], title='HHL QASM Simulation', legend=['expected', 'measured']) plt.subplots_adjust(left=0.15, right=0.72, top=0.9, bottom=0.15) plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, Aer, execute from qiskit.circuit import ParameterVector from qiskit.extensions import HamiltonianGate from qiskit.visualization import plot_histogram from qiskit.aqua.components.optimizers import COBYLA class QAOA: def __init__(self, clauses, p, num_shots=1024): # Assign weights and clauses if isinstance(clauses, dict): self.clauses = list(clauses.values()) self.weights = list(clauses.keys()) else: self.clauses = clauses self.weights = [1] * len(clauses) # Assign size parameters self.m = len(self.clauses) self.n = len(self.clauses[0]) self.p = p # Assign auxiliary parameters self.num_shots = num_shots self.error = -1 # Create variational parameters self.gamma = ParameterVector('gamma', length=p) self.beta = ParameterVector('beta', length=p) self.gamma_val = list(np.random.rand(p)) self.beta_val = list(np.random.rand(p)) # Create hamiltonians and variational circuit self.C = np.diag([self.cost(z) for z in range(2 ** self.n)]) self.varckt = self.build_varckt() self.optimize() def cost(self, z): # Convert to bitstr if not isinstance(z, str): z = format(z, '0' + str(self.n) + 'b') z: str # Evaluate C(z) cost = 0 for i in range(self.m): s = True for j in range(self.n): if self.clauses[i][j] != 'X' and self.clauses[i][j] != z[j]: s = False break if s: cost += self.weights[i] # Return output return cost def expectation(self, beta=None, gamma=None): # Resolve default values if beta is None: beta = self.beta_val if gamma is None: gamma = self.gamma_val # Evaluate expectation value circ = self.varckt.bind_parameters({self.beta: beta, self.gamma: gamma}) simulator = Aer.get_backend('qasm_simulator') result = execute(circ, simulator, shots=self.num_shots).result() counts = result.get_counts() expval = sum([self.cost(z) * counts[z] / self.num_shots for z in counts.keys()]) return expval def optimize(self): # Define objective function def objfunc(params): return -self.expectation(beta=params[0:self.p], gamma=params[self.p:2*self.p]) # Optimize parameters optimizer = COBYLA(maxiter=1000, tol=0.0001) params = self.beta_val + self.gamma_val ret = optimizer.optimize(num_vars=2*self.p, objective_function=objfunc, initial_point=params) self.beta_val = ret[0][0:self.p] self.gamma_val = ret[0][self.p:2*self.p] self.error = ret[1] return def build_varckt(self): # Build variational circuit circ = QuantumCircuit(self.n) circ.h(range(self.n)) for i in range(self.p): eC = QuantumCircuit(self.n, name='$U(C,\\gamma_' + str(i + 1) + ')$') eC.append(HamiltonianGate(self.C, self.gamma[i]), range(self.n)) eB = QuantumCircuit(self.n, name='$U(B,\\beta_' + str(i + 1) + ')$') eB.rx(2*self.beta[i], range(self.n)) circ.append(eC.to_gate(), range(self.n)) circ.append(eB.to_gate(), range(self.n)) circ.measure_all() return circ def sample(self, shots=None, vis=False): # Resolve defaults if shots is None: shots = self.num_shots # Sample maximum cost value circ = self.varckt.bind_parameters({self.beta: self.beta_val, self.gamma: self.gamma_val}) simulator = Aer.get_backend('qasm_simulator') result = execute(circ, simulator, shots=shots).result() counts = result.get_counts() if vis: plot_histogram(counts, title='Sample Output', bar_labels=False) plt.subplots_adjust(left=0.15, right=0.85, top=0.9, bottom=0.15) return max(counts, key=counts.get) if __name__ == '__main__': qaoa = QAOA(['10XX0', '11XXX'], 3) print('Maximized Expectation Value: ' + str(qaoa.expectation())) print('Sampled Output: ' + qaoa.sample()) qaoa.varckt.draw('mpl').suptitle('Variational Circuit', fontsize=16) plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit.quantum_info import Operator from qiskit.circuit.library.standard_gates import XGate, YGate, ZGate class FiveQubitCode: def __init__(self): # Initialize Registers self.code = QuantumRegister(5, name="code") self.syndrm = QuantumRegister(4, name="syndrome") # Build Circuit Components self.encoder_ckt = self.build_encoder() self.syndrome_ckt = self.build_syndrome() self.correction_ckt = self.build_correction() self.decoder_ckt = self.encoder_ckt.mirror() # Build Noisy Channel self.noise_ckt = QuantumCircuit(self.code, self.syndrm) for i in range(5): self.noise_ckt.unitary(Operator(np.eye(2)), [self.code[i]], label='noise') # Compose Full Circuit circ = QuantumCircuit(self.code, self.syndrm) circ.barrier() self.circuit = self.encoder_ckt + circ + self.noise_ckt + circ + self.syndrome_ckt self.circuit = self.circuit + circ + self.correction_ckt + circ + self.decoder_ckt def build_encoder(self): # Build Encoder Circuit circ = QuantumCircuit(self.code, self.syndrm, name="Encoder Circuit") circ.z(self.code[4]) circ.h(self.code[4]) circ.z(self.code[4]) circ.cx(self.code[4], self.code[3]) circ.h(self.code[4]) circ.h(self.code[3]) circ.cx(self.code[4], self.code[2]) circ.cx(self.code[3], self.code[2]) circ.h(self.code[2]) circ.cx(self.code[4], self.code[1]) circ.cx(self.code[2], self.code[1]) circ.h(self.code[1]) circ.h(self.code[4]) circ.cx(self.code[4], self.code[0]) circ.cx(self.code[3], self.code[0]) circ.cx(self.code[2], self.code[0]) circ.h(self.code[3]) circ.h(self.code[4]) return circ def build_syndrome(self): # Build Syndrome Circuit circ = QuantumCircuit(self.code, self.syndrm, name="Syndrome Circuit") circ.h(self.syndrm) circ.barrier() circ.cz(self.syndrm[0], self.code[4]) circ.cx(self.syndrm[0], self.code[3]) circ.cx(self.syndrm[0], self.code[2]) circ.cz(self.syndrm[0], self.code[1]) circ.cx(self.syndrm[1], self.code[4]) circ.cx(self.syndrm[1], self.code[3]) circ.cz(self.syndrm[1], self.code[2]) circ.cz(self.syndrm[1], self.code[0]) circ.cx(self.syndrm[2], self.code[4]) circ.cz(self.syndrm[2], self.code[3]) circ.cz(self.syndrm[2], self.code[1]) circ.cx(self.syndrm[2], self.code[0]) circ.cz(self.syndrm[3], self.code[4]) circ.cz(self.syndrm[3], self.code[2]) circ.cx(self.syndrm[3], self.code[1]) circ.cx(self.syndrm[3], self.code[0]) circ.barrier() circ.h(self.syndrm) return circ def build_correction(self): # Build Correction Circuit circ = QuantumCircuit(self.code, self.syndrm) circ.append(XGate().control(4, ctrl_state='0010'), [self.syndrm[i] for i in range(4)] + [self.code[0]]) circ.append(YGate().control(4, ctrl_state='1110'), [self.syndrm[i] for i in range(4)] + [self.code[0]]) circ.append(ZGate().control(4, ctrl_state='1100'), [self.syndrm[i] for i in range(4)] + [self.code[0]]) circ.append(XGate().control(4, ctrl_state='0101'), [self.syndrm[i] for i in range(4)] + [self.code[1]]) circ.append(YGate().control(4, ctrl_state='1101'), [self.syndrm[i] for i in range(4)] + [self.code[1]]) circ.append(ZGate().control(4, ctrl_state='1000'), [self.syndrm[i] for i in range(4)] + [self.code[1]]) circ.append(XGate().control(4, ctrl_state='1010'), [self.syndrm[i] for i in range(4)] + [self.code[2]]) circ.append(YGate().control(4, ctrl_state='1011'), [self.syndrm[i] for i in range(4)] + [self.code[2]]) circ.append(ZGate().control(4, ctrl_state='0001'), [self.syndrm[i] for i in range(4)] + [self.code[2]]) circ.append(XGate().control(4, ctrl_state='0100'), [self.syndrm[i] for i in range(4)] + [self.code[3]]) circ.append(YGate().control(4, ctrl_state='0111'), [self.syndrm[i] for i in range(4)] + [self.code[3]]) circ.append(ZGate().control(4, ctrl_state='0011'), [self.syndrm[i] for i in range(4)] + [self.code[3]]) circ.append(XGate().control(4, ctrl_state='1001'), [self.syndrm[i] for i in range(4)] + [self.code[4]]) circ.append(YGate().control(4, ctrl_state='1111'), [self.syndrm[i] for i in range(4)] + [self.code[4]]) circ.append(ZGate().control(4, ctrl_state='0110'), [self.syndrm[i] for i in range(4)] + [self.code[4]]) return circ def visualize(self): # Draw Circuits self.encoder_ckt.draw('mpl', reverse_bits=True).suptitle('Encoder Circuit', fontsize=16) self.syndrome_ckt.draw('mpl', reverse_bits=True).suptitle('Syndrome Circuit', fontsize=16) self.correction_ckt.draw('mpl', reverse_bits=True).suptitle('Error Correction', fontsize=16) self.decoder_ckt.draw('mpl', reverse_bits=True).suptitle('Decoder Circuit', fontsize=16) self.circuit.draw('mpl', reverse_bits=True, style={'fontsize': 4}) \ .suptitle('Five Qubit Error Correction', fontsize=16) plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
"""Performance Analysis of 5 Qubit Code under Depolarizing Error""" import noise import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, ClassicalRegister from qiskit import Aer, execute from qiskit.visualization import plot_histogram, plot_bloch_vector from five_qubit_code import FiveQubitCode # Parameters error_prob = 0.05 theta = np.pi / 3 phi = np.pi / 4 # Initialize error correcting circuit, backend and noise model qasm = Aer.get_backend('qasm_simulator') noise_depol = noise.depolarizing_noise(error_prob) qecc = FiveQubitCode() # Visualize parameters print(noise_depol) qecc.visualize() # Define test circuit and input state output = ClassicalRegister(5) circ = QuantumCircuit(qecc.code, qecc.syndrm, output) circ.ry(theta, qecc.code[4]) circ.rz(phi, qecc.code[4]) plot_bloch_vector([np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)], title="Input State") plt.show() # Define final measurement circuit meas = QuantumCircuit(qecc.code, qecc.syndrm, output) meas.measure(qecc.code, output) # QASM simulation w/o error correction job = execute(circ + qecc.encoder_ckt + qecc.noise_ckt + qecc.decoder_ckt + meas, backend=qasm, noise_model=noise_depol, basis_gates=noise_depol.basis_gates) counts_noisy = job.result().get_counts() # QASM simulation with error correction job = execute(circ + qecc.circuit + meas, backend=qasm, noise_model=noise_depol, basis_gates=noise_depol.basis_gates) counts_corrected = job.result().get_counts() # Plot QASM simulation data plot_histogram([counts_noisy, counts_corrected], title='5-Qubit Error Correction - Depolarizing Noise $(P_{error} = ' + str(error_prob) + ')$', legend=['w/o code', 'with code'], figsize=(12, 9), bar_labels=False) plt.subplots_adjust(left=0.15, right=0.72, top=0.9, bottom=0.20) plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit.quantum_info import Operator from qiskit.circuit.library.standard_gates import XGate class ThreeQubitCode: def __init__(self): # Initialize Registers self.code = QuantumRegister(3, name="code") self.syndrm = QuantumRegister(2, name="syndrome") # Build Circuit Components self.encoder_ckt = self.build_encoder() self.syndrome_ckt = self.build_syndrome() self.correction_ckt = self.build_correction() # Build Noisy Channel self.noise_ckt = QuantumCircuit(self.code, self.syndrm) self.noise_ckt.unitary(Operator(np.eye(2)), [self.code[0]], label='noise') self.noise_ckt.unitary(Operator(np.eye(2)), [self.code[1]], label='noise') self.noise_ckt.unitary(Operator(np.eye(2)), [self.code[2]], label='noise') # Compose Full Circuit circ = QuantumCircuit(self.code, self.syndrm) circ.barrier() self.circuit = self.encoder_ckt + circ + self.noise_ckt + circ + self.syndrome_ckt + circ + self.correction_ckt def build_encoder(self): # Build Encoder Circuit circ = QuantumCircuit(self.code, self.syndrm, name="Encoder Circuit") circ.cx(self.code[0], self.code[1]) circ.cx(self.code[0], self.code[2]) return circ def build_syndrome(self): # Build Syndrome Circuit circ = QuantumCircuit(self.code, self.syndrm, name="Syndrome Circuit") circ.h(self.syndrm) circ.barrier() circ.cz(self.syndrm[1], self.code[2]) circ.cz(self.syndrm[1], self.code[1]) circ.cz(self.syndrm[0], self.code[1]) circ.cz(self.syndrm[0], self.code[0]) circ.barrier() circ.h(self.syndrm) return circ def build_correction(self): # Build Correction Circuit circ = QuantumCircuit(self.code, self.syndrm) circ.append(XGate().control(2, ctrl_state=2), [self.syndrm[0], self.syndrm[1], self.code[2]]) circ.append(XGate().control(2, ctrl_state=3), [self.syndrm[0], self.syndrm[1], self.code[1]]) circ.append(XGate().control(2, ctrl_state=1), [self.syndrm[0], self.syndrm[1], self.code[0]]) return circ def visualize(self): # Draw Circuits self.encoder_ckt.draw('mpl', reverse_bits=True).suptitle('Encoder Circuit', fontsize=16) self.syndrome_ckt.draw('mpl', reverse_bits=True).suptitle('Syndrome Circuit', fontsize=16) self.correction_ckt.draw('mpl', reverse_bits=True).suptitle('Error Correction', fontsize=16) self.circuit.draw('mpl', reverse_bits=True).suptitle('Three Qubit Error Correction', fontsize=16) plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
"""Performance Analysis of 3 Qubit Code under Bit Flip Error""" import noise import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, ClassicalRegister from qiskit import Aer, execute from qiskit.quantum_info import partial_trace, state_fidelity from qiskit.quantum_info import DensityMatrix, Kraus from qiskit.visualization import plot_histogram, plot_bloch_vector from three_qubit_code import ThreeQubitCode # Parameters error_prob = 0.05 theta = np.pi/3 phi = np.pi/4 # Initialize error correcting circuit, backend and noise model qasm = Aer.get_backend('qasm_simulator') svsm = Aer.get_backend('statevector_simulator') unit = Aer.get_backend('unitary_simulator') noise_model = noise.bit_flip_noise(error_prob) qecc = ThreeQubitCode() # Visualize parameters print(noise_model) qecc.visualize() # Define test circuit and input state output = ClassicalRegister(3) circ = QuantumCircuit(qecc.code, qecc.syndrm, output) circ.ry(theta, qecc.code[0]) circ.rz(phi, qecc.code[0]) plot_bloch_vector([np.sin(theta)*np.cos(phi), np.sin(theta)*np.sin(phi), np.cos(theta)], title="Input State") plt.show() # Define final measurement circuit meas = QuantumCircuit(qecc.code, qecc.syndrm, output) meas.measure(qecc.code, output) # QASM simulation w/o error correction job = execute(circ + qecc.encoder_ckt + qecc.noise_ckt + meas, backend=qasm, noise_model=noise_model, basis_gates=noise_model.basis_gates) counts_noisy = job.result().get_counts() # QASM simulation with error correction job = execute(circ + qecc.circuit + meas, backend=qasm, noise_model=noise_model, basis_gates=noise_model.basis_gates) counts_corrected = job.result().get_counts() # Plot QASM simulation data plot_histogram([counts_noisy, counts_corrected], title='3-Qubit Error Correction $(P_{error} = ' + str(error_prob) + ')$', legend=['w/o code', 'with code'], figsize=(12, 9), bar_labels=False) plt.subplots_adjust(left=0.15, right=0.72, top=0.9, bottom=0.15) plt.show() # Initialize fidelity simulation objects job = execute(circ + qecc.encoder_ckt, backend=svsm) init_state = DensityMatrix(job.result().get_statevector()) job = execute(qecc.syndrome_ckt, backend=unit) syndrome_op = Kraus(job.result().get_unitary()) # Initialize fidelity simulation parameters p_error = [0.05 * i for i in range(11)] f1 = [] f2 = [] # Evolve initial state for p in p_error: # Build noise channel bit_flip_channel = Kraus([[[0, np.sqrt(p)], [np.sqrt(p), 0]], [[np.sqrt(1-p), 0], [0, np.sqrt(1-p)]]]) bit_flip_channel = bit_flip_channel.tensor(bit_flip_channel).tensor(bit_flip_channel) bit_flip_channel = bit_flip_channel.expand(Kraus(np.eye(2))).expand(Kraus(np.eye(2))) # Apply channels corrupted_state = DensityMatrix(init_state.evolve(bit_flip_channel)) corrected_state = DensityMatrix(corrupted_state.evolve(syndrome_op)) corrected_state = DensityMatrix(corrected_state.evolve(qecc.correction_ckt)) # Trace out syndrome ini = DensityMatrix(partial_trace(init_state, [3, 4])) corrupted_state = DensityMatrix(partial_trace(corrupted_state, [3, 4])) corrected_state = DensityMatrix(partial_trace(corrected_state, [3, 4])) # Record results f1.append(state_fidelity(ini, corrupted_state)) f2.append(state_fidelity(ini, corrected_state)) # Plot fidelity fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111) ax.plot(p_error, f1, label='w/o code') ax.plot(p_error, f2, label='with code') ax.set_title("$Fidelity$ vs $P_{error}$") ax.set_xlabel('$P_{error}$') ax.set_ylabel('$Fidelity$') ax.set_ylabel('$Fidelity$') ax.legend() plt.xlim(0, 0.5) plt.ylim(0, 1) plt.grid() plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import random import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, Aer, execute from qiskit.circuit import ParameterVector from qiskit.quantum_info import state_fidelity from qiskit.quantum_info import Statevector, DensityMatrix, Operator class Compressor: def __init__(self, ensemble, block_size): # Initialize parameters self.ensemble = ensemble self.n = block_size self.m = block_size self.theta = ParameterVector('theta', length=block_size) self.phi = ParameterVector('phi', length=block_size) # Initialize density matrix properties self.rho = np.zeros((2, 2)) self.s0 = np.array([0, 0]) self.s1 = np.array([0, 0]) self.entropy = 1 self.initialize_density_matrix() self.noise = ParameterVector('noise', length=self.m) # Build subcircuits self.ns_ckt = QuantumCircuit(self.n, name='$Noise$') self.source = QuantumCircuit(self.n, name='$Src$') self.tx_ckt = QuantumCircuit(self.n, name='$Tx$') self.rx_ckt = QuantumCircuit(self.n, name='$Rx$') self.initialize_subcircuits() def initialize_density_matrix(self): # Evaluate density matrix and list of states for key in self.ensemble.keys(): theta = key[0] phi = key[1] state = np.array([np.cos(theta/2), np.sin(theta/2) * np.exp(phi*complex(1, 0))]) self.rho = self.rho + self.ensemble[key] * np.outer(state, state) # Evaluate spectrum self.rho: np.ndarray v, w = np.linalg.eig(self.rho) s0 = Statevector(w[:, 0]) s1 = Statevector(w[:, 1]) self.rho = DensityMatrix(self.rho) # Evaluate entropy and typical basis if state_fidelity(s0, self.rho) > state_fidelity(s1, self.rho): self.s0 = s0 self.s1 = s1 else: self.s0 = s1 self.s1 = s0 self.entropy = -np.real(sum([p * np.log2(p) for p in v])) self.m = int(np.ceil(self.entropy * self.n)) def initialize_subcircuits(self): # Build source self.source.reset(range(self.n)) for i in range(self.n): self.source.ry(self.theta[i], i) self.source.rz(self.phi[i], i) # Build typical basis change operator U = Operator(np.column_stack((self.s0.data, self.s1.data))).adjoint() for i in range(self.n): self.tx_ckt.unitary(U, [i], label='$Basis$') # Build permutation operator data = list(range(2 ** self.n)) data = [("{0:0" + str(self.n) + "b}").format(i) for i in data] data = sorted(data, key=lambda x: x.count('1')) data = [int(x, 2) for x in data] V = np.zeros((2 ** self.n, 2 ** self.n)) for i in range(2 ** self.n): V[i, data[i]] = 1 self.tx_ckt.unitary(V, list(range(self.n)), label='$Perm$') # Build bit flip noisy channel for i in range(self.m): self.ns_ckt.u3(self.noise[i], 0, self.noise[i], i) # Build receiver self.rx_ckt.reset(range(self.m, self.n)) self.rx_ckt.append(self.tx_ckt.to_gate().inverse(), list(range(self.n))) def simulate(self, num_shots=1, bit_flip_prob=0.0): # Get backend and circuit simulator = Aer.get_backend('statevector_simulator') circ = self.source + self.tx_ckt + self.ns_ckt + self.rx_ckt fid_list = [] for i in range(num_shots): # Acquire parameters states = random.choices(list(self.ensemble.keys()), self.ensemble.values(), k=self.n) noise = random.choices([0, np.pi], [1-bit_flip_prob, bit_flip_prob], k=self.m) theta = [p[0] for p in states] phi = [p[1] for p in states] circ1 = self.source.bind_parameters({self.theta: theta, self.phi: phi}) circ2 = circ.bind_parameters({self.theta: theta, self.phi: phi, self.noise: noise}) # Simulate ini_state = execute(circ1, simulator).result().get_statevector() fin_state = execute(circ2, simulator).result().get_statevector() fid_list.append(state_fidelity(ini_state, fin_state)) # Return results return fid_list def visualize(self): # Draw components self.source.draw('mpl', reverse_bits=True).suptitle('Source Circuit') self.tx_ckt.draw('mpl', reverse_bits=True).suptitle('Tx Circuit') self.rx_ckt.draw('mpl', reverse_bits=True).suptitle('Rx Circuit') (self.source + self.tx_ckt + self.ns_ckt + self.rx_ckt).draw('mpl', reverse_bits=True).suptitle('Full Circuit') plt.show() if __name__ == '__main__': ensemble = {(0, 0): 0.5, (np.pi/2, 0): 0.5} com = Compressor(ensemble, 3) com.visualize() fid1 = com.simulate(num_shots=100) fid2 = com.simulate(num_shots=100, bit_flip_prob=0.1) print('Noiseless System Fidelity: ', np.mean(fid1)) print('Noisy (p = 0.1) System Fidelity: ', np.mean(fid2))
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.circuit import Gate # Define no. of message qubits n = 10 # Alice's end alice_prepare = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) alice_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) circ = QuantumCircuit(n, n) # Preparation circ.reset(range(n)) for i in range(n): if alice_prepare[i] == 1: circ.x(i) circ.barrier() # Hadamard Transform for i in range(n): if alice_hadamard[i] == 1: circ.h(i) circ.barrier() # Eavesdropper circ.append(Gate(name="$Eve$", num_qubits=n, params=[]), range(n)) # Bob's end bob_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) circ.barrier() # Hadamard Transform for i in range(n): if bob_hadamard[i] == 1: circ.h(i) circ.barrier() # Measurement circ.measure(range(n), range(n)) circ.draw('mpl', reverse_bits=True, scale=0.45) # Alice's end alice_prepare = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) alice_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) circ = QuantumCircuit(n, n) # Preparation circ.reset(range(n)) for i in range(n): if alice_prepare[i] == 1: circ.x(i) circ.barrier() # Hadamard Transform for i in range(n): if alice_hadamard[i] == 1: circ.h(i) circ.barrier() # Bob's end bob_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) # Hadamard Transform for i in range(n): if bob_hadamard[i] == 1: circ.h(i) circ.barrier() # Measurement circ.measure(range(n), range(n)) circ.draw('mpl', reverse_bits=True, scale=0.45) # Execute Circuit backend = Aer.get_backend('qasm_simulator') job = execute(circ, backend, shots=1) counts = job.result().get_counts(circ) bob_measure = list(counts.keys())[0][::-1] # Print Data print("".join(["Alice Prepared: ","".join([str(i) for i in alice_prepare])])) print("".join(["Alice H Transforms: ","".join([str(i) for i in alice_hadamard])])) print("".join(["Bob H Transforms: ","".join([str(i) for i in bob_hadamard])])) print("".join(["Bob Measurements: ", bob_measure])) # Extract Key alice_key = [] bob_key = [] for i in range(n): if alice_hadamard[i]==bob_hadamard[i]: alice_key.append(int(alice_prepare[i])) bob_key.append(int(bob_measure[i])) # Print Keys print("".join(["Alice extracts key as: ","".join([str(i) for i in alice_key])])) print("".join(["Bob extracts key as: ","".join([str(i) for i in bob_key])])) # Alice's end alice_prepare = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) alice_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) circ = QuantumCircuit(n, 2*n) # Preparation circ.reset(range(n)) for i in range(n): if alice_prepare[i] == 1: circ.x(i) circ.barrier() # Hadamard Transform for i in range(n): if alice_hadamard[i] == 1: circ.h(i) circ.barrier() # Eavesdropper circ.measure(range(n), range(n)) # Bob's end bob_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) circ.barrier() # Hadamard Transform for i in range(n): if bob_hadamard[i] == 1: circ.h(i) circ.barrier() # Measurement circ.measure(range(n), range(n,2*n)) circ.draw('mpl', reverse_bits=True, scale=0.45) # Execute Circuit backend = Aer.get_backend('qasm_simulator') job = execute(circ, backend, shots=1) counts = job.result().get_counts(circ) measure_data = list(counts.keys())[0][::-1] eve_measure = measure_data[0:n] bob_measure = measure_data[n:2*n] # Print Data print("".join(["Alice Prepared: ","".join([str(i) for i in alice_prepare])])) print("".join(["Alice H Transforms: ","".join([str(i) for i in alice_hadamard])])) print("".join(["Eve Measurements: ", eve_measure])) print("".join(["Bob H Transforms: ","".join([str(i) for i in bob_hadamard])])) print("".join(["Bob Measurements: ", bob_measure])) # Extract Key alice_key = [] bob_key = [] for i in range(n): if alice_hadamard[i]==bob_hadamard[i]: alice_key.append(int(alice_prepare[i])) bob_key.append(int(bob_measure[i])) # Print Keys print("".join(["Alice extracts key as: ","".join([str(i) for i in alice_key])])) print("".join(["Bob extracts key as: ","".join([str(i) for i in bob_key])]))
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
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/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.circuit import Gate from qiskit.visualization import plot_histogram, plot_bloch_multivector circ = QuantumCircuit(2, 1) circ.reset([0, 1]) circ.x(0) circ.barrier() circ.h([0, 1]) circ.barrier() circ.append(Gate(name="$U_f$", num_qubits=2, params=[]), [0, 1]) circ.barrier() circ.h(1) circ.barrier() circ.measure(1, 0) circ.draw('mpl', reverse_bits=True) # Implementation of f1(x) f1 = QuantumCircuit(2, name='f1') f1.id(0) f1.draw('mpl', reverse_bits=True) # Implementation of f2(x) f2 = QuantumCircuit(2, name='f2') f2.cx(1, 0) f2.id(0) f2.draw('mpl', reverse_bits=True) # Implementation of f3(x) f3 = QuantumCircuit(2, name='f3') f3.cx(1, 0) f3.x(0) f3.draw('mpl', reverse_bits=True) # Implementation of f4(x) f4 = QuantumCircuit(2, name='f4') f4.x(0) f4.draw('mpl', reverse_bits=True) circ = QuantumCircuit(2) circ.x(0) circ.barrier() circ.h([0, 1]) circ.append(f4.to_instruction(), [0, 1]) circ.h(1) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('statevector_simulator') result = execute(circ, simulator).result() state = result.get_statevector(circ) plot_bloch_multivector(state) circ = QuantumCircuit(2) circ.x(0) circ.barrier() circ.h([0, 1]) circ.append(f2.to_instruction(), [0, 1]) circ.h(1) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('statevector_simulator') result = execute(circ, simulator).result() state = result.get_statevector(circ) plot_bloch_multivector(state) circ = QuantumCircuit(2, 1) circ.x(0) circ.barrier() circ.h([0, 1]) circ.append(f2.to_instruction(), [0, 1]) circ.h(1) circ.measure(1, 0) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('qasm_simulator') result = execute(circ, simulator, shots=1000).result() counts = result.get_counts(circ) plot_histogram(counts)
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.circuit import Gate from qiskit.visualization import plot_histogram, plot_bloch_multivector # Define no. of input qubits n = 4 circ = QuantumCircuit(n+1, n) circ.reset(range(n+1)) circ.x(0) circ.barrier() circ.h(range(n+1)) circ.barrier() circ.append(Gate(name="$U_f$", num_qubits=n+1, params=[]), range(n+1)) circ.barrier() circ.h(range(1, n+1)) circ.barrier() circ.measure(range(1, n+1), range(n)) circ.draw('mpl', reverse_bits=True) # Constant Function constant = QuantumCircuit(n+1, name='Constant') constant.x(0) constant.draw('mpl', reverse_bits=True) # Balanced Function balanced = QuantumCircuit(n+1, name='Balanced') for i in range(1, n+1): balanced.cx(i, 0) balanced.draw('mpl', reverse_bits=True) circ = QuantumCircuit(n+1) circ.x(0) circ.barrier() circ.h(range(n+1)) circ.append(constant.to_instruction(), range(n+1)) circ.h(range(1, n+1)) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('statevector_simulator') result = execute(circ, simulator).result() state = result.get_statevector(circ) plot_bloch_multivector(state) circ = QuantumCircuit(n+1) circ.x(0) circ.barrier() circ.h(range(n+1)) circ.append(balanced.to_instruction(), range(n+1)) circ.h(range(1, n+1)) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('statevector_simulator') result = execute(circ, simulator).result() state = result.get_statevector(circ) plot_bloch_multivector(state) circ = QuantumCircuit(n+1, n) circ.x(0) circ.barrier() circ.h(range(n+1)) circ.append(constant.to_instruction(), range(n+1)) circ.h(range(1, n+1)) circ.measure(range(1, n+1), range(n)) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('qasm_simulator') result = execute(circ, simulator, shots=1000).result() counts = result.get_counts(circ) plot_histogram(counts)
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
my_list = [1,3,5,2,4,2,5,8,0,7,6] #classical computation method def oracle(my_input): winner =7 if my_input is winner: response = True else: response = False return response for index, trial_number in enumerate(my_list): if oracle(trial_number) is True: print("Winner is found at index %i" %index) print("%i calls to the oracle used " %(index +1)) break #quantum implemenation from qiskit import * import matplotlib.pyplot as plt import numpy as np from qiskit.tools import job_monitor # oracle circuit oracle = QuantumCircuit(2, name='oracle') oracle.cz(0,1) oracle.to_gate() oracle.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') grover_circuit = QuantumCircuit(2,2) grover_circuit.h([0,1]) grover_circuit.append(oracle,[0,1]) grover_circuit.draw(output='mpl') job= execute(grover_circuit, backend=backend) result= job.result() sv= result.get_statevector() np.around(sv,2) #amplitude amplification reflection = QuantumCircuit(2, name='reflection') reflection.h([0,1]) reflection.z([0,1]) reflection.cz(0,1) reflection.h([0,1]) reflection.to_gate() reflection.draw(output='mpl') #testing circuit on simulator simulator = Aer.get_backend('qasm_simulator') grover_circuit = QuantumCircuit(2,2) grover_circuit.h([0,1]) grover_circuit.append(oracle,[0,1]) grover_circuit.append(reflection, [0,1]) grover_circuit.barrier() grover_circuit.measure([0,1],[0,1]) grover_circuit.draw(output='mpl') job= execute(grover_circuit,backend=simulator,shots=1) result=job.result() result.get_counts() #testing on real backend system IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp= provider.get_backend('ibmq_manila') job = execute(grover_circuit,backend=qcomp) job_monitor(job) result=job.result() counts=result.get_counts(grover_circuit) from qiskit.visualization import plot_histogram plot_histogram(counts) counts['11']
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np from math import pi from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.circuit import Gate from qiskit.visualization import plot_histogram from qiskit.circuit.library.standard_gates import ZGate, XGate # Define circuit parameters a = '10x01xx' n = len(a) k = 7 circ = QuantumCircuit(k+n, k) circ.reset(range(k+n)) circ.h(range(k+n)) circ.barrier() for i in range(k): name = '$G_' + str(i) + '$' circ.append(QuantumCircuit(n, name=name).to_gate().control(1), [n+i]+list(range(n))) circ.barrier() circ.append(Gate(name="$QFT^{-1}$", num_qubits=k, params=[]), range(n, k+n)) circ.barrier() circ.measure(range(n, k+n), range(k)) circ.draw('mpl', reverse_bits=True, scale=0.5) def Gop(j): p = 2 ** j ctrl_bits = [] ctrl_state = '' for i in range(n): if a[n-i-1] != 'x': ctrl_bits.append(i+1) ctrl_state += a[n-i-1] G = QuantumCircuit(n+1, name='G'+str(j)) for i in range(p): G.append(XGate().control(len(ctrl_bits), ctrl_state=ctrl_state[::-1]), ctrl_bits + [0]) G.h(range(1, n+1)) G.x(range(1, n+1)) G.append(ZGate().control(n-1), reversed(range(1, n+1))) G.x(range(1, n+1)) G.h(range(1, n+1)) return G Gop(3).draw('mpl', reverse_bits=True, scale=0.5) QFT_inv = QuantumCircuit(k, name='QFT^{-1}') for i in reversed(range(k)): if i != k-1: QFT_inv.barrier() for j in reversed(range(i+1,k)): QFT_inv.cu1(-pi/(2 ** (j-i)), i, j) QFT_inv.h(i) QFT_inv.draw('mpl', reverse_bits=True) circ = QuantumCircuit(k+n+1, k) circ.reset(range(k+n+1)) circ.x(0) circ.h(range(k+n+1)) circ.z(n+1) circ.barrier() for i in range(k): circ.append(Gop(i).to_gate().control(1), [n+i+1]+list(range(n+1))) circ.barrier() circ.append(QFT_inv, range(n+1, k+n+1)) circ.barrier() circ.measure(range(n+1, k+n+1), range(k)) circ.draw(reverse_bits=True, scale=0.5) delta = 64 simulator = Aer.get_backend('qasm_simulator') result = execute(circ, simulator, shots=delta).result() counts = result.get_counts(circ) plot_histogram(counts) x = list(counts.keys()) x = [pi*int(i[::-1], 2)/(2 ** k) for i in x] p = list(counts.values()) p = p.index(max(p)) theta = min(x[p], pi-x[p]) m_estimate = (2 ** n) * (theta ** 2) m = 2 ** a.count('x') print('Estimated Count:') print(m_estimate) print('Actual Count:') print(m)
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
from qiskit import * from qiskit.visualization import plot_bloch_multivector, plot_bloch_vector, plot_histogram from qiskit.compiler import transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.providers.ibmq import least_busy import matplotlib import numpy as np %pylab inline qc = QuantumCircuit(4,3) qc.x(3) qc.h(range(3)) reps = 1 for count in range(3): for i in range (reps): qc.cp(pi/4, count, 3) reps *= 2 qc.barrier() qc.draw('mpl') def inv_qft(qc, n): for qubit in range (n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-pi/(2*(j-m)), m, j) qc.h(j) inv_qft(qc, 3) qc.barrier() qc.measure(range(3), range(3)) qc.draw('mpl') qasm_sim = Aer.get_backend('qasm_simulator') shots = 1 qobj = assemble(qc, qasm_sim) results = qasm_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 4 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 shots = 1024 transpiled_circuit = transpile(qc, backend) qobj = assemble(transpiled_circuit, shots=shots) job = backend.run(qobj) job_monitor(job, interval=2) results = job.result() answer = results.get_counts() plot_histogram(answer)
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute, Aer from qiskit.tools.jupyter import * provider = IBMQ.load_account() # import basic plot tools from qiskit.visualization import plot_histogram def initialize(circuit, n, m): circuit.h(range(n)) # Hadamard transform on measurment register circuit.x(n+m-1) # X gate on last qubit def c_amod15(a, x): if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11 or 13") # remember that a needs to be co-prime with N unitary = QuantumCircuit(4) for iteration in range(x): # bitwise arithmetic to represent modular exponentiation function if a in [2,13]: unitary.swap(0,1) unitary.swap(1,2) unitary.swap(2,3) if a in [7,8]: unitary.swap(2,3) unitary.swap(1,2) unitary.swap(0,1) if a == 11: unitary.swap(1,3) unitary.swap(0,2) if a in [7,11,13]: for q in range(4): unitary.x(q) unitary = unitary.to_gate() unitary.name = "%i^%i mod 15" % (a, x) # But we need to make it a controlled operation for phase kickback c_unitary = unitary.control() return c_unitary def modular_exponentiation(circuit, n, m, a): for exp in range(n): exponent = 2**exp circuit.append(a_x_mod15(a, exponent), [exp] + list(range(n, n+m))) from qiskit.circuit.library import QFT def apply_iqft(circuit, measurement_qubits): circuit.append(QFT( len(measurement_qubits), do_swaps=False).inverse(), measurement_qubits) def shor_algo(n, m, a): # set up the circuit circ = QuantumCircuit(n+m, n) # initialize the registers initialize(circ, n, m) circ.barrier() # map modular exponentiation problem onto qubits modular_exponentiation(circ, n, m, a) circ.barrier() # apply inverse QFT -- expose period apply_iqft(circ, range(n)) # measure the measurement register circ.measure(range(n), range(n)) return circ n = 4; m = 4; a = 11 mycircuit = shor_algo(n, m, a) mycircuit.draw('mpl') simulator = Aer.get_backend('qasm_simulator') counts = execute(mycircuit, backend=simulator, shots=1024).result().get_counts(mycircuit) plot_histogram(counts) for measured_value in counts: print(f"Measured {int(measured_value[::-1], 2)}") from math import gcd from math import sqrt from itertools import count, islice for measured_value in counts: measured_value_decimal = int(measured_value[::-1], 2) print(f"Measured {measured_value_decimal}") if measured_value_decimal % 2 != 0: print("Failed. Measured value is not an even number") continue x = int((a ** (measured_value_decimal/2)) % 15) if (x + 1) % 15 == 0: print("Failed. x + 1 = 0 (mod N) where x = a^(r/2) (mod N)") continue guesses = gcd(x + 1, 15), gcd(x - 1, 15) print(guesses) def is_prime(n): return n > 1 and all(n % i for i in islice(count(2), int(sqrt(n)-1))) if is_prime(guesses[0]) and is_prime(guesses[1]): print(f"**The prime factors are {guesses[0]} and {guesses[1]}**")
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
# Importing Packages from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble, QuantumRegister, ClassicalRegister from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle bb = input("Enter the input string:\n") ### Using in-built "simon_oracle" from QISKIT # importing Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle n = len(bb) simon_circuit = QuantumCircuit(n*2, n) # Apply Hadamard gates before querying the oracle simon_circuit.h(range(n)) # Apply barrier for visual separation simon_circuit.barrier() simon_circuit += simon_oracle(bb) # Apply barrier for visual separation simon_circuit.barrier() # Apply Hadamard gates to the input register simon_circuit.h(range(n)) # Measure qubits simon_circuit.measure(range(n), range(n)) simon_circuit.draw(output="mpl") # use local simulator aer_sim = Aer.get_backend('aer_simulator') shots = 500 qobj = assemble(simon_circuit, shots=shots) results = aer_sim.run(qobj).result() counts = results.get_counts() print(counts) plot_histogram(counts) # Calculate the dot product of the results def bdotz(b, z): accum = 0 for i in range(len(b)): accum += int(b[i]) * int(z[i]) return (accum % 2) for z in counts: print( '{}.{} = {} (mod 2)'.format(b, z, bdotz(b,z)) ) b = input("Enter a binary string:\n") # Actual b = 011 b_rev = b[::-1] flagbit = b_rev.find('1') n=len(b) q1=QuantumRegister(n,'q1') q2=QuantumRegister(n,'q2') c1=ClassicalRegister(n) qc = QuantumCircuit(q1,q2,c1) qc.barrier() qc.h(q1) qc.barrier() for i in range(n): qc.cx(q1[i],q2[i]) qc.barrier() if flagbit != -1: # print("test1") for ind, bit in enumerate(b_rev): # print("test2") if bit == "1": # print("test3") qc.cx(flagbit, q2[ind]) qc.barrier() qc.h(q1) qc.barrier() qc.measure(q1,c1) qc.draw("mpl") aer_sim = Aer.get_backend('aer_simulator') shots = 500 qobj = assemble(qc, shots=shots) results = aer_sim.run(qobj).result() counts = results.get_counts() print(counts) plot_histogram(counts) # Actual b = 011 b="1" b_rev = "1" flagbit = b_rev.find('1') n=len(b) q1=QuantumRegister(n,'q1') q2=QuantumRegister(n,'q2') c1=ClassicalRegister(n) qc = QuantumCircuit(q1,q2,c1) qc.barrier() qc.h(q1) qc.barrier() for i in range(n): qc.cx(q1[i],q2[i]) qc.barrier() if flagbit != -1: # print("test1") for ind, bit in enumerate(b_rev): # print("test2") if bit == "1": # print("test3") qc.cx(flagbit, q2[ind]) qc.barrier() qc.h(q1) qc.barrier() # qc.measure(q1,c1) # qc.draw("mpl") # Simulate the unitary usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() # Display the results: array_to_latex(unitary, prefix="\\text{Circuit = } ")
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.circuit import Gate from qiskit.visualization import plot_bloch_multivector from math import pi q = QuantumRegister(3, name='q') c = ClassicalRegister(2, name='c') circ = QuantumCircuit(q, c) circ.reset(q) circ.u3(pi/2,pi/2,pi/2,q[2]) circ.h(q[1]) circ.cx(q[1],q[0]) circ.barrier() circ.cx(q[2],q[1]) circ.h(q[2]) circ.barrier() circ.measure([q[2],q[1]],[c[1],c[0]]) circ.barrier() circ.x(0).c_if(c,1) circ.z(0).c_if(c,2) circ.x(0).c_if(c,3) circ.z(0).c_if(c,3) circ.draw('mpl', reverse_bits=True) theta = pi/3 phi = pi/2 q = QuantumRegister(3, name='q') c = ClassicalRegister(2, name='c') circ = QuantumCircuit(q, c) circ.reset(q) circ.u3(theta,phi,pi,q[2]) circ.h(q[1]) circ.cx(q[1],q[0]) circ.barrier() circ.draw('mpl', reverse_bits=True) backend = Aer.get_backend('statevector_simulator') job = execute(circ, backend) state = job.result().get_statevector(circ) plot_bloch_multivector(state) circ.cx(q[2],q[1]) circ.h(q[2]) circ.barrier() circ.measure([q[2],q[1]],[c[1],c[0]]) circ.barrier() circ.x(0).c_if(c,1) circ.z(0).c_if(c,2) circ.x(0).c_if(c,3) circ.z(0).c_if(c,3) circ.draw('mpl', reverse_bits=True) backend = Aer.get_backend('statevector_simulator') job = execute(circ, backend) state = job.result().get_statevector(circ) plot_bloch_multivector(state)
https://github.com/LohitPotnuru/TransverseIsingModelQiskit
LohitPotnuru
from qiskit import * from scipy.optimize import minimize import numpy as np from pylab import * #2^4 possible states of four qubits stored in dic bit = ['0','1'] dic = [] for i in bit: for j in bit: for k in bit: for l in bit: dic.append(i+j+l+k) def calcEJ(theta): #make quantum circuit with 2 qubits q = QuantumRegister(4) c = ClassicalRegister(4) circuit = QuantumCircuit(q,c) # entangled quantum state preparation q = circuit.qregs[0] circuit.u(theta[0], theta[1], 0, q[0]) circuit.cx(q[0],q[1]) circuit.cx(q[0],q[2]) circuit.cx(q[0],q[3]) for i in range(0,4): circuit.u(theta[i+2],0,0,q[i]) circuit.measure(range(4),range(4)) # Executing the circuit by qasm_simulation to caculate energy from result.get(counts) shots=18192 backend = BasicAer.get_backend('qasm_simulator') result = execute(circuit, backend, shots = shots).result() counts = result.get_counts() #make sure that all possible values accounted for to avoid errors for i in dic: if i not in counts: counts[i] = 0 #calculate expectation value in terms of sigma z of qubit i and qubit i+1 def prob(i): t1=0 t2=0 for j in counts.keys(): if j[i]=='0': t1+=counts[j] else: t1-=counts[j] t1=t1/shots for j in counts.keys(): if j[i+1]=='0': t2+=counts[j] else: t2-=counts[j] t2=t2/shots E=-1*t1*t2 return E E_J=0 for i in range(0,3): E_J+=prob(i) return E_J def calcEZ(theta): #make quantum circuit with 2 qubits q = QuantumRegister(4) c = ClassicalRegister(4) circuit = QuantumCircuit(q,c) # entangled quantum state preparation q = circuit.qregs[0] circuit.u(theta[0], theta[1], 0, q[0]) circuit.cx(q[0],q[1]) circuit.cx(q[0],q[2]) circuit.cx(q[0],q[3]) for i in range(0,4): circuit.u(theta[i+2],0,0,q[i]) circuit.h(range(4)) circuit.measure(range(4),range(4)) # Executing the circuit by qasm_simulation to caculate energy from result.get(counts) shots=18192 backend = BasicAer.get_backend('qasm_simulator') result = execute(circuit, backend, shots = shots).result() counts = result.get_counts() #make sure that all possible values accounted for to avoid errors for i in dic: if i not in counts: counts[i] = 0 #calculate expectation value in terms of sigma x of qubit i def prob(i): E=0 for j in counts.keys(): if j[i]=='0': E+=counts[j] else: E-=counts[j] E=E/shots return E E_Z=0 for i in range(0,3): E_Z+=prob(i) return E_Z # expectation value total def calcE(theta): # Summing the measurement results classical_adder = calcEJ(theta) + h * calcEZ(theta) return classical_adder h=2 calcE(theta=[1.5708,0,1.10715,0,2.03444,0]) theta0=[1.5708,0,1.10715,0,2.03444,0] tol = 1e-3 # tolerance for optimization precision. # Get expectation energy by optimization with corresponding h = 0.1, 0.2,..., 2.9, 3. y_vqe = [] for k in range(0,31): h=k/10 vqe_result = minimize(calcE, theta0 , method="COBYLA", tol=tol) y_vqe.append(vqe_result.fun) print(y_vqe) y_mean = np.array(y_vqe)/4 x2 = [] for k in range(0,31): x2.append(k/10) plot(x2,y_mean,'bs', label='VQE') plt.xlabel('h') plt.ylabel('E/N with N = 4')
https://github.com/mentesniker/Quantum-Cryptography
mentesniker
from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram import numpy as np #prepares the initial quantum states for the BB84 protocol by generating a list of quantum states and their associated bases. def prepare_bb84_states(num_qubits): states = [] bases = [] for _ in range(num_qubits): state, basis = generate_bb84_state() states.append(state) bases.append(basis) return states, bases #generates a single BB84 quantum state and its associated measurement basis. def generate_bb84_state(): basis = np.random.randint(2) # 0 for rectilinear basis, 1 for diagonal basis if np.random.rand() < 0.5: state = QuantumCircuit(1, 1) if basis == 0: state.h(0) else: state.s(0) state.h(0) else: state = QuantumCircuit(1, 1) if basis == 0: state.x(0) state.h(0) else: state.x(0) state.s(0) state.h(0) return state, basis #measures the quantum states with the appropriate basis and returns the measurement results def measure_bb84_states(states, bases): measurements = [] for state, basis in zip(states, bases): if basis == 0: state.measure(0, 0) else: state.h(0) state.measure(0, 0) measurements.append(state) return measurements #sifts the keys by comparing Alice and Bob's measurement bases and bits. It checks if the measurement bases match (the same basis) and appends the corresponding bits to the sifted keys def sift_keys(alice_bases, bob_bases, alice_bits, bob_bits): sifted_alice_bits = [] sifted_bob_bits = [] for a_basis, b_basis, a_bit, b_bit in zip(alice_bases, bob_bases, alice_bits, bob_bits): if a_basis == b_basis: sifted_alice_bits.append(a_bit) sifted_bob_bits.append(b_bit) return sifted_alice_bits, sifted_bob_bits #calculates the error rate between Alice's and Bob's sifted bits def error_rate(alice_bits, bob_bits): errors = sum([1 for a, b in zip(alice_bits, bob_bits) if a != b]) return errors / len(alice_bits) # simulates the BB84 protocol num_qubits = 100 num_qubits = 100 alice_states, alice_bases = prepare_bb84_states(num_qubits) bob_bases = np.random.randint(2, size=num_qubits) bob_measurements = measure_bb84_states(alice_states, bob_bases) alice_bits = [] for state in alice_states: result = execute(state, Aer.get_backend('qasm_simulator')).result() counts = result.get_counts(state) max_count = max(counts, key=counts.get) alice_bits.append(int(max_count)) bob_bits = [] for state in bob_measurements: result = execute(state, Aer.get_backend('qasm_simulator')).result() counts = result.get_counts(state) max_count = max(counts, key=counts.get) bob_bits.append(int(max_count)) sifted_alice_bits, sifted_bob_bits = sift_keys(alice_bases, bob_bases, alice_bits, bob_bits) error = error_rate(sifted_alice_bits, sifted_bob_bits) final_key = privacy_amplification(sifted_alice_bits) print("Sifted key length:", len(sifted_alice_bits)) print("Error rate:", error) print("Final secret key:", final_key)
https://github.com/mentesniker/Quantum-Cryptography
mentesniker
%matplotlib inline # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from random import randint import hashlib #These two functions were taken from https://stackoverflow.com/questions/10237926/convert-string-to-list-of-bits-and-viceversa def tobits(s): result = [] for c in s: bits = bin(ord(c))[2:] bits = '00000000'[len(bits):] + bits result.extend([int(b) for b in bits]) return ''.join([str(x) for x in result]) def frombits(bits): chars = [] for b in range(int(len(bits) / 8)): byte = bits[b*8:(b+1)*8] chars.append(chr(int(''.join([str(bit) for bit in byte]), 2))) return ''.join(chars) #Alice cell, Bob can't see what's going in on here m0 = tobits("Yes I want to go to the cinema with you!!!") m1 = tobits("No I dont want to go to the cinema with you...") messageToSend = m1 Alice_bases = [randint(0,1) for x in range(len(messageToSend))] qubits = list() for i in range(len(Alice_bases)): mycircuit = QuantumCircuit(1,1) if(Alice_bases[i] == 0): if(messageToSend[i] == "1"): mycircuit.x(0) else: if(messageToSend[i] == "0"): mycircuit.h(0) else: mycircuit.x(0) mycircuit.h(0) qubits.append(mycircuit) #Bob cell, Alice can't see what's going in on here backend = Aer.get_backend('qasm_simulator') measurements = list() for i in range(len(Alice_bases)): qubit = qubits[i] if(Alice_bases[i] == 0): qubit.measure(0,0) else: qubit.h(0) qubit.measure(0,0) result = execute(qubit, backend, shots=1, memory=True).result() measurements.append(int(result.get_memory()[0])) print("Alice message was: " + frombits(measurements))
https://github.com/mentesniker/Quantum-Cryptography
mentesniker
%matplotlib inline # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from random import randint import hashlib #These two functions were taken from https://stackoverflow.com/questions/10237926/convert-string-to-list-of-bits-and-viceversa def tobits(s): result = [] for c in s: bits = bin(ord(c))[2:] bits = '00000000'[len(bits):] + bits result.extend([int(b) for b in bits]) return ''.join([str(x) for x in result]) def frombits(bits): chars = [] for b in range(int(len(bits) / 8)): byte = bits[b*8:(b+1)*8] chars.append(chr(int(''.join([str(bit) for bit in byte]), 2))) return ''.join(chars) #Alice cell, Bob can't see what's going in on here m0 = tobits("I like dogs") m1 = tobits("I like cats") messageMerge = m0+m1 Alice_bases = [randint(0,1) for x in range(len(messageMerge))] qubits = list() for i in range(len(Alice_bases)): mycircuit = QuantumCircuit(1,1) if(Alice_bases[i] == 0): if(messageMerge[i] == "1"): mycircuit.x(0) else: if(messageMerge[i] == "0"): mycircuit.h(0) else: mycircuit.x(0) mycircuit.h(0) qubits.append(mycircuit) #Bob cell, Alice can't see what's going in on here Bob_bases = [randint(0,1) for x in range(176)] backend = Aer.get_backend('qasm_simulator') measurements = list() choice = 0 for i in range(len(Bob_bases)): qubit = qubits[i] if(Bob_bases[i] == 0): qubit.measure(0,0) else: qubit.h(0) qubit.measure(0,0) result = execute(qubit, backend, shots=1, memory=True).result() measurements.append(int(result.get_memory()[0])) #Bob cell, Alice can't see what's going in on here I0 = list() I1 = list() if(choice == 0): for i in range(len(Alice_bases)): if(Alice_bases[i] == Bob_bases[i]): I0.append(i) else: I1.append(i) else: for i in range(len(Alice_bases)): if(Alice_bases[i] == Bob_bases[i]): I1.append(i) else: I0.append(i) #Alice cell, Bob can't see what's going in on here x0 = list() for x in I0: x0.append(messageMerge[x]) x1 = list() for x in I1: x1.append(messageMerge[x]) fx0 = ''.join(format(ord(i), 'b') for i in hashlib.sha224(''.join(x0).encode('utf-8')).hexdigest()) fx1 = ''.join(format(ord(i), 'b') for i in hashlib.sha224(''.join(x1).encode('utf-8')).hexdigest()) s0 = '' s1 = '' for bit in range(len(m0)): s0 += str(int(fx0[bit]) ^ int(m0[bit])) for bit in range(len(m1)): s1 += str(int(fx1[bit]) ^ int(m1[bit])) xB0 = list() if(choice == 0): for x in I0: xB0.append(measurements[x]) else: for x in I1: xB0.append(measurements[x]) fxB0 = ''.join(format(ord(i), 'b') for i in hashlib.sha224(''.join([str(x) for x in xB0]).encode('utf-8')).hexdigest()) mB0 = bytearray() if(choice == 0): for bit in range(len(s0)): mB0.append(int(fxB0[bit]) ^ int(s0[bit])) print("Alice message was: " + frombits(mB0)) else: for bit in range(len(s1)): mB0.append(int(fxB0[bit]) ^ int(s1[bit])) print("Alice message was: " + frombits(mB0))
https://github.com/mentesniker/Quantum-Cryptography
mentesniker
%matplotlib inline # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from random import randint import hashlib #Alice cell, Bob can't see what's going in on here m0 = randint(0,1) Alice_base = randint(0,1) qubits = list() mycircuit = QuantumCircuit(1,1) if(Alice_base == 0): if(m0 == 1): mycircuit.x(0) else: if(m0 == 0): mycircuit.h(0) else: mycircuit.x(0) mycircuit.h(0) qubits.append(mycircuit) #Bob cell, Alice can't see what's going in on here backend = Aer.get_backend('qasm_simulator') a = 0 qubit = qubits[0] if(Alice_base == 0): qubit.measure(0,0) else: qubit.h(0) qubit.measure(0,0) result = execute(qubit, backend, shots=1, memory=True).result() a = int(result.get_memory()[0]) #Bob cell, Alice can't see what's going in on here m1 = randint(0,1) Bob_base = randint(0,1) qubitsB = list() mycircuitB = QuantumCircuit(1,1) if(Bob_base == 0): if(m1 == 1): mycircuitB.x(0) else: if(m1 == 0): mycircuitB.h(0) else: mycircuitB.x(0) mycircuitB.h(0) qubitsB.append(mycircuitB) #Alice cell, Bob can't see what's going in on here backend = Aer.get_backend('qasm_simulator') b = 0 qubit = qubitsB[0] if(Bob_base == 0): qubit.measure(0,0) else: qubit.h(0) qubit.measure(0,0) result = execute(qubit, backend, shots=1, memory=True).result() b = int(result.get_memory()[0]) #Alice cell, Bob can't see what's going in on here print("The result of the coin flip was: " + str(b ^ m0)) #Bob cell, Alice can't see what's going in on here print("The result of the coin flip was: " + str(m1 ^ a))
https://github.com/mentesniker/Quantum-Cryptography
mentesniker
from qiskit import QuantumCircuit from qiskit import BasicAer from qiskit import execute def encryption(qc, initialString, pk): for bit in range(0,len(initialString)): if(initialString[bit] == '1'): qc.x(bit) if(pk[2*bit] == '1'): qc.z(bit) if(pk[2*bit+1] == '1'): qc.x(bit) return qc def decryption(qc, lenCypher, pk): for bit in range(0,lenCypher): if(pk[2*bit] == '1'): qc.z(bit) if(pk[2*bit+1] == '1'): qc.x(bit) return qc def generate_random_key(length,backend): pk = '' for i in range(0,2*length): qc = QuantumCircuit(1,1) qc.h(0) qc.measure(0,0) counts = execute(qc, backend=backend, shots=1).result().get_counts(qc) pk += list(counts.keys())[0] return pk def run_circuit(qc,backend): job = execute(qc, backend, shots=100) result = job.result() return result.get_counts(qc) initialString = '0110' pk = generate_random_key(len(initialString),backend) encrypt = QuantumCircuit(len(initialString),len(initialString)) backend = BasicAer.get_backend('qasm_simulator') encryption(encrypt,initialString,pk) encrypt.barrier() encrypt.measure([0,1,2,3],[0,1,2,3]) print("the encrypted string is: " + str(run_circuit(encrypt,backend))) encrypt.barrier() decryption(encrypt,len(encrypt.qubits),pk) encrypt.barrier() encrypt.measure([0,1,2,3],[0,1,2,3]) print("the original string is: " + str(run_circuit(encrypt,backend))) encrypt.draw()
https://github.com/Axect/QuantumAlgorithms
Axect
import qiskit qiskit.__qiskit_version__ #initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load our saved IBMQ accounts. IBMQ.load_account() nQubits = 14 # number of physical qubits a = 101 # the hidden integer whose bitstring is 1100101 # make sure that a can be represented with nQubits a = a % 2**(nQubits) # Creating registers # qubits for querying the oracle and finding the hidden integer qr = QuantumRegister(nQubits) # for recording the measurement on qr cr = ClassicalRegister(nQubits) circuitName = "BernsteinVazirani" bvCircuit = QuantumCircuit(qr, cr) # Apply Hadamard gates before querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Apply barrier so that it is not optimized by the compiler bvCircuit.barrier() # Apply the inner-product oracle for i in range(nQubits): if (a & (1 << i)): bvCircuit.z(qr[i]) else: bvCircuit.iden(qr[i]) # Apply barrier bvCircuit.barrier() #Apply Hadamard gates after querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Measurement bvCircuit.barrier(qr) bvCircuit.measure(qr, cr) bvCircuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1000 results = execute(bvCircuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') shots = 1000 bvCompiled = transpile(bvCircuit, backend=backend, optimization_level=1) job_exp = execute(bvCircuit, backend=backend, shots=shots) job_monitor(job_exp) results = job_exp.result() answer = results.get_counts(bvCircuit) threshold = int(0.01 * shots) #the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} #filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) #number of counts removed filteredAnswer['other_bitstrings'] = removedCounts #the removed counts is assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/Axect/QuantumAlgorithms
Axect
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer from qiskit import QuantumCircuit, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 # Constant Oracle const_oracle = QuantumCircuit(n+1) # Random output output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() # Balanced Oracle balanced_oracle = QuantumCircuit(n+1) # Binary string length b_str = "101" # For each qubit in our circuit # we place an X-gate if the corresponding digit in b_str is 1 # or do nothing if the digit is 0 balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() # Creating the controlled-NOT gates # using each input qubit as a control # and the output as a target balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Wrapping the controls in X-gates # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw() # Viewing the output # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(dj_circuit).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/Axect/QuantumAlgorithms
Axect
import qiskit qiskit.__qiskit_version__ # useful additional packages 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.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load our saved IBMQ accounts IBMQ.load_account() n = 13 # the length of the first register for querying the oracle # Choose a type of oracle at random. With probability half it is constant, # and with the same probability it is balanced oracleType, oracleValue = np.random.randint(2), np.random.randint(2) if oracleType == 0: print("The oracle returns a constant value ", oracleValue) else: print("The oracle returns a balanced function") a = np.random.randint(1,2**n) # this is a hidden parameter for balanced oracle. # Creating registers # n qubits for querying the oracle and one qubit for storing the answer qr = QuantumRegister(n+1) #all qubits are initialized to zero # for recording the measurement on the first register cr = ClassicalRegister(n) circuitName = "DeutschJozsa" djCircuit = QuantumCircuit(qr, cr) # Create the superposition of all input queries in the first register by applying the Hadamard gate to each qubit. for i in range(n): djCircuit.h(qr[i]) # Flip the second register and apply the Hadamard gate. djCircuit.x(qr[n]) djCircuit.h(qr[n]) # Apply barrier to mark the beginning of the oracle djCircuit.barrier() if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue for all input. if oracleValue == 1: djCircuit.x(qr[n]) else: djCircuit.iden(qr[n]) else: # Otherwise, it returns the inner product of the input with a (non-zero bitstring) for i in range(n): if (a & (1 << i)): djCircuit.cx(qr[i], qr[n]) # Apply barrier to mark the end of the oracle djCircuit.barrier() # Apply Hadamard gates after querying the oracle for i in range(n): djCircuit.h(qr[i]) # Measurement djCircuit.barrier() for i in range(n): djCircuit.measure(qr[i], cr[i]) #draw the circuit djCircuit.draw(output='mpl',scale=0.5) backend = BasicAer.get_backend('qasm_simulator') shots = 1000 job = execute(djCircuit, backend=backend, shots=shots) results = job.result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') djCompiled = transpile(djCircuit, backend=backend, optimization_level=1) djCompiled.draw(output='mpl',scale=0.5) job = execute(djCompiled, backend=backend, shots=1024) job_monitor(job) results = job.result() answer = results.get_counts() threshold = int(0.01 * shots) # the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} # filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) # number of counts removed filteredAnswer['other_bitstrings'] = removedCounts # the removed counts are assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/Axect/QuantumAlgorithms
Axect
import pennylane as qml from pennylane import numpy as np import matplotlib.pyplot as plt from enum import Enum qml.drawer.use_style('sketch') class ReOrIm(Enum): real = 0 imag = 1 dev = qml.device('default.qubit', wires=2) @qml.qnode(dev) def hadamard_test_circuit(theta, phi, re_or_im=ReOrIm.real): # Prepare the superposition state |psi> = (|0>|a> + |1>|b>)/sqrt(2) # 1. Apply the Hadamard gate to the first qubit qml.Hadamard(wires=0) # 2. Apply S^dagger to the first qubit if we are measuring the imaginary part if re_or_im == ReOrIm.imag: qml.adjoint(qml.S)(wires=0) # 3. Apply the controlled unitary U where U|0> = |a> and U|1> = |b> qml.RY(2 * theta, wires=1) # |a> = Ry(theta)|0> qml.CRY(2 * (phi-theta), wires=[0, 1]) # 4. Apply the Hadamard gate to the first qubit qml.Hadamard(wires=0) return qml.probs(wires=0) qml.draw_mpl(hadamard_test_circuit)(np.pi/4, np.pi/3) plt.show() qml.draw_mpl(hadamard_test_circuit)(np.pi/4, np.pi/3, re_or_im=ReOrIm.imag) plt.show() p_0_real = hadamard_test_circuit(np.pi/4, np.pi/3, re_or_im=ReOrIm.real)[0] p_0_imag = hadamard_test_circuit(np.pi/4, np.pi/3, re_or_im=ReOrIm.imag)[0] print(f"Probability of measuring |0> when measuring the real part: {p_0_real:.4f}") print(f"Probability of measuring |0> when measuring the imaginary part: {p_0_imag:.4f}") inner_prod_real = 2 * p_0_real - 1 inner_prod_imag = 1 - 2 * p_0_imag print(f"Real part of the inner product: {inner_prod_real:.4f}") print(f"Imaginary part of the inner product: {inner_prod_imag:.4f}") # The inner product of the two states is the sum of the real and imaginary parts inner_prod = inner_prod_real + 1j * inner_prod_imag print(f"Inner product of the two states: {inner_prod:.4f}")
https://github.com/Axect/QuantumAlgorithms
Axect
#In case you don't have qiskit, install it now %pip install qiskit --quiet #Installing/upgrading pylatexenc seems to have fixed my mpl issue #If you try this and it doesn't work, try also restarting the runtime/kernel %pip install pylatexenc --quiet !pip install -Uqq ipdb !pip install qiskit_optimization import networkx as nx import matplotlib.pyplot as plt from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import BasicAer from qiskit.compiler import transpile from qiskit.quantum_info.operators import Operator, Pauli from qiskit.quantum_info import process_fidelity from qiskit.extensions.hamiltonian_gate import HamiltonianGate from qiskit.extensions import RXGate, XGate, CXGate from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute import numpy as np from qiskit.visualization import plot_histogram import ipdb from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * #quadratic optimization from qiskit_optimization import QuadraticProgram from qiskit_optimization.converters import QuadraticProgramToQubo %pdb on # def ApplyCost(qc, gamma): # Ix = np.array([[1,0],[0,1]]) # Zx= np.array([[1,0],[0,-1]]) # Xx = np.array([[0,1],[1,0]]) # Temp = (Ix-Zx)/2 # T = Operator(Temp) # I = Operator(Ix) # Z = Operator(Zx) # X = Operator(Xx) # FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T) # ham = HamiltonianGate(FinalOp,gamma) # qc.append(ham,[0,1,2]) task = QuadraticProgram(name = 'QUBO on QC') task.binary_var(name = 'x') task.binary_var(name = 'y') task.binary_var(name = 'z') task.minimize(linear = {"x":-1,"y":2,"z":-3}, quadratic = {("x", "z"): -2, ("y", "z"): -1}) qubo = QuadraticProgramToQubo().convert(task) #convert to QUBO operator, offset = qubo.to_ising() print(operator) # ham = HamiltonianGate(operator,0) # print(ham) Ix = np.array([[1,0],[0,1]]) Zx= np.array([[1,0],[0,-1]]) Xx = np.array([[0,1],[1,0]]) Temp = (Ix-Zx)/2 T = Operator(Temp) I = Operator(Ix) Z = Operator(Zx) X = Operator(Xx) FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T) ham = HamiltonianGate(FinalOp,0) print(ham) #define PYBIND11_DETAILED_ERROR_MESSAGES def compute_expectation(counts): """ Computes expectation value based on measurement results Args: counts: dict key as bitstring, val as count G: networkx graph Returns: avg: float expectation value """ avg = 0 sum_count = 0 for bitstring, count in counts.items(): x = int(bitstring[2]) y = int(bitstring[1]) z = int(bitstring[0]) obj = -2*x*z-y*z-x+2*y-3*z avg += obj * count sum_count += count return avg/sum_count # We will also bring the different circuit components that # build the qaoa circuit under a single function def create_qaoa_circ(theta): """ Creates a parametrized qaoa circuit Args: G: networkx graph theta: list unitary parameters Returns: qc: qiskit circuit """ nqubits = 3 n,m=3,3 p = len(theta)//2 # number of alternating unitaries qc = QuantumCircuit(nqubits,nqubits) Ix = np.array([[1,0],[0,1]]) Zx= np.array([[1,0],[0,-1]]) Xx = np.array([[0,1],[1,0]]) Temp = (Ix-Zx)/2 T = Operator(Temp) I = Operator(Ix) Z = Operator(Zx) X = Operator(Xx) FinalOp=-2*(Z^I^Z)-(I^Z^Z)-(Z^I^I)+2*(I^Z^I)-3*(I^I^Z) beta = theta[:p] gamma = theta[p:] # initial_state for i in range(0, nqubits): qc.h(i) for irep in range(0, p): #ipdb.set_trace(context=6) # problem unitary # for pair in list(G.edges()): # qc.rzz(2 * gamma[irep], pair[0], pair[1]) #ApplyCost(qc,2*0) ham = HamiltonianGate(operator,2 * gamma[irep]) qc.append(ham,[0,1,2]) # mixer unitary for i in range(0, nqubits): qc.rx(2 * beta[irep], i) qc.measure(qc.qubits[:n],qc.clbits[:m]) return qc # Finally we write a function that executes the circuit on the chosen backend def get_expectation(shots=512): """ Runs parametrized circuit Args: G: networkx graph p: int, Number of repetitions of unitaries """ backend = Aer.get_backend('qasm_simulator') backend.shots = shots def execute_circ(theta): qc = create_qaoa_circ(theta) # ipdb.set_trace(context=6) counts = {} job = execute(qc, backend, shots=1024) result = job.result() counts=result.get_counts(qc) return compute_expectation(counts) return execute_circ from scipy.optimize import minimize expectation = get_expectation() res = minimize(expectation, [1, 1], method='COBYLA') expectation = get_expectation() res = minimize(expectation, res.x, method='COBYLA') res from qiskit.visualization import plot_histogram backend = Aer.get_backend('aer_simulator') backend.shots = 512 qc_res = create_qaoa_circ(res.x) backend = Aer.get_backend('qasm_simulator') job = execute(qc_res, backend, shots=1024) result = job.result() counts=result.get_counts(qc_res) plot_histogram(counts)
https://github.com/Axect/QuantumAlgorithms
Axect
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/Axect/QuantumAlgorithms
Axect
import pennylane as qml from pennylane import numpy as np import matplotlib.pyplot as plt import scienceplots qml.drawer.use_style(style='sketch') def unitary_matrix_from_hermitian(A): eigenvalues, eigenvectors = np.linalg.eigh(A) D = np.diag(np.exp(2j * np.pi * eigenvalues)) U = np.dot(eigenvectors, np.dot(D, eigenvectors.conj().T)) return U def MultipleControlledRY(target_wire, control_wires, lamb1, lamb2): """ Apply a multiple controlled RY gate to the target wire, with control on the control wires. Args: target_wire (int): the target wire the RY gate acts on control_wires (list[int]): the control wires lamb (float): the eigenvalue. lamb should be converted to the qubit state (e.g. 0.25 (n=2) -> 01) """ n = len(control_wires) angle1 = 2 * np.arcsin(lamb1) lamb1_bin = format(int(lamb1 * 2**n), f'0{n}b') control_values1 = [int(bit) for bit in lamb1_bin] angle2 = 2 * np.arcsin(lamb2) lamb2_bin = format(int(lamb2 * 2**n), f'0{n}b') control_values2 = [int(bit) for bit in lamb2_bin] # print(control_values) qml.ctrl(qml.RY, control=control_wires, control_values=control_values1)(angle1, wires=target_wire) qml.ctrl(qml.RY, control=control_wires, control_values=control_values2)(angle2, wires=target_wire) dev = qml.device('default.qubit', wires=3) @qml.qnode(dev) def aqe_test(lamb1, lamb2): qml.PauliX(wires=2) MultipleControlledRY(0, [1, 2], lamb1, lamb2) return qml.state() lamb1 = 0.75 lamb2 = 0.25 qml.draw_mpl(aqe_test)(lamb1, lamb2) plt.show() state = aqe_test(lamb1, lamb2) print(state) @qml.qnode(dev) def aqe_test(lamb1, lamb2): qml.PauliX(wires=1) qml.PauliX(wires=2) MultipleControlledRY(0, [1, 2], lamb1, lamb2) return qml.state() state = aqe_test(lamb1, lamb2) print(state) qml.draw_mpl(aqe_test)(lamb1, lamb2) plt.show() A = np.array([[0.5, 0.25], [0.25, 0.5]]) U = unitary_matrix_from_hermitian(A) x = np.array([1, 0]) dev = qml.device('default.qubit', wires=3) @qml.qnode(dev) def qpe_test(U, x): # Encode the input vector x into the amplitudes of the state (here, only 2d vectors) qml.AmplitudeEmbedding(features=x, wires=2, normalize=True) # Apply Hadamard gate to the first n qubits qml.Hadamard(wires=0) qml.Hadamard(wires=1) # Apply controlled unitary operations qml.ControlledSequence(qml.QubitUnitary(U, wires=2), control=range(2)) # Apply inverse QFT qml.adjoint(qml.QFT)(wires=range(2)) # Measure c-register and return the probability distribution return qml.state() qml.draw_mpl(qpe_test)(U, x) plt.show() qpe_test(U, x).round(2) def gen_qmm(n: int, A): U = unitary_matrix_from_hermitian(A) U_inv = np.linalg.inv(U) dev1 = qml.device("default.qubit", wires=n+1) # c-register, encoding x dev2 = qml.device("lightning.qubit", wires=n+2, shots=10000, mcmc=True) # ancilla, c-register, encoding x @qml.qnode(dev1) def eigenvalue_circuit(x): # Encode the input vector x into the amplitudes of the state (here, only 2d vectors) qml.AmplitudeEmbedding(features=x, wires=n, normalize=True) # Apply Hadamard gate to the first n qubits for i in range(n): qml.Hadamard(wires=i) # Apply controlled unitary operations qml.ControlledSequence(qml.QubitUnitary(U, wires=n), control=range(n)) # Apply inverse QFT qml.adjoint(qml.QFT)(wires=range(n)) # Measure c-register and return the probability distribution return qml.probs(wires=range(n)) @qml.qnode(dev2) def final_circuit(x, lamb1, lamb2): # Encode the input vector x into the amplitudes of the state (here, only 2d vectors) qml.AmplitudeEmbedding(features=x, wires=n+1, normalize=True) # Apply Hadamard gate to the c-register for i in range(1, n+1): qml.Hadamard(wires=i) # Apply controlled unitary operations qml.ControlledSequence(qml.QubitUnitary(U, wires=n+1), control=range(1,n+1)) # Apply inverse QFT qml.adjoint(qml.QFT)(wires=range(1,n+1)) # Apply controlled rotations for |lambda> -> |lambda> (sqrt(1-lambda^2) |0> + lambda |1>) MultipleControlledRY([0], range(1, n+1), lamb1, lamb2) # Apply QFT qml.QFT(wires=range(1,n+1)) # Apply controlled unitary operations qml.ControlledSequence(qml.QubitUnitary(U_inv, wires=n+1), control=range(1,n+1)) # Apply Hadamard gate to the c-register for i in range(1, n+1): qml.Hadamard(wires=i) # Return the state of the last qubit and the measurement result return qml.sample(wires=[0, n+1]) def circuit(x): lamb_prob = eigenvalue_circuit(x) # lamb_cand = np.arange(2**n) / 2**n sorted_lamb_prob = np.argsort(lamb_prob)[::-1] lamb1 = sorted_lamb_prob[0] / 2**(n) lamb2 = sorted_lamb_prob[1] / 2**(n) print(lamb1, lamb2) samples = final_circuit(x, lamb1, lamb2) return samples return circuit, (dev1, eigenvalue_circuit), (dev2, final_circuit) A = np.array([[0.5, 0.25], [0.25, 0.5]]) x = np.array([1, 2]) A @ x eigv = np.linalg.eig(A) print(eigv) qmm_circuit, (dev1, ec), (dev2, fc) = gen_qmm(2, A) qml.draw_mpl(ec)(x) plt.show() qml.draw_mpl(fc)(x, 0.25, 0.75) plt.show() result = qmm_circuit(x) result meas_one = result[:,0] == 1 result_zero = result[meas_one & (result[:,1] == 0)] result_one = result[meas_one & (result[:,1] == 1)] from sklearn.metrics import confusion_matrix cm = confusion_matrix(result[:,0], result[:,1]) cm import matplotlib.pyplot as plt import seaborn as sns sns.heatmap(cm, annot=True, fmt='d') plt.show() res = np.array([result_zero.shape[0], result_one.shape[0]]) res np.sqrt(res) / np.linalg.norm(np.sqrt(res)) B = A @ x B / np.linalg.norm(B)
https://github.com/Axect/QuantumAlgorithms
Axect
#initialization import matplotlib.pyplot as plt import numpy as np import math # importing Qiskit from qiskit import IBMQ, Aer, transpile, assemble from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # import basic plot tools from qiskit.visualization import plot_histogram qpe = QuantumCircuit(4, 3) qpe.x(3) #Apply Hadamard gate for qubit in range(3): qpe.h(qubit) qpe.draw() repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe.cp(math.pi/4, counting_qubit, 3); # This is CU # we use 2*pi*(1/theta) repetitions *= 2 qpe.draw() def qft_dagger(qc, n): """n-qubit QFTdagger the first n qubits in circ""" # 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(-math.pi/float(2**(j-m)), m, j) qc.h(j) qpe.barrier() # Apply inverse QFT qft_dagger(qpe, 3) # Measure qpe.barrier() for n in range(3): qpe.measure(n,n) qpe.draw() aer_sim = Aer.get_backend('aer_simulator') shots = 2048 t_qpe = transpile(qpe, aer_sim) qobj = assemble(t_qpe, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe2 = QuantumCircuit(4, 3) # Apply H-Gates to counting qubits: for qubit in range(3): qpe2.h(qubit) # Prepare our eigenstate |psi>: qpe2.x(3) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe2.cp(angle, counting_qubit, 3); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe2, 3) # Measure of course! for n in range(3): qpe2.measure(n,n) qpe2.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe2 = transpile(qpe2, aer_sim) qobj = assemble(t_qpe2, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe3 = QuantumCircuit(6, 5) # Apply H-Gates to counting qubits: for qubit in range(5): qpe3.h(qubit) # Prepare our eigenstate |psi>: qpe3.x(5) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(5): for i in range(repetitions): qpe3.cp(angle, counting_qubit, 5); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe3, 5) # Measure of course! qpe3.barrier() for n in range(5): qpe3.measure(n,n) qpe3.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe3 = transpile(qpe3, aer_sim) qobj = assemble(t_qpe3, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/Axect/QuantumAlgorithms
Axect
import numpy as np from qiskit import BasicAer from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import Simon from qiskit.aqua.components.oracles import TruthTableOracle bitmaps = [ '01101001', '10011001', '01100110' ] oracle = TruthTableOracle(bitmaps) def compute_mask(input_bitmaps): vals = list(zip(*input_bitmaps))[::-1] def find_pair(): for i in range(len(vals)): for j in range(i + 1, len(vals)): if vals[i] == vals[j]: return i, j return 0, 0 k1, k2 = find_pair() return np.binary_repr(k1 ^ k2, int(np.log2(len(input_bitmaps[0])))) mask = compute_mask(bitmaps) print(f'The groundtruth mask is {mask}.') simon = Simon(oracle) backend = BasicAer.get_backend('qasm_simulator') result = simon.run(QuantumInstance(backend, shots=1024)) print('The mask computed using Simon is {}.'.format(result['result'])) assert(result['result'] == mask) bitmaps = [ '00011110', '01100110', '10101010' ] mask = compute_mask(bitmaps) print(f'The groundtruth mask is {mask}.') oracle = TruthTableOracle(bitmaps) simon = Simon(oracle) result = simon.run(QuantumInstance(backend, shots=1024)) print('The mask computed using Simon is {}.'.format(result['result'])) assert(result['result'] == mask)
https://github.com/Axect/QuantumAlgorithms
Axect
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt def circuit(alice): e = QuantumRegister(2, name='e') a = QuantumRegister(1, name='a') b = QuantumRegister(1, name='b') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(e, a, b, c, name='circuit') # Initialize Target qubit qc.initialize(alice / np.linalg.norm(alice), e) qc.barrier() # Create Bell pair qc.h(a) qc.cx(a, b) qc.barrier() # Write target qubit to Bell pair qc.cz(e[0], a) qc.cx(e[1], a) qc.barrier() # Decoding qc.cx(a, b) qc.h(a) qc.measure(a, c[1]) qc.measure(b, c[0]) backend = Aer.get_backend('qasm_simulator') return qc, execute(qc, backend).result().get_counts() qc, counts = circuit([1,0,0,1]) qc.draw(output='mpl', style='iqx') plot_histogram(counts)
https://github.com/Axect/QuantumAlgorithms
Axect
from qiskit import QuantumCircuit,Aer, execute from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt def check_computational_basis(basis): n = int(np.log2(len(basis))) qc = QuantumCircuit(n,n) initial_state = np.array(basis) / np.linalg.norm(basis) qc.initialize(initial_state, reversed(range(n))) # Input : LSB -> MSB qc.measure(range(n), reversed(range(n))) # Readout: LSB -> MSB backend = Aer.get_backend('qasm_simulator') counts = execute(qc,backend).result().get_counts().keys() return counts def gen_bases(n): return np.eye(2**n) bases = gen_bases(3) for i in range(bases.shape[0]): basis = bases[i].tolist() print(f"basis: {basis} -> {check_computational_basis(basis)}") def convert_zbasis_to_cbasis(zbasis): """ Converts a basis state in the Z basis to the computational basis Example: Input: [0,0] -> Output: [1,0,0,0] Input: [0,1] -> Output: [0,1,0,0] Input: [1,0] -> Output: [0,0,1,0] Input: [1,1] -> Output: [0,0,0,1] """ n = 2**len(zbasis) # z basis to binary number bin_str = "".join([str(x) for x in zbasis]) num = int(bin_str,2) # binary number to computational basis cbasis = np.zeros(n) cbasis[num] = 1 return cbasis def cswap_test(x): qc = QuantumCircuit(len(x)+1, 1) input_state = convert_zbasis_to_cbasis(x) qc.initialize(input_state, reversed(range(1,len(x)+1))) qc.barrier() qc.h(0) qc.cswap(0,1,2) qc.h(0) qc.measure(0,0) backend = Aer.get_backend('qasm_simulator') return qc, execute(qc,backend).result().get_counts() qc, counts = cswap_test([0,1]) qc.draw(output='mpl', style='iqx') plot_histogram(counts) states = [ [0,0], [0,1], [1,0], [1,1] ] fig, ax = plt.subplots(1,4, figsize=(16,4)) for i, state in enumerate(states): _, counts = cswap_test(state) plot_histogram(counts, ax=ax[i]) ax[i].set_title(f"Input: {state}") plt.tight_layout() plt.show()
https://github.com/Axect/QuantumAlgorithms
Axect
import pennylane as qml from pennylane import numpy as np import matplotlib.pyplot as plt qml.drawer.use_style(style='sketch') dev = qml.device('default.qubit', wires=['psi', 'a', 'b']) def teleport(theta): # Prepare the state to be teleported qml.QubitStateVector([np.cos(theta), np.sin(theta)], wires='psi') # Prepare the Bell state qml.Hadamard(wires='a') qml.CNOT(wires=['a', 'b']) # Alice applies a reverse bell gate to her qubit, controlled by theta qml.CNOT(wires=['psi', 'a']) qml.Hadamard(wires='psi') qml.Barrier(['psi', 'a'], only_visual=True) # Measure alice's qubits a1 = qml.measure('psi') a2 = qml.measure('a') # Send the classical bits to Bob qml.cond(a2, qml.PauliX)('b') qml.cond(a1, qml.PauliZ)('b') return qml.density_matrix(wires='b') qml.draw_mpl(teleport)(np.pi/4) plt.show() @qml.qnode(dev) def teleport(theta): # Prepare the state to be teleported qml.QubitStateVector([np.cos(theta), np.sin(theta)], wires='psi') # Prepare the Bell state qml.Hadamard(wires='a') qml.CNOT(wires=['a', 'b']) # Alice applies a reverse bell gate to her qubit, controlled by theta qml.CNOT(wires=['psi', 'a']) qml.Hadamard(wires='psi') qml.Barrier(['psi', 'a'], only_visual=True) # Measure alice's qubits a1 = qml.measure('psi') a2 = qml.measure('a') # Send the classical bits to Bob qml.cond(a2, qml.PauliX)('b') qml.cond(a1, qml.PauliZ)('b') return qml.probs(wires='b') qml.draw_mpl(teleport)(np.pi/4) plt.show() theta = np.pi/6 print("Input state: ", np.cos(theta), "|0> +", np.sin(theta), "|1>") print() print("Input probability vector: ") print(np.array([np.cos(theta)**2, np.sin(theta)**2])) print() print("Output probability vector: ") print(teleport(theta))
https://github.com/Axect/QuantumAlgorithms
Axect
import qiskit qiskit.__qiskit_version__ #initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load our saved IBMQ accounts. IBMQ.load_account() nQubits = 14 # number of physical qubits a = 101 # the hidden integer whose bitstring is 1100101 # make sure that a can be represented with nQubits a = a % 2**(nQubits) # Creating registers # qubits for querying the oracle and finding the hidden integer qr = QuantumRegister(nQubits) # for recording the measurement on qr cr = ClassicalRegister(nQubits) circuitName = "BernsteinVazirani" bvCircuit = QuantumCircuit(qr, cr) # Apply Hadamard gates before querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Apply barrier so that it is not optimized by the compiler bvCircuit.barrier() # Apply the inner-product oracle for i in range(nQubits): if (a & (1 << i)): bvCircuit.z(qr[i]) else: bvCircuit.iden(qr[i]) # Apply barrier bvCircuit.barrier() #Apply Hadamard gates after querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Measurement bvCircuit.barrier(qr) bvCircuit.measure(qr, cr) bvCircuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1000 results = execute(bvCircuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') shots = 1000 bvCompiled = transpile(bvCircuit, backend=backend, optimization_level=1) job_exp = execute(bvCircuit, backend=backend, shots=shots) job_monitor(job_exp) results = job_exp.result() answer = results.get_counts(bvCircuit) threshold = int(0.01 * shots) #the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} #filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) #number of counts removed filteredAnswer['other_bitstrings'] = removedCounts #the removed counts is assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/Axect/QuantumAlgorithms
Axect
import qiskit qiskit.__qiskit_version__ # useful additional packages 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.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load our saved IBMQ accounts IBMQ.load_account() n = 13 # the length of the first register for querying the oracle # Choose a type of oracle at random. With probability half it is constant, # and with the same probability it is balanced oracleType, oracleValue = np.random.randint(2), np.random.randint(2) if oracleType == 0: print("The oracle returns a constant value ", oracleValue) else: print("The oracle returns a balanced function") a = np.random.randint(1,2**n) # this is a hidden parameter for balanced oracle. # Creating registers # n qubits for querying the oracle and one qubit for storing the answer qr = QuantumRegister(n+1) #all qubits are initialized to zero # for recording the measurement on the first register cr = ClassicalRegister(n) circuitName = "DeutschJozsa" djCircuit = QuantumCircuit(qr, cr) # Create the superposition of all input queries in the first register by applying the Hadamard gate to each qubit. for i in range(n): djCircuit.h(qr[i]) # Flip the second register and apply the Hadamard gate. djCircuit.x(qr[n]) djCircuit.h(qr[n]) # Apply barrier to mark the beginning of the oracle djCircuit.barrier() if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue for all input. if oracleValue == 1: djCircuit.x(qr[n]) else: djCircuit.iden(qr[n]) else: # Otherwise, it returns the inner product of the input with a (non-zero bitstring) for i in range(n): if (a & (1 << i)): djCircuit.cx(qr[i], qr[n]) # Apply barrier to mark the end of the oracle djCircuit.barrier() # Apply Hadamard gates after querying the oracle for i in range(n): djCircuit.h(qr[i]) # Measurement djCircuit.barrier() for i in range(n): djCircuit.measure(qr[i], cr[i]) #draw the circuit djCircuit.draw(output='mpl',scale=0.5) backend = BasicAer.get_backend('qasm_simulator') shots = 1000 job = execute(djCircuit, backend=backend, shots=shots) results = job.result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') djCompiled = transpile(djCircuit, backend=backend, optimization_level=1) djCompiled.draw(output='mpl',scale=0.5) job = execute(djCompiled, backend=backend, shots=1024) job_monitor(job) results = job.result() answer = results.get_counts() threshold = int(0.01 * shots) # the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} # filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) # number of counts removed filteredAnswer['other_bitstrings'] = removedCounts # the removed counts are assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/Axect/QuantumAlgorithms
Axect
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt def circuit(alice): e = QuantumRegister(2, name='e') a = QuantumRegister(1, name='a') b = QuantumRegister(1, name='b') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(e, a, b, c, name='circuit') # Initialize Target qubit qc.initialize(alice / np.linalg.norm(alice), e) qc.barrier() # Create Bell pair qc.h(a) qc.cx(a, b) qc.barrier() # Write target qubit to Bell pair qc.cz(e[0], a) qc.cx(e[1], a) qc.barrier() # Decoding qc.cx(a, b) qc.h(a) qc.measure(a, c[1]) qc.measure(b, c[0]) backend = Aer.get_backend('qasm_simulator') return qc, execute(qc, backend).result().get_counts() qc, counts = circuit([1,0,0,1]) qc.draw(output='mpl', style='iqx') plot_histogram(counts)
https://github.com/Axect/QuantumAlgorithms
Axect
from qiskit import QuantumCircuit,Aer, execute from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt def check_computational_basis(basis): n = int(np.log2(len(basis))) qc = QuantumCircuit(n,n) initial_state = np.array(basis) / np.linalg.norm(basis) qc.initialize(initial_state, reversed(range(n))) # Input : LSB -> MSB qc.measure(range(n), reversed(range(n))) # Readout: LSB -> MSB backend = Aer.get_backend('qasm_simulator') counts = execute(qc,backend).result().get_counts().keys() return counts def gen_bases(n): return np.eye(2**n) bases = gen_bases(3) for i in range(bases.shape[0]): basis = bases[i].tolist() print(f"basis: {basis} -> {check_computational_basis(basis)}") def convert_zbasis_to_cbasis(zbasis): """ Converts a basis state in the Z basis to the computational basis Example: Input: [0,0] -> Output: [1,0,0,0] Input: [0,1] -> Output: [0,1,0,0] Input: [1,0] -> Output: [0,0,1,0] Input: [1,1] -> Output: [0,0,0,1] """ n = 2**len(zbasis) # z basis to binary number bin_str = "".join([str(x) for x in zbasis]) num = int(bin_str,2) # binary number to computational basis cbasis = np.zeros(n) cbasis[num] = 1 return cbasis def cswap_test(x): qc = QuantumCircuit(len(x)+1, 1) input_state = convert_zbasis_to_cbasis(x) qc.initialize(input_state, reversed(range(1,len(x)+1))) qc.barrier() qc.h(0) qc.cswap(0,1,2) qc.h(0) qc.measure(0,0) backend = Aer.get_backend('qasm_simulator') return qc, execute(qc,backend).result().get_counts() qc, counts = cswap_test([0,1]) qc.draw(output='mpl', style='iqx') plot_histogram(counts) states = [ [0,0], [0,1], [1,0], [1,1] ] fig, ax = plt.subplots(1,4, figsize=(16,4)) for i, state in enumerate(states): _, counts = cswap_test(state) plot_histogram(counts, ax=ax[i]) ax[i].set_title(f"Input: {state}") plt.tight_layout() plt.show()
https://github.com/Axect/QuantumAlgorithms
Axect
import qiskit qiskit.__qiskit_version__ #initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load our saved IBMQ accounts. IBMQ.load_account() nQubits = 14 # number of physical qubits a = 101 # the hidden integer whose bitstring is 1100101 # make sure that a can be represented with nQubits a = a % 2**(nQubits) # Creating registers # qubits for querying the oracle and finding the hidden integer qr = QuantumRegister(nQubits) # for recording the measurement on qr cr = ClassicalRegister(nQubits) circuitName = "BernsteinVazirani" bvCircuit = QuantumCircuit(qr, cr) # Apply Hadamard gates before querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Apply barrier so that it is not optimized by the compiler bvCircuit.barrier() # Apply the inner-product oracle for i in range(nQubits): if (a & (1 << i)): bvCircuit.z(qr[i]) else: bvCircuit.iden(qr[i]) # Apply barrier bvCircuit.barrier() #Apply Hadamard gates after querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Measurement bvCircuit.barrier(qr) bvCircuit.measure(qr, cr) bvCircuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1000 results = execute(bvCircuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') shots = 1000 bvCompiled = transpile(bvCircuit, backend=backend, optimization_level=1) job_exp = execute(bvCircuit, backend=backend, shots=shots) job_monitor(job_exp) results = job_exp.result() answer = results.get_counts(bvCircuit) threshold = int(0.01 * shots) #the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} #filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) #number of counts removed filteredAnswer['other_bitstrings'] = removedCounts #the removed counts is assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/Axect/QuantumAlgorithms
Axect
import qiskit qiskit.__qiskit_version__ # useful additional packages 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.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load our saved IBMQ accounts IBMQ.load_account() n = 13 # the length of the first register for querying the oracle # Choose a type of oracle at random. With probability half it is constant, # and with the same probability it is balanced oracleType, oracleValue = np.random.randint(2), np.random.randint(2) if oracleType == 0: print("The oracle returns a constant value ", oracleValue) else: print("The oracle returns a balanced function") a = np.random.randint(1,2**n) # this is a hidden parameter for balanced oracle. # Creating registers # n qubits for querying the oracle and one qubit for storing the answer qr = QuantumRegister(n+1) #all qubits are initialized to zero # for recording the measurement on the first register cr = ClassicalRegister(n) circuitName = "DeutschJozsa" djCircuit = QuantumCircuit(qr, cr) # Create the superposition of all input queries in the first register by applying the Hadamard gate to each qubit. for i in range(n): djCircuit.h(qr[i]) # Flip the second register and apply the Hadamard gate. djCircuit.x(qr[n]) djCircuit.h(qr[n]) # Apply barrier to mark the beginning of the oracle djCircuit.barrier() if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue for all input. if oracleValue == 1: djCircuit.x(qr[n]) else: djCircuit.iden(qr[n]) else: # Otherwise, it returns the inner product of the input with a (non-zero bitstring) for i in range(n): if (a & (1 << i)): djCircuit.cx(qr[i], qr[n]) # Apply barrier to mark the end of the oracle djCircuit.barrier() # Apply Hadamard gates after querying the oracle for i in range(n): djCircuit.h(qr[i]) # Measurement djCircuit.barrier() for i in range(n): djCircuit.measure(qr[i], cr[i]) #draw the circuit djCircuit.draw(output='mpl',scale=0.5) backend = BasicAer.get_backend('qasm_simulator') shots = 1000 job = execute(djCircuit, backend=backend, shots=shots) results = job.result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') djCompiled = transpile(djCircuit, backend=backend, optimization_level=1) djCompiled.draw(output='mpl',scale=0.5) job = execute(djCompiled, backend=backend, shots=1024) job_monitor(job) results = job.result() answer = results.get_counts() threshold = int(0.01 * shots) # the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} # filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) # number of counts removed filteredAnswer['other_bitstrings'] = removedCounts # the removed counts are assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/Axect/QuantumAlgorithms
Axect
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt def circuit(alice): e = QuantumRegister(2, name='e') a = QuantumRegister(1, name='a') b = QuantumRegister(1, name='b') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(e, a, b, c, name='circuit') # Initialize Target qubit qc.initialize(alice / np.linalg.norm(alice), e) qc.barrier() # Create Bell pair qc.h(a) qc.cx(a, b) qc.barrier() # Write target qubit to Bell pair qc.cz(e[0], a) qc.cx(e[1], a) qc.barrier() # Decoding qc.cx(a, b) qc.h(a) qc.measure(a, c[1]) qc.measure(b, c[0]) backend = Aer.get_backend('qasm_simulator') return qc, execute(qc, backend).result().get_counts() qc, counts = circuit([1,0,0,1]) qc.draw(output='mpl', style='iqx') plot_histogram(counts)
https://github.com/Axect/QuantumAlgorithms
Axect
from qiskit import QuantumCircuit,Aer, execute from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt def check_computational_basis(basis): n = int(np.log2(len(basis))) qc = QuantumCircuit(n,n) initial_state = np.array(basis) / np.linalg.norm(basis) qc.initialize(initial_state, reversed(range(n))) # Input : LSB -> MSB qc.measure(range(n), reversed(range(n))) # Readout: LSB -> MSB backend = Aer.get_backend('qasm_simulator') counts = execute(qc,backend).result().get_counts().keys() return counts def gen_bases(n): return np.eye(2**n) bases = gen_bases(3) for i in range(bases.shape[0]): basis = bases[i].tolist() print(f"basis: {basis} -> {check_computational_basis(basis)}") def convert_zbasis_to_cbasis(zbasis): """ Converts a basis state in the Z basis to the computational basis Example: Input: [0,0] -> Output: [1,0,0,0] Input: [0,1] -> Output: [0,1,0,0] Input: [1,0] -> Output: [0,0,1,0] Input: [1,1] -> Output: [0,0,0,1] """ n = 2**len(zbasis) # z basis to binary number bin_str = "".join([str(x) for x in zbasis]) num = int(bin_str,2) # binary number to computational basis cbasis = np.zeros(n) cbasis[num] = 1 return cbasis def cswap_test(x): qc = QuantumCircuit(len(x)+1, 1) input_state = convert_zbasis_to_cbasis(x) qc.initialize(input_state, reversed(range(1,len(x)+1))) qc.barrier() qc.h(0) qc.cswap(0,1,2) qc.h(0) qc.measure(0,0) backend = Aer.get_backend('qasm_simulator') return qc, execute(qc,backend).result().get_counts() qc, counts = cswap_test([0,1]) qc.draw(output='mpl', style='iqx') plot_histogram(counts) states = [ [0,0], [0,1], [1,0], [1,1] ] fig, ax = plt.subplots(1,4, figsize=(16,4)) for i, state in enumerate(states): _, counts = cswap_test(state) plot_histogram(counts, ax=ax[i]) ax[i].set_title(f"Input: {state}") plt.tight_layout() plt.show()
https://github.com/DarkStarQuantumLab/Qauntum-trading-a-disturbance-in-the-force-of-supply-and-demand
DarkStarQuantumLab
!python3 -m pip install -q qiskit !python3 -m pip install -q qiskit_ibm_runtime from qiskit import IBMQ from qiskit_ibm_runtime import QiskitRuntimeService, Session, Options, Sampler, Estimator from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.quantum_info.operators import Operator from qiskit.extensions.unitary import UnitaryGate from qiskit.providers.aer import AerSimulator, Aer from qiskit.execute_function import execute import numpy as np from typing import Dict, Optional # ==================================== # pass IBM API Token # ==================================== QiskitRuntimeService.save_account(channel='ibm_quantum', token="", overwrite=True) num_players = 2 # define the payoff matrices. Assume, the 1st matrix is Alice's payoff, the secomd matrix is Bob's payoff payoff_matrix =[[[3, 0], [5, 1]], [[3, 5], [0, 1]]] # players' matrices # |C> strategy # bob = [ # [1, 0], # [0, 1]] # |D> strategy # bob = [ # [0, 1], # [1, 0], # ] def alice_plays_quantum(theta:float, phi:float): """ Set up a quantum game for Alice playing quantum, and Bob playing classically. Arg: theta: the value of the theta parameter. phi: the value of the phi parameter. Returns: qc: the class of 'qiskit.circuit.quantumcircuit.QuantumCircuit', a constructed quantum circuit for the quantum game set up. """ alice = np.array([[np.exp(1.0j*phi)*np.cos(theta/2), np.sin(theta/2)], [-np.sin(theta/2), np.exp(-1.0j*phi)*np.cos(theta/2)]]) bob = np.array([ [1, 0], [0, 1]]).astype(complex) qc = QuantumCircuit(num_players) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0,1]) qc.barrier() unitary_alice = UnitaryGate(Operator(alice)) unitary_bob = UnitaryGate(Operator(bob)) qc.append(unitary_alice, [0]) qc.append(unitary_bob, [1]) qc.barrier() Jdagger_unitary = UnitaryGate(Operator(J.conj().T)) qc.append(Jdagger_unitary, [0,1]) return qc # test run # define the simulator simulator = Aer.get_backend('statevector_simulator') theta = np.pi phi = 0.0 qc = alice_plays_quantum(theta, phi) results = execute(qc, simulator, shots=1024).result().get_counts() results # calculating payoffs def get_payoff(counts): """ Calculate the reward for the players after the game ends. """ payoff_bob = [] payoff_alice = [] for strategy, prob in counts.items(): strategy_bob = int(strategy[1]) strategy_alice = int(strategy[0]) payoff_bob.append(prob * payoff_matrix[0][strategy_alice][strategy_bob]) payoff_alice.append(prob * payoff_matrix[0][strategy_bob][strategy_alice]) return sum(payoff_alice), sum(payoff_bob) # change the size on the quantum space to explore more quantum strategies space_size = 4 for phi in np.linspace(0, np.pi/2, space_size): for theta in np.linspace(0, np.pi, space_size): qc = alice_plays_quantum(theta, phi) results = execute(qc, simulator, shots=1024).result().get_counts() payoff_alice, payoff_bob = get_payoff(results) print("theta = {}, phi = {}, results = {}, Alice's payoff {}, Bob's payoff {}".format(theta, phi, results, payoff_alice, payoff_bob)) print("Next Game") qc = alice_plays_quantum(theta = np.pi/2, phi = np.pi/4) job = simulator.run(qc, shots=2048) result = job.result() outputstate = result.get_statevector(qc, decimals=3) print(outputstate) from qiskit.visualization import plot_state_city plot_state_city(outputstate) from qiskit.visualization import plot_histogram counts = result.get_counts() plot_histogram(counts) # probabilities of a certain outcome counts num_players = 2 def alice_bob_play_quantum(theta_a:float, phi_a:float, theta_b:float, phi_b:float, measure=False): """ Set up a quantum game. Both players have access to quantum strategies. Args: theta_a: Theta parameter for Alice's unitary. phi_a: Phi parameter for Alice's unitary. theta_b: Theta parameter for Bob's unitary. phi_b: Phi parameter for Bob's unitary. Returns: qc: the class of 'qiskit.circuit.quantumcircuit.QuantumCircuit', a constructed quantum circuit for the quantum game set up. """ alice = np.array([ [np.exp(1.0j*phi_a)*np.cos(theta_a/ 2), np.sin(theta_a / 2)], [-np.sin(theta_a / 2), np.exp(-1.0j*phi_a)*np.cos(theta_a / 2)]]) bob = np.array([ [np.exp(1.0j*phi_b)*np.cos(theta_b / 2), np.sin(theta_b / 2)], [-np.sin(theta_b / 2), np.exp(-1.0j*phi_b)*np.cos(theta_b / 2)]]) qc = QuantumCircuit(num_players) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0,1]) qc.barrier() unitary_alice = UnitaryGate(Operator(alice)) unitary_bob = UnitaryGate(Operator(bob)) qc.append(unitary_alice, [0]) qc.append(unitary_bob, [1]) qc.barrier() Jdagger_unitary = UnitaryGate(Operator(J.conj().T)) qc.append(Jdagger_unitary, [0,1]) if measure: qc.measure_all() return qc alice_reward = 0 bob_reward = 0 draw = 0 space_size = 2 for phi1 in np.linspace(0, 2*np.pi, space_size): for theta1 in np.linspace(0, np.pi, space_size): for phi2 in np.linspace(0, 2*np.pi, space_size): for theta2 in np.linspace(0, np.pi, space_size): qc = alice_bob_play_quantum(theta1, phi1, theta2, phi2) results = execute(qc, simulator, shots=1024).result().get_counts() payoff_alice, payoff_bob = get_payoff(results) # count winning if payoff_alice > payoff_bob: alice_reward += 1 elif payoff_bob > payoff_alice: bob_reward += 1 else: draw += 1 # print results print("theta_alice = {}, phi_alice = {}, theta_bob = {}, phi_bob = {}".format(theta1, phi1, theta2, phi2 )) print("results = {}, Alice's raward {}, Bob's reward {}".format(results, payoff_alice, payoff_bob)) print("Next Game") print("===================================================") print("In {} games Alice gets a higher reward than Bob.". format(alice_reward)) print("In {} games, Bob gets a higher reward than Alice.".format(bob_reward)) print("In {} games Alice and Bob get equal reward.".format(draw)) matrix = np.array([[1.0j, 0], [0, -1.0j]]) qc = QuantumCircuit(2) gate = UnitaryGate(Operator(matrix)) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0,1]) qc.barrier() qc.append(gate, [0]) qc.append(gate, [1]) qc.barrier() Jdagger_unitary = UnitaryGate(Operator(J.conj().T)) qc.append(Jdagger_unitary, [0,1]) results = execute(qc, simulator, shots=1024).result().get_counts() alice_payoff, bob_payoff = get_payoff(results) print("Strategy: {}".format(results)) print("Alice's payoff is {}, Bob's payoff is {}".format(alice_payoff, bob_payoff)) import matplotlib.pyplot as plt space_size = 40 def payoff_plot(): """ Plot expected payoff distribution for Alice. """ x = np.linspace(1, -1, space_size) y = np.linspace(-1, 1, space_size) X, Y = np.meshgrid(x, y) Z = np.zeros(X.shape) for i in range(0,space_size): for inner in range(0, space_size): if X[inner][i] < 0 and Y[inner][i] < 0: qc = alice_bob_play_quantum(0, X[inner][i]*np.pi/2, 0, Y[inner][i]*np.pi/2) payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts()) Z[inner][i] = payoff_alice elif X[inner][i] >= 0 and Y[inner][i] >= 0: qc = alice_bob_play_quantum(X[inner][i]*np.pi, 0, Y[inner][i]*np.pi, 0) payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts()) Z[inner][i] = payoff_alice elif X[inner][i] >= 0 and Y[inner][i] < 0: qc = alice_bob_play_quantum(X[inner][i]*np.pi, 0, 0, Y[inner][i]*np.pi/2) payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts()) Z[inner][i] = payoff_alice elif X[inner][i] < 0 and Y[inner][i] >= 0: qc = alice_bob_play_quantum(0, X[inner][i]*np.pi/2, Y[inner][i]*np.pi, 0) payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts()) Z[inner][i] = payoff_alice fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(111, projection='3d') ax.plot_surface(X, Y, Z, cmap=plt.cm.coolwarm, antialiased=True) ax.set(xlim=(-1, 1), ylim=(1, -1), xlabel="Bob strategy", ylabel='Alice strategy', zlabel="Alice's expected payoff") plt.show() payoff_plot() def build_qcir_three_parameters(theta1, phi1, lmbda, theta2, phi2): """ Set up a quantum game. Both players have access to quantum strategies space """ alice = np.array([ [np.exp(1.0j*phi1)*np.cos(theta1/2), 1.0j*np.exp(1.0j * lmbda) * np.sin(theta1/2)], [1.0j*np.exp(-1.0j * lmbda) * np.sin(theta1/2), np.exp(-1.0j*phi1)*np.cos(theta1/2)]]) bob = np.array([ [np.exp(1.0j*phi2)*np.cos(theta2/2), np.sin(theta2/2)], [-np.sin(theta2/2), np.exp(-1.0j*phi2)*np.cos(theta2/2)]]) qc = QuantumCircuit(num_players) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0,1]) qc.barrier() unitary_alice = UnitaryGate(Operator(alice)) unitary_bob = UnitaryGate(Operator(bob)) qc.append(unitary_alice, [0]) qc.append(unitary_bob, [1]) qc.barrier() Jdagger_unitary = UnitaryGate(Operator(J.conj().T)) qc.append(Jdagger_unitary, [0,1]) return qc alice_reward = 0 bob_reward = 0 draw = 0 space_size = 4 for phi1 in np.linspace(-np.pi, np.pi, space_size): for theta1 in np.linspace(0, np.pi, space_size): for phi2 in np.linspace(-np.pi, np.pi, space_size): for theta2 in np.linspace(0, np.pi, space_size): for lmbda in np.linspace(-np.pi, np.pi, 2*space_size): qc = build_qcir_three_parameters(theta1, phi1, lmbda, theta2, phi2) results = execute(qc, simulator, shots=1024).result().get_counts() payoff_alice, payoff_bob = get_payoff(results) # count winning if payoff_alice > payoff_bob: alice_reward += 1 elif payoff_bob > payoff_alice: bob_reward += 1 else: draw += 1 # print results print("theta_alice = {}, phi_alice = {}, theta_bob = {}, phi_bob = {}".format(theta1, phi1, theta2, phi2 )) print("results = {}, Alice's payoff {}, Bob's payoff {}".format(results, payoff_alice, payoff_bob)) print("Next Game") print("===================================================") print("In {} games Alice gets a higher reward than Bob.". format(alice_reward)) print("In {} games, Bob gets a higher reward than Alice.".format(bob_reward)) print("In {} games Alice and Bob get equal reward.".format(draw)) !python3 -m pip install -q qiskit-ibm-provider from qiskit.providers.ibmq import least_busy from qiskit_ibm_provider import IBMProvider provider = IBMProvider() # ==================================== # pass IBM API Token # ==================================== provider.save_account(token=, overwrite=True) small_devices = provider.backends(filters=lambda x: x.configuration().n_qubits == 5 and not x.configuration().simulator) least_busy(small_devices) backend = least_busy(small_devices) qc = alice_bob_play_quantum(theta_a = 0, phi_a = 0, theta_b = np.pi/2, phi_b = 0, measure=True) job = execute(qc, backend, optimization_level=2) result = job.result() counts = result.get_counts() counts plot_histogram(counts) job = execute(qc, backend=Aer.get_backend('statevector_simulator'), shots=1024) result = job.result() counts = result.get_counts() print(counts) plot_histogram(counts) from functools import reduce from operator import add from qiskit import quantum_info as qi def mixed_strategy(alpha_a:float, alpha_b:float): """ Set up a quantum game. Both players have access to quantum strategies. Args: theta_a: Theta parameter for Alice's unitary. phi_a: Phi parameter for Alice's unitary. theta_b: Theta parameter for Bob's unitary. phi_b: Phi parameter for Bob's unitary. Returns: qc: the class of 'qiskit.circuit.quantumcircuit.QuantumCircuit', a constructed quantum circuit for the quantum game set up. """ qc = QuantumCircuit(2) # Alice strategies unitary1_a = np.eye(2).astype(complex) unitary2_a = np.array([[-1.0j, 0], [0, 1.0j]]) # Bob's strategies unitary1_b = np.array([[0, 1], [-1, 0]]).astype(complex) unitary2_b = np.array([[0, -1.0j], [-1.0j, 0]]).astype(complex) # define probabilities for Alice p1_a = np.cos(alpha_a / 2) ** 2 p2_a = np.sin(alpha_a/ 2) ** 2 # define probabilities for Bob p1_b = np.cos(alpha_b / 2) ** 2 p2_b = np.sin(alpha_b/ 2) ** 2 # define the set of actions and their probability distribution. mixed_strategy = [[(p1_a, unitary1_a), (p2_a, unitary2_a)], [(p1_b, unitary1_b), (p2_b, unitary2_b)]] identity = np.eye(2) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0, 1]) rho = qi.DensityMatrix.from_instruction(qc) for index, strategy in enumerate(mixed_strategy): rho = reduce(add, (prob * rho.evolve(np.kron(*[strat if index == player else identity for player in range(num_players)])) for prob, strat in strategy)) rho = rho.evolve(Operator(J.conj().T)) return rho.probabilities() payoff_matrix =[[[3, 0], [5, 1]], [[3, 5], [0, 1]]] for alpha_a in np.linspace(0, np.pi, 4): for alpha_b in np.linspace(0, np.pi, 2): print("alpha_a = ", alpha_a) print("alpha_b = ", alpha_b) prob = mixed_strategy(alpha_a, alpha_b) print("prob = ", prob) alice_matrix = np.reshape(payoff_matrix[0], (1,4)) bob_matrix = np.reshape(payoff_matrix[1], (1,4)) print("Alice's Payoff = ", np.round(np.dot(prob, alice_matrix[0]), 3)) print("Bob's Payoff = ", np.round(np.dot(prob, bob_matrix[0]),3)) print("=======================") # probability of 1/2 and 1/2 yeilds the payoffs of 2.5 for each player. prob = mixed_strategy(np.pi/2, np.pi/2) print("prob = ", prob) alice_matrix = np.reshape(payoff_matrix[0], (1,4)) bob_matrix = np.reshape(payoff_matrix[1], (1,4)) print("Alice's Payoff = ", np.round(np.dot(prob, alice_matrix[0]), 3)) print("Bob's Payoff = ", np.round(np.dot(prob, bob_matrix[0]),3))
https://github.com/DarkStarQuantumLab/Qauntum-trading-a-disturbance-in-the-force-of-supply-and-demand
DarkStarQuantumLab
!python3 -m pip install -q qiskit !python3 -m pip install -q qiskit_ibm_runtime !python3 -m pip install qiskit-aer import numpy as np import pandas as pd from qiskit import IBMQ, BasicAer, Aer from qiskit_ibm_runtime import QiskitRuntimeService, Session, Options, Sampler, Estimator from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.quantum_info.operators import Operator from qiskit.extensions.unitary import UnitaryGate from qiskit.execute_function import execute from typing import Dict, Optional from sympy import Matrix from sympy.physics.quantum import TensorProduct num_players = 2 # define the payoff matrices. Assume, the 1st matrix is Alice's payoff, the secomd matrix is Bob's payoff payoff_matrix =[[[3, 0], [5, 1]], [[3, 5], [0, 1]]] # calculating payoffs def get_payoff(counts): """ Calculate the reward for the players after the game ends. """ payoff_bob = [] payoff_alice = [] for strategy, prob in counts.items(): strategy_bob = int(strategy[1]) strategy_alice = int(strategy[0]) payoff_bob.append(prob * payoff_matrix[0][strategy_alice][strategy_bob]) payoff_alice.append(prob * payoff_matrix[0][strategy_bob][strategy_alice]) return sum(payoff_alice), sum(payoff_bob) # define the simulator simulator = Aer.get_backend('statevector_simulator') def build_qcir_two_by_two_parameters(theta1, phi1, theta2, phi2): alice = np.array([ [np.exp(1.0j*phi1)*np.cos(theta1), np.sin(theta1)], [-np.sin(theta1), np.exp(-1.0j*phi1)*np.cos(theta1)]]) bob = np.array([ [np.exp(1.0j*phi2)*np.cos(theta2), np.sin(theta2)], [-np.sin(theta2), np.exp(-1.0j*phi2)*np.cos(theta2)]]) qc = QuantumCircuit(num_players) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0,1]) qc.barrier() unitary_alice = UnitaryGate(Operator(alice)) unitary_bob = UnitaryGate(Operator(bob)) qc.append(unitary_alice, [0]) qc.append(unitary_bob, [1]) qc.barrier() Jdagger_unitary = UnitaryGate(Operator(J.conj().T)) qc.append(Jdagger_unitary, [0,1]) return qc space_size = 4 actions_list = [] "quantum games theta and phi ranges" for theta1 in np.linspace(0, np.pi/2, space_size): for phi1 in np.linspace(0, np.pi/2, space_size): actions_list.append((theta1,phi1)) def epsilon_Greedy_Policy_2x2(eps, playerName): p = np.random.random() if p < eps: index = np.random.choice(len(actions_list)) action_chosen = actions_list[index] else: if(playerName == "Alice"): index = np.argmax(Q_Alice) action_chosen = actions_list[index] elif(playerName == "Bob"): index = np.argmax(Q_Bob) action_chosen = actions_list[index] return (action_chosen[0],action_chosen[1], index) epsilonArray = [] payoffPercentage3_3 = [] eps = np.arange(0.0, 0.1, 0.01) for e in eps: count = 0 for k in range(100): Q_Alice = [0]*len(actions_list) Q_Bob = [0]*len(actions_list) T = 20 #assuming t = 100 alice_reward = [0]*len(actions_list) bob_reward = [0]*len(actions_list) # Initialize parameters #gamma = 0.5 # Discount factor alpha = 0.9 # Learning rate #epsilon = 0.04 for t in range(T): theta1, phi1, action_index_Alice = epsilon_Greedy_Policy_2x2(e,"Alice") theta2, phi2, action_index_Bob = epsilon_Greedy_Policy_2x2(e, "Bob") qc = build_qcir_two_by_two_parameters(theta1, phi1, theta2, phi2) results = execute(qc, simulator, shots=1024).result().get_counts() payoff_alice, payoff_bob = get_payoff(results) alice_reward[action_index_Alice] = payoff_alice bob_reward[action_index_Bob] = payoff_bob Q_Alice[action_index_Alice] = Q_Alice[action_index_Alice] + alpha * (alice_reward[action_index_Alice]-(Q_Alice[action_index_Alice])) Q_Bob[action_index_Bob] = Q_Bob[action_index_Bob] + alpha * (bob_reward[action_index_Bob]-(Q_Bob[action_index_Bob])) #Q_Alice[action_index_Alice] = Q_Alice[action_index_Alice] + alpha * (alice_reward[action_index_Alice] + (gamma*max(Q_Alice)) -(Q_Alice[action_index_Alice])) #Q_Bob[action_index_Bob] = Q_Bob[action_index_Bob] + alpha * (bob_reward[action_index_Bob] + (gamma*max(Q_Bob)) - (Q_Bob[action_index_Bob])) for i in range(len(Q_Alice)): if(Q_Alice[i] == 3 and Q_Bob[i] ==3): count+=1 epsilonArray.append(e) payoffPercentage3_3.append(count) print(epsilonArray) print(payoffPercentage3_3) import matplotlib.pyplot as plt x = epsilonArray y = payoffPercentage3_3 plt.scatter(x, y) plt.show()
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from scipy.stats import kruskal import pandas as pd import numpy as np #if p value less than alpha reject qiskit_data = np.full(100000, 0) print(qiskit_data) cirq_data = np.full(100000, 0) qs_data = np.full(100000, 0) kruskal(qiskit_data, cirq_data, qs_data) qiskit_data = np.concatenate((np.full(41192, 8), np.full(1555, 9), np.full(7096, 10), np.full(226, 11), np.full(41044, 12), np.full(1637, 13), np.full(6961, 14), np.full(289, 15))) print(qiskit_data) cirq_data = np.concatenate((np.full(41016, 8), np.full(1163, 9), np.full(7092, 10), np.full(301, 11), np.full(41024, 12), np.full(1635, 13), np.full(7017, 14), np.full(282, 15))) print(cirq_data) qs_data = np.concatenate((np.full(40973, 8), np.full(1706, 9), np.full(7123, 10), np.full(314, 11), np.full(40899, 12), np.full(1621, 13), np.full(7076, 14), np.full(288, 15))) print(qs_data) kruskal(qiskit_data, cirq_data, qs_data) qiskit_data = np.concatenate((np.full(1676, 8), np.full(40877, 9), np.full(285, 10), np.full(7103, 11), np.full(1610, 12), np.full(41135, 13), np.full(256, 14), np.full(7058, 15))) print(qiskit_data) cirq_data = np.concatenate((np.full(1639, 8), np.full(40954, 9), np.full(285, 10), np.full(6906, 11), np.full(1582, 12), np.full(41332, 13), np.full(265, 14), np.full(7037, 15))) print(cirq_data) qs_data = np.concatenate((np.full(1656, 8), np.full(41277, 9), np.full(251, 10), np.full(7103, 11), np.full(1608, 12), np.full(40752, 13), np.full(271, 14), np.full(7082, 15))) print(qs_data) kruskal(qiskit_data, cirq_data, qs_data) qiskit_data = np.concatenate((np.full(41064, 8), np.full(1645, 9), np.full(7072, 10), np.full(261, 11), np.full(40850, 12), np.full(1612, 13), np.full(7223, 14), np.full(273, 15))) print(qiskit_data) cirq_data = np.concatenate((np.full(41036, 8), np.full(1582, 9), np.full(7094, 10), np.full(250, 11), np.full(41178, 12), np.full(1621, 13), np.full(6967, 14), np.full(272, 15))) print(cirq_data) qs_data = np.concatenate((np.full(41120, 8), np.full(1643, 9), np.full(6953, 10), np.full(251, 11), np.full(41011, 12), np.full(1631, 13), np.full(7131, 14), np.full(260, 15))) print(qs_data) kruskal(qiskit_data, cirq_data, qs_data)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from scipy.stats import kruskal, f_oneway import pandas as pd import numpy as np #if p value less than alpha reject qiskit_data = np.full(10000, 0.25) cirq_data = np.full(10000, 0.25) qs_data = np.full(10000, 0.25) kruskal(qiskit_data, cirq_data, qs_data) #if p value less than alpha reject qiskit_data = np.full(10000, 0.75) cirq_data = np.full(10000, 0.75) qs_data = np.full(10000, 0.75) kruskal(qiskit_data, cirq_data, qs_data) qiskit_data = np.concatenate((np.full(7576, 0.375), np.full(1253, 0.3125), np.full(359, 0.4375), np.full(218, 0.25), np.full(121, 0.5), np.full(101, 0.1875), np.full(66, 0.5625), np.full(57, 0.125), np.full(42, 0.625), np.full(41, 0.0625), np.full(35, 0), np.full(29, 0.9375), np.full(27, 0.8125), np.full(27, 0.6875), np.full(25, 0.75), np.full(23, 0.875))) print(qiskit_data) cirq_data = np.concatenate((np.full(7610, 0.375), np.full(1208, 0.3125), np.full(377, 0.4375), np.full(235, 0.25), np.full(129, 0.5), np.full(89, 0.1875), np.full(68, 0.5625), np.full(55, 0.125), np.full(36, 0.625), np.full(30, 0.0625), np.full(31, 0), np.full(28, 0.9375), np.full(24, 0.8125), np.full(34, 0.6875), np.full(25, 0.75), np.full(21, 0.875))) print(cirq_data) qs_data = np.concatenate((np.full(7593, 0.375), np.full(1247, 0.3125), np.full(384, 0.4375), np.full(213, 0.25), np.full(121, 0.5), np.full(114, 0.1875), np.full(61, 0.5625), np.full(35, 0.125), np.full(39, 0.625), np.full(28, 0.0625), np.full(38, 0), np.full(22, 0.9375), np.full(18, 0.8125), np.full(28, 0.6875), np.full(27, 0.75), np.full(32, 0.875))) print(qs_data) kruskal(qiskit_data, cirq_data, qs_data) qiskit_data = np.concatenate((np.full(137,0.375), np.full(9375,0.359375), np.full(235,0.34375), np.full(4,0.265625), np.full(52,0.390625), np.full(4,0.453125), np.full(58,0.328125), np.full(15,0.296875), np.full(10,0.421875), np.full(27,0.40625), np.full(1,0.890625), np.full(21,0.3125), np.full(1,0.140625), np.full(1,0.171875), np.full(5,0.53125), np.full(1,0.921875), np.full(2,0.21875), np.full(1,0), np.full(1,0.9375), np.full(1,0.203125), np.full(1,0.5625), np.full(4,0.234375), np.full(1,0.59375), np.full(1,0.09375), np.full(1,0.734375), np.full(7,0.4375), np.full(1,0.953125), np.full(2,0.1875), np.full(2,0.671875), np.full(1,0.0625), np.full(1,0.703125), np.full(1,0.796875), np.full(1,0.484375), np.full(11,0.28125), np.full(2,0.15625), np.full(2,0.609375), np.full(1,0.84375), np.full(1,0.65625), np.full(1,0.046875), np.full(3,0.25), np.full(2,0.5), np.full(1,0.46875))) print(qiskit_data) cirq_data = np.concatenate((np.full(143,0.375), np.full(9340,0.359375), np.full(3,0.484375), np.full(61,0.328125), np.full(13,0.40625), np.full(260,0.34375), np.full(1,0.921875), np.full(45,0.390625), np.full(13,0.421875), np.full(2,0.09375), np.full(5,0.234375), np.full(14,0.296875), np.full(3,0.4375), np.full(34,0.3125), np.full(1,0.765625), np.full(2,0.75), np.full(11,0.28125), np.full(6,0.46875), np.full(5,0.265625), np.full(2,0.140625), np.full(2,0.796875), np.full(2,0.515625), np.full(3,0.21875), np.full(2,0.703125), np.full(1,0.625), np.full(1,0.53125), np.full(1,0.984375), np.full(1,0.546875), np.full(2,0.640625), np.full(2,0.1875), np.full(2,0.15625), np.full(2,0.125), np.full(1,0.03125), np.full(1,0.859375), np.full(2,0.25), np.full(1,0.453125), np.full(3,0.046875), np.full(1,0.0625), np.full(1,0.953125), np.full(1,0.59375), np.full(1,0.90625), np.full(1,0.078125), np.full(1,0.78125), np.full(1,0.5))) print(cirq_data) qs_data = np.concatenate((np.full(9324,0.359375), np.full(290,0.34375), np.full(137,0.375), np.full(57,0.328125), np.full(30,0.390625), np.full(20,0.3125), np.full(18,0.296875), np.full(17,0.40625), np.full(13,0.421875), np.full(11,0.28125), np.full(10,0.4375), np.full(9,0.265625), np.full(8,0.25), np.full(6,0.453125), np.full(4,0.46875), np.full(4,0.515625), np.full(4,0.234375), np.full(3,0.5), np.full(3,0.1875), np.full(3,0.171875), np.full(2,0.125), np.full(2,0.21875), np.full(2,0.75), np.full(2,0.609375), np.full(2,0.140625), np.full(2,0.203125), np.full(1,0.53125), np.full(1,0.546875), np.full(1,0.640625), np.full(1,0.0625), np.full(1,0.78125), np.full(1,0.671875), np.full(1,0), np.full(1,0.484375), np.full(1,0.796875), np.full(1,0.921875), np.full(1,0.03125), np.full(1,0.015625), np.full(1,0.84375), np.full(1,0.578125), np.full(1,0.078125), np.full(1,0.9375), np.full(1,0.984375))) print(qs_data) # since we have so many 'categories' it makes more sense to run a traditional ANOVA test f_oneway(qiskit_data, cirq_data, qs_data) qiskit_data = np.concatenate((np.full(4969,0.71875), np.full(2,0.0546875), np.full(4,0.5078125), np.full(3171,0.7265625), np.full(48,0.6875), np.full(7,0.828125), np.full(53,0.7578125), np.full(176,0.703125), np.full(8,0.8125), np.full(406,0.734375), np.full(144,0.7421875), np.full(475,0.7109375), np.full(8,0.8359375), np.full(1,0.265625), np.full(3,0.484375), np.full(3,0.8828125), np.full(6,0.6015625), np.full(38,0.6796875), np.full(80,0.75), np.full(1,0.1640625), np.full(87,0.6953125), np.full(25,0.7734375), np.full(18,0.78125), np.full(5,0.5859375), np.full(5,0.9296875), np.full(14,0.6640625), np.full(10,0.6484375), np.full(3,0.8984375), np.full(2,0.6171875), np.full(31,0.765625), np.full(16,0.671875), np.full(14,0.7890625), np.full(4,0.8671875), np.full(7,0.625), np.full(12,0.6328125), np.full(4,0.609375), np.full(3,0.875), np.full(2,0.4765625), np.full(1,0.2734375), np.full(2,0.34375), np.full(1,0.40625), np.full(5,0.5390625), np.full(8,0.640625), np.full(6,0.796875), np.full(1,0.21875), np.full(9,0.8046875), np.full(4,0.5703125), np.full(1,0.4453125), np.full(3,0.5), np.full(1,0.046875), np.full(11,0.65625), np.full(6,0.8203125), np.full(7,0.84375), np.full(1,0.296875), np.full(2,0.015625), np.full(1,0.53125), np.full(1,0.953125), np.full(1,0.4140625), np.full(5,0.8515625), np.full(1,0.9921875), np.full(1,0.5234375), np.full(1,0.0390625), np.full(1,0.4609375), np.full(1,0.921875), np.full(4,0.59375), np.full(2,0.90625), np.full(9,0.578125), np.full(1,0.4921875), np.full(1,0.2578125), np.full(4,0.859375), np.full(1,0.4296875), np.full(1,0.5625), np.full(2,0), np.full(2,0.546875), np.full(2,0.234375), np.full(1,0.2109375), np.full(1,0.328125), np.full(3,0.890625), np.full(1,0.171875), np.full(1,0.375), np.full(4,0.9375), np.full(1,0.9609375), np.full(1,0.15625), np.full(1,0.390625), np.full(2,0.0859375), np.full(3,0.3984375), np.full(1,0.9140625), np.full(1,0.2265625), np.full(1,0.109375), np.full(1,0.203125), np.full(1,0.515625))) print(qiskit_data) cirq_data = np.concatenate((np.full(5010,0.71875), np.full(3207,0.7265625), np.full(372,0.734375), np.full(32,0.765625), np.full(153,0.7421875), np.full(164,0.703125), np.full(28,0.7734375), np.full(19,0.671875), np.full(454,0.7109375), np.full(5,0.8828125), np.full(19,0.6640625), np.full(78,0.6953125), np.full(11,0.7890625), np.full(1,0.3515625), np.full(8,0.640625), np.full(38,0.6875), np.full(88,0.75), np.full(10,0.65625), np.full(3,0.59375), np.full(45,0.7578125), np.full(3,0.328125), np.full(3,0.5234375), np.full(3,0.6171875), np.full(40,0.6796875), np.full(6,0.84375), np.full(9,0.6328125), np.full(1,0.359375), np.full(2,0.4296875), np.full(2,0.515625), np.full(6,0.5546875), np.full(13,0.796875), np.full(4,0.8671875), np.full(5,0.6015625), np.full(2,0.09375), np.full(10,0.8046875), np.full(2,0.1796875), np.full(4,0.5625), np.full(12,0.78125), np.full(7,0.828125), np.full(12,0.8203125), np.full(3,0.859375), np.full(3,0.875), np.full(1,0.4609375), np.full(4,0.578125), np.full(2,0.984375), np.full(3,0.96875), np.full(1,0.3359375), np.full(5,0.890625), np.full(8,0.625), np.full(5,0.8359375), np.full(3,0.171875), np.full(3,0.8515625), np.full(12,0.6484375), np.full(2,0.453125), np.full(1,0.90625), np.full(2,0.3828125), np.full(5,0.53125), np.full(1,0.1953125), np.full(1,0.03125), np.full(2,0.953125), np.full(1,0.34375), np.full(3,0.8125), np.full(1,0.0078125), np.full(1,0.9609375), np.full(1,0.0234375), np.full(2,0.609375), np.full(1,0.1015625), np.full(1,0.921875), np.full(3,0.9140625), np.full(7,0.546875), np.full(1,0.5703125), np.full(2,0.25), np.full(1,0.5), np.full(1,0.0703125), np.full(2,0.9765625), np.full(2,0.9453125), np.full(1,0.2890625), np.full(1,0.046875), np.full(1,0.9296875), np.full(1,0.8984375), np.full(1,0.203125), np.full(2,0.484375), np.full(2,0.5859375), np.full(1,0.2578125), np.full(1,0.2109375), np.full(1,0.21875))) print(cirq_data) qs_data = np.concatenate((np.full(4903,0.71875), np.full(3204,0.7265625), np.full(466,0.7109375), np.full(427,0.734375), np.full(162,0.703125), np.full(160,0.7421875), np.full(95,0.6953125), np.full(78,0.75), np.full(56,0.6875), np.full(41,0.6796875), np.full(38,0.7578125), np.full(30,0.765625), np.full(24,0.671875), np.full(21,0.65625), np.full(20,0.7734375), np.full(16,0.78125), np.full(15,0.8046875), np.full(14,0.6640625), np.full(14,0.6484375), np.full(13,0.7890625), np.full(11,0.796875), np.full(9,0.640625), np.full(8,0.8203125), np.full(6,0.6171875), np.full(6,0.6328125), np.full(5,0.8359375), np.full(5,0.8125), np.full(5,0.625), np.full(5,0.953125), np.full(5,0.5859375), np.full(4,0.9140625), np.full(4,0.609375), np.full(4,0.6015625), np.full(4,0.84375), np.full(4,0.875), np.full(4,0.8828125), np.full(4,0.59375), np.full(4,0.828125), np.full(4,0.5234375), np.full(3,0.90625), np.full(3,0.8984375), np.full(3,0.859375), np.full(3,0.9765625), np.full(3,0.1171875), np.full(3,0.5625), np.full(3,0.03125), np.full(3,0.8515625), np.full(3,0.21875), np.full(3,0.4921875), np.full(3,0.546875), np.full(2,0.515625), np.full(2,0.5390625), np.full(2,0.375), np.full(2,0.3125), np.full(2,0.9296875), np.full(2,0.8671875), np.full(2,0.53125), np.full(2,0.234375), np.full(2,0.5546875), np.full(2,0.0703125), np.full(2,0.203125), np.full(2,0.921875), np.full(2,0.5), np.full(2,0.5703125), np.full(2,0.3203125), np.full(2,0.046875), np.full(2,0.171875), np.full(2,0.9453125), np.full(2,0.3984375), np.full(1,0.484375), np.full(1,0.4140625), np.full(1,0.9375), np.full(1,0.15625), np.full(1,0.96875), np.full(1,0.421875), np.full(1,0.46875), np.full(1,0.4296875), np.full(1,0.9921875), np.full(1,0.109375), np.full(1,0.1328125), np.full(1,0.1796875), np.full(1,0.4765625), np.full(1,0.1015625), np.full(1,0.2890625), np.full(1,0.078125), np.full(1,0.265625), np.full(1,0.1953125), np.full(1,0.0078125), np.full(1,0.25), np.full(1,0.453125), np.full(1,0), np.full(1,0.390625), np.full(1,0.09375), np.full(1,0.5078125), np.full(1,0.890625), np.full(1,0.4609375), np.full(1,0.984375), np.full(1,0.3359375), np.full(1,0.0859375), np.full(1,0.2734375))) print(qs_data) # since we have so many 'categories' it makes more sense to run a traditional ANOVA test f_oneway(qiskit_data, cirq_data, qs_data)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from scipy.stats import kruskal, f_oneway import pandas as pd import numpy as np #if p value less than alpha reject qiskit_data = np.concatenate((np.full(245, 0.75), np.full(264, 0.5), np.full(243, 0.25), np.full(248, 0))) cirq_data = np.concatenate((np.full(259, 0.75), np.full(234, 0.5), np.full(249, 0.25), np.full(258, 0))) qs_data = np.concatenate((np.full(260, 0.75), np.full(234, 0.5), np.full(264, 0.25), np.full(242, 0))) kruskal(qiskit_data, cirq_data, qs_data) #if p value less than alpha reject qiskit_data = np.concatenate((np.full(254, 0.75), np.full(254, 0.5), np.full(230, 0.25), np.full(262, 0))) cirq_data = np.concatenate((np.full(251, 0.75), np.full(258, 0.5), np.full(269, 0.25), np.full(222, 0))) qs_data = np.concatenate((np.full(254, 0.75), np.full(232, 0.5), np.full(268, 0.25), np.full(246, 0))) kruskal(qiskit_data, cirq_data, qs_data) #if p value less than alpha reject qiskit_data = np.concatenate((np.full(486, 0.5), np.full(514, 0))) cirq_data = np.concatenate((np.full(483, 0.5), np.full(517, 0))) qs_data = np.concatenate((np.full(491, 0.5), np.full(509, 0))) kruskal(qiskit_data, cirq_data, qs_data) #if p value less than alpha reject qiskit_data = np.concatenate((np.full(246, 0.75), np.full(226, 0.5), np.full(237, 0.25), np.full(291, 0))) cirq_data = np.concatenate((np.full(247, 0.75), np.full(272, 0.5), np.full(230, 0.25), np.full(251, 0))) qs_data = np.concatenate((np.full(262, 0.75), np.full(243, 0.5), np.full(251, 0.25), np.full(244, 0))) kruskal(qiskit_data, cirq_data, qs_data) #if p value less than alpha reject qiskit_data = np.concatenate((np.full(651, 3+5), np.full(349, 3))) cirq_data = np.concatenate((np.full(685, 3+5), np.full(315, 3))) qs_data = np.concatenate((np.full(662, 3+5), np.full(338, 3))) kruskal(qiskit_data, cirq_data, qs_data) #if p value less than alpha reject qiskit_data = np.concatenate((np.full(1000, 3+5), np.full(0, 3))) cirq_data = np.concatenate((np.full(1000, 3+5), np.full(0, 3))) qs_data = np.concatenate((np.full(1000, 3+5), np.full(0, 3))) kruskal(qiskit_data, cirq_data, qs_data)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from scipy.stats import kruskal import pandas as pd import numpy as np #if p value less than alpha reject qiskit_data = np.concatenate((np.full(4925, 'z00'), np.full(5075, 'z11'), np.full(5016, 'x00'), np.full(4984, 'x11'), np.full(4898, 'y10'), np.full(5102, 'y01'))) print(qiskit_data) cirq_data = np.concatenate((np.full(5043, 'z00'), np.full(4957, 'z11'), np.full(5041, 'x00'), np.full(4959, 'x11'), np.full(4971, 'y10'), np.full(5029, 'y01'))) print(cirq_data) qs_data = np.concatenate((np.full(4981, 'z00'), np.full(5019, 'z11'), np.full(4994, 'x00'), np.full(5006, 'x11'), np.full(4956, 'y10'), np.full(5044, 'y01'))) print(qs_data) kruskal(qiskit_data, cirq_data, qs_data) qiskit_data = np.concatenate((np.full(4957, 'z10'), np.full(5043, 'z01'), np.full(5039, 'x10'), np.full(4961, 'x01'), np.full(5059, 'y10'), np.full(4941, 'y01'))) print(qiskit_data) cirq_data = np.concatenate((np.full(4946, 'z10'), np.full(5054, 'z01'), np.full(4926, 'x10'), np.full(5074, 'x01'), np.full(5078, 'y10'), np.full(4922, 'y01'))) print(cirq_data) qs_data = np.concatenate((np.full(5012, 'z10'), np.full(4988, 'z01'), np.full(4990, 'x10'), np.full(5010, 'x01'), np.full(4956, 'y10'), np.full(5044, 'y01'))) print(qs_data) kruskal(qiskit_data, cirq_data, qs_data) qiskit_data = np.concatenate((np.full(4958, 'z00'), np.full(5042, 'z11'), np.full(4950, 'x10'), np.full(5050, 'x01'), np.full(5029, 'y00'), np.full(4971, 'y11'))) print(qiskit_data) cirq_data = np.concatenate((np.full(5063, 'z00'), np.full(4937, 'z11'), np.full(5001, 'x10'), np.full(4999, 'x01'), np.full(4921, 'y00'), np.full(5079, 'y11'))) print(cirq_data) qs_data = np.concatenate((np.full(4993, 'z00'), np.full(5007, 'z11'), np.full(5058, 'x10'), np.full(4942, 'x01'), np.full(4998, 'y00'), np.full(5002, 'y11'))) print(qs_data) kruskal(qiskit_data, cirq_data, qs_data) qiskit_data = np.concatenate((np.full(10000, 'z00'), np.full(2545, 'x00'), np.full(2486, 'x01'), np.full(2458, 'x10'), np.full(2511, 'x11'), np.full(2479, 'y00'), np.full(2436, 'y01'), np.full(2583, 'y10'), np.full(2502, 'y11'))) print(qiskit_data) cirq_data = np.concatenate((np.full(10000, 'z00'), np.full(2431, 'x00'), np.full(2506, 'x01'), np.full(2498, 'x10'), np.full(2565, 'x11'), np.full(2436, 'y00'), np.full(2563, 'y01'), np.full(2538, 'y10'), np.full(2463, 'y11'))) print(cirq_data) qs_data = np.concatenate((np.full(10000, 'z00'), np.full(2512, 'x00'), np.full(2528, 'x01'), np.full(2529, 'x10'), np.full(2431, 'x11'), np.full(2560, 'y00'), np.full(2524, 'y01'), np.full(2451, 'y10'), np.full(2465, 'y11'))) print(qs_data) kruskal(qiskit_data, cirq_data, qs_data) qiskit_data = np.concatenate((np.full(10000, 'z01'), np.full(2528, 'x00'), np.full(2475, 'x01'), np.full(2493, 'x10'), np.full(2504, 'x11'), np.full(2502, 'y00'), np.full(2569, 'y01'), np.full(2474, 'y10'), np.full(2455, 'y11'))) print(qiskit_data) cirq_data = np.concatenate((np.full(10000, 'z01'), np.full(2497, 'x00'), np.full(2525, 'x01'), np.full(2512, 'x10'), np.full(2466, 'x11'), np.full(2487, 'y00'), np.full(2484, 'y01'), np.full(2507, 'y10'), np.full(2522, 'y11'))) print(cirq_data) qs_data = np.concatenate((np.full(10000, 'z01'), np.full(2551, 'x00'), np.full(2504, 'x01'), np.full(2490, 'x10'), np.full(2455, 'x11'), np.full(2528, 'y00'), np.full(2494, 'y01'), np.full(2506, 'y10'), np.full(2472, 'y11'))) print(qs_data) kruskal(qiskit_data, cirq_data, qs_data)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import cirq from cirq import Simulator import numpy as np #instantiate simulator simulator = Simulator() #instantiate qubit qubits = cirq.LineQubit.range(3) #make circuit circuit = cirq.Circuit() circuit.append(cirq.H(qubits[0])) circuit.append(cirq.CNOT(qubits[0], qubits[1])) circuit.append(cirq.H(qubits[2])) circuit.append(cirq.Z(qubits[2])**0.5) #print circuit print(circuit) #space the outputs print("\n\n\n") #print the statevectors result = simulator.simulate(circuit) print(np.around(result.final_state_vector, 3))
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
# importing Qiskit from qiskit import Aer, transpile, assemble from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.visualization import plot_histogram, plot_bloch_multivector from qiskit.visualization import plot_state_paulivec, plot_state_hinton, plot_state_city from qiskit.visualization import plot_state_qsphere # import basic plot tools from qiskit.visualization import plot_histogram, plot_bloch_multivector import matplotlib.pyplot as plt #get backend simulator sim = Aer.get_backend('aer_simulator') qc = QuantumCircuit(3) qc.h(0) qc.cx(0,1) qc.h(2) qc.s(2) #print circuit print(qc) #draw bloch spheres qc.save_statevector() statevector = sim.run(qc).result().get_statevector() print("\n") print(statevector) print("\n") plot_bloch_multivector(statevector) plot_state_city(statevector) plot_state_qsphere(statevector)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import cirq import matplotlib.pyplot as plt import numpy as np def qft_dagger_cirq(qc, qubits, n): for qubit in range(n//2): qc.append(cirq.SWAP(qubits[qubit], qubits[n-qubit-1])) for j in range(n): for m in range(j): qc.append((cirq.CZ**(-1/2**(j-m)))(qubits[m],qubits[j])) qc.append(cirq.H(qubits[j])) def generalised_qpe_cirq(amt_estimation_qubits, angle, shots = 4098): # Create and set up circuit qubits = cirq.LineQubit.range(amt_estimation_qubits+1) circuit = cirq.Circuit() # Apply H-Gates to counting qubits: for qubit in range(amt_estimation_qubits): circuit.append(cirq.H(qubits[qubit])) # Prepare our eigenstate |psi>: circuit.append(cirq.X(qubits[amt_estimation_qubits])) repetitions = 1 for counting_qubit in range(amt_estimation_qubits): for i in range(repetitions): circuit.append((cirq.CZ**(angle))(qubits[counting_qubit],qubits[amt_estimation_qubits])); repetitions *= 2 # Do the inverse QFT: qft_dagger_cirq(circuit, qubits, amt_estimation_qubits) # Measure of course! circuit.append(cirq.measure(*qubits[:-1], key='m')) simulator = cirq.Simulator() results = simulator.run(circuit , repetitions = shots) theta_estimates = np.sum(2 ** np.arange(amt_estimation_qubits) * results.measurements['m'], axis=1) / 2**amt_estimation_qubits unique,pos = np.unique(theta_estimates,return_inverse=True) counts = np.bincount(pos) maxpos = counts.argmax() generalised_qpe_cirq(8,(2*(1/3))) %timeit -p 8 -r 1 -n 1 generalised_qpe_cirq(8,(2*(1/3)),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_cirq(8,(2*(1/3)),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_cirq(8,(2*(1/3)),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_cirq(8,(2*(1/3)),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_cirq(8,(2*(1/3)),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_cirq(8,(2*(1/3)),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_cirq(8,(2*(1/3)),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_cirq(8,(2*(1/3)),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_cirq(8,(2*(1/3)),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_cirq(8,(2*(1/3)),10000)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
#initialization import matplotlib.pyplot as plt import numpy as np import math # importing Qiskit from qiskit import Aer, transpile, assemble from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.circuit.library import QFT # import basic plot tools from qiskit.visualization import plot_histogram, plot_bloch_multivector def qft_dagger(qc, n): """n-qubit QFTdagger the first n qubits in circ""" # 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(-math.pi/float(2**(j-m)), m, j) qc.h(j) #Modified to remove prints def generalised_qpe_timing(amt_estimation_qubits, angle, shots=4096): # Create and set up circuit qpe3 = QuantumCircuit(amt_estimation_qubits+1, amt_estimation_qubits) # Apply H-Gates to counting qubits: for qubit in range(amt_estimation_qubits): qpe3.h(qubit) # Prepare our eigenstate |psi>: qpe3.x(amt_estimation_qubits) repetitions = 1 for counting_qubit in range(amt_estimation_qubits): for i in range(repetitions): qpe3.cp(angle, counting_qubit, amt_estimation_qubits); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe3, amt_estimation_qubits) # Measure of course! qpe3.barrier() for n in range(amt_estimation_qubits): qpe3.measure(n,n) #print(qpe3) # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') t_qpe3 = transpile(qpe3, aer_sim) qobj = assemble(t_qpe3, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() ##return(plot_histogram(answer)) ##comment out the return if you want to see the histogram ## do not output value to not skew timing return ((int(answer.most_frequent(), 2)/2**amt_estimation_qubits)) generalised_qpe_timing(8,(2*math.pi/3),10000) #generalised_qpe(2,(2*math.pi/4)) %timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000) %timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import warnings warnings.filterwarnings('ignore') import unittest import pandas as pd import numpy as np from qiskit import Aer from qiskit import QuantumCircuit from qiskit.visualization import plot_histogram, plot_bloch_multivector from QuantumAssertions import assertPhase, assertEqual from BenchmarkQA import returnPhase import math import qiskit.quantum_info import numpy as np backend = Aer.get_backend('aer_simulator') # deg = 20 # backend = Aer.get_backend('aer_simulator') # qc = QuantumCircuit(1,1) # qc.save_statevector() # statevector = backend.run(qc).result().get_statevector() # plot_bloch_multivector(statevector) qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.p(10*2*math.pi/100, 0) qc.p(20*2*math.pi/100, 1) assertPhase(backend, qc, [0,1], [36,72], 100000, 0.01) qc = QuantumCircuit(2) qc.h(0) qc.h(1) #qc.p(0.5*2*math.pi/100, 1) assertEqual(backend, qc, 0, 1, 300000, 0.01) # ## benchmark 100 shots at 1000 runs # shots = 100 # runs = 5000 # df = pd.DataFrame(columns=['results']) # for i in range(runs): # qc = QuantumCircuit(1,1) # qc.h(0) # qc.p(20*2*math.pi/100, 0) # df = df.append({'results': returnPhase(backend, qc, [0], [0], shots, 180)}, ignore_index=True) # if (i % 10 == 9): # print(f"progress: {i+1}/{runs}") # df.hist(bins=12) # print(df) # ## benchmark 1000 shots at 1000 runs # shots = 1000 # runs = 5000 # df = pd.DataFrame(columns=['results']) # for i in range(runs): # qc = QuantumCircuit(1,1) # qc.h(0) # qc.p(20*2*math.pi/100, 0) # df = df.append({'results': returnPhase(backend, qc, [0], [0], shots, 180)}, ignore_index=True) # if (i % 10 == 9): # print(f"progress: {i+1}/{runs}") # df.hist(bins=12) # print(df) # shots = 10000 # runs = 5000 # df = pd.DataFrame(columns=['results']) # for i in range(runs): # qc = QuantumCircuit(1,1) # qc.h(0) # qc.p(20*2*math.pi/100, 0) # df = df.append({'results': returnPhase(backend, qc, [0], [0], shots, 180)}, ignore_index=True) # if (i % 10 == 9): # print(f"progress: {i+1}/{runs}") # df.hist(bins=12) # print(df) # shots = 100000 # runs = 5000 # df = pd.DataFrame(columns=['results']) # for i in range(runs): # qc = QuantumCircuit(1,1) # qc.h(0) # qc.p(20*2*math.pi/100, 0) # df = df.append({'results': returnPhase(backend, qc, [0], [0], shots, 180)}, ignore_index=True) # if (i % 10 == 9): # print(f"progress: {i+1}/{runs}") # df.hist(bins=12) # print(df)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import pandas as pd import math import numpy as np import scipy.stats as sci from qiskit import execute from qiskit.circuit import ClassicalRegister def returnPhase(backend, quantumCircuit, qubits_to_assert, expected_phases, measurements_to_make, tolerance): ## if "qubits to assert" is just a single value, convert it to a list containing the single value if (not isinstance(qubits_to_assert, list)): qubits_to_assert = [qubits_to_assert] ## if "expected phases" is just a single value, convert it to a list containing the single value if (not isinstance(expected_phases, list)): expected_phases = [expected_phases] ## needs to make at least 2 measurements, one for x axis, one for y axis ## realistically we need more for any statistical significance if (measurements_to_make < 2): raise ValueError("Must make at least 2 measurements") ## classical register must be of same length as amount of qubits to assert ## if there is no classical register, add one if (quantumCircuit.num_clbits == 0): quantumCircuit.add_register(ClassicalRegister(len(qubits_to_assert))) elif (quantumCircuit.num_clbits != len(qubits_to_assert)): raise ValueError("QuantumCircuit classical register length not equal to qubits to assert") ## divide measurements to make by 2 as we need to run measurements twice, one for x and one for y measurements_to_make = measurements_to_make // 2 ## copy the circit and set measurement to y axis yQuantumCircuit = measure_y(quantumCircuit.copy(), qubits_to_assert) ## measure the x axis xQuantumCircuit = measure_x(quantumCircuit, qubits_to_assert) ## get y axis results yJob = execute(yQuantumCircuit, backend, shots=measurements_to_make, memory=True) yCounts = yJob.result().get_counts() ## get x axis results xJob = execute(xQuantumCircuit, backend, shots=measurements_to_make, memory=True) xCounts = xJob.result().get_counts() ## make a df to keep track of the predicted angles resDf = pd.DataFrame(columns=['+','i','-','-i']) ## fill the df with the x and y results of each qubit that is being asserted classical_qubit_index = 1 for qubit in qubits_to_assert: plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0 for experiment in xCounts: if (experiment[len(qubits_to_assert)-classical_qubit_index] == '0'): plus_amount += xCounts[experiment] else: minus_amount += xCounts[experiment] for experiment in yCounts: if (experiment[len(qubits_to_assert)-classical_qubit_index] == '0'): i_amount += yCounts[experiment] else: minus_i_amount += yCounts[experiment] df = {'+':plus_amount, 'i':i_amount, '-':minus_amount, '-i':minus_i_amount} resDf = resDf.append(df, ignore_index = True) classical_qubit_index+=1 ## convert the columns to a strict numerical type resDf['+'] = resDf['+'].astype(int) resDf['i'] = resDf['i'].astype(int) resDf['-'] = resDf['-'].astype(int) resDf['-i'] = resDf['-i'].astype(int) ## make a dataframe that contains p values of chi square tests to analyse results ## if x and y counts are both 25/25/25/25, it means that we cannot calculate a phase ## we assume that a qubit that is in |0> or |1> position to have 50% chance to fall ## either way, like a coin toss: We treat X and Y results like coin tosses pValues = pd.DataFrame(columns=['X','Y']) pValues['X'] = resDf.apply(lambda row: applyChiSquareX(row, measurements_to_make/2), axis=1) pValues['Y'] = resDf.apply(lambda row: applyChiSquareY(row, measurements_to_make/2), axis=1) ## check p values on chi square test, we use a low value to be sure that ## we only except if we are certain there is an issue with the x, y results pValues = pValues > 0.00001 ## if both pvalues are more than 0.00001, we are pretty certain that the results follow an even distribution ## likely that the qubit is not in the fourier basis (very likely in the |0> or |1> state) pValues.apply(lambda row: assertIfBothTrue(row), axis=1) ## this sequence of operations converts from measured results ## into an angle for phase: ## with 0 ( 0 rad) signifying the |+> state ## with 90 ( pi/2 rad) signifying the |i> state ## with 180 ( pi rad) signifying the |-> state ## with 270 (3 * pi/2 rad) signifying the |-i> state resDf = resDf / measurements_to_make resDf = resDf * 2 resDf = resDf - 1 resDf = np.arccos(resDf) resDf = resDf * 180 resDf = resDf / math.pi ## to get a final result for phase on each qubit: ## we must get the lowest 2 values for each column lowestDf = pd.DataFrame(columns=['lowest','lowest-location','second-lowest','second-lowest-location','estimated-phase']) ## store the lowest value as well as what column it is from lowestDf['lowest'] = resDf.min(axis=1) lowestDf['lowest-location'] = resDf.idxmin(axis=1) ## remove the lowest value from the dataframe lowestDf = lowestDf.apply(lambda row: setLowestCellToNan(row, resDf), axis=1) ## store the second lowest value from the dataframe as well as the column lowestDf['second-lowest'] = resDf.min(axis=1) lowestDf['second-lowest-location'] = resDf.idxmin(axis=1) ## estimate the phase and put it in a new column lowestDf['estimated-phase'] = lowestDf.apply(lambda row: setPhaseEstimate(row, resDf), axis=1) ## check that the estimated phase fits in the tolerance lowestDf.apply(lambda row: assertIfExpectedDoNotFitTolerance(row, expected_phases, tolerance), axis=1) return(lowestDf['estimated-phase'][0]) #return(lowestDf['estimated-phase'][0]) def measure_x(circuit, qubitIndexes): cBitIndex = 0 for index in qubitIndexes: circuit.h(index) circuit.measure(index, cBitIndex) cBitIndex+=1 return circuit def measure_y(circuit, qubit_indexes): cBitIndex = 0 for index in qubit_indexes: circuit.sdg(index) circuit.h(index) circuit.measure(index, cBitIndex) cBitIndex+=1 return circuit def setLowestCellToNan(row, resDf): for col in row.index: resDf.iloc[row.name][row[col]] = np.nan return row def setPhaseEstimate(row, resDf): overallPhase = 0 if(row['lowest-location'] == '+'): if(row['second-lowest-location'] == 'i'): overallPhase = 0 + row['lowest'] elif (row['second-lowest-location'] == '-i'): overallPhase = 360 - row['lowest'] if (row['lowest'] == 0): overallPhase = 0 elif(row['lowest-location'] == 'i'): if(row['second-lowest-location'] == '+'): overallPhase = 90 - row['lowest'] elif (row['second-lowest-location'] == '-'): overallPhase = 90 + row['lowest'] elif(row['lowest-location'] == '-'): if(row['second-lowest-location'] == 'i'): overallPhase = 180 - row['lowest'] elif (row['second-lowest-location'] == '-i'): overallPhase = 180 + row['lowest'] elif(row['lowest-location'] == '-i'): if(row['second-lowest-location'] == '+'): overallPhase = 270 + row['lowest'] elif (row['second-lowest-location'] == '-'): overallPhase = 270 - row['lowest'] return overallPhase def applyChiSquareX(row, expected_amount): observed = [row['+'],row['-']] expected = [expected_amount,expected_amount] return(sci.chisquare(f_obs=observed, f_exp=expected)[1]) def applyChiSquareY(row, expected_amount): observed = [row['i'],row['-i']] expected = [expected_amount,expected_amount] return(sci.chisquare(f_obs=observed, f_exp=expected)[1]) def assertIfBothTrue(row): if row.all(): #raise AssertionError("Qubit does not appear to have a phase applied to it!") pass def assertIfExpectedDoNotFitTolerance(row, expected, tolerance): deltaAngle = (row['estimated-phase'] - expected[row.name] + 180 + 360) % 360 - 180 #print('observed: ' + str(row['estimated-phase'])) #print('predicted: ' + str(expected[row.name])) #print('diff: ' + str(deltaAngle)) if (abs(deltaAngle) > tolerance): #raise AssertionError(f"The estimated angle ({row['estimated-phase']}) is off the prediction ({expected[row.name]}) +- tolerance value ({tolerance}) specified") pass
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import warnings warnings.simplefilter(action='ignore', category=FutureWarning) warnings.simplefilter(action='ignore', category=RuntimeWarning) import pandas as pd import math import numpy as np import scipy.stats as sci from statsmodels.stats.proportion import proportions_ztest from qiskit import execute from qiskit.circuit import ClassicalRegister def assertPhase(backend, quantumCircuit, qubits_to_assert, expected_phases, measurements_to_make, alpha): ## if "qubits to assert" is just a single value, convert it to a list containing the single value if (not isinstance(qubits_to_assert, list)): qubits_to_assert = [qubits_to_assert] ## if "expected phases" is just a single value, convert it to a list containing the single value if (not isinstance(expected_phases, list)): expected_phases = [expected_phases] ## needs to make at least 2 measurements, one for x axis, one for y axis ## realistically we need more for any statistical significance if (measurements_to_make < 2): raise ValueError("Must make at least 2 measurements") ## classical register must be of same length as amount of qubits to assert ## if there is no classical register, add one if (quantumCircuit.num_clbits == 0): quantumCircuit.add_register(ClassicalRegister(len(qubits_to_assert))) elif (quantumCircuit.num_clbits != len(qubits_to_assert)): raise ValueError("QuantumCircuit classical register length not equal to qubits to assert") ## divide measurements to make by 2 as we need to run measurements twice, one for x and one for y measurements_to_make = measurements_to_make // 2 ## copy the circit and set measurement to y axis yQuantumCircuit = measure_y(quantumCircuit.copy(), qubits_to_assert) ## measure the x axis xQuantumCircuit = measure_x(quantumCircuit, qubits_to_assert) ## get y axis results yJob = execute(yQuantumCircuit, backend, shots=measurements_to_make, memory=True) yCounts = yJob.result().get_counts() ## get x axis results xJob = execute(xQuantumCircuit, backend, shots=measurements_to_make, memory=True) xCounts = xJob.result().get_counts() ## make a df to keep track of the predicted angles resDf = pd.DataFrame(columns=['+','i','-','-i']) ## fill the df with the x and y results of each qubit that is being asserted classical_qubit_index = 1 for qubit in qubits_to_assert: plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0 for experiment in xCounts: if (experiment[len(qubits_to_assert)-classical_qubit_index] == '0'): plus_amount += xCounts[experiment] else: minus_amount += xCounts[experiment] for experiment in yCounts: if (experiment[len(qubits_to_assert)-classical_qubit_index] == '0'): i_amount += yCounts[experiment] else: minus_i_amount += yCounts[experiment] df = {'+':plus_amount, 'i':i_amount, '-':minus_amount, '-i':minus_i_amount} resDf = resDf.append(df, ignore_index = True) classical_qubit_index+=1 ## convert the columns to a strict numerical type resDf['+'] = resDf['+'].astype(int) resDf['i'] = resDf['i'].astype(int) resDf['-'] = resDf['-'].astype(int) resDf['-i'] = resDf['-i'].astype(int) #print(f"full df \n {resDf}") xAmount = resDf['-'].tolist() yAmount = resDf['-i'].tolist() # print(f"x amounts {xAmount}") # print(f"y amounts {yAmount}") ## make a dataframe that contains p values of chi square tests to analyse results ## if x and y counts are both 25/25/25/25, it means that we cannot calculate a phase ## we assume that a qubit that is in |0> or |1> position to have 50% chance to fall ## either way, like a coin toss: We treat X and Y results like coin tosses pValues = pd.DataFrame(columns=['X','Y']) pValues['X'] = resDf.apply(lambda row: applyChiSquareX(row, measurements_to_make/2), axis=1) pValues['Y'] = resDf.apply(lambda row: applyChiSquareY(row, measurements_to_make/2), axis=1) ## check p values on chi square test, we use a low value to be sure that ## we only except if we are certain there is an issue with the x, y results pValues = pValues > 0.00001 ## if both pvalues are more than 0.00001, we are pretty certain that the results follow an even distribution ## likely that the qubit is not in the fourier basis (very likely in the |0> or |1> state) pValues.apply(lambda row: assertIfBothTrue(row), axis=1) ## this sequence of operations converts from measured results ## into an angle for phase: ## with 0 ( 0 rad) signifying the |+> state ## with 90 ( pi/2 rad) signifying the |i> state ## with 180 ( pi rad) signifying the |-> state ## with 270 (3 * pi/2 rad) signifying the |-i> state resDf = resDf / measurements_to_make resDf = resDf * 2 resDf = resDf - 1 resDf = np.arccos(resDf) resDf = resDf * 180 resDf = resDf / math.pi ## to get a final result for phase on each qubit: ## we must get the lowest 2 values for each column lowestDf = pd.DataFrame(columns=['lowest','lowest-location','second-lowest','second-lowest-location','estimated-phase']) ## store the lowest value as well as what column it is from lowestDf['lowest'] = resDf.min(axis=1) lowestDf['lowest-location'] = resDf.idxmin(axis=1) ## remove the lowest value from the dataframe lowestDf = lowestDf.apply(lambda row: setLowestCellToNan(row, resDf), axis=1) ## store the second lowest value from the dataframe as well as the column lowestDf['second-lowest'] = resDf.min(axis=1) lowestDf['second-lowest-location'] = resDf.idxmin(axis=1) ## estimate the phase and put it in a new column lowestDf['estimated-phase'] = lowestDf.apply(lambda row: setPhaseEstimate(row), axis=1) ## calculate what the expected row would be for the expected phase #expectedX, expectedY = expectedPhaseToRow(expected_phases[0],measurements_to_make) expectedX = np.zeros(len(expected_phases)).astype(int) expectedY = np.zeros(len(expected_phases)).astype(int) for idx, phase in enumerate(expected_phases): expectedX[idx], expectedY[idx] = expectedPhaseToRow(expected_phases[idx],measurements_to_make) #print(type(expectedX[0])) # print(f"expected x {expectedX}") # print(f"expected y {expectedY}") p_values = [] for i in range(len(qubits_to_assert)): ## set observed X values in a table observedXtable = [xAmount[i],measurements_to_make-xAmount[i]] ## set expected X values in a table expectedXtable = [expectedX[i],measurements_to_make-expectedX[i]] ## set observed Y values in a table observedYtable = [yAmount[i],measurements_to_make-yAmount[i]] ## set expected Y values in a table expectedYtable = [expectedY[i],measurements_to_make-expectedY[i]] xPvalue = sci.chisquare(f_obs=observedXtable, f_exp=expectedXtable)[1] yPvalue = sci.chisquare(f_obs=observedYtable, f_exp=expectedYtable)[1] #print(observedXtable) #print(expectedXtable) #print(sci.chisquare(f_obs=observedXtable, f_exp=expectedXtable)[1]) #print(observedYtable) #print(expectedYtable) print(sci.chisquare(f_obs=observedYtable, f_exp=expectedYtable)[1]) p_values.append(xPvalue) p_values.append(yPvalue) #if (yPvalue != np.NaN and yPvalue <= alpha): # raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in qubit {qubits_to_assert[i]} according to significance level {alpha}")) #if (xPvalue != np.NaN and xPvalue <= alpha): # raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in qubit {qubits_to_assert[i]} according to significance level {alpha}")) holm_bonferroni_correction(p_values, alpha) # ## set observed X values in a table # observedX = [xAmount,measurements_to_make-xAmount] # ## set expected X values in a table # expectedX = [expectedX,measurements_to_make-expectedX] # ## set observed Y values in a table # observedY = [yAmount,measurements_to_make-yAmount] # ## set expected Y values in a table # expectedY = [expectedY,measurements_to_make-expectedY] # print(observedX) # print(expectedX) # print(observedY) # print(expectedY) # print(sci.chisquare(f_obs=observedX, f_exp=expectedX)[1]) # xPvalue = sci.chisquare(f_obs=observedX, f_exp=expectedX)[1] # print(sci.chisquare(f_obs=observedY, f_exp=expectedY)[1]) # yPvalue = sci.chisquare(f_obs=observedY, f_exp=expectedY)[1] # if (yPvalue != np.NaN and yPvalue <= alpha): # raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) # if (xPvalue != np.NaN and xPvalue <= alpha): # raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) ## assert that 2 qubits are equal def assertEqual(backend, quantumCircuit, qubit1, qubit2, measurements_to_make, alpha): ## needs to make at least 2 measurements, one for x axis, one for y axis ## realistically we need more for any statistical significance if (measurements_to_make < 2): raise ValueError("Must make at least 2 measurements") ## classical register must be of same length as amount of qubits to assert ## if there is no classical register, add one if (quantumCircuit.num_clbits == 0): quantumCircuit.add_register(ClassicalRegister(2)) elif (quantumCircuit.num_clbits != 2): raise ValueError("QuantumCircuit classical register must be of length 2") ## divide measurements to make by 3 as we need to run measurements twice, one for x and one for y measurements_to_make = measurements_to_make // 3 ## copy the circit and set measurement to y axis yQuantumCircuit = measure_y(quantumCircuit.copy(), [qubit1, qubit2]) ## measure the x axis xQuantumCircuit = measure_x(quantumCircuit.copy(), [qubit1, qubit2]) ## measure the z axis zQuantumCircuit = measure_z(quantumCircuit, [qubit1, qubit2]) ## get y axis results yJob = execute(yQuantumCircuit, backend, shots=measurements_to_make, memory=True) yMemory = yJob.result().get_memory() yCounts = yJob.result().get_counts() ## get x axis results xJob = execute(xQuantumCircuit, backend, shots=measurements_to_make, memory=True) xMemory = xJob.result().get_memory() xCounts = xJob.result().get_counts() ## get z axis results zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True) zMemory = zJob.result().get_memory() zCounts = zJob.result().get_counts() # xDf = pd.DataFrame(columns=['q0', 'q1']) # yDf = pd.DataFrame(columns=['q0', 'q1']) # zDf = pd.DataFrame(columns=['q0', 'q1']) # for row in yMemory: # yDf = yDf.append({'q0':row[0], 'q1':row[1]}, ignore_index=True) # for row in xMemory: # xDf = xDf.append({'q0':row[0], 'q1':row[1]}, ignore_index=True) # for row in zMemory: # zDf = zDf.append({'q0':row[0], 'q1':row[1]}, ignore_index=True) # yDf = yDf.astype(int) # xDf = xDf.astype(int) # zDf = zDf.astype(int) #yStat, yPvalue = (sci.ttest_ind(yDf['q0'], yDf['q1'])) #xStat, xPvalue = (sci.ttest_ind(xDf['q0'], xDf['q1'])) #zStat, zPvalue = (sci.ttest_ind(zDf['q0'], zDf['q1'])) print(alpha) #print(f"Y p-value {yPvalue}") #print(f"X p-value {xPvalue}") #print(f"Z p-value {zPvalue}") # if (yPvalue != np.NaN and yPvalue <= alpha): # raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) # if (xPvalue != np.NaN and xPvalue <= alpha): # raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) # if (zPvalue != np.NaN and zPvalue <= alpha): # raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) ## make a df to keep track of the predicted angles resDf = pd.DataFrame(columns=['0','1','+','i','-','-i']) ## fill the df with the x and y results of each qubit that is being asserted classical_qubit_index = 1 for qubit in [qubit1,qubit2]: zero_amount, one_amount, plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0,0,0 for experiment in xCounts: if (experiment[2-classical_qubit_index] == '0'): plus_amount += xCounts[experiment] else: minus_amount += xCounts[experiment] for experiment in yCounts: if (experiment[2-classical_qubit_index] == '0'): i_amount += yCounts[experiment] else: minus_i_amount += yCounts[experiment] for experiment in zCounts: if (experiment[2-classical_qubit_index] == '0'): zero_amount += zCounts[experiment] else: one_amount += zCounts[experiment] df = {'0':zero_amount, '1':one_amount, '+':plus_amount, 'i':i_amount, '-':minus_amount,'-i':minus_i_amount} resDf = resDf.append(df, ignore_index = True) classical_qubit_index+=1 ## convert the columns to a strict numerical type resDf['+'] = resDf['+'].astype(int) resDf['i'] = resDf['i'].astype(int) resDf['-'] = resDf['-'].astype(int) resDf['-i'] = resDf['-i'].astype(int) resDf['0'] = resDf['0'].astype(int) resDf['1'] = resDf['1'].astype(int) print(resDf.astype(str)) print(resDf['1'][0].astype(int)) print(resDf['1'][1].astype(int)) print(resDf['-'][0].astype(int)) print(resDf['-'][1].astype(int)) print(resDf['-i'][0].astype(int)) print(resDf['-i'][1].astype(int)) zStat_z, zPvalue = proportions_ztest(count=[resDf['1'][0],resDf['1'][1]], nobs=[measurements_to_make, measurements_to_make], alternative='two-sided') zStat_x, xPvalue = proportions_ztest(count=[resDf['-'][0],resDf['-'][1]], nobs=[measurements_to_make, measurements_to_make], alternative='two-sided') zStat_y, yPvalue = proportions_ztest(count=[resDf['-i'][0],resDf['-i'][1]], nobs=[measurements_to_make, measurements_to_make], alternative='two-sided') print(zPvalue, zStat_z) print(xPvalue, zStat_x) print(yPvalue, zStat_y) if (yPvalue != np.NaN and yPvalue <= alpha): raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) if (xPvalue != np.NaN and xPvalue <= alpha): raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) if (zPvalue != np.NaN and zPvalue <= alpha): raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) # ## apply t test to see if two populations of results on qu bits are expected to from the same population # resDf.apply(lambda row: applyTtest(row), axis=1) def measure_x(circuit, qubitIndexes): cBitIndex = 0 for index in qubitIndexes: circuit.h(index) circuit.measure(index, cBitIndex) cBitIndex+=1 return circuit def measure_y(circuit, qubit_indexes): cBitIndex = 0 for index in qubit_indexes: circuit.sdg(index) circuit.h(index) circuit.measure(index, cBitIndex) cBitIndex+=1 return circuit def measure_z(circuit, qubit_indexes): cBitIndex = 0 for index in qubit_indexes: circuit.measure(index, cBitIndex) cBitIndex+=1 return circuit def setLowestCellToNan(row, resDf): for col in row.index: resDf.iloc[row.name][row[col]] = np.nan return row def setPhaseEstimate(row): overallPhase = 0 if(row['lowest-location'] == '+'): if(row['second-lowest-location'] == 'i'): overallPhase = 0 + row['lowest'] elif (row['second-lowest-location'] == '-i'): overallPhase = 360 - row['lowest'] if (row['lowest'] == 0): overallPhase = 0 elif(row['lowest-location'] == 'i'): if(row['second-lowest-location'] == '+'): overallPhase = 90 - row['lowest'] elif (row['second-lowest-location'] == '-'): overallPhase = 90 + row['lowest'] elif(row['lowest-location'] == '-'): if(row['second-lowest-location'] == 'i'): overallPhase = 180 - row['lowest'] elif (row['second-lowest-location'] == '-i'): overallPhase = 180 + row['lowest'] elif(row['lowest-location'] == '-i'): if(row['second-lowest-location'] == '+'): overallPhase = 270 + row['lowest'] elif (row['second-lowest-location'] == '-'): overallPhase = 270 - row['lowest'] return overallPhase def expectedPhaseToRow(expected_phase, number_of_measurements): # print(expected_phase) # print(number_of_measurements) expected_phase_y = expected_phase - 90 expected_phase_y = expected_phase_y * math.pi expected_phase_y = expected_phase_y / 180 expected_phase_y = np.cos(expected_phase_y) expected_phase_y = expected_phase_y + 1 expected_phase_y = expected_phase_y / 2 expected_phase_y = expected_phase_y * number_of_measurements expected_phase = expected_phase * math.pi expected_phase = expected_phase / 180 expected_phase = np.cos(expected_phase) expected_phase = expected_phase + 1 expected_phase = expected_phase / 2 expected_phase = expected_phase * number_of_measurements # print(f"phase + {expected_phase} ---- phase - {number_of_measurements-expected_phase}") # print(f"phase i {expected_phase_y} ---- phase -i {number_of_measurements-expected_phase_y}") xRes = int(round(number_of_measurements-expected_phase)) yRes = int(round(number_of_measurements-expected_phase_y)) return((xRes, yRes)) def applyChiSquareX(row, expected_amount): observed = [row['+'],row['-']] expected = [expected_amount,expected_amount] return(sci.chisquare(f_obs=observed, f_exp=expected)[1]) def applyChiSquareY(row, expected_amount): observed = [row['i'],row['-i']] expected = [expected_amount,expected_amount] return(sci.chisquare(f_obs=observed, f_exp=expected)[1]) def assertIfBothTrue(row): if row.all(): raise AssertionError("Qubit does not appear to have a phase applied to it!") def holm_bonferroni_correction(p_values, family_wise_alpha): print("holm") p_values = [1 if math.isnan(x) else x for x in p_values] p_values.sort() print(p_values) for i in range(len(p_values)): if (p_values[i] <= (family_wise_alpha/(len(p_values)-i))): print("failed it !") raise(AssertionError(f"Null hypothesis rejected")) # def assertIfExpectedDoNotFitTolerance(row, expected, tolerance): # deltaAngle = (row['estimated-phase'] - expected[row.name] + 180 + 360) % 360 - 180 # print('observed: ' + str(row['estimated-phase'])) # print('predicted: ' + str(expected[row.name])) # print('diff: ' + str(deltaAngle)) # if (abs(deltaAngle) > tolerance): # raise AssertionError(f"The estimated angle ({row['estimated-phase']}) is off the prediction ({expected[row.name]}) +- tolerance value ({tolerance}) specified")
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import cirq import random import matplotlib.pyplot as plt import numpy as np def set_measure_x(circuit, qubits, n): for num in range(n): circuit.append(cirq.H(qubits[num])) def set_measure_y(circuit, qubits, n): for num in range(n): circuit.append((cirq.Z**(-1/2))(qubits[num])) circuit.append(cirq.H(qubits[num])) def qft_rotations_cirq(circuit, qubits, n): if n == 0: #print(circuit) set_measure_x(circuit, qubits, 4) circuit.append(cirq.measure(*qubits, key='this')) return circuit n -= 1 circuit.append(cirq.H(qubits[n])) for qubit in range(n): circuit.append((cirq.CZ**(1/2**(n-qubit)))(qubits[qubit],qubits[n])) return qft_rotations_cirq(circuit, qubits, n) qubits = cirq.LineQubit.range(4) circuit = cirq.Circuit() circuit.append(cirq.X(qubits[0])) qft_rotations_cirq(circuit, qubits, 4) ##set it to measure Y axis #set_measure_x(circuit, qubits, 4) #circuit.append(cirq.measure(*qubits, key='this')) simulator = cirq.Simulator() results = simulator.run(circuit , repetitions =100000) #results = simulator.run(circuit) print(circuit) print(results.histogram(key="this")) def qft_rotations_cirq(circuit, qubits, n): #this implementation is taken from https://qiskit.org/textbook/ch-algorithms/quantum-fourier-transform.html #if qubit amount is 0, then do nothing and return #print("loop n# %s"%n) if n == 0: #print(circuit) return circuit n -= 1 circuit.append(cirq.H(qubits[n])) for qubit in range(n): circuit.append((cirq.CZ**(1/2**(n-qubit)))(qubits[qubit],qubits[n])) #print(n) #print(qubit) return qft_rotations_cirq(circuit, qubits, n) qubits = cirq.LineQubit.range(4) circuit = cirq.Circuit() circuit.append(cirq.X(qubits[0])) qft_rotations_cirq(circuit, qubits, 4) ##set it to measure Y axis set_measure_x(circuit, qubits, 4) ##measure the first qubit ---------V circuit.append(cirq.measure(qubits[0], key='this')) simulator = cirq.Simulator() results = simulator.run(circuit , repetitions =1000000) #results = simulator.run(circuit) print(circuit) print(results.histogram(key="this"))
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### added h gate ### qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).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
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": ### added x gate ### qc.x(qubit) 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
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).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) ### added y gate ### qc.y(0) qc.h(1) return qc
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### added y gate ### qc.cx(0, 1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).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) ### added h gate ### qc.h(0) return qc
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) ### added x gate ### qc.x(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### added z gate ### qc.z(1) qc.h(1) return qc
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import unittest from matplotlib.pyplot import close import numpy as np import hypothesis.strategies as st from hypothesis import given, settings from qiskit import QuantumCircuit, Aer, execute from qiskit.circuit.library import QFT from math import pi, degrees, sqrt, sin, cos # importing sys import sys from sympy import false # adding Folder_2 to the system path import pathlib sys.path.insert(0, str(pathlib.Path().resolve())+f"/Property_Assertion") from QuantumAssertions import assertPhase ##################################################################################### ### Change the file to import from, in order to test a mutant version of the code ### ################################################################################################## ### e.g. from Add_mutant_1 import remove_garbage, generate_binary, encode_message, measure_message ################################################################################################## from QuantumFourierTransform import qft_rotations, flip_endian, qft_rotations_not_inplace ########################################################################### ## Define composite strategies to generate lists of ints in equal length ## ########################################################################### @st.composite def size_and_value_to_input(draw): circuit_size = draw(st.integers(min_value=1, max_value=4)) value = draw(st.integers(min_value=0, max_value=(2**circuit_size)-1)) return(circuit_size,value) ########################## ## test generate binary ## ########################## @given(size_and_value_to_input()) @settings(deadline=None) def test_qft_then_inverse(vals): size = vals[0] value = vals[1] qc = QuantumCircuit(size) binValue = bin(value)[2:].zfill(size)[::-1] for i in range(size): if binValue[i] == "1": qc.x(i) qft_rotations(qc, size) qc.append(QFT(num_qubits=size, do_swaps=false, inverse=True), [i for i in range(size)]) qc.measure_all() backend = Aer.get_backend('aer_simulator') job = execute(qc, backend, shots=1, memory=True) readings = job.result().get_memory()[0] assert(value == int(readings,2)) @given(size_and_value_to_input()) @settings(deadline=None) def test_specific_phase(vals): size = vals[0] value = vals[1] qc = QuantumCircuit(size) binValue = bin(value)[2:].zfill(size)[::-1] for i in range(size): if binValue[i] == "1": qc.x(i) qft_rotations(qc, size) backend = Aer.get_backend('aer_simulator') expected_values = [] print(size) print(value) for i in range(size): expected_values.append(degrees(pi*value/2**i)%360) assertPhase(backend, qc, [i for i in range(size)], expected_values, 3000000, 0.01) @given(size_and_value_to_input()) @settings(deadline=None) def test_superposition_inputs(vals): size = vals[0] value = vals[1] qc = QuantumCircuit(size) expected_values = [] for i in range(size): expected_values.append(degrees(pi*value/2**i)%360) init_vector = calculate_tensor_product(angle_to_vector(expected_values))[0] #for vect in init_vector: #print(vect) qc.initialize(init_vector, [i for i in range(size)]) qc.append(qft_rotations_not_inplace(size).inverse(), [i for i in range(size)]) qc.measure_all() backend = Aer.get_backend('aer_simulator') job = execute(qc, backend, shots=10000)#run the circuit 1000000 times assert(len(job.result().get_counts()) == 1) assert(int(job.result().get_counts().most_frequent(), 2) == value) print(int(job.result().get_counts().most_frequent(), 2)) print(job.result().get_counts()) print(value) ########################### ## Define helper methods ## ########################### def calculate_tensor_product(vectors): """ takes in array of pairs of complex numbers returns statevector array (recursively) """ if vectors == []: return vectors elif len(vectors) == 1: return vectors else: v1 = vectors.pop(-1) v2 = vectors.pop(-1) newvect = [] for v1_val in v1: for v2_val in v2: newvect.append(v1_val*v2_val) vectors.append(newvect) return calculate_tensor_product(vectors) def angle_to_vector(expected_values): """ takes in array of angles (degrees) returns pairs of complex numbers """ plus = 1/sqrt(2) minus = -1/sqrt(2) plus_i = complex(0,1)/sqrt(2) minus_i = complex(0,-1)/sqrt(2) ret_vector = [] for angle in expected_values: basis_arr = [0, 90, 180, 270, 360] closest_basis_arr = [abs(x-angle) for x in basis_arr] closest = basis_arr[closest_basis_arr.index(min(closest_basis_arr))] closest_angle = closest_basis_arr[closest_basis_arr.index(min(closest_basis_arr))] #print("closest " + str(closest)) #print("closest angle " + str(closest_angle)) basis_arr.pop(closest_basis_arr.index(min(closest_basis_arr))) closest_basis_arr.pop(closest_basis_arr.index(min(closest_basis_arr))) second_closest = basis_arr[closest_basis_arr.index(min(closest_basis_arr))] second_closest_angle = closest_basis_arr[closest_basis_arr.index(min(closest_basis_arr))] #print("second closest " + str(second_closest)) #print("second closest angle " + str(second_closest_angle)) if closest == 0: if second_closest == 90: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * plus + sin(closest_angle * pi / 180) * plus_i]) else: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * plus + sin(closest_angle * pi / 180) * minus_i]) elif closest == 90: if second_closest == 180: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * plus_i + sin(closest_angle * pi / 180) * minus]) else: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * plus_i + sin(closest_angle * pi / 180) * plus]) elif closest == 180: if second_closest == 270: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * minus + sin(closest_angle * pi / 180) * minus_i]) else: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * minus + sin(closest_angle * pi / 180) * plus_i]) elif closest == 270: if second_closest == 360: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * minus_i + sin(closest_angle * pi / 180) * plus]) else: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * minus_i + sin(closest_angle * pi / 180) * minus]) elif closest == 360: if second_closest == 90: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * plus + sin(closest_angle * pi / 180) * plus_i]) else: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * plus + sin(closest_angle * pi / 180) * minus_i]) #print(ret_vector) return ret_vector if __name__ == "__main__": #test_qft_then_inverse() test_specific_phase() #test_superposition_inputs()
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import warnings from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, transpile from qiskit.tools.monitor import job_monitor from qiskit.circuit.library import QFT from qiskit.visualization import plot_histogram, plot_bloch_multivector warnings.filterwarnings("ignore", category=DeprecationWarning) import numpy as np pi = np.pi def flip_endian(dict): newdict = {} for key in list(dict): newdict[key[::-1]] = dict.pop(key) return newdict def qft_rotations(circuit, n): #if qubit amount is 0, then do nothing and return if n == 0: #set it to measure the x axis #set_measure_x(circuit, 4) #circuit.measure_all() return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) return qft_rotations(circuit, n) def qft_rotations_not_inplace(n): circuit = QuantumCircuit(n) #if qubit amount is 0, then do nothing and return if n == 0: #set it to measure the x axis #set_measure_x(circuit, 4) #circuit.measure_all() return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) return qft_rotations(circuit, n)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### removed cx gate ### return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).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
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": ### removed x gate ### pass if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).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) ### removed h gate ### return qc
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### replaced cx gate ### qc.cy(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).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
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": ### replaced z gate ### qc.x(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).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) ### replaced x gate ### qc.x(1) return qc
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) ### replaced x gate ### qc.x(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).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) ### replaced x gate ### qc.x(1) return qc
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": ### replaced x gate ### qc.z(qubit) if msg[0] == "1": ### replaced z gate ### qc.x(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import warnings from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, transpile from qiskit.tools.monitor import job_monitor from qiskit.circuit.library import QFT from qiskit.visualization import plot_histogram, plot_bloch_multivector warnings.filterwarnings("ignore", category=DeprecationWarning) import numpy as np pi = np.pi def flip_endian(dict): newdict = {} for key in list(dict): newdict[key[::-1]] = dict.pop(key) return newdict def set_measure_x(circuit, n): for num in range(n): circuit.h(num) def set_measure_y(circuit, n): for num in range(n): circuit.sdg(num) circuit.h(num) def qft_rotations(circuit, n): #if qubit amount is 0, then do nothing and return if n == 0: #set it to measure the x axis set_measure_x(qc, 4) qc.measure_all() return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) return qft_rotations(circuit, n) backend = Aer.get_backend('aer_simulator') qc = QuantumCircuit(4) qc.x(0) qft_rotations(qc,4)#call the recursive qft method #set it to measure the x axis set_measure_x(qc, 4) job = execute(qc, backend, shots=100000)#run the circuit 1000000 times print(flip_endian(job.result().get_counts()))#return the result counts def qft_rotations(circuit, n): #if qubit amount is 0, then do nothing and return if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) #print(n) #print(qubit) return qft_rotations(circuit, n) sim = Aer.get_backend('aer_simulator') q = QuantumRegister(4,'q') c = ClassicalRegister(4,'c') qc = QuantumCircuit(q,c) qc.x(0) qc.x(1) qc.x(2) #qc.x(3) #qc.h(0) #qc.p( 20 * pi / 180, 0) qft_rotations(qc,4)#call the recursive qft method qc.save_statevector() statevector = sim.run(qc).result().get_statevector() print(statevector) plot_bloch_multivector(statevector) backend = Aer.get_backend('aer_simulator') q = QuantumRegister(4,'q') c = ClassicalRegister(1,'c') qc = QuantumCircuit(q,c) qc.x(0) qft_rotations(qc,4)#call the recursive qft method set_measure_x(qc, 4) print(qc) qc.measure(q[3],c)#select qubits registers to measure job = execute(qc, backend, shots=1000000)#run the circuit 1000 times dictRes = job.result().get_counts()#return the result counts print(dictRes)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import unittest import cirq from cirq.ops import H, X, I import random import matplotlib.pyplot as plt import numpy as np from numpy.random import randint import hypothesis.strategies as st from hypothesis import given, settings def generate_binary(len): return randint(2, size=len) def encode_message(bits, bases, messageLen): message = [] for i in range(messageLen): qubits = cirq.LineQubit.range(1) qc = cirq.Circuit() if bases[i] == 0: # Prepare qubit in Z-basis if bits[i] == 0: qc.append(cirq.I(qubits[0])) else: qc.append(cirq.X(qubits[0])) else: # Prepare qubit in X-basis if bits[i] == 0: qc.append(cirq.H(qubits[0])) else: qc.append(cirq.X(qubits[0])) qc.append(cirq.H(qubits[0])) message.append(qc) return message def measure_message(message, bases, messageLen): measurements = [] for q in range(messageLen): if bases[q] == 0: # measuring in Z-basis if (not message[q].has_measurements()): for qubit in message[q].all_qubits(): message[q].append(cirq.measure(qubit)) if bases[q] == 1: # measuring in X-basis if (not message[q].has_measurements()): for qubit in message[q].all_qubits(): message[q].append(cirq.H(qubit)) message[q].append(cirq.measure(qubit)) simulator = cirq.Simulator() measured_bit = simulator.run(message[q]) measurements.append((measured_bit.data.iat[0,0])) return measurements def remove_garbage(a_bases, b_bases, bits, messageLen): good_bits = [] for q in range(messageLen): if a_bases[q] == b_bases[q]: # If both used the same basis, add # this to the list of 'good' bits good_bits.append(bits[q]) return good_bits def sample_bits(bits, selection): sample = [] for i in selection: # use np.mod to make sure the # bit we sample is always in # the list range i = np.mod(i, len(bits)) # pop(i) removes the element of the # list at index 'i' sample.append(bits.pop(i)) return sample np.random.seed(seed=0) messageLen = 100 ## Step 1 # Alice generates bits alice_bits = generate_binary(messageLen) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = generate_binary(messageLen) message = encode_message(alice_bits, alice_bases, messageLen) ## Step 3 # Decide which basis to measure in: bob_bases = generate_binary(messageLen) bob_results = measure_message(message, bob_bases, messageLen) ## Step 4 alice_key = remove_garbage(alice_bases, bob_bases, alice_bits, messageLen) bob_key = remove_garbage(alice_bases, bob_bases, bob_results, messageLen) ## Step 5 sample_size = 15 bit_selection = generate_binary(sample_size) bob_sample = sample_bits(bob_key, bit_selection) print(" bob_sample = " + str(bob_sample)) alice_sample = sample_bits(alice_key, bit_selection) print("alice_sample = "+ str(alice_sample)) bob_sample == alice_sample n = 100 # Step 1 alice_bits = generate_binary(messageLen) alice_bases = generate_binary(messageLen) # Step 2 message = encode_message(alice_bits, alice_bases, messageLen) # Interception! eve_bases = generate_binary(messageLen) intercepted_message = measure_message(message, eve_bases, messageLen) # Step 3 bob_bases = generate_binary(messageLen) bob_results = measure_message(message, bob_bases, messageLen) # Step 4 bob_key = remove_garbage(alice_bases, bob_bases, bob_results, messageLen) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits, messageLen) # Step 5 sample_size = 15 # Change this to something lower and see if # Eve can intercept the message without Alice # and Bob finding out bit_selection = generate_binary(sample_size) bob_sample = sample_bits(bob_key, bit_selection) alice_sample = sample_bits(alice_key, bit_selection) if bob_sample != alice_sample: print("Eve's interference was detected.") else: print("Eve went undetected!") ########################################################################### ## Define composite strategies to generate lists of ints in equal length ## ########################################################################### @st.composite def single_list(draw): arrayLengths = draw(st.integers(min_value=1, max_value=100)) fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths) return (draw(fixed_length_list)) @st.composite def pair_of_lists(draw): arrayLengths = draw(st.integers(min_value=1, max_value=100)) fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths) return (draw(fixed_length_list), draw(fixed_length_list)) @st.composite def trio_of_lists(draw): arrayLengths = draw(st.integers(min_value=1, max_value=100)) fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths) return (draw(fixed_length_list), draw(fixed_length_list), draw(fixed_length_list)) @st.composite def long_trio_of_lists(draw): arrayLengths = draw(st.integers(min_value=100, max_value=110)) fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths) return (draw(fixed_length_list), draw(fixed_length_list), draw(fixed_length_list)) ########################## ## test generate binary ## ########################## @given(testLength = st.integers(min_value=0, max_value=10000)) def test_created_message_is_binary(testLength): binArr = generate_binary(testLength) for i in binArr: assert (i == 1 or i == 0) @given(testLength = st.integers(min_value=1, max_value=10000)) def test_created_message_equal_length_to_int_passed_in(testLength): binArr = generate_binary(testLength) assert(len(binArr) == testLength) ############################ ## encoding message tests ## ############################ @given(pair_of_lists()) @settings(deadline=None) def test_encode_message_equal_length_to_base(lists): alice_bits, alice_bases = lists circuitArr = encode_message(alice_bits, alice_bases, len(alice_bits)) assert(len(circuitArr) == len(alice_bits)) @given(pair_of_lists()) @settings(deadline=None) def test_encode_message_are_circuits(lists): alice_bits, alice_bases = lists circuitArr = encode_message(alice_bits, alice_bases, len(alice_bits)) for i in circuitArr: assert(isinstance(i, cirq.Circuit)) @given(pair_of_lists()) @settings(deadline=None) def test_encode_message_circuits_are_not_longer_than_2(lists): alice_bits, alice_bases = lists circuitArr = encode_message(alice_bits, alice_bases, len(alice_bits)) for i in circuitArr: assert(not(sum(1 for _ in i.all_operations()) > 2)) @given(pair_of_lists()) @settings(deadline=None) def test_encode_message_circuits_use_only_H_X_I(lists): alice_bits, alice_bases = lists circuitArr = encode_message(alice_bits, alice_bases, len(alice_bits)) for i in circuitArr: for gate in i.all_operations(): assert(isinstance(gate.gate, cirq.ops.identity.IdentityGate) or isinstance(gate.gate, cirq.ops.pauli_gates._PauliX) or isinstance(gate.gate, cirq.ops.common_gates.HPowGate)) ############################ ## decoding message tests ## ############################ @given(lists = trio_of_lists()) @settings(deadline=None) def test_decode_message_length_equals_base_length(lists): alice_bits, alice_bases, bob_base = lists encoded_message = encode_message(alice_bits, alice_bases, len(bob_base)) msmtArr = measure_message(encoded_message, bob_base, len(bob_base)) assert len(msmtArr) == len(bob_base) @given(lists = trio_of_lists()) @settings(deadline=None) def test_decode_message_is_binary(lists): alice_bits, alice_bases, bob_base = lists encoded_message = encode_message(alice_bits, alice_bases, len(bob_base)) msmtArr = measure_message(encoded_message, bob_base, len(bob_base)) for i in msmtArr: assert (i == 1 or i == 0) @given(lists = pair_of_lists()) @settings(deadline=None) def test_decode_with_same_base_returns_original_bits(lists): alice_bits, alice_bases = lists encoded_message = encode_message(alice_bits, alice_bases, len(alice_bits)) decodeWithSameBases = measure_message(encoded_message, alice_bases, len(alice_bases)) assert(np.array_equal(np.array(alice_bits), np.array(decodeWithSameBases))) @given(lists = pair_of_lists()) @settings(deadline=None) def test_decode_with_same_bases_return_same_array(lists): alice_bits, alice_bases = lists encoded_message = encode_message(alice_bits, alice_bases, len(alice_bits)) encoded_message2 = encode_message(alice_bits, alice_bases, len(alice_bits)) decodeWithSameBases = measure_message(encoded_message, alice_bases, len(alice_bases)) decodeWithSameBases2 = measure_message(encoded_message2, alice_bases, len(alice_bases)) assert(np.array_equal(np.array(decodeWithSameBases), np.array(decodeWithSameBases2))) @given(lists = long_trio_of_lists()) @settings(deadline=None) def test_decoding_runs_likely_different(lists): alice_bits, alice_bases, bob_base = lists encoded_message = encode_message(alice_bits, alice_bases, len(bob_base)) msmtArr = measure_message(encoded_message, alice_bases, len(alice_bases)) msmtArrRun2 = measure_message(encoded_message, bob_bases, len(bob_base)) assert(not np.array_equal(np.array(msmtArr), np.array(msmtArrRun2))) ############################## ## remove garbage/key tests ## ############################## @given(lists = trio_of_lists()) @settings(deadline=None) def test_key_smaller_or_equal_len_to_original_bits(lists): alice_bits, alice_bases, bob_base = lists assert len(remove_garbage(alice_bits, alice_bases, bob_base, len(bob_base))) <= len(bob_base) @given(lists = trio_of_lists()) @settings(deadline=None) def test_check_keys_equal(lists): alice_bits, alice_bases, bob_bases = lists message = encode_message(alice_bits, alice_bases, len(bob_bases)) bob_results = measure_message(message, bob_bases, len(bob_bases)) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits, len(bob_bases)) bob_key = remove_garbage(alice_bases, bob_bases, bob_results, len(bob_bases)) assert(np.array_equal(np.array(alice_key), np.array(bob_key))) @given(lists = trio_of_lists()) @settings(deadline=None) def test_key_is_binary(lists): alice_bits, alice_bases, bob_bases = lists alice_key = remove_garbage(alice_bases, bob_bases, alice_bits, len(bob_bases)) for i in alice_key: assert (i == 1 or i == 0) if __name__ == "__main__": #test_created_message_is_binary() #test_created_message_equal_length_to_int_passed_in() #test_encode_message_equal_length_to_base() #test_encode_message_are_circuits() #test_encode_message_circuits_are_not_longer_than_2() #test_encode_message_circuits_use_only_H_X_I() #test_decode_message_length_equals_base_length() #test_decode_message_is_binary() #test_decode_with_same_base_returns_original_bits() #test_decode_with_same_bases_return_same_array() #test_decoding_runs_likely_different() #test_key_smaller_or_equal_len_to_original_bits() #test_check_keys_equal() #test_key_is_binary()
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### added h gate ### qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).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
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": ### added x gate ### qc.x(qubit) 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
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).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) ### added y gate ### qc.y(0) qc.h(1) return qc