repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/COFAlumni-USB/qiskit-fall-2022
COFAlumni-USB
import numpy as np import math import qiskit as qiskit from numpy import sqrt from random import randint from qiskit import * from qiskit import Aer, QuantumCircuit, IBMQ, execute, quantum_info, transpile from qiskit.visualization import plot_state_city, plot_bloch_multivector from qiskit.visualization import plot_histogram from qiskit.tools import job_monitor from qiskit.providers.fake_provider import FakeOpenPulse2Q, FakeOpenPulse3Q, FakeManila, FakeValencia, FakeHanoi from qiskit import pulse, transpile from qiskit.pulse.library import Gaussian #Compuertas personalizadas from qiskit.circuit import Gate from qiskit import QiskitError #informacion import qiskit.tools.jupyter provider = IBMQ.load_account() belem = provider.get_backend('ibmq_belem') print('se ha ejecutado correctamente') def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Simulador de prueba FakeManila backend = FakeManila() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') result = execute(circ, backend=FakeManila()).result(); job = backend.run(circ) counts = job.result().get_counts() plot_histogram(counts) backend = FakeManila(); with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0)) h_q0.draw() backend = FakeManila(); with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=100, amp=0.1, sigma=33.33), pulse.drive_channel(0)) h_q0.draw() circ.add_calibration( 'h', [0], h_q0) circ.add_calibration( 'x', [0], h_q0) circ.add_calibration( 'cx',[0], h_q0) circ.add_calibration( 'sx',[0], h_q0) circ.add_calibration( 'id',[0], h_q0) circ.add_calibration( 'rz',[0], h_q0) circ.add_calibration( 'reset',[0], h_q0) backend = FakeManila() circ1 = transpile(circ, backend) print(backend.configuration().basis_gates) circ1.draw('mpl', idle_wires=False) result = execute(circ1, backend=FakeManila()).result(); job = backend.run(circ1) counts = job.result().get_counts() plot_histogram(counts) def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Simulador de prueba FakeOpenPulse3Q backend = FakeOpenPulse3Q() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') result = execute(circ, backend=FakeOpenPulse3Q()).result(); job = backend.run(circ) counts = job.result().get_counts() plot_histogram(counts) backend = FakeOpenPulse3Q(); with pulse.build(backend, name='hadamard') as h_q1: pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0)) h_q1.draw() backend = FakeOpenPulse3Q(); with pulse.build(backend, name='hadamard') as h_q1: pulse.play(Gaussian(duration=100, amp=0.3, sigma=33.33), pulse.drive_channel(0)) h_q1.draw() circ.add_calibration( 'h', [0], h_q1) circ.add_calibration( 'x', [0], h_q1) circ.add_calibration( 'cx',[0], h_q1) circ.add_calibration( 'sx',[0], h_q1) circ.add_calibration( 'id',[0], h_q1) circ.add_calibration( 'rz',[0], h_q1) circ.add_calibration( 'reset',[0], h_q1) backend = FakeOpenPulse3Q() circ2 = transpile(circ, backend) print(backend.configuration().basis_gates) circ2.draw('mpl', idle_wires=False) result = execute(circ2, backend=FakeOpenPulse3Q()).result(); job = backend.run(circ2) counts = job.result().get_counts() plot_histogram(counts) def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Simulador de prueba FakeManila backend = FakeManila() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') result = execute(circ, backend=FakeManila()).result(); job = backend.run(circ) counts = job.result().get_counts() plot_histogram(counts) backend = FakeManila(); with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0)) h_q0.draw() backend = FakeManila(); with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=100, amp=0.3, sigma=33.33), pulse.drive_channel(0)) h_q0.draw() circ.add_calibration( 'h', [0], h_q0) circ.add_calibration( 'x', [0], h_q0) circ.add_calibration( 'cx',[0], h_q0) circ.add_calibration( 'sx',[0], h_q0) circ.add_calibration( 'id',[0], h_q0) circ.add_calibration( 'rz',[0], h_q0) circ.add_calibration( 'reset',[0], h_q0) backend = FakeManila() circ1 = transpile(circ, backend) print(backend.configuration().basis_gates) circ1.draw('mpl', idle_wires=False) result = execute(circ1, backend=FakeManila()).result(); job = backend.run(circ1) counts = job.result().get_counts() plot_histogram(counts) def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Simulador de prueba FakeOpenPulse3Q backend = FakeOpenPulse3Q() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') result = execute(circ, backend=FakeOpenPulse3Q()).result(); job = backend.run(circ) counts = job.result().get_counts() plot_histogram(counts) backend = FakeOpenPulse3Q(); with pulse.build(backend, name='hadamard') as h_q1: pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0)) h_q1.draw() backend = FakeOpenPulse3Q(); with pulse.build(backend, name='hadamard') as h_q1: pulse.play(Gaussian(duration=100, amp=0.3, sigma=33.33), pulse.drive_channel(0)) h_q1.draw() circ.add_calibration( 'h', [0], h_q1) circ.add_calibration( 'x', [0], h_q1) circ.add_calibration( 'cx',[0], h_q1) circ.add_calibration( 'sx',[0], h_q1) circ.add_calibration( 'id',[0], h_q1) circ.add_calibration( 'rz',[0], h_q1) circ.add_calibration( 'reset',[0], h_q1) backend = FakeOpenPulse3Q() circ2 = transpile(circ, backend) print(backend.configuration().basis_gates) circ2.draw('mpl', idle_wires=False) result = execute(circ2, backend=FakeOpenPulse3Q()).result(); job = backend.run(circ2) counts = job.result().get_counts() plot_histogram(counts) def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Simulador de prueba FakeManila backend = FakeManila() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') result = execute(circ, backend=FakeManila()).result(); job = backend.run(circ) counts = job.result().get_counts() plot_histogram(counts) backend = FakeManila(); with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0)) h_q0.draw() backend = FakeManila(); with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0)) h_q0.draw() backend = FakeManila(); with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=100, amp=1, sigma=33.33), pulse.drive_channel(0)) h_q0.draw() circ.add_calibration( 'h', [0], h_q0) circ.add_calibration( 'x', [0], h_q0) circ.add_calibration( 'cx',[0], h_q0) circ.add_calibration( 'sx',[0], h_q0) circ.add_calibration( 'id',[0], h_q0) circ.add_calibration( 'rz',[0], h_q0) circ.add_calibration( 'reset',[0], h_q0) backend = FakeManila() circ1 = transpile(circ, backend) print(backend.configuration().basis_gates) circ1.draw('mpl', idle_wires=False) result = execute(circ1, backend=FakeManila()).result(); job = backend.run(circ1) counts = job.result().get_counts() plot_histogram(counts) def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Simulador de prueba FakeOpenPulse3Q backend = FakeOpenPulse3Q() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') result = execute(circ, backend=FakeOpenPulse3Q()).result(); job = backend.run(circ) counts = job.result().get_counts() plot_histogram(counts) backend = FakeOpenPulse3Q(); with pulse.build(backend, name='hadamard') as h_q1: pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0)) h_q1.draw() backend = FakeOpenPulse3Q(); with pulse.build(backend, name='hadamard') as h_q1: pulse.play(Gaussian(duration=100, amp=1, sigma=33.33), pulse.drive_channel(0)) h_q1.draw() circ.add_calibration( 'h', [0], h_q1) circ.add_calibration( 'x', [0], h_q1) circ.add_calibration( 'cx',[0], h_q1) circ.add_calibration( 'sx',[0], h_q1) circ.add_calibration( 'id',[0], h_q1) circ.add_calibration( 'rz',[0], h_q1) circ.add_calibration( 'reset',[0], h_q1) backend = FakeOpenPulse3Q() circ2 = transpile(circ, backend) print(backend.configuration().basis_gates) circ2.draw('mpl', idle_wires=False) result = execute(circ2, backend=FakeOpenPulse3Q()).result(); job = backend.run(circ2) counts = job.result().get_counts() plot_histogram(counts)
https://github.com/COFAlumni-USB/qiskit-fall-2022
COFAlumni-USB
import numpy as np import math import qiskit as qiskit from numpy import sqrt from random import randint from qiskit import * from qiskit import Aer, QuantumCircuit, IBMQ, execute, quantum_info, transpile from qiskit.visualization import plot_state_city, plot_bloch_multivector from qiskit.visualization import plot_histogram from qiskit.tools import job_monitor from qiskit.providers.fake_provider import FakeOpenPulse2Q, FakeOpenPulse3Q, FakeManila, FakeValencia, FakeHanoi from qiskit import pulse, transpile from qiskit.pulse.library import Gaussian #Compuertas personalizadas from qiskit.circuit import Gate from qiskit import QiskitError #informacion import qiskit.tools.jupyter provider = IBMQ.load_account() belem = provider.get_backend('ibmq_belem') print('se ha ejecutado correctamente') def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Simulador de prueba FakeManila backend = FakeManila() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') result = execute(circ, backend=FakeManila()).result(); job = backend.run(circ) counts = job.result().get_counts() plot_histogram(counts) backend = FakeManila(); with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0)) h_q0.draw() backend = FakeManila(); with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=100, amp=0.1, sigma=33.33), pulse.drive_channel(0)) h_q0.draw() circ.add_calibration( 'h', [0], h_q0) circ.add_calibration( 'x', [0], h_q0) circ.add_calibration( 'cx',[0], h_q0) circ.add_calibration( 'sx',[0], h_q0) circ.add_calibration( 'id',[0], h_q0) circ.add_calibration( 'rz',[0], h_q0) circ.add_calibration( 'reset',[0], h_q0) backend = FakeManila() circ1 = transpile(circ, backend) print(backend.configuration().basis_gates) circ1.draw('mpl', idle_wires=False) result = execute(circ1, backend=FakeManila()).result(); job = backend.run(circ1) counts = job.result().get_counts() plot_histogram(counts) def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Simulador de prueba FakeOpenPulse3Q backend = FakeOpenPulse3Q() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') result = execute(circ, backend=FakeOpenPulse3Q()).result(); job = backend.run(circ) counts = job.result().get_counts() plot_histogram(counts) backend = FakeOpenPulse3Q(); with pulse.build(backend, name='hadamard') as h_q1: pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0)) h_q1.draw() backend = FakeOpenPulse3Q(); with pulse.build(backend, name='hadamard') as h_q1: pulse.play(Gaussian(duration=100, amp=0.1, sigma=33.33), pulse.drive_channel(0)) h_q1.draw() circ.add_calibration( 'h', [0], h_q1) circ.add_calibration( 'x', [0], h_q1) circ.add_calibration( 'cx',[0], h_q1) circ.add_calibration( 'sx',[0], h_q1) circ.add_calibration( 'id',[0], h_q1) circ.add_calibration( 'rz',[0], h_q1) circ.add_calibration( 'reset',[0], h_q1) backend = FakeOpenPulse3Q() circ2 = transpile(circ, backend) print(backend.configuration().basis_gates) circ2.draw('mpl', idle_wires=False) result = execute(circ2, backend=FakeOpenPulse3Q()).result(); job = backend.run(circ2) counts = job.result().get_counts() plot_histogram(counts) def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Simulador de prueba FakeManila backend = FakeManila() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') result = execute(circ, backend=FakeManila()).result(); job = backend.run(circ) counts = job.result().get_counts() plot_histogram(counts) backend = FakeManila(); with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0)) h_q0.draw() backend = FakeManila(); with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=50, amp=0.1, sigma=16.66), pulse.drive_channel(0)) h_q0.draw() circ.add_calibration( 'h', [0], h_q0) circ.add_calibration( 'x', [0], h_q0) circ.add_calibration( 'cx',[0], h_q0) circ.add_calibration( 'sx',[0], h_q0) circ.add_calibration( 'id',[0], h_q0) circ.add_calibration( 'rz',[0], h_q0) circ.add_calibration( 'reset',[0], h_q0) backend = FakeManila() circ1 = transpile(circ, backend) print(backend.configuration().basis_gates) circ1.draw('mpl', idle_wires=False) result = execute(circ1, backend=FakeManila()).result(); job = backend.run(circ1) counts = job.result().get_counts() plot_histogram(counts) def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Simulador de prueba FakeOpenPulse3Q backend = FakeOpenPulse3Q() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') result = execute(circ, backend=FakeOpenPulse3Q()).result(); job = backend.run(circ) counts = job.result().get_counts() plot_histogram(counts) backend = FakeOpenPulse3Q(); with pulse.build(backend, name='hadamard') as h_q1: pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0)) h_q1.draw() backend = FakeOpenPulse3Q(); with pulse.build(backend, name='hadamard') as h_q1: pulse.play(Gaussian(duration=50, amp=0.1, sigma=16.66), pulse.drive_channel(0)) h_q1.draw() circ.add_calibration( 'h', [0], h_q1) circ.add_calibration( 'x', [0], h_q1) circ.add_calibration( 'cx',[0], h_q1) circ.add_calibration( 'sx',[0], h_q1) circ.add_calibration( 'id',[0], h_q1) circ.add_calibration( 'rz',[0], h_q1) circ.add_calibration( 'reset',[0], h_q1) backend = FakeOpenPulse3Q() circ2 = transpile(circ, backend) print(backend.configuration().basis_gates) circ2.draw('mpl', idle_wires=False) result = execute(circ2, backend=FakeOpenPulse3Q()).result(); job = backend.run(circ2) counts = job.result().get_counts() plot_histogram(counts) def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Simulador de prueba FakeManila backend = FakeManila() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') result = execute(circ, backend=FakeManila()).result(); job = backend.run(circ) counts = job.result().get_counts() plot_histogram(counts) backend = FakeManila(); with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0)) h_q0.draw() backend = FakeManila(); with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=10, amp=0.1, sigma=3.33), pulse.drive_channel(0)) h_q0.draw() circ.add_calibration( 'h', [0], h_q0) circ.add_calibration( 'x', [0], h_q0) circ.add_calibration( 'cx',[0], h_q0) circ.add_calibration( 'sx',[0], h_q0) circ.add_calibration( 'id',[0], h_q0) circ.add_calibration( 'rz',[0], h_q0) circ.add_calibration( 'reset',[0], h_q0) backend = FakeManila() circ1 = transpile(circ, backend) print(backend.configuration().basis_gates) circ1.draw('mpl', idle_wires=False) result = execute(circ1, backend=FakeManila()).result(); job = backend.run(circ1) counts = job.result().get_counts() plot_histogram(counts) def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Simulador de prueba FakeOpenPulse3Q backend = FakeOpenPulse3Q() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') result = execute(circ, backend=FakeOpenPulse3Q()).result(); job = backend.run(circ) counts = job.result().get_counts() plot_histogram(counts) backend = FakeOpenPulse3Q(); with pulse.build(backend, name='hadamard') as h_q1: pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0)) h_q1.draw() backend = FakeOpenPulse3Q(); with pulse.build(backend, name='hadamard') as h_q1: pulse.play(Gaussian(duration=10, amp=1, sigma=3.33), pulse.drive_channel(0)) h_q1.draw() circ.add_calibration( 'h', [0], h_q1) circ.add_calibration( 'x', [0], h_q1) circ.add_calibration( 'cx',[0], h_q1) circ.add_calibration( 'sx',[0], h_q1) circ.add_calibration( 'id',[0], h_q1) circ.add_calibration( 'rz',[0], h_q1) circ.add_calibration( 'reset',[0], h_q1) backend = FakeOpenPulse3Q() circ2 = transpile(circ, backend) print(backend.configuration().basis_gates) circ2.draw('mpl', idle_wires=False) result = execute(circ2, backend=FakeOpenPulse3Q()).result(); job = backend.run(circ2) counts = job.result().get_counts() plot_histogram(counts)
https://github.com/COFAlumni-USB/qiskit-fall-2022
COFAlumni-USB
import numpy as np import math import qiskit as qiskit from numpy import sqrt from random import randint from qiskit import * from qiskit import Aer, QuantumCircuit, IBMQ, execute, quantum_info from qiskit.visualization import plot_state_city, plot_bloch_multivector from qiskit.visualization import plot_histogram from qiskit.tools import job_monitor provider = IBMQ.load_account() nairobi=provider.get_backend('ibm_nairobi') print('ejecutado correctamente') def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc print('ejecutado correctamente') x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) random_oracle(circ, 0,1,2) circ.draw('mpl') circ.count_ops() circ.depth() circ2 = qiskit.transpile(circ,basis_gates =['u1', 'u2', 'u3', 'cx'], optimization_level=3) circ2.draw('mpl') circ2.depth()
https://github.com/COFAlumni-USB/qiskit-fall-2022
COFAlumni-USB
import qiskit as qiskit import numpy as np import math from numpy import sqrt from random import randint from qiskit import * from qiskit import Aer, QuantumCircuit, IBMQ, execute, quantum_info from qiskit.visualization import plot_state_city, plot_bloch_multivector from qiskit.visualization import plot_histogram from qiskit.tools import job_monitor provider = IBMQ.load_account() belem = provider.get_backend('ibmq_belem') print('se ha ejecutado correctamente') def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc print('se ha ejecutado correctamente') x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.h(range(x_register+y_register)) circ.draw('mpl') #se aΓ±ade una barra para separar la x-gate de la h-gate (compuerta de Hadamard) x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.draw('mpl') #es una evoluciΓ³n de la anterior, y podemos ver que entre la dos barras se aΓ±ade el random_oracle # con sus valores respectivos. x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() circ.draw('mpl') circ.count_ops() circ.depth() def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc #nota: podemos ver la definiciΓ³n y su respectivo comportamiento def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Como podemos ver se ha aΓ±adido la def Grover_Iteration x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.draw('mpl') #Se aΓ±ade el circ_measure, con rangos de registro x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') circ.count_ops() circ.depth() transpile_circuit = qiskit.transpile(circ,basis_gates =['u1', 'u2', 'u3', 'cx'],optimization_level=3) transpile_circuit.draw('mpl') transpile_circuit.depth() Ahora con la ΓΊltima definiciΓ³n con la cual hemos estructurado el circuito, vamos a probarla y lo que vamos a hacer es inducirle las instrucciones al qiskit.circuit y los vamos a llevar a la simulaciΓ³n con el Aer_Simulator el cual nos darΓ‘ el estado que debe dar el algoritmo de Grover. x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) #nota: son las mismas instruccions expresadas a la hora de dar el resultado grΓ‘fico arriba, el circuito #completamente estructurado. #circ.draw('mpl') EN ESTE CASO NO LO UTILIZAREMOS solo daremos instrucciones al circuito #simulaciΓ³n backend = Aer.get_backend('aer_simulator') #simulador a usar job = execute(circ, backend, shots=1024) #descripciΓ³n del trabajo result = job.result() counts = result.get_counts(circ) plot_histogram(counts) #expresa los datos en un histograma #Se establecen las instrucciones para ejecutarlo en el procesador. job_q = execute(circ,belem,shots=1024) job_monitor(job_q) result = job.result() counts = result.get_counts(circ) plot_histogram(counts)
https://github.com/COFAlumni-USB/qiskit-fall-2022
COFAlumni-USB
import numpy as np import math import qiskit as qiskit from numpy import sqrt from random import randint from qiskit import * from qiskit import Aer, QuantumCircuit, IBMQ, execute, quantum_info, transpile from qiskit.visualization import plot_state_city, plot_bloch_multivector from qiskit.visualization import plot_histogram from qiskit.tools import job_monitor from qiskit.providers.fake_provider import FakeOpenPulse2Q, FakeOpenPulse3Q, FakeManilaV2, FakeManila provider = IBMQ.load_account() print('se ha ejecutado correctamente') def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Se aΓ±ade el circ_measure, y el Grover_Iteration con rangos de registro x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 #Se define la variable circ circ = QuantumCircuit(x_register+y_register,measure_register) #Se describen las compuertas y barreras circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') circ.count_ops() #nΓΊmero de compuertas circ.depth() #calcula la profundidad del circuito x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) #nota: son las mismas instruccions expresadas a la hora de dar el resultado grΓ‘fico arriba, el circuito #completamente estructurado. #circ.draw('mpl') EN ESTE CASO NO LO UTILIZAREMOS solo daremos instrucciones al circuito #circ.draw('mpl') #simulaciΓ³n Aer Simulator backend = Aer.get_backend('aer_simulator') #simulador a usar job = execute(circ, backend, shots=1024) #descripciΓ³n del trabajo result = job.result() counts = result.get_counts(circ) plot_histogram(counts) #expresa los datos en un histograma #Simulador de prueba FakeManilaV2 backend = FakeManilaV2() #la ΓΊnica diferencia es que ahora establecemos un backend determinado #para el circuito a simular x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') circ.count_ops() circ.depth() transpiled_circ = transpile(circ, backend) transpiled_circ.draw() #Resultados de transpilaciΓ³n con FakeManilaV2 transpiled_circ.count_ops() transpiled_circ.depth() job = backend.run(transpiled_circ) #la variable establece la funciΓ³n de correr el backend = FakeManilaV2 counts = job.result().get_counts() plot_histogram(counts) #analiza los datos a travΓ©s del histograma #Resultados de SimulaciΓ³n con FakeManilaV2 #Simulador de prueba FakeManila backend = FakeManila() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') circ.count_ops() circ.depth() transpiled_circ = transpile(circ, backend) transpiled_circ.draw() #Resultados de transpilaciΓ³n con FakeManila transpiled_circ.count_ops() transpiled_circ.depth() job = backend.run(transpiled_circ) #la variable establece la funciΓ³n de correr el backend = FakeManila counts = job.result().get_counts() plot_histogram(counts) #analiza los datos a travΓ©s del histograma #Resultados de SimulaciΓ³n con FakeManila Como observamos, tenemos un poco de ruido.(Con el backend=FakeManila) #Simulador de prueba FakeOpenPulse2Q backend = FakeOpenPulse2Q() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') circ.count_ops() circ.depth() job = backend.run(circ) counts = job.result().get_counts() plot_histogram(counts) #Resultados de SimulaciΓ³n con FakeOpenPulse2Q Como observamos, tenemos demasiado ruido en comparaciΓ³n con las otras simulaciones.(Con el backend=FakeOpenPulse2Q) #Simulador de prueba FakeOpenPulse3Q backend = FakeOpenPulse3Q() x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') circ.count_ops() circ.depth() transpiled_circ = transpile(circ, backend) transpiled_circ.draw() #Resultados de transpilaciΓ³n con FakeOpenPulse3Q transpiled_circ.count_ops() transpiled_circ.depth() job = backend.run(transpiled_circ) counts = job.result().get_counts() plot_histogram(counts) #Resultado de SimulaciΓ³n con FakeOpenPulse3Q En esta simulaciΓ³n, no poseemos ruido.(Con el backend=FakeOpenPulse3Q)
https://github.com/Cryoris/surfer
Cryoris
import numpy as np from time import time from qiskit import IBMQ, Aer from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.circuit.library import EfficientSU2, RealAmplitudes from qiskit.opflow import QFI, StateFn, PauliExpectation, CircuitSampler from surfer.qfi import OverlapQFI, ReverseQFI # num_qubits = 27 # coupling_map = [ # (0, 1), (4, 7), (10, 12), (15, 18), (21, 23), (24, 25), # (22, 19), (16, 14), (11, 8), (5, 3), # ] + [ # (1, 4), (7, 6), (12, 13), (18, 17), (23, 24), (25, 26), # (19, 20), (14, 11), (8, 9), (3, 2) # ] + [ # (7, 10), (12, 15), (18, 21), (25, 22), (19, 16), # (13, 14), (8, 5), (2, 1) # ] num_qubits = 20 reps = 1 circuit = EfficientSU2(num_qubits, reps=reps, entanglement="pairwise").decompose() # circuit = RealAmplitudes(num_qubits, reps=reps, entanglement=coupling_map).decompose() parameters = circuit.parameters values = np.zeros(circuit.num_parameters) # for i in range(circuit.num_qubits): # values[~i] = np.pi / 2 # start = time() # qfi = ReverseQFI(do_checks=False).compute(circuit, values) # time_taken = time() - start # print(time_taken) # print(qfi) start = time() qgt = OverlapQFI(clifford=True).compute(circuit, values) / 4 time_taken = time() - start print(time_taken) print(qgt) # np.save("qfi_cliff_realamp_plus_kolkata.npy", qfi) # np.save("qfi_cliff_realamp_+_kolkata.npy", qfi) np.save("qgt_line20_esu2_pairwise_0.npy", qgt)
https://github.com/Cryoris/surfer
Cryoris
import numpy as np from time import time from qiskit import IBMQ from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import QFI, StateFn from surfer.qfi import OverlapQFI num_qubits = [10] reps = 1 runs = 1 backend = provider.get_backend(backend_name) coupling_map = backend.configuration().coupling_map num_qubits = backend.configuration().num_qubits ansatz = EfficientSU2(hamiltonian.num_qubits, reps=1, entanglement=coupling_map) return hamiltonian, ansatz def run_single(num_qubits, reps): circuit = EfficientSU2(num_qubits, reps=reps, entanglement="pairwise") values = np.zeros(circuit.num_parameters) start = time() qfi = OverlapQFI(clifford=True).compute(circuit, values) return time() - start times = [] times_std = [] for n in num_qubits: results = [run_single(n, reps) for _ in range(runs)] times.append(np.mean(results)) times_std.append(np.std(results)) print(f"{n} qubits took {times[-1]}s +- {times_std[-1]}") # np.save("cliffsimv2_su2r4.npy", np.vstack((num_qubits, times, times_std)))
https://github.com/Cryoris/surfer
Cryoris
"""The Gradient interface. Avoids using the plain name Gradient since that exists in Qiskit and I want to avoid conflicts. """ from abc import ABC, abstractmethod import qiskit import qiskit.opflow import numpy as np class GradientCalculator(ABC): """The Gradient interface.""" def __init__(self, do_checks: bool = True): """ Args: do_checks: Do some sanity checks on the inputs. Can be disabled for performance. """ self.do_checks = do_checks @abstractmethod def compute( self, operator: qiskit.opflow.OperatorBase, circuit: qiskit.QuantumCircuit, values: np.ndarray, ) -> np.ndarray: """Compute the Gradient for the given circuit. The initial state is assumed to be the all-zero state. Args: operator: The operator for the expectation value. circuit: A parameterized unitary circuit preparing the quantum state of which we compute the Gradient. values: The parameter values. """ raise NotImplementedError @staticmethod def check_inputs(circuit: qiskit.QuantumCircuit, values: np.ndarray) -> None: """Check the circuit and values. Args: circuit: A parameterized unitary circuit preparing the quantum state of which we compute the Gradient. values: The parameter values. Raises: ValueError: If the circuit is invalid (non unitary or gates with more than 1 parameter). ValueError: If the number of values doesn't match the parameters. """ _check_circuit_is_unitay(circuit) _check_1_parameter_per_gate(circuit) # check the number of parameters if circuit.num_parameters != values.size: raise ValueError( f"Mismatching number of parameters ({circuit.num_parameters}) " f"and values ({values.size})." ) def _check_circuit_is_unitay(circuit): try: _ = circuit.to_gate() except qiskit.circuit.exceptions.CircuitError: # pylint: disable=raise-missing-from raise ValueError("The circuit is not unitary.") def _check_1_parameter_per_gate(circuit): for inst, _, _ in circuit.data: params = inst.params if ( any(isinstance(params, qiskit.circuit.ParameterExpression)) and len(params) > 1 ): raise ValueError( "If a gate is parameterized, it can only have 1 parameter." )
https://github.com/Cryoris/surfer
Cryoris
"""The QFI interface. Avoids using the plain name QFI since that exists in Qiskit and I want to avoid conflicts. """ from typing import List, Optional from abc import ABC, abstractmethod import qiskit import numpy as np class QFICalculator(ABC): """The QFI interface.""" def __init__(self, do_checks: bool = True): """ Args: do_checks: Do some sanity checks on the inputs. Can be disabled for performance. """ self.do_checks = do_checks @abstractmethod def compute( self, circuit: qiskit.QuantumCircuit, values: np.ndarray, parameters: Optional[List[qiskit.circuit.Parameter]] = None, ) -> np.ndarray: """Compute the QFI for the given circuit. The initial state is assumed to be the all-zero state. Args: circuit: A parameterized unitary circuit preparing the quantum state of which we compute the QFI. values: The parameter values. """ raise NotImplementedError @staticmethod def check_inputs( circuit: qiskit.QuantumCircuit, values: np.ndarray, ) -> None: """Check the circuit and values. Args: circuit: A parameterized unitary circuit preparing the quantum state of which we compute the QFI. values: The parameter values. Raises: ValueError: If the circuit is invalid (non unitary or gates with more than 1 parameter). ValueError: If the number of values doesn't match the parameters. NotImplementedError: If the circuit has repeated parameters. """ _check_circuit_is_unitay(circuit) # _check_1_parameter_per_gate(circuit) # check the number of parameters if circuit.num_parameters != values.size: raise ValueError( f"Mismatching number of parameters ({circuit.num_parameters}) " f"and values ({values.size})." ) # _check_no_duplicate_params(circuit) def _check_circuit_is_unitay(circuit): try: _ = circuit.to_gate() except qiskit.circuit.exceptions.CircuitError: # pylint: disable=raise-missing-from raise ValueError("The circuit is not unitary.") def _check_1_parameter_per_gate(circuit): for inst, _, _ in circuit.data: params = inst.params if ( any( isinstance(param, qiskit.circuit.ParameterExpression) for param in params ) and len(params) > 1 ): raise ValueError( "If a gate is parameterized, it can only have 1 parameter." ) def _check_no_duplicate_params(circuit): # pylint: disable=protected-access for _, gates in circuit._parameter_table.items(): if len(gates) > 1: raise NotImplementedError( "The product rule is currently not implemented, parameters must be unique." )
https://github.com/jakelishman/qiskit-qasm2
jakelishman
import qiskit_qasm2 project = 'Qiskit OpenQASM 2 Tools' copyright = '2022, Jake Lishman' author = 'Jake Lishman' version = qiskit_qasm2.__version__ extensions = [ "sphinx.ext.autodoc", "sphinx.ext.intersphinx", ] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # Document the docstring for the class and the __init__ method together. autoclass_content = "both" html_theme = 'alabaster' intersphinx_mapping = { "qiskit-terra": ("https://qiskit.org/documentation", None), }
https://github.com/jakelishman/qiskit-qasm2
jakelishman
import contextlib import pathlib import uuid import sys from typing import Iterable import pytest from qiskit.circuit import QuantumCircuit, Parameter import qiskit_qasm2.parse if sys.version_info >= (3, 8): def _unlink(path: pathlib.Path): path.unlink(missing_ok=True) else: def _unlink(path: pathlib.Path): try: path.unlink() except FileNotFoundError: pass def gate_builder(name: str, parameters: Iterable[Parameter], definition: QuantumCircuit): """Get a builder for a custom gate. Ideally we would just use an eagerly defined `Gate` instance here, but limitations in how `QuantumCircuit.__eq__` and `Instruction.__eq__` work mean that we have to ensure we're using the same class as the parser for equality checks to work.""" # Ideally we wouldn't have this at all, but hiding it away in one function is likely the safest # and easiest to update if the Python component of the library changes. # pylint: disable=protected-access def definer(*arguments): # We can supply empty lists for the gates and the bytecode, because we're going to override # the definition manually ourselves. gate = qiskit_qasm2.parse._DefinedGate(name, definition.num_qubits, arguments, (), ()) gate._definition = definition.assign_parameters(dict(zip(parameters, arguments))) return gate return definer class _TemporaryFilePathFactory: def __init__(self, basedir): self._basedir = basedir @contextlib.contextmanager def __call__(self): path = self._basedir / str(uuid.uuid4()) path.touch() try: yield path finally: _unlink(path) @pytest.fixture(scope="session") def tmp_file_path_factory(tmp_path_factory): """Get a path to a unique read/writeable temporary file that already exists on disk (with no content), has a valid file name, and can be opened for both reading and writing in any mode. The file will cleaned up after the function, if it still exists.""" return _TemporaryFilePathFactory(tmp_path_factory.getbasetemp())
https://github.com/jakelishman/qiskit-qasm2
jakelishman
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """These tests are the examples given in the arXiv paper describing OpenQASM 2. Specifically, there is a test for each subsection (except the description of 'qelib1.inc') in section 3 of https://arxiv.org/abs/1707.03429v2. The examples are copy/pasted from the source files there.""" # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import math import os import tempfile import ddt from qiskit import qasm2 from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister, Qubit from qiskit.circuit.library import U1Gate, U3Gate, CU1Gate from qiskit.test import QiskitTestCase from . import gate_builder def load(string, *args, **kwargs): # We're deliberately not using the context-manager form here because we need to use it in a # slightly odd pattern. # pylint: disable=consider-using-with temp = tempfile.NamedTemporaryFile(mode="w", delete=False) try: temp.write(string) # NamedTemporaryFile claims not to be openable a second time on Windows, so close it # (without deletion) so Rust can open it again. temp.close() return qasm2.load(temp.name, *args, **kwargs) finally: # Now actually clean up after ourselves. os.unlink(temp.name) @ddt.ddt class TestArxivExamples(QiskitTestCase): @ddt.data(qasm2.loads, load) def test_teleportation(self, parser): example = """\ // quantum teleportation example OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; creg c0[1]; creg c1[1]; creg c2[1]; // optional post-rotation for state tomography gate post q { } u3(0.3,0.2,0.1) q[0]; h q[1]; cx q[1],q[2]; barrier q; cx q[0],q[1]; h q[0]; measure q[0] -> c0[0]; measure q[1] -> c1[0]; if(c0==1) z q[2]; if(c1==1) x q[2]; post q[2]; measure q[2] -> c2[0];""" parsed = parser(example) post = gate_builder("post", [], QuantumCircuit([Qubit()])) q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2) qc.append(U3Gate(0.3, 0.2, 0.1), [q[0]], []) qc.h(q[1]) qc.cx(q[1], q[2]) qc.barrier(q) qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.append(post(), [q[2]], []) qc.measure(q[2], c2[0]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_qft(self, parser): example = """\ // quantum Fourier transform OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; creg c[4]; x q[0]; x q[2]; barrier q; h q[0]; cu1(pi/2) q[1],q[0]; h q[1]; cu1(pi/4) q[2],q[0]; cu1(pi/2) q[2],q[1]; h q[2]; cu1(pi/8) q[3],q[0]; cu1(pi/4) q[3],q[1]; cu1(pi/2) q[3],q[2]; h q[3]; measure q -> c;""" parsed = parser(example) qc = QuantumCircuit(QuantumRegister(4, "q"), ClassicalRegister(4, "c")) qc.x(0) qc.x(2) qc.barrier(range(4)) qc.h(0) qc.append(CU1Gate(math.pi / 2), [1, 0]) qc.h(1) qc.append(CU1Gate(math.pi / 4), [2, 0]) qc.append(CU1Gate(math.pi / 2), [2, 1]) qc.h(2) qc.append(CU1Gate(math.pi / 8), [3, 0]) qc.append(CU1Gate(math.pi / 4), [3, 1]) qc.append(CU1Gate(math.pi / 2), [3, 2]) qc.h(3) qc.measure(range(4), range(4)) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_inverse_qft_1(self, parser): example = """\ // QFT and measure, version 1 OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; creg c[4]; h q; barrier q; h q[0]; measure q[0] -> c[0]; if(c==1) u1(pi/2) q[1]; h q[1]; measure q[1] -> c[1]; if(c==1) u1(pi/4) q[2]; if(c==2) u1(pi/2) q[2]; if(c==3) u1(pi/2+pi/4) q[2]; h q[2]; measure q[2] -> c[2]; if(c==1) u1(pi/8) q[3]; if(c==2) u1(pi/4) q[3]; if(c==3) u1(pi/4+pi/8) q[3]; if(c==4) u1(pi/2) q[3]; if(c==5) u1(pi/2+pi/8) q[3]; if(c==6) u1(pi/2+pi/4) q[3]; if(c==7) u1(pi/2+pi/4+pi/8) q[3]; h q[3]; measure q[3] -> c[3];""" parsed = parser(example) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c) qc.h(q) qc.barrier(q) qc.h(q[0]) qc.measure(q[0], c[0]) qc.append(U1Gate(math.pi / 2).c_if(c, 1), [q[1]]) qc.h(q[1]) qc.measure(q[1], c[1]) qc.append(U1Gate(math.pi / 4).c_if(c, 1), [q[2]]) qc.append(U1Gate(math.pi / 2).c_if(c, 2), [q[2]]) qc.append(U1Gate(math.pi / 4 + math.pi / 2).c_if(c, 3), [q[2]]) qc.h(q[2]) qc.measure(q[2], c[2]) qc.append(U1Gate(math.pi / 8).c_if(c, 1), [q[3]]) qc.append(U1Gate(math.pi / 4).c_if(c, 2), [q[3]]) qc.append(U1Gate(math.pi / 8 + math.pi / 4).c_if(c, 3), [q[3]]) qc.append(U1Gate(math.pi / 2).c_if(c, 4), [q[3]]) qc.append(U1Gate(math.pi / 8 + math.pi / 2).c_if(c, 5), [q[3]]) qc.append(U1Gate(math.pi / 4 + math.pi / 2).c_if(c, 6), [q[3]]) qc.append(U1Gate(math.pi / 8 + math.pi / 4 + math.pi / 2).c_if(c, 7), [q[3]]) qc.h(q[3]) qc.measure(q[3], c[3]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_inverse_qft_2(self, parser): example = """\ // QFT and measure, version 2 OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; creg c0[1]; creg c1[1]; creg c2[1]; creg c3[1]; h q; barrier q; h q[0]; measure q[0] -> c0[0]; if(c0==1) u1(pi/2) q[1]; h q[1]; measure q[1] -> c1[0]; if(c0==1) u1(pi/4) q[2]; if(c1==1) u1(pi/2) q[2]; h q[2]; measure q[2] -> c2[0]; if(c0==1) u1(pi/8) q[3]; if(c1==1) u1(pi/4) q[3]; if(c2==1) u1(pi/2) q[3]; h q[3]; measure q[3] -> c3[0];""" parsed = parser(example) q = QuantumRegister(4, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") c3 = ClassicalRegister(1, "c3") qc = QuantumCircuit(q, c0, c1, c2, c3) qc.h(q) qc.barrier(q) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.append(U1Gate(math.pi / 2).c_if(c0, 1), [q[1]]) qc.h(q[1]) qc.measure(q[1], c1[0]) qc.append(U1Gate(math.pi / 4).c_if(c0, 1), [q[2]]) qc.append(U1Gate(math.pi / 2).c_if(c1, 1), [q[2]]) qc.h(q[2]) qc.measure(q[2], c2[0]) qc.append(U1Gate(math.pi / 8).c_if(c0, 1), [q[3]]) qc.append(U1Gate(math.pi / 4).c_if(c1, 1), [q[3]]) qc.append(U1Gate(math.pi / 2).c_if(c2, 1), [q[3]]) qc.h(q[3]) qc.measure(q[3], c3[0]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_ripple_carry_adder(self, parser): example = """\ // quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184 OPENQASM 2.0; include "qelib1.inc"; gate majority a,b,c { cx c,b; cx c,a; ccx a,b,c; } gate unmaj a,b,c { ccx a,b,c; cx c,a; cx a,b; } qreg cin[1]; qreg a[4]; qreg b[4]; qreg cout[1]; creg ans[5]; // set input states x a[0]; // a = 0001 x b; // b = 1111 // add a to b, storing result in b majority cin[0],b[0],a[0]; majority a[0],b[1],a[1]; majority a[1],b[2],a[2]; majority a[2],b[3],a[3]; cx a[3],cout[0]; unmaj a[2],b[3],a[3]; unmaj a[1],b[2],a[2]; unmaj a[0],b[1],a[1]; unmaj cin[0],b[0],a[0]; measure b[0] -> ans[0]; measure b[1] -> ans[1]; measure b[2] -> ans[2]; measure b[3] -> ans[3]; measure cout[0] -> ans[4];""" parsed = parser(example) majority_definition = QuantumCircuit([Qubit(), Qubit(), Qubit()]) majority_definition.cx(2, 1) majority_definition.cx(2, 0) majority_definition.ccx(0, 1, 2) majority = gate_builder("majority", [], majority_definition) unmaj_definition = QuantumCircuit([Qubit(), Qubit(), Qubit()]) unmaj_definition.ccx(0, 1, 2) unmaj_definition.cx(2, 0) unmaj_definition.cx(0, 1) unmaj = gate_builder("unmaj", [], unmaj_definition) cin = QuantumRegister(1, "cin") a = QuantumRegister(4, "a") b = QuantumRegister(4, "b") cout = QuantumRegister(1, "cout") ans = ClassicalRegister(5, "ans") qc = QuantumCircuit(cin, a, b, cout, ans) qc.x(a[0]) qc.x(b) qc.append(majority(), [cin[0], b[0], a[0]]) qc.append(majority(), [a[0], b[1], a[1]]) qc.append(majority(), [a[1], b[2], a[2]]) qc.append(majority(), [a[2], b[3], a[3]]) qc.cx(a[3], cout[0]) qc.append(unmaj(), [a[2], b[3], a[3]]) qc.append(unmaj(), [a[1], b[2], a[2]]) qc.append(unmaj(), [a[0], b[1], a[1]]) qc.append(unmaj(), [cin[0], b[0], a[0]]) qc.measure(b, ans[:4]) qc.measure(cout[0], ans[4]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_randomised_benchmarking(self, parser): example = """\ // One randomized benchmarking sequence OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[2]; h q[0]; barrier q; cz q[0],q[1]; barrier q; s q[0]; cz q[0],q[1]; barrier q; s q[0]; z q[0]; h q[0]; barrier q; measure q -> c; """ parsed = parser(example) q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.barrier(q) qc.cz(q[0], q[1]) qc.barrier(q) qc.s(q[0]) qc.cz(q[0], q[1]) qc.barrier(q) qc.s(q[0]) qc.z(q[0]) qc.h(q[0]) qc.barrier(q) qc.measure(q, c) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_process_tomography(self, parser): example = """\ OPENQASM 2.0; include "qelib1.inc"; gate pre q { } // pre-rotation gate post q { } // post-rotation qreg q[1]; creg c[1]; pre q[0]; barrier q; h q[0]; barrier q; post q[0]; measure q[0] -> c[0];""" parsed = parser(example) pre = gate_builder("pre", [], QuantumCircuit([Qubit()])) post = gate_builder("post", [], QuantumCircuit([Qubit()])) qc = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "c")) qc.append(pre(), [0]) qc.barrier(qc.qubits) qc.h(0) qc.barrier(qc.qubits) qc.append(post(), [0]) qc.measure(0, 0) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_error_correction(self, parser): example = """\ // Repetition code syndrome measurement OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; qreg a[2]; creg c[3]; creg syn[2]; gate syndrome d1,d2,d3,a1,a2 { cx d1,a1; cx d2,a1; cx d2,a2; cx d3,a2; } x q[0]; // error barrier q; syndrome q[0],q[1],q[2],a[0],a[1]; measure a -> syn; if(syn==1) x q[0]; if(syn==2) x q[2]; if(syn==3) x q[1]; measure q -> c;""" parsed = parser(example) syndrome_definition = QuantumCircuit([Qubit() for _ in [None] * 5]) syndrome_definition.cx(0, 3) syndrome_definition.cx(1, 3) syndrome_definition.cx(1, 4) syndrome_definition.cx(2, 4) syndrome = gate_builder("syndrome", [], syndrome_definition) q = QuantumRegister(3, "q") a = QuantumRegister(2, "a") c = ClassicalRegister(3, "c") syn = ClassicalRegister(2, "syn") qc = QuantumCircuit(q, a, c, syn) qc.x(q[0]) qc.barrier(q) qc.append(syndrome(), [q[0], q[1], q[2], a[0], a[1]]) qc.measure(a, syn) qc.x(q[0]).c_if(syn, 1) qc.x(q[2]).c_if(syn, 2) qc.x(q[1]).c_if(syn, 3) qc.measure(q, c) self.assertEqual(parsed, qc)
https://github.com/jakelishman/qiskit-qasm2
jakelishman
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import itertools import math import sys import ddt import qiskit.qasm2 from qiskit.test import QiskitTestCase @ddt.ddt class TestSimple(QiskitTestCase): def test_unary_constants(self): program = "qreg q[1]; U(-(0.5 + 0.5), +(+1 - 2), -+-+2) q[0];" parsed = qiskit.qasm2.loads(program) expected = [-1.0, -1.0, 2.0] self.assertEqual(list(parsed.data[0].operation.params), expected) def test_unary_symbolic(self): program = """ gate u(a, b, c) q { U(-(a + a), +(+b - c), -+-+c) q; } qreg q[1]; u(0.5, 1.0, 2.0) q[0]; """ parsed = qiskit.qasm2.loads(program) expected = [-1.0, -1.0, 2.0] actual = [float(x) for x in parsed.data[0].operation.definition.data[0].operation.params] self.assertEqual(list(actual), expected) @ddt.data( ("+", lambda a, b: a + b), ("-", lambda a, b: a - b), ("*", lambda a, b: a * b), ("/", lambda a, b: a / b), ("^", lambda a, b: a**b), ) @ddt.unpack def test_binary_constants(self, str_op, py_op): program = f"qreg q[1]; U(0.25{str_op}0.5, 1.0{str_op}0.5, 3.2{str_op}-0.8) q[0];" parsed = qiskit.qasm2.loads(program) expected = [py_op(0.25, 0.5), py_op(1.0, 0.5), py_op(3.2, -0.8)] # These should be bit-for-bit exact. self.assertEqual(list(parsed.data[0].operation.params), expected) @ddt.data( ("+", lambda a, b: a + b), ("-", lambda a, b: a - b), ("*", lambda a, b: a * b), ("/", lambda a, b: a / b), ("^", lambda a, b: a**b), ) @ddt.unpack def test_binary_symbolic(self, str_op, py_op): program = f""" gate u(a, b, c) q {{ U(a {str_op} b, a {str_op} (b {str_op} c), 0.0) q; }} qreg q[1]; u(1.0, 2.0, 3.0) q[0]; """ parsed = qiskit.qasm2.loads(program) outer = [1.0, 2.0, 3.0] abstract_op = parsed.data[0].operation self.assertEqual(list(abstract_op.params), outer) expected = [py_op(1.0, 2.0), py_op(1.0, py_op(2.0, 3.0)), 0.0] actual = [float(x) for x in abstract_op.definition.data[0].operation.params] self.assertEqual(list(actual), expected) @ddt.data( ("cos", math.cos), ("exp", math.exp), ("ln", math.log), ("sin", math.sin), ("sqrt", math.sqrt), ("tan", math.tan), ) @ddt.unpack def test_function_constants(self, function_str, function_py): program = f"qreg q[1]; U({function_str}(0.5),{function_str}(1.0),{function_str}(pi)) q[0];" parsed = qiskit.qasm2.loads(program) expected = [function_py(0.5), function_py(1.0), function_py(math.pi)] # These should be bit-for-bit exact. self.assertEqual(list(parsed.data[0].operation.params), expected) @ddt.data( ("cos", math.cos), ("exp", math.exp), ("ln", math.log), ("sin", math.sin), ("sqrt", math.sqrt), ("tan", math.tan), ) @ddt.unpack def test_function_symbolic(self, function_str, function_py): program = f""" gate u(a, b, c) q {{ U({function_str}(a), {function_str}(b), {function_str}(c)) q; }} qreg q[1]; u(0.5, 1.0, pi) q[0]; """ parsed = qiskit.qasm2.loads(program) outer = [0.5, 1.0, math.pi] abstract_op = parsed.data[0].operation self.assertEqual(list(abstract_op.params), outer) expected = [function_py(x) for x in outer] actual = [float(x) for x in abstract_op.definition.data[0].operation.params] self.assertEqual(list(actual), expected) class TestPrecedenceAssociativity(QiskitTestCase): def test_precedence(self): # OQ3's precedence rules are the same as Python's, so we can effectively just eval. expr = " 1.0 + 2.0 * -3.0 ^ 1.5 - 0.5 / +0.25" expected = 1.0 + 2.0 * -(3.0**1.5) - 0.5 / +0.25 program = f"qreg q[1]; U({expr}, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(parsed.data[0].operation.params[0], expected) def test_addition_left(self): # `eps` is the smallest floating-point value such that `1 + eps != 1`. That means that if # addition is correctly parsed and resolved as left-associative, then the first parameter # should first calculate `1 + (eps / 2)`, which will be 1, and then the same again, whereas # the second will do `(eps / 2) + (eps / 2) = eps`, then `eps + 1` will be different. eps = sys.float_info.epsilon program = f"qreg q[1]; U(1 + {eps / 2} + {eps / 2}, {eps / 2} + {eps / 2} + 1, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertNotEqual(1.0 + eps, 1.0) # Sanity check for the test. self.assertEqual(list(parsed.data[0].operation.params), [1.0, 1.0 + eps, 0.0]) def test_multiplication_left(self): # A similar principle to the epsilon test for addition; if multiplication associates right, # then `(0.5 * 2.0 * fmax)` is `inf`, otherwise it's `fmax`. fmax = sys.float_info.max program = f"qreg q[1]; U({fmax} * 0.5 * 2.0, 2.0 * 0.5 * {fmax}, 2.0 * {fmax} * 0.5) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [fmax, fmax, math.inf]) def test_subtraction_left(self): # If subtraction associated right, we'd accidentally get 2. program = "qreg q[1]; U(2.0 - 1.0 - 1.0, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [0.0, 0.0, 0.0]) def test_division_left(self): # If division associated right, we'd accidentally get 4. program = "qreg q[1]; U(4.0 / 2.0 / 2.0, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [1.0, 0.0, 0.0]) def test_power_right(self): # If the power operator associated left, we'd accidentally get 64 instead. program = "qreg q[1]; U(2.0 ^ 3.0 ^ 2.0, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [512.0, 0.0, 0.0]) class TestCustomClassical(QiskitTestCase): def test_evaluation_order(self): """We should be evaluating all functions, including custom user ones the exact number of times we expect, and left-to-right in parameter lists.""" # pylint: disable=invalid-name order = itertools.count() def f(): return next(order) program = """ qreg q[1]; U(f(), 2 * f() + f(), atan2(f(), f()) - f()) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_classical=[ qiskit.qasm2.CustomClassical("f", 0, f), qiskit.qasm2.CustomClassical("atan2", 2, math.atan2), ], ) self.assertEqual( list(parsed.data[0].operation.params), [0, 2 * 1 + 2, math.atan2(3, 4) - 5] ) self.assertEqual(next(order), 6) @ddt.ddt class TestErrors(QiskitTestCase): @ddt.data("0.0", "(1.0 - 1.0)") def test_refuses_to_divide_by_zero(self, denom): program = f"qreg q[1]; U(2.0 / {denom}, 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "divide by zero"): qiskit.qasm2.loads(program) program = f"gate rx(a) q {{ U(a / {denom}, 0.0, 0.0) q; }}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "divide by zero"): qiskit.qasm2.loads(program) @ddt.data("0.0", "1.0 - 1.0", "-2.0", "2.0 - 3.0") def test_refuses_to_ln_non_positive(self, operand): program = f"qreg q[1]; U(ln({operand}), 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "ln of non-positive"): qiskit.qasm2.loads(program) program = f"gate rx(a) q {{ U(a + ln({operand}), 0.0, 0.0) q; }}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "ln of non-positive"): qiskit.qasm2.loads(program) @ddt.data("-2.0", "2.0 - 3.0") def test_refuses_to_sqrt_negative(self, operand): program = f"qreg q[1]; U(sqrt({operand}), 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "sqrt of negative"): qiskit.qasm2.loads(program) program = f"gate rx(a) q {{ U(a + sqrt({operand}), 0.0, 0.0) q; }}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "sqrt of negative"): qiskit.qasm2.loads(program) @ddt.data("*", "/", "^") def test_cannot_use_nonunary_operators_in_unary_position(self, operator): program = f"qreg q[1]; U({operator}1.0, 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not a valid unary operator"): qiskit.qasm2.loads(program) @ddt.data("+", "-", "*", "/", "^") def test_missing_binary_operand_errors(self, operator): program = f"qreg q[1]; U(1.0 {operator}, 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "missing operand"): qiskit.qasm2.loads(program) program = f"qreg q[1]; U((1.0 {operator}), 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "missing operand"): qiskit.qasm2.loads(program) def test_parenthesis_must_be_closed(self): program = "qreg q[1]; U((1 + 1 2), 3, 2) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "needed a closing parenthesis"): qiskit.qasm2.loads(program) def test_premature_right_parenthesis(self): program = "qreg q[1]; U(sin(), 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "did not find an .* expression"): qiskit.qasm2.loads(program)
https://github.com/jakelishman/qiskit-qasm2
jakelishman
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import ddt import qiskit.qasm2 from qiskit.test import QiskitTestCase @ddt.ddt class TestLexer(QiskitTestCase): # Most of the lexer is fully exercised in the parser tests. These tests here are really mopping # up some error messages and whatnot that might otherwise be missed. def test_pathological_formatting(self): # This is deliberately _terribly_ formatted, included multiple blanks lines in quick # succession and comments in places you really wouldn't expect to see comments. program = """ OPENQASM // do we really need a comment here? 2.0//and another comment very squished up ; include // this line introduces a file import "qelib1.inc" // this is the file imported ; // this is a semicolon gate // we're making a gate bell( // void, with loose parenthesis in comment ) ) a,// b{h a;cx a //,,,, ,b;} qreg // a quantum register q [ // a square bracket 2];bell q[0],// q[1];creg c[2];measure q->c;""" parsed = qiskit.qasm2.loads(program) expected_unrolled = qiskit.QuantumCircuit( qiskit.QuantumRegister(2, "q"), qiskit.ClassicalRegister(2, "c") ) expected_unrolled.h(0) expected_unrolled.cx(0, 1) expected_unrolled.measure([0, 1], [0, 1]) self.assertEqual(parsed.decompose(), expected_unrolled) @ddt.data("0.25", "00.25", "2.5e-1", "2.5e-01", "0.025E+1", ".25", ".025e1", "25e-2") def test_float_lexes(self, number): program = f"qreg q[1]; U({number}, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [0.25, 0, 0]) def test_no_decimal_float_rejected_in_strict_mode(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"\[strict\] all floats must include a decimal point", ): qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(25e-2, 0, 0) q[0];", strict=True) @ddt.data("", "qre", "cre", ".") def test_non_ascii_bytes_error(self, prefix): token = f"{prefix}\xff" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "encountered a non-ASCII byte"): qiskit.qasm2.loads(token) def test_integers_cannot_start_with_zero(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "integers cannot have leading zeroes" ): qiskit.qasm2.loads("0123") @ddt.data("", "+", "-") def test_float_exponents_must_have_a_digit(self, sign): token = f"12.34e{sign}" with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "needed to see an integer exponent" ): qiskit.qasm2.loads(token) def test_non_builtins_cannot_be_capitalised(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "identifiers cannot start with capital" ): qiskit.qasm2.loads("Qubit") def test_unterminated_filename_is_invalid(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "unexpected end-of-file while lexing string literal" ): qiskit.qasm2.loads('include "qelib1.inc') def test_filename_with_linebreak_is_invalid(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "unexpected line break while lexing string literal" ): qiskit.qasm2.loads('include "qe\nlib1.inc";') def test_strict_single_quoted_path_rejected(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"\[strict\] paths must be in double quotes" ): qiskit.qasm2.loads("OPENQASM 2.0; include 'qelib1.inc';", strict=True) def test_version_must_have_word_boundary_after(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version" ): qiskit.qasm2.loads("OPENQASM 2a;") with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version" ): qiskit.qasm2.loads("OPENQASM 2.0a;") def test_no_boundary_float_in_version_position(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float" ): qiskit.qasm2.loads("OPENQASM .5a;") with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float" ): qiskit.qasm2.loads("OPENQASM 0.2e1a;") def test_integers_must_have_word_boundaries_after(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after an integer" ): qiskit.qasm2.loads("OPENQASM 2.0; qreg q[2a];") def test_floats_must_have_word_boundaries_after(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float" ): qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(2.0a, 0, 0) q[0];") def test_single_equals_is_rejected(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"single equals '=' is never valid" ): qiskit.qasm2.loads("if (a = 2) U(0, 0, 0) q[0];") def test_bare_dot_is_not_valid_float(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a numeric fractional part" ): qiskit.qasm2.loads("qreg q[0]; U(2 + ., 0, 0) q[0];") def test_invalid_token(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"encountered '!', which doesn't match" ): qiskit.qasm2.loads("!")
https://github.com/jakelishman/qiskit-qasm2
jakelishman
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import enum import math import ddt import qiskit.qasm2 from qiskit.circuit import Gate, library as lib from qiskit.test import QiskitTestCase from test import combine # pylint: disable=wrong-import-order # We need to use this enum a _bunch_ of times, so let's not give it a long name. # pylint: disable=invalid-name class T(enum.Enum): # This is a deliberately stripped-down list that doesn't include most of the expression-specific # tokens, because we don't want to complicate matters with those in tests of the general parser # errors. We test the expression subparser elsewhere. OPENQASM = "OPENQASM" BARRIER = "barrier" CREG = "creg" GATE = "gate" IF = "if" INCLUDE = "include" MEASURE = "measure" OPAQUE = "opaque" QREG = "qreg" RESET = "reset" PI = "pi" ARROW = "->" EQUALS = "==" SEMICOLON = ";" COMMA = "," LPAREN = "(" RPAREN = ")" LBRACKET = "[" RBRACKET = "]" LBRACE = "{" RBRACE = "}" ID = "q" REAL = "1.5" INTEGER = "1" FILENAME = '"qelib1.inc"' def bad_token_parametrisation(): """Generate the test cases for the "bad token" tests; this makes a sequence of OpenQASM 2 statements, then puts various invalid tokens after them to verify that the parser correctly throws an error on them.""" token_set = frozenset(T) def without(*tokens): return token_set - set(tokens) # ddt isn't a particularly great parametriser - it'll only correctly unpack tuples and lists in # the way we really want, but if we want to control the test id, we also have to set `__name__` # which isn't settable on either of those. We can't use unpack, then, so we just need a class # to pass. class BadTokenCase: def __init__(self, statement, disallowed, name=None): self.statement = statement self.disallowed = disallowed self.__name__ = name for statement, disallowed in [ # This should only include stopping points where the next token is somewhat fixed; in # places where there's a real decision to be made (such as number of qubits in a gate, # or the statement type in a gate body), there should be a better error message. # # There's a large subset of OQ2 that's reducible to a regular language, so we _could_ # define that, build a DFA for it, and use that to very quickly generate a complete set # of tests. That would be more complex to read and verify for correctness, though. ( "", without( T.OPENQASM, T.ID, T.INCLUDE, T.OPAQUE, T.GATE, T.QREG, T.CREG, T.IF, T.RESET, T.BARRIER, T.MEASURE, T.SEMICOLON, ), ), ("OPENQASM", without(T.REAL, T.INTEGER)), ("OPENQASM 2.0", without(T.SEMICOLON)), ("include", without(T.FILENAME)), ('include "qelib1.inc"', without(T.SEMICOLON)), ("opaque", without(T.ID)), ("opaque bell", without(T.LPAREN, T.ID, T.SEMICOLON)), ("opaque bell (", without(T.ID, T.RPAREN)), ("opaque bell (a", without(T.COMMA, T.RPAREN)), ("opaque bell (a,", without(T.ID, T.RPAREN)), ("opaque bell (a, b", without(T.COMMA, T.RPAREN)), ("opaque bell (a, b)", without(T.ID, T.SEMICOLON)), ("opaque bell (a, b) q1", without(T.COMMA, T.SEMICOLON)), ("opaque bell (a, b) q1,", without(T.ID, T.SEMICOLON)), ("opaque bell (a, b) q1, q2", without(T.COMMA, T.SEMICOLON)), ("gate", without(T.ID)), ("gate bell (", without(T.ID, T.RPAREN)), ("gate bell (a", without(T.COMMA, T.RPAREN)), ("gate bell (a,", without(T.ID, T.RPAREN)), ("gate bell (a, b", without(T.COMMA, T.RPAREN)), ("gate bell (a, b) q1", without(T.COMMA, T.LBRACE)), ("gate bell (a, b) q1,", without(T.ID, T.LBRACE)), ("gate bell (a, b) q1, q2", without(T.COMMA, T.LBRACE)), ("qreg", without(T.ID)), ("qreg reg", without(T.LBRACKET)), ("qreg reg[", without(T.INTEGER)), ("qreg reg[5", without(T.RBRACKET)), ("qreg reg[5]", without(T.SEMICOLON)), ("creg", without(T.ID)), ("creg reg", without(T.LBRACKET)), ("creg reg[", without(T.INTEGER)), ("creg reg[5", without(T.RBRACKET)), ("creg reg[5]", without(T.SEMICOLON)), ("CX", without(T.LPAREN, T.ID, T.SEMICOLON)), ("CX(", without(T.PI, T.INTEGER, T.REAL, T.ID, T.LPAREN, T.RPAREN)), ("CX()", without(T.ID, T.SEMICOLON)), ("CX q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)), ("CX q[", without(T.INTEGER)), ("CX q[0", without(T.RBRACKET)), ("CX q[0]", without(T.COMMA, T.SEMICOLON)), ("CX q[0],", without(T.ID, T.SEMICOLON)), ("CX q[0], q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)), # No need to repeatedly "every" possible number of arguments. ("measure", without(T.ID)), ("measure q", without(T.LBRACKET, T.ARROW)), ("measure q[", without(T.INTEGER)), ("measure q[0", without(T.RBRACKET)), ("measure q[0]", without(T.ARROW)), ("measure q[0] ->", without(T.ID)), ("measure q[0] -> c", without(T.LBRACKET, T.SEMICOLON)), ("measure q[0] -> c[", without(T.INTEGER)), ("measure q[0] -> c[0", without(T.RBRACKET)), ("measure q[0] -> c[0]", without(T.SEMICOLON)), ("reset", without(T.ID)), ("reset q", without(T.LBRACKET, T.SEMICOLON)), ("reset q[", without(T.INTEGER)), ("reset q[0", without(T.RBRACKET)), ("reset q[0]", without(T.SEMICOLON)), ("barrier", without(T.ID, T.SEMICOLON)), ("barrier q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)), ("barrier q[", without(T.INTEGER)), ("barrier q[0", without(T.RBRACKET)), ("barrier q[0]", without(T.COMMA, T.SEMICOLON)), ("if", without(T.LPAREN)), ("if (", without(T.ID)), ("if (cond", without(T.EQUALS)), ("if (cond ==", without(T.INTEGER)), ("if (cond == 0", without(T.RPAREN)), ("if (cond == 0)", without(T.ID, T.RESET, T.MEASURE)), ]: for token in disallowed: yield BadTokenCase(statement, token.value, name=f"'{statement}'-{token.name.lower()}") def eof_parametrisation(): for tokens in [ ("OPENQASM", "2.0", ";"), ("include", '"qelib1.inc"', ";"), ("opaque", "bell", "(", "a", ",", "b", ")", "q1", ",", "q2", ";"), ("gate", "bell", "(", "a", ",", "b", ")", "q1", ",", "q2", "{", "}"), ("qreg", "qr", "[", "5", "]", ";"), ("creg", "cr", "[", "5", "]", ";"), ("CX", "(", ")", "q", "[", "0", "]", ",", "q", "[", "1", "]", ";"), ("measure", "q", "[", "0", "]", "->", "c", "[", "0", "]", ";"), ("reset", "q", "[", "0", "]", ";"), ("barrier", "q", ";"), # No need to test every combination of `if`, really. ("if", "(", "cond", "==", "0", ")", "CX q[0], q[1];"), ]: prefix = "" for token in tokens[:-1]: prefix = f"{prefix} {token}".strip() yield prefix @ddt.ddt class TestIncompleteStructure(QiskitTestCase): PRELUDE = "OPENQASM 2.0; qreg q[5]; creg c[5]; creg cond[1];" @ddt.idata(bad_token_parametrisation()) def test_bad_token(self, case): """Test that the parser raises an error when an incorrect token is given.""" statement = case.statement disallowed = case.disallowed prelude = "" if statement.startswith("OPENQASM") else self.PRELUDE full = f"{prelude} {statement} {disallowed}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "needed .*, but instead"): qiskit.qasm2.loads(full) @ddt.idata(eof_parametrisation()) def test_eof(self, statement): """Test that the parser raises an error when the end-of-file is reached instead of a token that is required.""" prelude = "" if statement.startswith("OPENQASM") else self.PRELUDE full = f"{prelude} {statement}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "unexpected end-of-file"): qiskit.qasm2.loads(full) def test_loading_directory(self): """Test that the correct error is raised when a file fails to open.""" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "failed to read"): qiskit.qasm2.load(".") class TestVersion(QiskitTestCase): def test_invalid_version(self): program = "OPENQASM 3.0;" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only handle OpenQASM 2.0"): qiskit.qasm2.loads(program) program = "OPENQASM 2.1;" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only handle OpenQASM 2.0"): qiskit.qasm2.loads(program) program = "OPENQASM 20.e-1;" with self.assertRaises(qiskit.qasm2.QASM2ParseError): qiskit.qasm2.loads(program) def test_openqasm_must_be_first_statement(self): program = "qreg q[0]; OPENQASM 2.0;" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "only the first statement"): qiskit.qasm2.loads(program) @ddt.ddt class TestScoping(QiskitTestCase): def test_register_use_before_definition(self): program = "CX after[0], after[1]; qreg after[2];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined in this scope"): qiskit.qasm2.loads(program) program = "qreg q[2]; measure q[0] -> c[0]; creg c[2];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined in this scope"): qiskit.qasm2.loads(program) @combine( definer=["qreg reg[2];", "creg reg[2];", "gate reg a {}", "opaque reg a;"], bad_definer=["qreg reg[2];", "creg reg[2];"], ) def test_register_already_defined(self, definer, bad_definer): program = f"{definer} {bad_definer}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads(program) def test_qelib1_not_implicit(self): program = """ OPENQASM 2.0; qreg q[2]; cx q[0], q[1]; """ with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"): qiskit.qasm2.loads(program) def test_cannot_access_gates_before_definition(self): program = """ qreg q[2]; cx q[0], q[1]; gate cx a, b { CX a, b; } """ with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"): qiskit.qasm2.loads(program) def test_cannot_access_gate_recursively(self): program = """ gate cx a, b { cx a, b; } """ with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"): qiskit.qasm2.loads(program) def test_cannot_access_qubits_from_previous_gate(self): program = """ gate cx a, b { CX a, b; } gate other c { CX a, b; } """ with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'a' is not defined"): qiskit.qasm2.loads(program) def test_cannot_access_parameters_from_previous_gate(self): program = """ gate first(a, b) q { U(a, 0, b) q; } gate second q { U(a, 0, b) q; } """ with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "'a' is not a parameter.*defined" ): qiskit.qasm2.loads(program) def test_cannot_access_quantum_registers_within_gate(self): program = """ qreg q[2]; gate my_gate a { CX a, q; } """ with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a quantum register"): qiskit.qasm2.loads(program) def test_parameters_not_defined_outside_gate(self): program = """ gate my_gate(a) q {} qreg qr[2]; U(a, 0, 0) qr; """ with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "'a' is not a parameter.*defined" ): qiskit.qasm2.loads(program) def test_qubits_not_defined_outside_gate(self): program = """ gate my_gate(a) q {} U(0, 0, 0) q; """ with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is not defined"): qiskit.qasm2.loads(program) @ddt.data('include "qelib1.inc";', "gate h q { }") def test_gates_cannot_redefine(self, definer): program = f"{definer} gate h q {{ }}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads(program) def test_cannot_use_undeclared_register_conditional(self): program = "qreg q[1]; if (c == 0) U(0, 0, 0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined"): qiskit.qasm2.loads(program) @ddt.ddt class TestTyping(QiskitTestCase): @ddt.data( "CX q[0], U;", "measure U -> c[0];", "measure q[0] -> U;", "reset U;", "barrier U;", "if (U == 0) CX q[0], q[1];", "gate my_gate a { U(0, 0, 0) U; }", ) def test_cannot_use_gates_incorrectly(self, usage): program = f"qreg q[2]; creg c[2]; {usage}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'U' is a gate"): qiskit.qasm2.loads(program) @ddt.data( "measure q[0] -> q[1];", "if (q == 0) CX q[0], q[1];", "q q[0], q[1];", "gate my_gate a { U(0, 0, 0) q; }", ) def test_cannot_use_qregs_incorrectly(self, usage): program = f"qreg q[2]; creg c[2]; {usage}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a quantum register"): qiskit.qasm2.loads(program) @ddt.data( "CX q[0], c[1];", "measure c[0] -> c[1];", "reset c[0];", "barrier c[0];", "c q[0], q[1];", "gate my_gate a { U(0, 0, 0) c; }", ) def test_cannot_use_cregs_incorrectly(self, usage): program = f"qreg q[2]; creg c[2]; {usage}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'c' is a classical register"): qiskit.qasm2.loads(program) def test_cannot_use_parameters_incorrectly(self): program = "gate my_gate(p) q { CX p, q; }" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'p' is a parameter"): qiskit.qasm2.loads(program) def test_cannot_use_qubits_incorrectly(self): program = "gate my_gate(p) q { U(q, q, q) q; }" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a gate qubit"): qiskit.qasm2.loads(program) @ddt.data(("h", 0), ("h", 2), ("CX", 0), ("CX", 1), ("CX", 3), ("ccx", 2), ("ccx", 4)) @ddt.unpack def test_gates_accept_only_valid_number_qubits(self, gate, bad_count): arguments = ", ".join(f"q[{i}]" for i in range(bad_count)) program = f'include "qelib1.inc"; qreg q[5];\n{gate} {arguments};' with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "takes .* quantum arguments?"): qiskit.qasm2.loads(program) @ddt.data(("U", 2), ("U", 4), ("rx", 0), ("rx", 2), ("u3", 1)) @ddt.unpack def test_gates_accept_only_valid_number_parameters(self, gate, bad_count): arguments = ", ".join("0" for _ in [None] * bad_count) program = f'include "qelib1.inc"; qreg q[5];\n{gate}({arguments}) q[0];' with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "takes .* parameters?"): qiskit.qasm2.loads(program) @ddt.ddt class TestGateDefinition(QiskitTestCase): def test_no_zero_qubit(self): program = "gate zero {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"): qiskit.qasm2.loads(program) program = "gate zero(a) {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"): qiskit.qasm2.loads(program) def test_no_zero_qubit_opaque(self): program = "opaque zero;" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"): qiskit.qasm2.loads(program) program = "opaque zero(a);" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"): qiskit.qasm2.loads(program) def test_cannot_subscript_qubit(self): program = """ gate my_gate a { CX a[0], a[1]; } """ with self.assertRaises(qiskit.qasm2.QASM2ParseError): qiskit.qasm2.loads(program) def test_cannot_repeat_parameters(self): program = "gate my_gate(a, a) q {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads(program) def test_cannot_repeat_qubits(self): program = "gate my_gate a, a {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads(program) def test_qubit_cannot_shadow_parameter(self): program = "gate my_gate(a) a {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads(program) @ddt.data("measure q -> c;", "reset q", "if (c == 0) U(0, 0, 0) q;", "gate my_x q {}") def test_definition_cannot_contain_nonunitary(self, statement): program = f"OPENQASM 2.0; creg c[5]; gate my_gate q {{ {statement} }}" with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "only gate applications are valid" ): qiskit.qasm2.loads(program) def test_cannot_redefine_u(self): program = "gate U(a, b, c) q {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads(program) def test_cannot_redefine_cx(self): program = "gate CX a, b {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads(program) @ddt.ddt class TestBitResolution(QiskitTestCase): def test_disallow_out_of_range(self): with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"): qiskit.qasm2.loads("qreg q[2]; U(0, 0, 0) q[2];") with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"): qiskit.qasm2.loads("qreg q[2]; creg c[2]; measure q[2] -> c[0];") with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"): qiskit.qasm2.loads("qreg q[2]; creg c[2]; measure q[0] -> c[2];") @combine( conditional=[True, False], call=[ "CX q1[0], q1[0];", "CX q1, q1[0];", "CX q1[0], q1;", "CX q1, q1;", "ccx q1[0], q1[1], q1[0];", "ccx q2, q1, q2[0];", ], ) def test_disallow_duplicate_qubits(self, call, conditional): program = """ include "qelib1.inc"; qreg q1[3]; qreg q2[3]; qreg q3[3]; """ if conditional: program += "creg cond[1]; if (cond == 0) " program += call with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "duplicate qubit"): qiskit.qasm2.loads(program) @ddt.data( (("q1[1]", "q2[2]"), "CX q1, q2"), (("q1[1]", "q2[2]"), "CX q2, q1"), (("q1[3]", "q2[2]"), "CX q1, q2"), (("q1[2]", "q2[3]", "q3[3]"), "ccx q1, q2, q3"), (("q1[2]", "q2[3]", "q3[3]"), "ccx q2, q3, q1"), (("q1[2]", "q2[3]", "q3[3]"), "ccx q3, q1, q2"), (("q1[2]", "q2[3]", "q3[3]"), "ccx q1, q2[0], q3"), (("q1[2]", "q2[3]", "q3[3]"), "ccx q2[0], q3, q1"), (("q1[2]", "q2[3]", "q3[3]"), "ccx q3, q1, q2[0]"), ) @ddt.unpack def test_incorrect_gate_broadcast_lengths(self, registers, call): setup = 'include "qelib1.inc";\n' + "\n".join(f"qreg {reg};" for reg in registers) program = f"{setup}\n{call};" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"): qiskit.qasm2.loads(program) cond = "creg cond[1];\nif (cond == 0)" program = f"{setup}\n{cond} {call};" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"): qiskit.qasm2.loads(program) @ddt.data( ("qreg q[2]; creg c[2];", "q[0] -> c"), ("qreg q[2]; creg c[2];", "q -> c[0]"), ("qreg q[1]; creg c[2];", "q -> c[0]"), ("qreg q[2]; creg c[1];", "q[0] -> c"), ("qreg q[2]; creg c[3];", "q -> c"), ) @ddt.unpack def test_incorrect_measure_broadcast_lengths(self, setup, operands): program = f"{setup}\nmeasure {operands};" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"): qiskit.qasm2.loads(program) program = f"{setup}\ncreg cond[1];\nif (cond == 0) measure {operands};" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"): qiskit.qasm2.loads(program) @ddt.ddt class TestCustomInstructions(QiskitTestCase): def test_cannot_use_custom_before_definition(self): program = "qreg q[2]; my_gate q[0], q[1];" class MyGate(Gate): def __init__(self): super().__init__("my_gate", 2, []) with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "cannot use .* before definition" ): qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 0, 2, MyGate)], ) def test_cannot_misdefine_u(self): program = "qreg q[1]; U(0.5, 0.25) q[0]" with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "custom instruction .* mismatched" ): qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("U", 2, 1, lib.U2Gate)] ) def test_cannot_misdefine_cx(self): program = "qreg q[1]; CX q[0]" with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "custom instruction .* mismatched" ): qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("CX", 0, 1, lib.XGate)] ) def test_builtin_is_typechecked(self): program = "qreg q[1]; my(0.5) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' takes 2 quantum arguments"): qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate, builtin=True) ], ) with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' takes 2 parameters"): qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("my", 2, 1, lib.U2Gate, builtin=True) ], ) def test_cannot_define_builtin_twice(self): program = "gate builtin q {}; gate builtin q {};" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'builtin' is already defined"): qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("builtin", 0, 1, lambda: Gate("builtin", 1, [])) ], ) def test_cannot_redefine_custom_u(self): program = "gate U(a, b, c) q {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("U", 3, 1, lib.UGate, builtin=True) ], ) def test_cannot_redefine_custom_cx(self): program = "gate CX a, b {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("CX", 0, 2, lib.CXGate, builtin=True) ], ) @combine( program=["gate my(a) q {}", "opaque my(a) q;"], builtin=[True, False], ) def test_custom_definition_must_match_gate(self, program, builtin): with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' is mismatched"): qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate, builtin=builtin) ], ) with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' is mismatched"): qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("my", 2, 1, lib.U2Gate, builtin=builtin) ], ) def test_cannot_have_duplicate_customs(self): customs = [ qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate), qiskit.qasm2.CustomInstruction("x", 0, 1, lib.XGate), qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RZZGate), ] with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "duplicate custom instruction"): qiskit.qasm2.loads("", custom_instructions=customs) def test_qiskit_delay_float_input_wraps_exception(self): program = "opaque delay(t) q; qreg q[1]; delay(1.5) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only accept an integer"): qiskit.qasm2.loads(program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS) def test_u0_float_input_wraps_exception(self): program = "opaque u0(n) q; qreg q[1]; u0(1.1) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "must be an integer"): qiskit.qasm2.loads(program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS) @ddt.ddt class TestCustomClassical(QiskitTestCase): @ddt.data("cos", "exp", "sin", "sqrt", "tan", "ln") def test_cannot_override_builtin(self, builtin): with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"cannot override builtin"): qiskit.qasm2.loads( "", custom_classical=[qiskit.qasm2.CustomClassical(builtin, 1, math.exp)], ) def test_duplicate_names_disallowed(self): with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"duplicate custom classical"): qiskit.qasm2.loads( "", custom_classical=[ qiskit.qasm2.CustomClassical("f", 1, math.exp), qiskit.qasm2.CustomClassical("f", 1, math.exp), ], ) def test_cannot_shadow_custom_instruction(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"custom classical.*naming clash" ): qiskit.qasm2.loads( "", custom_instructions=[ qiskit.qasm2.CustomInstruction("f", 0, 1, lib.RXGate, builtin=True) ], custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)], ) def test_cannot_shadow_builtin_instruction(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"custom classical.*cannot shadow" ): qiskit.qasm2.loads( "", custom_classical=[qiskit.qasm2.CustomClassical("U", 1, math.exp)], ) def test_cannot_shadow_with_gate_definition(self): with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"'f' is already defined"): qiskit.qasm2.loads( "gate f q {}", custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)], ) @ddt.data("qreg", "creg") def test_cannot_shadow_with_register_definition(self, regtype): with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"'f' is already defined"): qiskit.qasm2.loads( f"{regtype} f[2];", custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)], ) @ddt.data((0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)) @ddt.unpack def test_mismatched_argument_count(self, n_good, n_bad): arg_string = ", ".join(["0" for _ in [None] * n_bad]) program = f""" qreg q[1]; U(f({arg_string}), 0, 0) q[0]; """ with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"custom function argument-count mismatch" ): qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("f", n_good, lambda *_: 0)] ) def test_output_type_error_is_caught(self): program = """ qreg q[1]; U(f(), 0, 0) q[0]; """ with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"user.*returned non-float"): qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("f", 0, lambda: "not a float")], ) def test_inner_exception_is_wrapped(self): inner_exception = Exception("custom exception") def raises(): raise inner_exception program = """ qreg q[1]; U(raises(), 0, 0) q[0]; """ with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "caught exception when constant folding" ) as excinfo: qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("raises", 0, raises)] ) assert excinfo.exception.__cause__ is inner_exception def test_cannot_be_used_as_gate(self): program = """ qreg q[1]; f(0) q[0]; """ with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function" ): qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)] ) def test_cannot_be_used_as_qarg(self): program = """ U(0, 0, 0) f; """ with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function" ): qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)] ) def test_cannot_be_used_as_carg(self): program = """ qreg q[1]; measure q[0] -> f; """ with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function" ): qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)] ) @ddt.ddt class TestStrict(QiskitTestCase): @ddt.data( "gate my_gate(p0, p1,) q0, q1 {}", "gate my_gate(p0, p1) q0, q1, {}", "opaque my_gate(p0, p1,) q0, q1;", "opaque my_gate(p0, p1) q0, q1,;", 'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125,) q[0], q[1];', 'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125) q[0], q[1],;', "qreg q[2]; barrier q[0], q[1],;", 'include "qelib1.inc"; qreg q[1]; rx(sin(pi,)) q[0];', ) def test_trailing_comma(self, program): with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*trailing comma"): qiskit.qasm2.loads("OPENQASM 2.0;\n" + program, strict=True) def test_trailing_semicolon_after_gate(self): program = "OPENQASM 2.0; gate my_gate q {};" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*extra semicolon"): qiskit.qasm2.loads(program, strict=True) def test_empty_statement(self): program = "OPENQASM 2.0; ;" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*empty statement"): qiskit.qasm2.loads(program, strict=True) def test_required_version_regular(self): program = "qreg q[1];" with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"\[strict\] the first statement" ): qiskit.qasm2.loads(program, strict=True) def test_required_version_empty(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"\[strict\] .*needed a version statement" ): qiskit.qasm2.loads("", strict=True) def test_barrier_requires_args(self): program = "OPENQASM 2.0; qreg q[2]; barrier;" with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"\[strict\] barrier statements must have at least one" ): qiskit.qasm2.loads(program, strict=True)
https://github.com/jakelishman/qiskit-qasm2
jakelishman
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import io import math import os import pathlib import pickle import shutil import tempfile import unittest import ddt import qiskit.qasm2 from qiskit import qpy from qiskit.circuit import ( ClassicalRegister, Gate, Parameter, QuantumCircuit, QuantumRegister, Qubit, library as lib, ) from qiskit.test import QiskitTestCase from . import gate_builder class TestEmpty(QiskitTestCase): def test_allows_empty(self): self.assertEqual(qiskit.qasm2.loads(""), QuantumCircuit()) class TestVersion(QiskitTestCase): def test_complete_version(self): program = "OPENQASM 2.0;" parsed = qiskit.qasm2.loads(program) self.assertEqual(parsed, QuantumCircuit()) def test_incomplete_version(self): program = "OPENQASM 2;" parsed = qiskit.qasm2.loads(program) self.assertEqual(parsed, QuantumCircuit()) def test_after_comment(self): program = """ // hello, world OPENQASM 2.0; qreg q[2]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) class TestRegisters(QiskitTestCase): def test_qreg(self): program = "qreg q1[2]; qreg q2[1]; qreg q3[4];" parsed = qiskit.qasm2.loads(program) regs = [QuantumRegister(2, "q1"), QuantumRegister(1, "q2"), QuantumRegister(4, "q3")] self.assertEqual(list(parsed.qregs), regs) self.assertEqual(list(parsed.cregs), []) def test_creg(self): program = "creg c1[2]; creg c2[1]; creg c3[4];" parsed = qiskit.qasm2.loads(program) regs = [ClassicalRegister(2, "c1"), ClassicalRegister(1, "c2"), ClassicalRegister(4, "c3")] self.assertEqual(list(parsed.cregs), regs) self.assertEqual(list(parsed.qregs), []) def test_interleaved_registers(self): program = "qreg q1[3]; creg c1[2]; qreg q2[1]; creg c2[1];" parsed = qiskit.qasm2.loads(program) qregs = [QuantumRegister(3, "q1"), QuantumRegister(1, "q2")] cregs = [ClassicalRegister(2, "c1"), ClassicalRegister(1, "c2")] self.assertEqual(list(parsed.qregs), qregs) self.assertEqual(list(parsed.cregs), cregs) def test_registers_after_gate(self): program = "qreg before[2]; CX before[0], before[1]; qreg after[2]; CX after[0], after[1];" parsed = qiskit.qasm2.loads(program) before = QuantumRegister(2, "before") after = QuantumRegister(2, "after") qc = QuantumCircuit(before, after) qc.cx(before[0], before[1]) qc.cx(after[0], after[1]) self.assertEqual(parsed, qc) def test_empty_registers(self): program = "qreg q[0]; creg c[0];" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "q"), ClassicalRegister(0, "c")) self.assertEqual(parsed, qc) @ddt.ddt class TestGateApplication(QiskitTestCase): def test_builtin_single(self): program = """ qreg q[2]; U(0, 0, 0) q[0]; CX q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.u(0, 0, 0, 0) qc.cx(0, 1) self.assertEqual(parsed, qc) def test_builtin_1q_broadcast(self): program = "qreg q[2]; U(0, 0, 0) q;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.u(0, 0, 0, 0) qc.u(0, 0, 0, 1) self.assertEqual(parsed, qc) def test_builtin_2q_broadcast(self): program = """ qreg q1[2]; qreg q2[2]; CX q1[0], q2; barrier; CX q1, q2[1]; barrier; CX q1, q2; """ parsed = qiskit.qasm2.loads(program) q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[0]) qc.cx(q1[0], q2[1]) qc.barrier() qc.cx(q1[0], q2[1]) qc.cx(q1[1], q2[1]) qc.barrier() qc.cx(q1[0], q2[0]) qc.cx(q1[1], q2[1]) self.assertEqual(parsed, qc) def test_3q_broadcast(self): program = """ include "qelib1.inc"; qreg q1[2]; qreg q2[2]; qreg q3[2]; ccx q1, q2[0], q3[1]; ccx q1[1], q2, q3[0]; ccx q1[0], q2[1], q3; barrier; ccx q1, q2, q3[1]; ccx q1[1], q2, q3; ccx q1, q2[1], q3; barrier; ccx q1, q2, q3; """ parsed = qiskit.qasm2.loads(program) q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") q3 = QuantumRegister(2, "q3") qc = QuantumCircuit(q1, q2, q3) qc.ccx(q1[0], q2[0], q3[1]) qc.ccx(q1[1], q2[0], q3[1]) qc.ccx(q1[1], q2[0], q3[0]) qc.ccx(q1[1], q2[1], q3[0]) qc.ccx(q1[0], q2[1], q3[0]) qc.ccx(q1[0], q2[1], q3[1]) qc.barrier() qc.ccx(q1[0], q2[0], q3[1]) qc.ccx(q1[1], q2[1], q3[1]) qc.ccx(q1[1], q2[0], q3[0]) qc.ccx(q1[1], q2[1], q3[1]) qc.ccx(q1[0], q2[1], q3[0]) qc.ccx(q1[1], q2[1], q3[1]) qc.barrier() qc.ccx(q1[0], q2[0], q3[0]) qc.ccx(q1[1], q2[1], q3[1]) self.assertEqual(parsed, qc) @ddt.data(True, False) def test_broadcast_against_empty_register(self, conditioned): cond = "if (cond == 0) " if conditioned else "" program = f""" OPENQASM 2; include "qelib1.inc"; qreg q1[1]; qreg q2[1]; qreg empty1[0]; qreg empty2[0]; qreg empty3[0]; creg cond[1]; // None of the following statements should produce any gate applications. {cond}h empty1; {cond}cx q1[0], empty1; {cond}cx empty1, q2[0]; {cond}cx empty1, empty2; {cond}ccx empty1, q1[0], q2[0]; {cond}ccx q1[0], empty2, q2[0]; {cond}ccx q1[0], q2[0], empty3; {cond}ccx empty1, empty2, q1[0]; {cond}ccx empty1, q1[0], empty2; {cond}ccx q1[0], empty1, empty2; {cond}ccx empty1, empty2, empty3; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit( QuantumRegister(1, "q1"), QuantumRegister(1, "q2"), QuantumRegister(0, "empty1"), QuantumRegister(0, "empty2"), QuantumRegister(0, "empty3"), ClassicalRegister(1, "cond"), ) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ qreg q[2]; creg cond[1]; if (cond == 0) U(0, 0, 0) q[0]; if (cond == 1) CX q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), cond) qc.u(0, 0, 0, 0).c_if(cond, 0) qc.cx(1, 0).c_if(cond, 1) self.assertEqual(parsed, qc) def test_conditioned_broadcast(self): program = """ qreg q1[2]; qreg q2[2]; creg cond[1]; if (cond == 0) U(0, 0, 0) q1; if (cond == 1) CX q1[0], q2; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2, cond) qc.u(0, 0, 0, q1[0]).c_if(cond, 0) qc.u(0, 0, 0, q1[1]).c_if(cond, 0) qc.cx(q1[0], q2[0]).c_if(cond, 1) qc.cx(q1[0], q2[1]).c_if(cond, 1) self.assertEqual(parsed, qc) def test_constant_folding(self): # Most expression-related things are tested in `test_expression.py` instead. program = """ qreg q[1]; U(4 + 3 * 2 ^ 2, cos(pi) * (1 - ln(1)), 2 ^ 3 ^ 2) q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.u(16.0, -1.0, 512.0, 0) self.assertEqual(parsed, qc) def test_call_defined_gate(self): program = """ gate my_gate a { U(0, 0, 0) a; } qreg q[2]; my_gate q[0]; my_gate q; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit()]) my_gate_def.u(0, 0, 0, 0) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0]) qc.append(my_gate(), [0]) qc.append(my_gate(), [1]) self.assertEqual(parsed, qc) def test_parameterless_gates_accept_parentheses(self): program = """ qreg q[2]; CX q[0], q[1]; CX() q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.cx(0, 1) qc.cx(1, 0) self.assertEqual(parsed, qc) class TestGateDefinition(QiskitTestCase): def test_simple_definition(self): program = """ gate not_bell a, b { U(0, 0, 0) a; CX a, b; } qreg q[2]; not_bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) not_bell_def = QuantumCircuit([Qubit(), Qubit()]) not_bell_def.u(0, 0, 0, 0) not_bell_def.cx(0, 1) not_bell = gate_builder("not_bell", [], not_bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(not_bell(), [0, 1]) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ gate not_bell a, b { U(0, 0, 0) a; CX a, b; } qreg q[2]; creg cond[1]; if (cond == 0) not_bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) not_bell_def = QuantumCircuit([Qubit(), Qubit()]) not_bell_def.u(0, 0, 0, 0) not_bell_def.cx(0, 1) not_bell = gate_builder("not_bell", [], not_bell_def) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), cond) qc.append(not_bell().c_if(cond, 0), [0, 1]) self.assertEqual(parsed, qc) def test_constant_folding_in_definition(self): program = """ gate bell a, b { U(pi/2, 0, pi) a; CX a, b; } qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.u(math.pi / 2, 0, math.pi, 0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_parameterised_gate(self): # Most of the tests of deep parameter expressions are in `test_expression.py`. program = """ gate my_gate(a, b) c { U(a, b, a + 2 * b) c; } qreg q[1]; my_gate(0.25, 0.5) q[0]; my_gate(0.5, 0.25) q[0]; """ parsed = qiskit.qasm2.loads(program) a, b = Parameter("a"), Parameter("b") my_gate_def = QuantumCircuit([Qubit()]) my_gate_def.u(a, b, a + 2 * b, 0) my_gate = gate_builder("my_gate", [a, b], my_gate_def) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(my_gate(0.25, 0.5), [0]) qc.append(my_gate(0.5, 0.25), [0]) self.assertEqual(parsed, qc) # Also check the decomposition has come out exactly as expected. The floating-point # assertions are safe as exact equality checks because there are no lossy operations with # these parameters, and the answer should be exact. decomposed = qc.decompose() self.assertEqual(decomposed.data[0].operation.name, "u") self.assertEqual(list(decomposed.data[0].operation.params), [0.25, 0.5, 1.25]) self.assertEqual(decomposed.data[1].operation.name, "u") self.assertEqual(list(decomposed.data[1].operation.params), [0.5, 0.25, 1.0]) def test_parameterless_gate_with_parentheses(self): program = """ gate my_gate() a { U(0, 0, 0) a; } qreg q[1]; my_gate q[0]; my_gate() q[0]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit()]) my_gate_def.u(0, 0, 0, 0) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(my_gate(), [0]) qc.append(my_gate(), [0]) self.assertEqual(parsed, qc) def test_access_includes_in_definition(self): program = """ include "qelib1.inc"; gate bell a, b { h a; cx a, b; } qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_access_previous_defined_gate(self): program = """ include "qelib1.inc"; gate bell a, b { h a; cx a, b; } gate second_bell a, b { bell b, a; } qreg q[2]; second_bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) second_bell_def = QuantumCircuit([Qubit(), Qubit()]) second_bell_def.append(bell(), [1, 0]) second_bell = gate_builder("second_bell", [], second_bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(second_bell(), [0, 1]) self.assertEqual(parsed, qc) def test_qubits_lookup_differently_to_gates(self): # The spec is somewhat unclear on this, and this leads to super weird text, but it's # technically unambiguously resolvable and this is more permissive. program = """ include "qelib1.inc"; gate bell h, cx { h h; cx h, cx; } qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_parameters_lookup_differently_to_gates(self): # The spec is somewhat unclear on this, and this leads to super weird text, but it's # technically unambiguously resolvable and this is more permissive. program = """ include "qelib1.inc"; gate shadow(rx, rz) a { rz(rz) a; rx(rx) a; } qreg q[1]; shadow(0.5, 2.0) q[0]; """ parsed = qiskit.qasm2.loads(program) rx, rz = Parameter("rx"), Parameter("rz") shadow_def = QuantumCircuit([Qubit()]) shadow_def.rz(rz, 0) shadow_def.rx(rx, 0) shadow = gate_builder("shadow", [rx, rz], shadow_def) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(shadow(0.5, 2.0), [0]) self.assertEqual(parsed, qc) def test_unused_parameters_convert_correctly(self): # The main risk here is that there might be lazy application in the gate definition # bindings, and we might accidentally try and bind parameters that aren't actually in the # definition. program = """ gate my_gate(p) q { U(0, 0, 0) q; } qreg q[1]; my_gate(0.5) q[0]; """ parsed = qiskit.qasm2.loads(program) # No top-level circuit equality test here, because all the internals of gate application are # an implementation detail, and we don't want to tie the tests and implementation together # too closely. self.assertEqual(list(parsed.qregs), [QuantumRegister(1, "q")]) self.assertEqual(list(parsed.cregs), []) self.assertEqual(len(parsed.data), 1) self.assertEqual(parsed.data[0].qubits, (parsed.qubits[0],)) self.assertEqual(parsed.data[0].clbits, ()) self.assertEqual(parsed.data[0].operation.name, "my_gate") self.assertEqual(list(parsed.data[0].operation.params), [0.5]) decomposed = QuantumCircuit(QuantumRegister(1, "q")) decomposed.u(0, 0, 0, 0) self.assertEqual(parsed.decompose(), decomposed) def test_qubit_barrier_in_definition(self): program = """ gate my_gate a, b { barrier a; barrier b; barrier a, b; } qreg q[2]; my_gate q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.barrier(0) my_gate_def.barrier(1) my_gate_def.barrier([0, 1]) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0, 1]) self.assertEqual(parsed, qc) def test_bare_barrier_in_definition(self): program = """ gate my_gate a, b { barrier; } qreg q[2]; my_gate q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.barrier(my_gate_def.qubits) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0, 1]) self.assertEqual(parsed, qc) def test_duplicate_barrier_in_definition(self): program = """ gate my_gate a, b { barrier a, a; barrier b, a, b; } qreg q[2]; my_gate q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.barrier(0) my_gate_def.barrier([1, 0]) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0, 1]) self.assertEqual(parsed, qc) def test_pickleable(self): program = """ include "qelib1.inc"; gate my_gate(a) b, c { rz(2 * a) b; h b; cx b, c; } qreg q[2]; my_gate(0.5) q[0], q[1]; my_gate(0.25) q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) a = Parameter("a") my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.rz(2 * a, 0) my_gate_def.h(0) my_gate_def.cx(0, 1) my_gate = gate_builder("my_gate", [a], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(0.5), [0, 1]) qc.append(my_gate(0.25), [1, 0]) self.assertEqual(parsed, qc) with io.BytesIO() as fptr: pickle.dump(parsed, fptr) fptr.seek(0) loaded = pickle.load(fptr) self.assertEqual(parsed, loaded) def test_qpy_single_call_roundtrip(self): program = """ include "qelib1.inc"; gate my_gate(a) b, c { rz(2 * a) b; h b; cx b, c; } qreg q[2]; my_gate(0.5) q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) # QPY won't persist custom gates by design choice, so instead let us check against the # explicit form it uses. my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.rz(1.0, 0) my_gate_def.h(0) my_gate_def.cx(0, 1) my_gate = Gate("my_gate", 2, [0.5]) my_gate.definition = my_gate_def qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate, [0, 1]) with io.BytesIO() as fptr: qpy.dump(parsed, fptr) fptr.seek(0) loaded = qpy.load(fptr)[0] self.assertEqual(loaded, qc) # See https://github.com/Qiskit/qiskit-terra/issues/8941 @unittest.expectedFailure def test_qpy_double_call_roundtrip(self): program = """ include "qelib1.inc"; gate my_gate(a) b, c { rz(2 * a) b; h b; cx b, c; } qreg q[2]; my_gate(0.5) q[0], q[1]; my_gate(0.25) q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) my_gate1_def = QuantumCircuit([Qubit(), Qubit()]) my_gate1_def.rz(1.0, 0) my_gate1_def.h(0) my_gate1_def.cx(0, 1) my_gate1 = Gate("my_gate", 2, [0.5]) my_gate1.definition = my_gate1_def my_gate2_def = QuantumCircuit([Qubit(), Qubit()]) my_gate2_def.rz(0.5, 0) my_gate2_def.h(0) my_gate2_def.cx(0, 1) my_gate2 = Gate("my_gate", 2, [0.25]) my_gate2.definition = my_gate2_def qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate1, [0, 1]) qc.append(my_gate2, [1, 0]) with io.BytesIO() as fptr: qpy.dump(parsed, fptr) fptr.seek(0) loaded = qpy.load(fptr)[0] self.assertEqual(loaded, qc) class TestOpaque(QiskitTestCase): def test_simple(self): program = """ opaque my_gate a; opaque my_gate2() a; qreg q[2]; my_gate q[0]; my_gate() q[1]; my_gate2 q[0]; my_gate2() q[1]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(Gate("my_gate", 1, []), [0]) qc.append(Gate("my_gate", 1, []), [1]) qc.append(Gate("my_gate2", 1, []), [0]) qc.append(Gate("my_gate2", 1, []), [1]) self.assertEqual(parsed, qc) def test_parameterised(self): program = """ opaque my_gate(a, b) c, d; qreg q[2]; my_gate(0.5, 0.25) q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(Gate("my_gate", 2, [0.5, 0.25]), [1, 0]) self.assertEqual(parsed, qc) class TestBarrier(QiskitTestCase): def test_single_register_argument(self): program = """ qreg first[3]; qreg second[3]; barrier first; barrier second; """ parsed = qiskit.qasm2.loads(program) first = QuantumRegister(3, "first") second = QuantumRegister(3, "second") qc = QuantumCircuit(first, second) qc.barrier(first) qc.barrier(second) self.assertEqual(parsed, qc) def test_single_qubit_argument(self): program = """ qreg first[3]; qreg second[3]; barrier first[1]; barrier second[0]; """ parsed = qiskit.qasm2.loads(program) first = QuantumRegister(3, "first") second = QuantumRegister(3, "second") qc = QuantumCircuit(first, second) qc.barrier(first[1]) qc.barrier(second[0]) self.assertEqual(parsed, qc) def test_empty_circuit_empty_arguments(self): program = "barrier;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit() self.assertEqual(parsed, qc) def test_one_register_circuit_empty_arguments(self): program = "qreg q1[2]; barrier;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q1")) qc.barrier(qc.qubits) self.assertEqual(parsed, qc) def test_multi_register_circuit_empty_arguments(self): program = "qreg q1[2]; qreg q2[3]; qreg q3[1]; barrier;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit( QuantumRegister(2, "q1"), QuantumRegister(3, "q2"), QuantumRegister(1, "q3") ) qc.barrier(qc.qubits) self.assertEqual(parsed, qc) def test_include_empty_register(self): program = """ qreg q[2]; qreg empty[0]; barrier empty; barrier q, empty; barrier; """ parsed = qiskit.qasm2.loads(program) q = QuantumRegister(2, "q") qc = QuantumCircuit(q, QuantumRegister(0, "empty")) qc.barrier(q) qc.barrier(qc.qubits) self.assertEqual(parsed, qc) def test_allows_duplicate_arguments(self): # There's nothing in the paper that implies this should be forbidden. program = """ qreg q1[3]; qreg q2[2]; barrier q1, q1; barrier q1[0], q1; barrier q1, q1[0]; barrier q1, q2, q1; """ parsed = qiskit.qasm2.loads(program) q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.barrier(q1) qc.barrier(q1) qc.barrier(q1) qc.barrier(q1, q2) self.assertEqual(parsed, qc) class TestMeasure(QiskitTestCase): def test_single(self): program = """ qreg q[1]; creg c[1]; measure q[0] -> c[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "c")) qc.measure(0, 0) self.assertEqual(parsed, qc) def test_broadcast(self): program = """ qreg q[2]; creg c[2]; measure q -> c; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c")) qc.measure(0, 0) qc.measure(1, 1) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ qreg q[2]; creg c[2]; creg cond[1]; if (cond == 0) measure q[0] -> c[0]; if (cond == 1) measure q -> c; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"), cond) qc.measure(0, 0).c_if(cond, 0) qc.measure(0, 0).c_if(cond, 1) qc.measure(1, 1).c_if(cond, 1) self.assertEqual(parsed, qc) def test_broadcast_against_empty_register(self): program = """ qreg q_empty[0]; creg c_empty[0]; measure q_empty -> c_empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "q_empty"), ClassicalRegister(0, "c_empty")) self.assertEqual(parsed, qc) def test_conditioned_broadcast_against_empty_register(self): program = """ qreg q_empty[0]; creg c_empty[0]; creg cond[1]; if (cond == 0) measure q_empty -> c_empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit( QuantumRegister(0, "q_empty"), ClassicalRegister(0, "c_empty"), ClassicalRegister(1, "cond"), ) self.assertEqual(parsed, qc) class TestReset(QiskitTestCase): def test_single(self): program = """ qreg q[1]; reset q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.reset(0) self.assertEqual(parsed, qc) def test_broadcast(self): program = """ qreg q[2]; reset q; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.reset(0) qc.reset(1) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ qreg q[2]; creg cond[1]; if (cond == 0) reset q[0]; if (cond == 1) reset q; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), cond) qc.reset(0).c_if(cond, 0) qc.reset(0).c_if(cond, 1) qc.reset(1).c_if(cond, 1) self.assertEqual(parsed, qc) def test_broadcast_against_empty_register(self): program = """ qreg empty[0]; reset empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "empty")) self.assertEqual(parsed, qc) def test_conditioned_broadcast_against_empty_register(self): program = """ qreg empty[0]; creg cond[1]; if (cond == 0) reset empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "empty"), ClassicalRegister(1, "cond")) self.assertEqual(parsed, qc) class TestInclude(QiskitTestCase): def setUp(self): super().setUp() self.tmp_dir = pathlib.Path(tempfile.mkdtemp()) def tearDown(self): # Doesn't really matter if the removal fails, since this was a tempdir anyway; it'll get # cleaned up by the OS at some point. shutil.rmtree(self.tmp_dir, ignore_errors=True) super().tearDown() def test_qelib1_include(self): program = """ include "qelib1.inc"; qreg q[3]; u3(0.5, 0.25, 0.125) q[0]; u2(0.5, 0.25) q[0]; u1(0.5) q[0]; cx q[0], q[1]; id q[0]; x q[0]; y q[0]; z q[0]; h q[0]; s q[0]; sdg q[0]; t q[0]; tdg q[0]; rx(0.5) q[0]; ry(0.5) q[0]; rz(0.5) q[0]; cz q[0], q[1]; cy q[0], q[1]; ch q[0], q[1]; ccx q[0], q[1], q[2]; crz(0.5) q[0], q[1]; cu1(0.5) q[0], q[1]; cu3(0.5, 0.25, 0.125) q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(3, "q")) qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0]) qc.append(lib.U2Gate(0.5, 0.25), [0]) qc.append(lib.U1Gate(0.5), [0]) qc.append(lib.CXGate(), [0, 1]) qc.append(lib.UGate(0, 0, 0), [0]) # Stand-in for id. qc.append(lib.XGate(), [0]) qc.append(lib.YGate(), [0]) qc.append(lib.ZGate(), [0]) qc.append(lib.HGate(), [0]) qc.append(lib.SGate(), [0]) qc.append(lib.SdgGate(), [0]) qc.append(lib.TGate(), [0]) qc.append(lib.TdgGate(), [0]) qc.append(lib.RXGate(0.5), [0]) qc.append(lib.RYGate(0.5), [0]) qc.append(lib.RZGate(0.5), [0]) qc.append(lib.CZGate(), [0, 1]) qc.append(lib.CYGate(), [0, 1]) qc.append(lib.CHGate(), [0, 1]) qc.append(lib.CCXGate(), [0, 1, 2]) qc.append(lib.CRZGate(0.5), [0, 1]) qc.append(lib.CU1Gate(0.5), [0, 1]) qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1]) self.assertEqual(parsed, qc) def test_qelib1_after_gate_definition(self): program = """ gate bell a, b { U(pi/2, 0, pi) a; CX a, b; } include "qelib1.inc"; qreg q[2]; bell q[0], q[1]; rx(0.5) q[0]; bell q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.u(math.pi / 2, 0, math.pi, 0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) qc.rx(0.5, 0) qc.append(bell(), [1, 0]) self.assertEqual(parsed, qc) def test_include_can_define_version(self): include = """ OPENQASM 2.0; qreg inner_q[2]; """ with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write(include) program = """ OPENQASM 2.0; include "include.qasm"; """ parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) qc = QuantumCircuit(QuantumRegister(2, "inner_q")) self.assertEqual(parsed, qc) def test_can_define_gates(self): include = """ gate bell a, b { h a; cx a, b; } """ with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write(include) program = """ OPENQASM 2.0; include "qelib1.inc"; include "include.qasm"; qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_nested_include(self): inner = "creg c[2];" with open(self.tmp_dir / "inner.qasm", "w") as fp: fp.write(inner) outer = """ qreg q[2]; include "inner.qasm"; """ with open(self.tmp_dir / "outer.qasm", "w") as fp: fp.write(outer) program = """ OPENQASM 2.0; include "outer.qasm"; """ parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c")) self.assertEqual(parsed, qc) def test_first_hit_is_used(self): empty = self.tmp_dir / "empty" empty.mkdir() first = self.tmp_dir / "first" first.mkdir() with open(first / "include.qasm", "w") as fp: fp.write("qreg q[1];") second = self.tmp_dir / "second" second.mkdir() with open(second / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' parsed = qiskit.qasm2.loads(program, include_path=(empty, first, second)) qc = QuantumCircuit(QuantumRegister(1, "q")) self.assertEqual(parsed, qc) def test_qelib1_ignores_search_path(self): with open(self.tmp_dir / "qelib1.inc", "w") as fp: fp.write("qreg not_used[2];") program = 'include "qelib1.inc";' parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) qc = QuantumCircuit() self.assertEqual(parsed, qc) def test_include_from_current_directory(self): include = """ qreg q[2]; """ with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write(include) program = """ OPENQASM 2.0; include "include.qasm"; """ prevdir = os.getcwd() os.chdir(self.tmp_dir) try: parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) finally: os.chdir(prevdir) def test_load_searches_source_directory(self): with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) parsed = qiskit.qasm2.load(self.tmp_dir / "program.qasm") qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) def test_load_searches_source_directory_last(self): first = self.tmp_dir / "first" first.mkdir() with open(first / "include.qasm", "w") as fp: fp.write("qreg q[2];") with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg not_used[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) parsed = qiskit.qasm2.load(self.tmp_dir / "program.qasm", include_path=(first,)) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) def test_load_searches_source_directory_prepend(self): first = self.tmp_dir / "first" first.mkdir() with open(first / "include.qasm", "w") as fp: fp.write("qreg not_used[2];") with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) parsed = qiskit.qasm2.load( self.tmp_dir / "program.qasm", include_path=(first,), include_input_directory="prepend" ) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) def test_load_can_ignore_source_directory(self): with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "unable to find 'include.qasm'"): qiskit.qasm2.load(self.tmp_dir / "program.qasm", include_input_directory=None) @ddt.ddt class TestCustomInstructions(QiskitTestCase): def test_qelib1_include_overridden(self): program = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; u3(0.5, 0.25, 0.125) q[0]; u2(0.5, 0.25) q[0]; u1(0.5) q[0]; cx q[0], q[1]; id q[0]; x q[0]; y q[0]; z q[0]; h q[0]; s q[0]; sdg q[0]; t q[0]; tdg q[0]; rx(0.5) q[0]; ry(0.5) q[0]; rz(0.5) q[0]; cz q[0], q[1]; cy q[0], q[1]; ch q[0], q[1]; ccx q[0], q[1], q[2]; crz(0.5) q[0], q[1]; cu1(0.5) q[0], q[1]; cu3(0.5, 0.25, 0.125) q[0], q[1]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(3, "q")) qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0]) qc.append(lib.U2Gate(0.5, 0.25), [0]) qc.append(lib.U1Gate(0.5), [0]) qc.append(lib.CXGate(), [0, 1]) qc.append(lib.IGate(), [0]) qc.append(lib.XGate(), [0]) qc.append(lib.YGate(), [0]) qc.append(lib.ZGate(), [0]) qc.append(lib.HGate(), [0]) qc.append(lib.SGate(), [0]) qc.append(lib.SdgGate(), [0]) qc.append(lib.TGate(), [0]) qc.append(lib.TdgGate(), [0]) qc.append(lib.RXGate(0.5), [0]) qc.append(lib.RYGate(0.5), [0]) qc.append(lib.RZGate(0.5), [0]) qc.append(lib.CZGate(), [0, 1]) qc.append(lib.CYGate(), [0, 1]) qc.append(lib.CHGate(), [0, 1]) qc.append(lib.CCXGate(), [0, 1, 2]) qc.append(lib.CRZGate(0.5), [0, 1]) qc.append(lib.CU1Gate(0.5), [0, 1]) qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1]) self.assertEqual(parsed, qc) # Also test that the output matches what Qiskit puts out. from_qiskit = QuantumCircuit.from_qasm_str(program) self.assertEqual(parsed, from_qiskit) def test_qelib1_sparse_overrides(self): """Test that the qelib1 special import still works as expected when a couple of gates in the middle of it are custom. As long as qelib1 is handled specially, there is a risk that this handling will break in weird ways when custom instructions overlap it.""" program = """ include "qelib1.inc"; qreg q[3]; u3(0.5, 0.25, 0.125) q[0]; u2(0.5, 0.25) q[0]; u1(0.5) q[0]; cx q[0], q[1]; id q[0]; x q[0]; y q[0]; z q[0]; h q[0]; s q[0]; sdg q[0]; t q[0]; tdg q[0]; rx(0.5) q[0]; ry(0.5) q[0]; rz(0.5) q[0]; cz q[0], q[1]; cy q[0], q[1]; ch q[0], q[1]; ccx q[0], q[1], q[2]; crz(0.5) q[0], q[1]; cu1(0.5) q[0], q[1]; cu3(0.5, 0.25, 0.125) q[0], q[1]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("id", 0, 1, lib.IGate), qiskit.qasm2.CustomInstruction("h", 0, 1, lib.HGate), qiskit.qasm2.CustomInstruction("crz", 1, 2, lib.CRZGate), ], ) qc = QuantumCircuit(QuantumRegister(3, "q")) qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0]) qc.append(lib.U2Gate(0.5, 0.25), [0]) qc.append(lib.U1Gate(0.5), [0]) qc.append(lib.CXGate(), [0, 1]) qc.append(lib.IGate(), [0]) qc.append(lib.XGate(), [0]) qc.append(lib.YGate(), [0]) qc.append(lib.ZGate(), [0]) qc.append(lib.HGate(), [0]) qc.append(lib.SGate(), [0]) qc.append(lib.SdgGate(), [0]) qc.append(lib.TGate(), [0]) qc.append(lib.TdgGate(), [0]) qc.append(lib.RXGate(0.5), [0]) qc.append(lib.RYGate(0.5), [0]) qc.append(lib.RZGate(0.5), [0]) qc.append(lib.CZGate(), [0, 1]) qc.append(lib.CYGate(), [0, 1]) qc.append(lib.CHGate(), [0, 1]) qc.append(lib.CCXGate(), [0, 1, 2]) qc.append(lib.CRZGate(0.5), [0, 1]) qc.append(lib.CU1Gate(0.5), [0, 1]) qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1]) self.assertEqual(parsed, qc) def test_user_gate_after_overidden_qelib1(self): program = """ include "qelib1.inc"; qreg q[1]; opaque my_gate q; my_gate q[0]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(Gate("my_gate", 1, []), [0]) self.assertEqual(parsed, qc) def test_qiskit_extra_builtins(self): program = """ qreg q[5]; u(0.5 ,0.25, 0.125) q[0]; p(0.5) q[0]; sx q[0]; sxdg q[0]; swap q[0], q[1]; cswap q[0], q[1], q[2]; crx(0.5) q[0], q[1]; cry(0.5) q[0], q[1]; cp(0.5) q[0], q[1]; csx q[0], q[1]; cu(0.5, 0.25, 0.125, 0.0625) q[0], q[1]; rxx(0.5) q[0], q[1]; rzz(0.5) q[0], q[1]; rccx q[0], q[1], q[2]; rc3x q[0], q[1], q[2], q[3]; c3x q[0], q[1], q[2], q[3]; c3sqrtx q[0], q[1], q[2], q[3]; c4x q[0], q[1], q[2], q[3], q[4]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(5, "q")) qc.append(lib.UGate(0.5, 0.25, 0.125), [0]) qc.append(lib.PhaseGate(0.5), [0]) qc.append(lib.SXGate(), [0]) qc.append(lib.SXdgGate(), [0]) qc.append(lib.SwapGate(), [0, 1]) qc.append(lib.CSwapGate(), [0, 1, 2]) qc.append(lib.CRXGate(0.5), [0, 1]) qc.append(lib.CRYGate(0.5), [0, 1]) qc.append(lib.CPhaseGate(0.5), [0, 1]) qc.append(lib.CSXGate(), [0, 1]) qc.append(lib.CUGate(0.5, 0.25, 0.125, 0.0625), [0, 1]) qc.append(lib.RXXGate(0.5), [0, 1]) qc.append(lib.RZZGate(0.5), [0, 1]) qc.append(lib.RCCXGate(), [0, 1, 2]) qc.append(lib.RC3XGate(), [0, 1, 2, 3]) qc.append(lib.C3XGate(), [0, 1, 2, 3]) qc.append(lib.C3SXGate(), [0, 1, 2, 3]) qc.append(lib.C4XGate(), [0, 1, 2, 3, 4]) self.assertEqual(parsed, qc) # There's also the 'u0' gate, but this is weird so we don't wildly care what its definition # is and it has no Qiskit equivalent, so we'll just test that it using it doesn't produce an # error. parsed = qiskit.qasm2.loads( "qreg q[1]; u0(1) q[0];", custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) self.assertEqual(parsed.data[0].operation.name, "u0") def test_qiskit_override_delay_opaque(self): program = """ opaque delay(t) q; qreg q[1]; delay(1) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.delay(1, 0, unit="dt") self.assertEqual(parsed, qc) def test_qiskit_override_u0_opaque(self): program = """ opaque u0(n) q; qreg q[1]; u0(2) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.id(0) qc.id(0) self.assertEqual(parsed.decompose(), qc) def test_can_override_u(self): program = """ qreg q[1]; U(0.5, 0.25, 0.125) q[0]; """ class MyGate(Gate): def __init__(self, a, b, c): super().__init__("u", 1, [a, b, c]) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("U", 3, 1, MyGate, builtin=True)], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5, 0.25, 0.125), [0]) self.assertEqual(parsed, qc) def test_can_override_cx(self): program = """ qreg q[2]; CX q[0], q[1]; """ class MyGate(Gate): def __init__(self): super().__init__("cx", 2, []) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("CX", 0, 2, MyGate, builtin=True)], ) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(MyGate(), [0, 1]) self.assertEqual(parsed, qc) @ddt.data(lambda x: x, reversed) def test_can_override_both_builtins_with_other_gates(self, order): program = """ gate unimportant q {} qreg q[2]; U(0.5, 0.25, 0.125) q[0]; CX q[0], q[1]; """ class MyUGate(Gate): def __init__(self, a, b, c): super().__init__("u", 1, [a, b, c]) class MyCXGate(Gate): def __init__(self): super().__init__("cx", 2, []) custom = [ qiskit.qasm2.CustomInstruction("unused", 0, 1, lambda: Gate("unused", 1, [])), qiskit.qasm2.CustomInstruction("U", 3, 1, MyUGate, builtin=True), qiskit.qasm2.CustomInstruction("CX", 0, 2, MyCXGate, builtin=True), ] custom = order(custom) parsed = qiskit.qasm2.loads(program, custom_instructions=custom) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(MyUGate(0.5, 0.25, 0.125), [0]) qc.append(MyCXGate(), [0, 1]) self.assertEqual(parsed, qc) def test_custom_builtin_gate(self): program = """ qreg q[1]; builtin(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("builtin", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True) ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_builtin_as_gate(self): program = """ qreg q[1]; gate builtin(t) q {} builtin(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("builtin", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True) ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_builtin_as_opaque(self): program = """ qreg q[1]; opaque builtin(t) q; builtin(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("builtin", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True) ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_custom_as_gate(self): program = """ qreg q[1]; gate my_gate(t) q {} my_gate(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("my_gate", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 1, 1, MyGate)] ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_custom_as_opaque(self): program = """ qreg q[1]; opaque my_gate(t) q; my_gate(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("my_gate", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 1, 1, MyGate)] ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) class TestCustomClassical(QiskitTestCase): def test_qiskit_extensions(self): program = """ include "qelib1.inc"; qreg q[1]; rx(asin(0.3)) q[0]; ry(acos(0.3)) q[0]; rz(atan(0.3)) q[0]; """ parsed = qiskit.qasm2.loads(program, custom_classical=qiskit.qasm2.LEGACY_CUSTOM_CLASSICAL) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.rx(math.asin(0.3), 0) qc.ry(math.acos(0.3), 0) qc.rz(math.atan(0.3), 0) self.assertEqual(parsed, qc) def test_zero_parameter_custom(self): program = """ qreg q[1]; U(f(), 0, 0) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("f", 0, lambda: 0.2)] ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.u(0.2, 0, 0, 0) self.assertEqual(parsed, qc) def test_multi_parameter_custom(self): program = """ qreg q[1]; U(f(0.2), g(0.4, 0.1), h(1, 2, 3)) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_classical=[ qiskit.qasm2.CustomClassical("f", 1, lambda x: 1 + x), qiskit.qasm2.CustomClassical("g", 2, math.atan2), qiskit.qasm2.CustomClassical("h", 3, lambda x, y, z: z - y + x), ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.u(1.2, math.atan2(0.4, 0.1), 2, 0) self.assertEqual(parsed, qc) def test_use_in_gate_definition(self): # pylint: disable=invalid-name program = """ gate my_gate(a, b) q { U(f(a, b), g(f(b, f(b, a))), b) q; } qreg q[1]; my_gate(0.5, 0.25) q[0]; my_gate(0.25, 0.5) q[0]; """ f = lambda x, y: x - y g = lambda x: 2 * x parsed = qiskit.qasm2.loads( program, custom_classical=[ qiskit.qasm2.CustomClassical("f", 2, f), qiskit.qasm2.CustomClassical("g", 1, g), ], ) first_gate = parsed.data[0].operation second_gate = parsed.data[1].operation self.assertEqual(list(first_gate.params), [0.5, 0.25]) self.assertEqual(list(second_gate.params), [0.25, 0.5]) self.assertEqual( list(first_gate.definition.data[0].operation.params), [ f(0.5, 0.25), g(f(0.25, f(0.25, 0.5))), 0.25, ], ) self.assertEqual( list(second_gate.definition.data[0].operation.params), [ f(0.25, 0.5), g(f(0.5, f(0.5, 0.25))), 0.5, ], ) @ddt.ddt class TestStrict(QiskitTestCase): @ddt.data( "gate my_gate(p0, p1$) q0, q1 {}", "gate my_gate(p0, p1) q0, q1$ {}", "opaque my_gate(p0, p1$) q0, q1;", "opaque my_gate(p0, p1) q0, q1$;", 'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125$) q[0], q[1];', 'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125) q[0], q[1]$;', "qreg q[2]; barrier q[0], q[1]$;", 'include "qelib1.inc"; qreg q[1]; rx(sin(pi$)) q[0];', ) def test_trailing_comma(self, program): without = qiskit.qasm2.loads("OPENQASM 2.0;\n" + program.replace("$", ""), strict=True) with_ = qiskit.qasm2.loads(program.replace("$", ","), strict=False) self.assertEqual(with_, without) def test_trailing_semicolon_after_gate(self): program = """ include "qelib1.inc"; gate bell a, b { h a; cx a, b; }; // <- the important bit of the test qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_empty_statement(self): # This is allowed more as a side-effect of allowing the trailing semicolon after gate # definitions. program = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; h q[0]; ; cx q[0], q[1]; ;;;; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.h(0) qc.cx(0, 1) self.assertEqual(parsed, qc) def test_single_quoted_path(self): program = """ include 'qelib1.inc'; qreg q[1]; h q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.h(0) self.assertEqual(parsed, qc)
https://github.com/pragyakatyayan/Playing-with-parametrized-quantum-gates
pragyakatyayan
%matplotlib inline %config InlineBackend.figure_format = 'svg' from IPython.display import clear_output from qiskit import QuantumCircuit std_cirq=QuantumCircuit(2) std_cirq.h(0) # Hadamard gate on q0 std_cirq.x(1) # X gate on q1 std_cirq.cx(0,1) # CNOT on q1 controlled on q0 std_cirq.draw('mpl') from qiskit import Aer, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram backend = Aer.get_backend('statevector_simulator') #state = execute(std_cirq,backend).result().get_statevector() results = execute(std_cirq,backend).result().get_counts() plot_histogram(results, color='darkturquoise') from numpy import pi cirq = QuantumCircuit(2) cirq.ry(pi/2, 0) cirq.rx(pi, 0) cirq.rx(pi, 1) cirq.cx(0,1) cirq.draw('mpl') results = execute(cirq,backend).result().get_counts() plot_histogram(results, color='deepskyblue') from qiskit.visualization import plot_state_qsphere sv = Statevector.from_label('00').evolve(cirq) plot_state_qsphere(sv.data, show_state_phases=True) import qiskit qiskit.__qiskit_version__
https://github.com/pragyakatyayan/Playing-with-parametrized-quantum-gates
pragyakatyayan
%matplotlib inline %config InlineBackend.figure_format = 'svg' from IPython.display import clear_output from qiskit import QuantumCircuit circuit = QuantumCircuit(1) circuit.u3(f"$\\theta$",f"$\\phi$",f"$\\lambda$", 0) circuit.draw('mpl') from numpy import pi circuit = QuantumCircuit(1) circuit.u3(2*pi/3, pi/2, 0, 0) circuit.draw('mpl') from qiskit import execute, Aer from qiskit.visualization import plot_bloch_multivector backend = Aer.get_backend("statevector_simulator") job = execute(circuit,backend=backend) statevector = job.result().get_statevector() print(statevector) plot_bloch_multivector(statevector) from qiskit.visualization import plot_histogram results = execute(circuit,backend).result().get_counts() plot_histogram(results, color='midnightblue') # initial circuit from qiskit import QuantumCircuit from numpy import pi circuit = QuantumCircuit(2) circuit.h(0) circuit.x(1) circuit.draw('mpl') # transformed circuit circuit.cu3(0,3*pi/2, 0, 0, 1) circuit.draw('mpl') from qiskit import execute, Aer from qiskit.visualization import plot_bloch_multivector backend = Aer.get_backend("statevector_simulator") job = execute(circuit,backend=backend) statevector = job.result().get_statevector() print(statevector) plot_bloch_multivector(statevector) from qiskit.visualization import plot_state_qsphere from qiskit.quantum_info import Statevector sv = Statevector.from_label('00').evolve(circuit) plot_state_qsphere(sv.data, show_state_phases=True) circuit2 = QuantumCircuit(2) circuit2.h(0) circuit2.x(1) circuit2.cu3(0, 0, 3*pi/2, 0, 1) circuit2.draw('mpl') job = execute(circuit2,backend=backend) statevector = job.result().get_statevector() print(statevector) plot_bloch_multivector(statevector) circuit3 = QuantumCircuit(2) circuit3.h(0) circuit3.x(1) circuit3.cu3(0, pi, pi/2, 0, 1) circuit3.draw('mpl') job = execute(circuit3,backend=backend) statevector = job.result().get_statevector() print(statevector) plot_bloch_multivector(statevector) circuit4 = QuantumCircuit(2) circuit4.h(0) circuit4.x(1) circuit4.cu3(0, pi/2, pi, 0, 1) circuit4.draw('mpl') job = execute(circuit4,backend=backend) statevector = job.result().get_statevector() print(statevector) plot_bloch_multivector(statevector) import qiskit qiskit.__qiskit_version__
https://github.com/fysmoe1121/entanglementQKDprotocol-qiskit
fysmoe1121
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/mrvee-qC-bee/SCQC23
mrvee-qC-bee
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.quantum_info import Statevector from qiskit_aer import AerSimulator # qiskit-ibmq-provider has been deprecated. # Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail. from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options # Loading your IBM Quantum account(s) service = QiskitRuntimeService(channel="ibm_quantum") # Invoke a primitive inside a session. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html # with Session(backend=service.backend("ibmq_qasm_simulator")): # result = Sampler().run(circuits).result() import math #may be helpful coords = [] # Put your code here in this format: [radius, theta, phi] plot_bloch_vector(coords, coord_type='spherical') qc = QuantumCircuit(1) # Add your code here sv = Statevector(qc) plot_bloch_multivector(sv) # You will already have defined 'qc' in the code cell above. Use that circuit for this exercise. backend = # Choose your backend - this should be the Aer Simulator! job = # Run your circuit through a job result = # Get the result from the job counts = # Get the counts dictionary from the result plot_histogram(counts)
https://github.com/mrvee-qC-bee/SCQC23
mrvee-qC-bee
# Automatically appears upon opening a new python notebook in the IBM Quantum Lab # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit_aer import AerSimulator # qiskit-ibmq-provider has been deprecated. # Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail. from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options # Loading your IBM Quantum account(s) service = QiskitRuntimeService(channel="ibm_quantum") # Invoke a primitive inside a session. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html # with Session(backend=service.backend("ibmq_qasm_simulator")): # result = Sampler().run(circuits).result() # Copied from IBM Quantum Composer from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi qreg_q = QuantumRegister(2, 'q') creg_c = ClassicalRegister(2, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.h(qreg_q[0]) # h gate on 1st qubit circuit.cx(qreg_q[0], qreg_q[1]) # control, target circuit.measure(qreg_q[0], creg_c[0]) # measure qubit 1 onto classical bit 1 circuit.measure(qreg_q[1], creg_c[1]) # measure qubit 2 onto bit 2 circuit.draw() # condensed notation circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) circuit.measure_all() circuit.draw() # running on a simulator sim = AerSimulator() job = sim.run(circuit) # shots = 1024 is the default result = job.result() counts = result.get_counts() counts plot_histogram(counts) # running on a real device from qiskit_ibm_provider import IBMProvider, least_busy provider = IBMProvider(instance='ibm-q/open/main') # get the least-busy backend real_backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 1 and not b.configuration().simulator and b.status().operational==True)) print(f"The best backend is: {real_backend.name}") # Transpile to a circuit optimized for execution on a real machine backend and Execute it circuit_transpiled = transpile(circuit, real_backend) # submit the job job = real_backend.run(circuit, shots = 1024) # Monitoring our job from qiskit_ibm_provider.job import job_monitor print(f"Job ID: {job.job_id()}") job_monitor(job) results = job.result() counts = results.get_counts() counts plot_histogram(count) # what you will additionally need to run locally IBMProvider.save_account(token="", overwrite=True) # get your token from the dashboard in the IBM Quantum Platform
https://github.com/mrvee-qC-bee/SCQC23
mrvee-qC-bee
import numpy as np # for plotting results import matplotlib.pyplot as plt # Import Scikit-learn(QML library for Python) from sklearn import datasets from sklearn.model_selection import train_test_split # for splitting test data from sklearn.svm import SVC # SVM Classification from sklearn.decomposition import PCA # Principal component analysis from sklearn.preprocessing import StandardScaler, MinMaxScaler # for standardization, normalization scale conversion # Import Qiskit from qiskit import Aer, execute from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit_machine_learning.kernels import QuantumKernel # Reads two classes of data (0 and 1) from a numeric data set digits = datasets.load_digits(n_class=2) # Plot the first 100 images loaded fig, axes = plt.subplots(10, 10, figsize=(15, 15), subplot_kw={'xticks':[], 'yticks':[]}, gridspec_kw=dict(hspace=0.5, wspace=0.5)) for i, ax in enumerate(axes.flat): ax.set_axis_off() ax.imshow(digits.images[i], cmap=plt.cm.gray_r, interpolation='nearest') ax.set_title(digits.target[i]) print(digits.images[0]) # Splitting the dataset sample_train, sample_test, labels_train, labels_test = train_test_split( digits.data, digits.target, test_size=0.2, random_state=22) # Delete dimension n_dim = 4 pca = PCA(n_components=n_dim).fit(sample_train) sample_train = pca.transform(sample_train) sample_test = pca.transform(sample_test) # Standardize std_scale = StandardScaler().fit(sample_train) sample_train = std_scale.transform(sample_train) sample_test = std_scale.transform(sample_test) # Normalize samples = np.append(sample_train, sample_test, axis=0) minmax_scale = MinMaxScaler((-1, 1)).fit(samples) sample_train = minmax_scale.transform(sample_train) sample_test = minmax_scale.transform(sample_test) # Select 100 for training and 20 for testing train_size = 100 sample_train = sample_train[:train_size] labels_train = labels_train[:train_size] test_size = 20 sample_test = sample_test[:test_size] labels_test = labels_test[:test_size] # Display each of the first data print(sample_train[0], labels_train[0]) print(sample_test[0], labels_test[0]) # ZZFeatureMap with 4 features and depth (number of iterations)1 zz_map = ZZFeatureMap(feature_dimension=4, reps=1, entanglement='linear', insert_barriers=True) zz_map.decompose().draw('mpl') zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator')) print(sample_train[0]) print(sample_train[1]) zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1]) zz_circuit.decompose().decompose().draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(zz_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(zz_circuit) counts['0000']/sum(counts.values()) matrix_train = zz_kernel.evaluate(x_vec=sample_train) matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(matrix_train), interpolation='nearest', origin='upper', cmap='Blues') axs[0].set_title("training kernel matrix") axs[1].imshow(np.asmatrix(matrix_test), interpolation='nearest', origin='upper', cmap='Reds') axs[1].set_title("testing kernel matrix") plt.show() zzpc_svc = SVC(kernel='precomputed') zzpc_svc.fit(matrix_train, labels_train) # Train zzpc_score = zzpc_svc.score(matrix_test, labels_test) # Determine the percentage of correct answers print(f'Kernel classification test score: {zzpc_score}') # General imports import os import gzip import numpy as np import matplotlib.pyplot as plt from pylab import cm import warnings warnings.filterwarnings("ignore") # Import Scikit-learn(QML library for Python) from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA from sklearn.svm import SVC from sklearn.metrics import accuracy_score # Import Qiskit from qiskit import Aer, execute from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2 from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate from qiskit_machine_learning.kernels import QuantumKernel # Load data DATA_PATH = 'fashion.npz' data = np.load(DATA_PATH) sample_train = data['sample_train'] labels_train = data['labels_train'] sample_test = data['sample_test'] # Splitting the dataset sample_train, sample_test, labels_train, labels_test = train_test_split( sample_train, labels_train, test_size=0.2, random_state=42) # Show data fig = plt.figure() LABELS = [2,3] num_labels = len(LABELS) for i in range(num_labels): ax = fig.add_subplot(2, num_labels, i+1) img = sample_train[labels_train==LABELS[i]][0].reshape((28, 28)) ax.imshow(img, cmap="Greys") # change the dimension N_DIM = 4 pca = PCA(n_components=N_DIM).fit(sample_train) sample_train = pca.transform(sample_train) sample_test = pca.transform(sample_test) # standardize std_scale = StandardScaler().fit(sample_train) sample_train = std_scale.transform(sample_train) sample_test = std_scale.transform(sample_test) # normalize samples = np.append(sample_train, sample_test, axis=0) minmax_scale = MinMaxScaler((-1, 1)).fit(samples) sample_train = minmax_scale.transform(sample_train) sample_test = minmax_scale.transform(sample_test) # Display each of the first data print(sample_train[0], labels_train[0]) print(sample_test[0], labels_test[0]) zz_map = # Write your featuremap here zz_map.decompose().draw('mpl') zz_kernel = # Construct your kernel here print(sample_train[0]) print(sample_train[1]) zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1]) zz_circuit.decompose().decompose().draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(zz_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(zz_circuit) counts['0000']/sum(counts.values()) matrix_train = # Write your code here matrix_test = # Write your code here fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(matrix_train), interpolation='nearest', origin='upper', cmap='Blues') axs[0].set_title("training kernel matrix") axs[1].imshow(np.asmatrix(matrix_test), interpolation='nearest', origin='upper', cmap='Reds') axs[1].set_title("testing kernel matrix") plt.show() zzpc_svc = # Write your code here zzpc_svc.fit(matrix_train, labels_train) # Train zzpc_score = zzpc_svc.score(matrix_test, labels_test) # Determine the percentage of correct answers print(f'Kernel classification test score: {zzpc_score}')
https://github.com/mrvee-qC-bee/SCQC23
mrvee-qC-bee
from qiskit import QuantumCircuit from qiskit.visualization import plot_histogram from qiskit.circuit import Parameter import numpy as np # Define a variable theta to be a parameter with name 'theta' theta = Parameter('theta') # Initialize a quantum circuit with one qubit quantum_circuit = QuantumCircuit(1) # Add a parametrized RX rotation on the qubit quantum_circuit.rx(theta, 0) quantum_circuit.draw(output="mpl") # Set the value of the parameter theta_value = np.pi # Bind the value to the parametrized circuit qc = quantum_circuit.bind_parameters({theta: theta_value}) # Add a measurement gate to the circuit before we run it qc.measure_all() qc.draw(output="mpl") # Running on a simulator from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc) # shots = 1024 is the default result = job.result() counts = result.get_counts() counts # running on a quantum device from qiskit import transpile from qiskit_ibm_provider import IBMProvider, least_busy provider = IBMProvider(instance='ibm-q/open/main') # get the least-busy backend real_backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 1 and not b.configuration().simulator and b.status().operational==True)) print(f"The best backend is: ", real_backend.name) # transpilation circuit_transpiled = transpile(qc, real_backend) # submit the job job = real_backend.run(circuit_transpiled, shots = 1024) # Monitoring our job from qiskit_ibm_provider.job import job_monitor print(f"Job ID: {job.job_id()}") job_monitor(job) results = job.result() counts = results.get_counts() counts from qiskit import QuantumCircuit bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) bell.measure_all() bell.draw() from qiskit.primitives import Sampler sampler = Sampler(options={"shots": 100}) job = sampler.run(bell) # uses local simulator under the hood result = job.result() print(result) # quasi-distribution: dist = result.quasi_dists[0].binary_probabilities() print(f"Quasi-distribution is: ", dist) plot_histogram(dist) quantum_circuit.measure_all() quantum_circuit.draw() #notice that theta is an unbound parameter thetas = [0, np.pi/4, np.pi/3, np.pi/2, 2*np.pi/3, 3*np.pi/4, np.pi] indv_thetas = [[ph] for ph in thetas] #[[0], [np.pi/4], [np.pi/3], [np.pi/2], [2*np.pi/3], [3*np.pi/4], [np.pi]] job = sampler.run([quantum_circuit]*len(indv_thetas), parameter_values=indv_thetas) # uses local simulator under the hood result = job.result() quasi_dists = result.quasi_dists quasi_dists # Get the prob values for each of the states prob_values_0 = [dist.get(0, 0) for dist in result.quasi_dists] prob_values_1 = [dist.get(1, 0) for dist in result.quasi_dists] import matplotlib.pyplot as plt plt.plot(thetas, prob_values_0, 'o', label='zero state') plt.plot(thetas, prob_values_1, 'o', label='one state') plt.xlabel('Theta') plt.ylabel('Probability') plt.legend(); from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler from qiskit import QuantumCircuit # QiskitRuntimeService.save_account(channel='ibm_quantum', token='my_token', overwrite=True) #uncomment if you need to save your account again service = QiskitRuntimeService( channel='ibm_quantum', instance='ibm-q/open/main', ) print(service.backends()) real_backend = service.least_busy(min_num_qubits=2, simulator=False, operational=True) print(f"The best backend is {real_backend.name}") # backend = service.get_backend('ibmq_qasm_simulator') # simulator # can also use noisy simulators # Execute both example circuits with Session(service=service, backend=real_backend) as session: sampler = Sampler(session=session) # now we can run multiple jobs but only queue once job = sampler.run([bell], [[]]) samples_bell = job.result().quasi_dists[0] job = sampler.run([quantum_circuit]*len(indv_thetas), parameter_values=indv_thetas) samples_param = job.result().quasi_dists samples_bell.binary_probabilities() samples_param import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/mrvee-qC-bee/SCQC23
mrvee-qC-bee
from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 42 from qiskit.circuit import QuantumCircuit, ParameterVector inputs2 = ParameterVector("input", 2) weights2 = ParameterVector("weight", 4) print(f"input parameters: {[str(item) for item in inputs2.params]}") print(f"weight parameters: {[str(item) for item in weights2.params]}") qc2 = QuantumCircuit(2) qc2.ry(inputs2[0], 0) qc2.ry(inputs2[1], 1) qc2.cx(0, 1) qc2.ry(weights2[0], 0) qc2.ry(weights2[1], 1) qc2.cx(0, 1) qc2.ry(weights2[2], 0) qc2.ry(weights2[3], 1) qc2.draw(output="mpl") from qiskit_machine_learning.neural_networks import SamplerQNN sampler_qnn = SamplerQNN(circuit=qc2, input_params=inputs2, weight_params=weights2) sampler_qnn sampler_qnn_input = algorithm_globals.random.random(sampler_qnn.num_inputs) sampler_qnn_weights = algorithm_globals.random.random(sampler_qnn.num_weights) print( f"Number of input features for SamplerQNN: {sampler_qnn.num_inputs} \nInput: {sampler_qnn_input}" ) print( f"Number of trainable weights for SamplerQNN: {sampler_qnn.num_weights} \nWeights: {sampler_qnn_weights}" ) sampler_qnn_forward = sampler_qnn.forward(sampler_qnn_input, sampler_qnn_weights) print( f"Forward pass result for SamplerQNN: {sampler_qnn_forward}. \nShape: {sampler_qnn_forward.shape}" ) sampler_qnn_forward_batched = sampler_qnn.forward( [sampler_qnn_input, sampler_qnn_input], sampler_qnn_weights ) print( f"Forward pass result for SamplerQNN: {sampler_qnn_forward_batched}. \nShape: {sampler_qnn_forward_batched.shape}" ) sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward( sampler_qnn_input, sampler_qnn_weights ) print( f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad}" ) print( f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}" ) sampler_qnn.input_gradients = True sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward( sampler_qnn_input, sampler_qnn_weights ) print( f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad.shape}" ) print( f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}" ) parity = lambda x: "{:b}".format(x).count("1") % 2 output_shape = 2 # parity = 0, 1 sampler_qnn2 = SamplerQNN( circuit=qc2, input_params=inputs2, weight_params=weights2, interpret=parity, output_shape=output_shape, ) sampler_qnn_forward2 = sampler_qnn2.forward(sampler_qnn_input, sampler_qnn_weights) sampler_qnn_input_grad2, sampler_qnn_weight_grad2 = sampler_qnn2.backward( sampler_qnn_input, sampler_qnn_weights ) print(f"Forward output for SamplerQNN1: {sampler_qnn_forward.shape}") print(f"Forward output for SamplerQNN2: {sampler_qnn_forward2.shape}") print(f"Backward output for SamplerQNN1: {sampler_qnn_weight_grad.shape}") print(f"Backward output for SamplerQNN2: {sampler_qnn_weight_grad2.shape}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/mrvee-qC-bee/SCQC23
mrvee-qC-bee
from sklearn.datasets import load_iris iris_data = load_iris() print(iris_data.DESCR) features = iris_data.data labels = iris_data.target from sklearn.preprocessing import MinMaxScaler features = MinMaxScaler().fit_transform(features) import pandas as pd import seaborn as sns df = pd.DataFrame(iris_data.data, columns=iris_data.feature_names) df["class"] = pd.Series(iris_data.target) sns.pairplot(df, hue="class", palette="tab10") from sklearn.model_selection import train_test_split from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123 train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=0.8, random_state=algorithm_globals.random_seed ) from sklearn.svm import SVC svc = SVC() _ = svc.fit(train_features, train_labels) # suppress printing the return value train_score_c4 = svc.score(train_features, train_labels) test_score_c4 = svc.score(test_features, test_labels) print(f"Classical SVC on the training dataset: {train_score_c4:.2f}") print(f"Classical SVC on the test dataset: {test_score_c4:.2f}") from qiskit.circuit.library import EfficientSU2 circuit = EfficientSU2(num_qubits=3, reps=1, insert_barriers=True) circuit.decompose().draw(output='mpl') x = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2] encode = circuit.bind_parameters(x) encode.decompose().draw(output='mpl') from qiskit.circuit.library import ZZFeatureMap circuit = ZZFeatureMap(3, reps=1, insert_barriers=True) circuit.decompose().draw(output='mpl') x = [0.1,0.2,0.3] encode = circuit.bind_parameters(x) encode.decompose().draw(output='mpl') from qiskit.circuit.library import ZZFeatureMap x = [-0.1,0.2] # YOUR CODE HERE # circuit = # encode = circuit.decompose().draw(output='mpl') from qiskit.circuit.library import ZZFeatureMap num_features = features.shape[1] feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1) feature_map.decompose().draw(output="mpl", fold=20) from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=num_features, reps=3) ansatz.decompose().draw(output="mpl", fold=20) from qiskit.algorithms.optimizers import COBYLA optimizer = COBYLA(maxiter=100) from matplotlib import pyplot as plt from IPython.display import clear_output objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() from qiskit_ibm_runtime import QiskitRuntimeService, Session, Options, Estimator, Sampler service = QiskitRuntimeService(channel='ibm_quantum') service.backends() backend = service.backends(simulator=True)[0] print(backend) import time from qiskit_machine_learning.algorithms.classifiers import VQC # from qiskit.primitives import Sampler with Session(service = service, backend = backend): vqc = VQC( sampler=Sampler(), feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q4 = vqc.score(train_features, train_labels) test_score_q4 = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}") print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}") from qiskit.circuit.library import ZZFeatureMap, ZFeatureMap, PauliFeatureMap, StatePreparation num_features = features.shape[1] feature_map_ex = # Use any featuremap of your choice! feature_map_ex.decompose().draw(output="mpl", fold=20) from qiskit.circuit.library import RealAmplitudes, EfficientSU2, ExcitationPreserving, PauliTwoDesign, TwoLocal, NLocal ansatz_ex = # Use any ansatz of your choice! ansatz_ex.decompose().draw(output="mpl", fold=20) from qiskit.algorithms.optimizers import COBYLA, SPSA, L_BFGS_B, NELDER_MEAD, UMDA, TNC optimizer_ex = # Use any optimizer of your choice! import time from qiskit_machine_learning.algorithms.classifiers import VQC from qiskit.primitives import Sampler with Session(service = service, backend = backend): vqc_ex = VQC( feature_map=feature_map_ex, ansatz=ansatz_ex, optimizer=optimizer_ex, callback=callback_graph, ) # clear objective value history objective_func_vals = [] start = time.time() vqc_ex.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q4_ex = vqc_ex.score(train_features, train_labels) test_score_q4_ex = vqc_ex.score(test_features, test_labels) print(f"Quantum VQC on the training dataset: {train_score_q4_ex:.2f}") print(f"Quantum VQC on the test dataset: {test_score_q4_ex:.2f}") from sklearn.decomposition import PCA features = PCA(n_components=2).fit_transform(features) plt.rcParams["figure.figsize"] = (6, 6) sns.scatterplot(x=features[:, 0], y=features[:, 1], hue=labels, palette="tab10") train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=0.8, random_state=algorithm_globals.random_seed ) svc.fit(train_features, train_labels) train_score_c2 = svc.score(train_features, train_labels) test_score_c2 = svc.score(test_features, test_labels) print(f"Classical SVC on the training dataset: {train_score_c2:.2f}") print(f"Classical SVC on the test dataset: {test_score_c2:.2f}") num_features = features.shape[1] feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1) ansatz = RealAmplitudes(num_qubits=num_features, reps=3) ansatz.decompose().draw("mpl") from qiskit.algorithms.optimizers import COBYLA, SPSA, L_BFGS_B, NELDER_MEAD, UMDA, TNC optimizer = COBYLA(maxiter=50) from qiskit.primitives import Sampler with Session(service = service, backend = backend): vqc = VQC( feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] # make the objective function plot look nicer. plt.rcParams["figure.figsize"] = (12, 6) start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q2_ra = vqc.score(train_features, train_labels) test_score_q2_ra = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset using RealAmplitudes: {train_score_q2_ra:.2f}") print(f"Quantum VQC on the test dataset using RealAmplitudes: {test_score_q2_ra:.2f}") from qiskit.circuit.library import EfficientSU2 ansatz = EfficientSU2(num_qubits=num_features, reps=3) optimizer = COBYLA(maxiter=100) with Session(service = service, backend = backend): vqc = VQC( feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q2_eff = vqc.score(train_features, train_labels) test_score_q2_eff = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset using EfficientSU2: {train_score_q2_eff:.2f}") print(f"Quantum VQC on the test dataset using EfficientSU2: {test_score_q2_eff:.2f}") print(f"Model | Test Score | Train Score") print(f"SVC, 4 features | {train_score_c4:10.2f} | {test_score_c4:10.2f}") print(f"VQC, 4 features, RealAmplitudes | {train_score_q4:10.2f} | {test_score_q4:10.2f}") print(f"----------------------------------------------------------") print(f"SVC, 2 features | {train_score_c2:10.2f} | {test_score_c2:10.2f}") print(f"VQC, 2 features, EfficientSU2 | {train_score_q2_eff:10.2f} | {test_score_q2_eff:10.2f}") print(f"VQC, 2 features, RealAmplitudes | {train_score_q2_ra:10.2f} | {test_score_q2_ra:10.2f}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/JavaFXpert/llm-grovers-search-party
JavaFXpert
import os os.environ["OPENAI_API_KEY"] = "" !pip install langchain !pip install langchain[llms] !pip install openai from langchain.llms import OpenAI from langchain.prompts import PromptTemplate from langchain.chains import LLMChain llm = OpenAI(temperature=0.0) template = """Create a boolean expression that expresses the following situation: Situation: Alice and Bob are in a relationship, as are Carol and David. However, Alice and David had a bad breakup a while ago and haven't been civil with each other since. Expression: ((Alice & Bob) | (Carol & David)) & ~(Alice and David) Situation: {situation} Expression:""" prompt_template = PromptTemplate( input_variables=["situation"], template=template, ) chain = LLMChain(llm=llm, prompt=prompt_template) from qiskit.algorithms import AmplificationProblem, Grover from qiskit.circuit.library import PhaseOracle from qiskit import Aer from qiskit.visualization import plot_histogram situation = """There are four people, Abe, Amira, Jin, Olivia. Abe and Olivia are good friends from Qiskit Camp. Abe and Amira just had a big fight and don't want to hang""" bool_expr = chain.run(situation).strip() print(bool_expr) oracle = PhaseOracle(bool_expr) problem = AmplificationProblem(oracle) backend = Aer.get_backend("aer_simulator") grover = Grover(quantum_instance=backend) result = grover.amplify(problem) counts = result.circuit_results plot_histogram(counts)
https://github.com/minminjao/qiskit1
minminjao
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() circ=QuantumCircuit(2,2) circ.h(0) circ.cx(0,1) circ.x(0) circ.barrier(range(2)) circ.cx(0,1) circ.h(0) circ.measure(range(2),range(2)) circ.draw() backend_sim=Aer.get_backend('qasm_simulator') ch_sim=backend_sim.run(transpile(circ, backend_sim), shots=1024) result_sim=ch_sim.result() counts=result_sim.get_counts(circ) print(counts)
https://github.com/minminjao/qiskit1
minminjao
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() circ=QuantumCircuit(5,5) circ.h(0) circ.cx(0,1) circ.cx(1,2) circ.cx(2,3) circ.cx(3,4) circ.barrier(range(5)) circ.measure(range(5),range(5)) circ.draw('mpl')
https://github.com/minminjao/qiskit1
minminjao
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() import numpy as np import qiskit as q qr = q.QuantumRegister(4) circ2 = q.QuantumCircuit(qr) ### encode the state 110 at first circ2.x(qr[0]) circ2.x(qr[1]) circ2.x(qr[2]) circ2.x(qr[3]) ### repeat what's done before ### add the first H gate (in qiskit east significant bit has the lowest index) circ2.h(qr[2]) ### add the controlled phase gate circ2.cp(np.pi/2, qr[1], qr[2]) # based on qubit 1 apply 2pi/2**(k-1) rotation to qubit 2 ### add the next cp gate circ2.cp(np.pi/4, qr[0], qr[2]) # based on qubit 0 apply 2pi/2**(k-1) rotation to qubit 2 ### repeat the process for qubit 1 circ2.h(qr[1]) circ2.cp(np.pi/2, qr[0], qr[1]) ### add the final h gate circ2.h(qr[0]) circ2.ry(np.pi / 4, qr[2]) circ2.ry(-np.pi /2 , qr[3]) circ2.rz(-np.pi/4, qr[3]) ### finally swap the bits 0 th, and 2nd qubit circ2.swap(qr[0], qr[2]) circ2.swap(qr[1],qr[2]) circ2.swap(qr[1],qr[3]) circ2.save_statevector() qasm_sim = q.Aer.get_backend('qasm_simulator') statevector = qasm_sim.run(circ2).result().get_statevector() q.visualization.plot_bloch_multivector(statevector) from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') counts = execute(circ2, backend=simulator, shots=1000).result().get_counts(circ2) from qiskit.visualization import plot_histogram plot_histogram(counts) import numpy as np import qiskit as q qr = q.QuantumRegister(4) circ = q.QuantumCircuit(qr) ### add the first H gate (in qiskit least significant bit has the lowest index) circ.h(qr[3]) ### add the controlled phase gate circ.cp(np.pi/2, qr[1], qr[2]) # based on qubit 1 apply 2pi/2**(k-1) rotation to qubit 2 ### add the next cp gate circ.cp(np.pi/4, qr[0], qr[2]) # based on qubit 0 apply 2pi/2**(k-1) rotation to qubit 2 ### repeat the process for qubit 1 circ.h(qr[1]) circ.cp(np.pi/2, qr[0], qr[1]) ### add the final h gate ### finally swap the bits 0 th, and 2nd qubit circ.swap(qr[0], qr[2])
https://github.com/minminjao/qiskit1
minminjao
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(10) qc.h(2) qc.cp(pi/2, 1, 2) qc.cp(pi/4, 0, 2) qc.h(1) qc.cp(pi/2, 0, 1) # CROT from qubit 0 to qubit 1 qc.h(0) qc.swap(0,2) def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) # At the end of our function, we call the same function again on # the next qubits (we reduced n by one earlier in the function) qft_rotations(circuit, n) # Let's see how it looks: qc = QuantumCircuit(10) qft_rotations(qc,10) qc.draw() def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): """QFT on the first n qubits in circuit""" qft_rotations(circuit, n) swap_registers(circuit, n) return circuit # Let's see how it looks: qc = QuantumCircuit(10) qft(qc,10) qc.draw() def inverse_qft(circuit, n): """Does the inverse QFT on the first n qubits in circuit""" # First we create a QFT circuit of the correct size: qft_circ = qft(QuantumCircuit(n), n) # Then we take the inverse of this circuit invqft_circ = qft_circ.inverse() # And add it to the first n qubits in our existing circuit circuit.append(invqft_circ, circuit.qubits[:n]) return circuit.decompose() # .decompose() allows us to see the individual gates nqubits = 10 number = 5 qc = QuantumCircuit(nqubits) for qubit in range(nqubits): qc.h(qubit) qc.p(number*pi/4,0) qc.p(number*pi/2,1) qc.p(number*pi,2) qc.p(number*pi/4,3) qc.p(number*pi/2,4) qc.p(number*pi,5) qc.p(number*pi/4,6) qc.p(number*pi/2,7) qc.p(number*pi,8) qc.p(number*pi/4,9) qc.draw() μœ„μ— μ½”λ“œλ“€μ€ ibm qiskit textbook을 기초둜 ν•˜μ—¬μ„œ μž‘μ„±ν•œ μ½”λ“œμ΄λ‹€. 10νλΉ„νŠΈλ‘œ λ°”λ€Œμ—ˆμœΌλ―€λ‘œ nqubits = 10) <- 10을 μž‘μ„±ν•˜μ—¬μ„œ 10νλΉ„νŠΈλ₯Ό κ΅¬ν˜„ν•˜λ„λ‘ ν•˜μ˜€κ³  μœ„ 그림은 그에 λ”°λ₯Έ 결과이닀. 그리고 μ›λž˜λŠ” 3νλΉ„νŠΈλ§Œ ν•˜μ—¬μ„œ μ½”λ“œλ“€μ΄ κ΅¬ν˜„μ΄ λ˜λ„λ‘ ν•˜μ˜€μ§€λ§Œ 문제λ₯Ό ν’€κΈ°μœ„ν•΄μ„œλŠ” 10νλΉ„νŠΈλ₯Ό μž‘μ„±ν•˜κ³  μ½”λ“œμ—°μ‚°λ“€μ„ μ μš©ν•΄μ•Όν•œλ‹€. κ·ΈλŸ¬λ―€λ‘œ h κ²Œμ΄νŠΈλ„ 10νλΉ„νŠΈκΉŒμ§€ λ‹€ μ μš©λ˜λ„λ‘ ν•˜μ˜€κ³  p κ²Œμ΄νŠΈκ°€ λ„λŠ” 각도듀도 μΌμ •νŒ¨ν„΄μ„ κ°€μ§€κ³  μ μš©λ˜λ„λ‘ μž‘μ„±ν•˜μ˜€λ‹€. qc.p(number*pi/4,n) qc.p(number*pi/2,n) qc.p(number*pi,n) => 의 파이 각도듀이 μΌμ •ν•˜κ²Œ λ°˜λ³΅λ˜λ„λ‘ μ½”λ“œλ“€μ„ μΆ”κ°€ν•˜μ˜€λ‹€. qc_init = qc.copy() qc_init.save_statevector() sim = Aer.get_backend("aer_simulator") statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qc = inverse_qft(qc, nqubits) qc.measure_all() qc.draw() shots = 2048 backend = Aer.get_backend('qasm_simulator') transpiled_qc = transpile(qc, backend, optimization_level=3) job = backend.run(transpiled_qc, shots=shots) job_monitor(job) counts = job.result().get_counts() plot_histogram(counts) print(counts)
https://github.com/minminjao/qiskit1
minminjao
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi qreg_q = QuantumRegister(3, 'q') creg_c = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.u(0, pi / 4, pi / 4, qreg_q[0]).c_if(creg_c, 0) circuit.x(qreg_q[0]) circuit.measure(qreg_q[0], creg_c[0]) from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') counts = execute(circuit, backend=simulator, shots=1000).result().get_counts(circuit) from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/minminjao/qiskit1
minminjao
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() circ=QuantumCircuit(2) circ.h(0) circ.cx(0,1) meas=QuantumCircuit(2,2) meas.barrier(range(2)) circ.add_register(meas.cregs[0]) qc=circ.compose(meas) circ.draw('mpl') meas.measure(range(2),range(2)) circ.draw('mpl') job=backend.run(circ)
https://github.com/VoicuTomut/Qsiris-Quantum-Odyssey-and-Qiskit
VoicuTomut
import numpy as np from qiskit import( QuantumCircuit, execute, Aer) from qiskit.visualization import plot_histogram # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(2, 2) # Add a H gate on qubit 0 circuit.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 1) # Map the quantum measurement to the classical bits circuit.measure([0,1], [0,1]) # Execute the circuit on the qasm simulator job = execute(circuit, simulator, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(circuit) print(counts) # Draw the circuit circuit.draw() print(circuit)
https://github.com/VoicuTomut/Qsiris-Quantum-Odyssey-and-Qiskit
VoicuTomut
import numpy as np import cmath from qiskit import QuantumCircuit, transpile from qiskit import Aer, execute from qiskit import IBMQ from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram from project_qsiris.conversion_qo_qiskit import odyssey_to_qiskit,load_oddysey_puzzle #Enable this line if you plan to use IBM Q Experience and run these circuit on real IBM hw (and see results in IBMQ) #IBMQ.load_account() #Step 1: Read the QO puzzle file (has extension .qpf). #If you want to change the puzzle file, simply add the new path or puzzle in path= folder path = "circuits/qiskit_to_odyssey/example_002.qpf" puzzle = load_oddysey_puzzle(path) #Step 2: convert your QO puzzle to a Qiskit circuit and draw the mpl qc = odyssey_to_qiskit(puzzle, incl_initial_state = False, use_barrier = False, incl_all_measurements = True) qc.draw('mpl') #Step 3: Run your puzzle on a qiskit simulator and plot counts backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend,shots=1000) result = job.result() counts = result.get_counts() plot_histogram(counts) #Step 4: Run your puzzle on a real QPU from IBM. You can customize the execution here. # It will take some time for the job to be executed provider = IBMQ.get_provider('ibm-q') ibm_QPU=provider.get_backend('ibmq_santiago') job=execute(qc, backend=ibm_QPU, shots=100) job_monitor(job,interval=10) result = job.result() counts = result.get_counts() plot_histogram(counts) path = "circuits/odyssey_circuits/asdasd.qpf" res = load_oddysey_puzzle(path) res.keys() qc = odyssey_to_qiskit(res, incl_initial_state = False, use_barrier = False, incl_all_measurements = True) qc.draw('mpl') backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend,shots=1000) result = job.result() counts = result.get_counts() plot_histogram(counts) backend = Aer.get_backend('qasm_simulator') result = transpile(qc, backend=backend, optimization_level=3) result.draw(output='mpl') # This runbook is for testing how much you can approximate decimals if Qiskit is still able to rec as unitary # It is important to have as many decimals as possible # Otherwise we can get unitary errors (even if we can introduce the gate in the circuit) . unit=[[ 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.70710679+0.j, 0.70710679+0.j],#np.sqrt(1/2)+0.j, np.sqrt(1/2)+0.j], [ 0.+0.j, 0.+0.j, 0.70710679+0.j, -0.70710679+0.j],]#np.sqrt(1/2)+0.j, -np.sqrt(1/2)+0.j],]#0.70710679+0.j, -0.70710679+0.j],] qc=QuantumCircuit(2) qc.unitary(unit,[0,1]) qc.draw() print(qc.qasm())
https://github.com/VoicuTomut/Qsiris-Quantum-Odyssey-and-Qiskit
VoicuTomut
import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.compiler import transpile import matplotlib.pyplot as plt import matplotlib.image as mpimg from project_qsiris.conversion_qiskit_qo import qiskit_to_odyssey, save_odyssey_puzzle #Add here any Qiskit gates you'd like to be converted to Quantum Odyssey. What you see bellow is an example #You can change the QuantumRegister between 1 to 5 qubits. qreg_q = QuantumRegister(2,'q') circuit = QuantumCircuit(qreg_q) circuit.x(qreg_q[0]) circuit.y(qreg_q[1]) circuit.draw('mpl') # This creates the QO puzzle out of your Qiskit circuit. # You can save it in two ways: General (as an actual puzzle to be solved) or Editor (to just visualize it in QO). puzzle = qiskit_to_odyssey(circuit, puzzle_type="General") # The name of the puzzle (by default example_001). QO puzzles have extension .qpf save_odyssey_puzzle(puzzle, 'example_001' ) #Step 1: Build the circuit in Qiskit qreg_q = QuantumRegister(4,'q') circuit = QuantumCircuit(qreg_q) circuit.cx(qreg_q[1],qreg_q[2]) circuit.h(qreg_q[1]) circuit.z(qreg_q[3]) circuit.u(np.pi/7,np.pi/3,np.pi/5,qreg_q[0]) circuit.swap(qreg_q[0], qreg_q[3]) circuit.draw('mpl') #Step 2: Transpile your Qiskit circuit to simple gates to conversion avoid problems circuit = transpile(circuit, basis_gates=['id','u3', 'cx'], optimization_level=1, seed_transpiler=1) circuit.draw(output='mpl') #Step 3: Convert your circuit in dictionary that represents a QO puzzle. puzzle=qiskit_to_odyssey(circuit, puzzle_type="General") #Step 4: Save your puzzle save_odyssey_puzzle(puzzle, 'example_002' ) circuit = QuantumCircuit(2,name='matchgate_2Q') circuit.cx(0,1) circuit.z(0) circuit.cry(np.pi/7,1,0) circuit.cx(0,1) circuit.draw('mpl') circuit = transpile(circuit, basis_gates=['id','u3', 'cx'], optimization_level=1, seed_transpiler=1) circuit.draw(output='mpl') puzzle = qiskit_to_odyssey(circuit) save_odyssey_puzzle(puzzle, 'example_003' ) # Let's see here how the default example_003 puzzle file will look like in Quantum Odyssey img_circuit = mpimg.imread('img/qiskit_circuit_to_QO.png') img_circuit_gate = mpimg.imread('img/qo_circuit_as_1gate.png') fig, ax = plt.subplots(1,2) ax[0].imshow(img_circuit); ax[1].imshow(img_circuit_gate); ax[0].set_title('Circuit in QO') #Quantum Odyssey allows compilation of any number of logic gates in a single custom gate (right side bellow=left) ax[1].set_title('Circuit in QO as a gate') #Here is how the QO puzzle file looks like, this is an example puzzle
https://github.com/VoicuTomut/Qsiris-Quantum-Odyssey-and-Qiskit
VoicuTomut
from qiskit import Aer, execute from qiskit import QuantumCircuit from qiskit import IBMQ from qiskit.tools.monitor import job_monitor from project_qsiris.conversion_qo_qiskit import * def qiskit_test(): # test circuit circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.measure_all() backend = Aer.get_backend("qasm_simulator") result = execute(circ, backend=backend, shots=10).result() counts = result.get_counts() return counts def execute_qiskit(res): qc = odyssey_to_qiskit(res, incl_initial_state = False, use_barrier = True, incl_all_measurements = True) backend = Aer.get_backend("qasm_simulator") result = execute(qc, backend=backend, shots=100).result() counts = result.get_counts() return counts def decompose_qiskit(res): qc = odyssey_to_qiskit(res, incl_initial_state=False, use_barrier=True, incl_all_measurements=True) try: qasm_circuit = qc.qasm() except: qasm_circuit = ( "The matrix is not unitary." " At the moment the error is probably caused by the fact that " "the numbers do not have enough decimals" ) return qasm_circuit def real_device_qiskit(res): IBMQ.load_account() provider = IBMQ.get_provider('ibm-q') ibmq_lima = provider.get_backend("ibmq_lima") qc = odyssey_to_qiskit(res, incl_initial_state=False, use_barrier=True, incl_all_measurements=True) try: qasm_circuit = qc.qasm() job=execute(qc, backend=ibmq_lima, shots=100) job_monitor(job) result = job.result() counts = result.get_counts() except: qasm_circuit = ( "The matrix is not unitary." " At the moment the error is probably caused by the fact that " "the numbers do not have enough decimals" ) result = {"ibmq_lima_counts": counts, "qasm_circuit": qasm_circuit} return result
https://github.com/VoicuTomut/Qsiris-Quantum-Odyssey-and-Qiskit
VoicuTomut
import json import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import project_qsiris.conversion_gates as conv from project_qsiris.conversion_intermediates import OdysseyMoment def get_odyssey_nr_qubits(res): """ :param res: (puzzle)dictionary :return: (number of qubits from puzzle)int """ nr_q = res["PuzzleDefinition"]["QubitCapacity"] return nr_q def extract_odyssey_matrix(mat): """ :param mat: matrix of complex numbers in dictionary form :return: matrix ov 'complex' numbers #example: mat=[[{'Real': 0.0, 'Imaginary': 0.0, 'Magnitude': 0.0, 'Phase': 0.0}, {'Real': 1.0, 'Imaginary': 0.0, 'Magnitude': 1.0, 'Phase': 0.0}], [{'Real': 1.0, 'Imaginary': 0.0, 'Magnitude': 1.0, 'Phase': 0.0}, {'Real': 0.0, 'Imaginary': 0.0, 'Magnitude': 0.0, 'Phase': 0.0}]] g_mat = extract_odyssey_matrix(mat) print("matrice:\n",g_mat) """ mat_conv = [] for i in mat: linie = [] for j in i: linie.append(conv._odyssey_to_complex(j)) mat_conv.append(linie) return mat_conv def add_odyssey_moment(puzzle_gate, qc): """ :param puzzle_gate: string of gates :param qc: QuantumCircuit Qiskit Add gates from moment to the Qiskit circuit """ moment = OdysseyMoment(puzzle_gate) if len(moment.control_q) == 0: """ This is the default case """ for qubit in range(moment.nr_q): gate_name = moment.original_form[qubit]["GateInSlot"]["Name"] if gate_name == "X": qc.x(qubit) elif gate_name == "Y": qc.y(qubit) elif gate_name == "Z": qc.z(qubit) elif gate_name == "H": qc.h(qubit) elif gate_name == "I": qc.id(qubit) elif gate_name == "Filler": print( "The fillers are empty gates so they will not be converted to qiskit", qubit, ) else: unit = extract_odyssey_matrix( moment.original_form[qubit]["GateInSlot"]["DefinitionMatrix"] ) qubits = [k for k in moment.filler_q] qubits.append(qubit) qc.unitary(unit, qubits, moment.original_form[qubit]["GateInSlot"]["Name"]) if len(moment.filler_q) > 0: print( "This gate {} is not necessarily converted correctly." " The order of the qubits maybe reversed Please check! ".format( gate_name ) ) return """ If there are controls on the puzzle gate """ for i in range(moment.nr_q): if ( (moment.original_form[i]["GateInSlot"]["Name"] != "CTRL") and (moment.original_form[i]["GateInSlot"]["Name"] != "I") and (moment.original_form[i]["GateInSlot"]["Name"] != "Filler") ): control = moment.control_q.copy() qubits = [l for l in control] for l in range(len(moment.filler_q)): qubits.append(moment.filler_q[l]) qubits.append(i) unit = np.identity(2 ** len(qubits), dtype=complex) mat = extract_odyssey_matrix(moment.original_form[i]["GateInSlot"]["DefinitionMatrix"]) """ unit[-1][-1]=mat[1][1] unit[-1][-2]=mat[1][0] unit[-2][-1]=mat[0][1] unit[-2][-2]=mat[0][0] """ for k in range(1, len(mat) + 1): for j in range(1, len(mat) + 1): unit[-k][-j] = mat[-k][-j] qc.unitary( unit, qubits[::-1], "C " + str(moment.control_q) + " -> " + moment.original_form[i]["GateInSlot"]["Name"] + "[" + str(i) + "]", ) def load_oddysey_puzzle(path): file = open(path, "r") content = file.read() puzzle = json.loads(content) return puzzle def odyssey_to_qiskit(puzzle, incl_initial_state = False, use_barrier = False, incl_all_measurements = False): """ :param path: (puzzle) path to puzzle :param initial_state: (initial qubits state ) string of dictionaries :return: quantum circuit in qiskit equivalent with the circuit from puzzle """ nr_q = get_odyssey_nr_qubits(puzzle) qc = QuantumCircuit(QuantumRegister(nr_q), ClassicalRegister(nr_q)) if incl_initial_state != False: qc.initialize(incl_initial_state) for puzzle_gate in conv._transpose_list(puzzle["PuzzleGates"]): if use_barrier: qc.barrier() add_odyssey_moment(puzzle_gate, qc) if incl_all_measurements: for index in range(nr_q): qc.measure(qc.qregs[0][index], qc.cregs[0][nr_q - 1 - index]) return qc
https://github.com/JavierPerez21/QiskitPractice
JavierPerez21
%%capture !pip install qiskit %matplotlib inline from qiskit import * import numpy as np from math import pi from qiskit.visualization import plot_histogram, plot_bloch_multivector, plot_state_qsphere, plot_state_city from qiskit.quantum_info import Statevector from qiskit.quantum_info import state_fidelity import matplotlib.pyplot as plt class RandomCircuitGenerator: def __init__(self, qubits=1, max_depth=3): self.qubits = np.arange(0,qubits).tolist() self.max_depth = max_depth self.qc = QuantumCircuit(qubits, qubits) self.single_qubit_gates = ['x', 'z', 'y', 'h', 's', 't', 'rx', 'rz', 'ry', ''] self.multi_qubit_gates = ['cx', 'cz', 'cy', 'ch', 'cs', 'ct', 'crx', 'crz', 'cry', ''] self.angles = [0, pi / 8, pi / 4, 3 * pi / 8, pi / 2, 5 * pi / 8, 3 * pi / 4, 7 * pi / 8, pi, 9 * pi / 8, 5 * pi / 4, 11 * pi / 8, 3 * pi / 2, 13 * pi / 8, 7 * pi / 4, 15 * pi / 8, 2 * pi] if len(self.qubits) > 1: self.available_gates = self.single_qubit_gates + self.multi_qubit_gates else: self.available_gates = self.single_qubit_gates def generate_random_circuit(self): for i in range(0, self.max_depth): gate = self.available_gates[np.random.randint(0, len(self.available_gates))] self.add_gate(gate) def add_gate(self, gate): if gate == 'x': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.x(qubit) elif gate == 'z': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.z(qubit) elif gate == 'y': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.y(qubit) elif gate == 'h': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.h(qubit) elif gate == 's': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.s(qubit) elif gate == 't': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.t(qubit) elif gate == 'rx': qubit = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.rx(angle, qubit) elif gate == 'rz': qubit = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.rz(angle, qubit) elif gate == 'ry': qubit = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.ry(angle, qubit) elif gate == 'cx': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.cx(qubit1, qubit2) elif gate == 'cz': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.cz(qubit1, qubit2) elif gate == 'cy': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.cy(qubit1, qubit2) elif gate == 'ch': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.ch(qubit1, qubit2) elif gate == 'cs': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.cs(qubit1, qubit2) elif gate == 'ct': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.ct(qubit1, qubit2) elif gate == 'crx': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.crx(angle, qubit1, qubit2) elif gate == 'crz': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.crz(angle, qubit1, qubit2) elif gate == 'cry': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.cry(angle, qubit1, qubit2) def show_circuit(self): print(self.qc) def execution_historgram(self): qc = self.qc.copy() qc.measure(self.qubits, self.qubits) backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend) return plot_histogram(job.result().get_counts(), color='midnightblue', title="Execution Histogram") def bloch_sphere(self): qc = self.qc.copy() state = Statevector.from_instruction(qc) return plot_bloch_multivector(state, title="Bloch Sphere", reverse_bits=False) def q_sphere(self): qc = self.qc.copy() state = Statevector.from_instruction(qc) return plot_state_qsphere(state) def state_city(self): qc = self.qc.copy() backend = BasicAer.get_backend('statevector_simulator') result = backend.run(transpile(qc, backend)).result() psi = result.get_statevector(qc) return plot_state_city(psi) def add_circuit_guess(self, circuit_guess): qc = self.qc.copy() self.circuit_guess = circuit_guess circuit_guess = circuit_guess.copy() backend = BasicAer.get_backend('statevector_simulator') qc_state = execute(qc, backend).result().get_statevector(qc) circuit_guess_state = execute(circuit_guess, backend).result().get_statevector(circuit_guess) print("State fidelity of your circuit: {}".format(state_fidelity(circuit_guess_state, qc_state))) # Generate a random circuit circuit = RandomCircuitGenerator(qubits=1, max_depth=2) circuit.generate_random_circuit() # Visualize som information about the random circuit #circuit.execution_historgram() circuit.bloch_sphere() #circuit.q_sphere() #circuit.show_circuit() # Try to generate a similar circuit circuit_guess = QuantumCircuit(1) circuit_guess.h(0) circuit.add_circuit_guess(circuit_guess)
https://github.com/JavierPerez21/QiskitPractice
JavierPerez21
from qiskit import * import numpy as np from math import pi from qiskit.visualization import plot_histogram, plot_bloch_multivector, plot_state_qsphere, plot_state_city from qiskit.quantum_info import Statevector from qiskit.quantum_info import state_fidelity import matplotlib.pyplot as plt class RandomCircuitGenerator: def __init__(self, qubits=1, max_depth=3): self.qubits = np.arange(0,qubits).tolist() self.max_depth = max_depth self.qc = QuantumCircuit(qubits, qubits) self.single_qubit_gates = ['x', 'z', 'y', 'h', 's', 't', 'rx', 'rz', 'ry', ''] self.multi_qubit_gates = ['cx', 'cz', 'cy', 'ch', 'cs', 'ct', 'crx', 'crz', 'cry', ''] self.angles = [0, pi / 8, pi / 4, 3 * pi / 8, pi / 2, 5 * pi / 8, 3 * pi / 4, 7 * pi / 8, pi, 9 * pi / 8, 5 * pi / 4, 11 * pi / 8, 3 * pi / 2, 13 * pi / 8, 7 * pi / 4, 15 * pi / 8, 2 * pi] if len(self.qubits) > 1: self.available_gates = self.single_qubit_gates + self.multi_qubit_gates else: self.available_gates = self.single_qubit_gates def generate_random_circuit(self): for i in range(0, self.max_depth): gate = self.available_gates[np.random.randint(0, len(self.available_gates))] self.add_gate(gate) def add_gate(self, gate): if gate == 'x': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.x(qubit) elif gate == 'z': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.z(qubit) elif gate == 'y': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.y(qubit) elif gate == 'h': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.h(qubit) elif gate == 's': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.s(qubit) elif gate == 't': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.t(qubit) elif gate == 'rx': qubit = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.rx(angle, qubit) elif gate == 'rz': qubit = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.rz(angle, qubit) elif gate == 'ry': qubit = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.ry(angle, qubit) elif gate == 'cx': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.cx(qubit1, qubit2) elif gate == 'cz': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.cz(qubit1, qubit2) elif gate == 'cy': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.cy(qubit1, qubit2) elif gate == 'ch': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.ch(qubit1, qubit2) elif gate == 'cs': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.cs(qubit1, qubit2) elif gate == 'ct': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.ct(qubit1, qubit2) elif gate == 'crx': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.crx(angle, qubit1, qubit2) elif gate == 'crz': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.crz(angle, qubit1, qubit2) elif gate == 'cry': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.cry(angle, qubit1, qubit2) def show_circuit(self): print(self.qc) def execution_historgram(self): qc = self.qc.copy() qc.measure(self.qubits, self.qubits) backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend) return plot_histogram(job.result().get_counts(), color='midnightblue', title="Execution Histogram") def bloch_sphere(self): qc = self.qc.copy() state = Statevector.from_instruction(qc) return plot_bloch_multivector(state, title="Bloch Sphere", reverse_bits=False) def q_sphere(self): qc = self.qc.copy() state = Statevector.from_instruction(qc) return plot_state_qsphere(state) def state_city(self): qc = self.qc.copy() backend = BasicAer.get_backend('statevector_simulator') result = backend.run(transpile(qc, backend)).result() psi = result.get_statevector(qc) return plot_state_city(psi) def add_circuit_guess(self, circuit_guess): qc = self.qc.copy() self.circuit_guess = circuit_guess circuit_guess = circuit_guess.copy() backend = BasicAer.get_backend('statevector_simulator') qc_state = execute(qc, backend).result().get_statevector(qc) circuit_guess_state = execute(circuit_guess, backend).result().get_statevector(circuit_guess) print("State fidelity of your circuit: {}".format(state_fidelity(circuit_guess_state, qc_state)))
https://github.com/SammithSB/virat-and-toss
SammithSB
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ from qiskit.visualization import plot_histogram, plot_bloch_multivector ### Creating 3 qubit and 2 classical bits in each separate register qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(1) teleportation_circuit = QuantumCircuit(qr, crz, crx) ### A third party eve helps to create an entangled state def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a, b) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, a, b): qc.cx(a, b) qc.h(a) teleportation_circuit.barrier() alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() def measure_and_send(qc, a, b): qc.barrier() qc.measure(a,0) qc.measure(b,1) teleportation_circuit.barrier() measure_and_send(teleportation_circuit, 0, 1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) qc.z(qubit).c_if(crz, 1) teleportation_circuit.barrier() bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() from qiskit.extensions import Initialize import math qc = QuantumCircuit(1) initial_state = [0,1] init_gate = Initialize(initial_state) # qc.append(initialize_qubit, [0]) qr = QuantumRegister(3) # Protocol uses 3 qubits crz = ClassicalRegister(1) # and 2 classical registers crx = ClassicalRegister(1) qc = QuantumCircuit(qr, crz, crx) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) # Bob decodes qubits bob_gates(qc, 2, crz, crx) qc.draw() backend = BasicAer.get_backend('statevector_simulator') out_vector = execute(qc, backend).result().get_statevector() plot_bloch_multivector(out_vector) inverse_init_gate = init_gate.gates_to_uncompute() qc.append(inverse_init_gate, [2]) qc.draw() cr_result = ClassicalRegister(1) qc.add_register(cr_result) qc.measure(2,2) qc.draw() backend = BasicAer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1024).result().get_counts() plot_histogram(counts) def bob_gates(qc, a, b, c): qc.cz(a, c) qc.cx(b, c) qc = QuantumCircuit(3,1) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) qc.barrier() # Alice sends classical bits to Bob bob_gates(qc, 0, 1, 2) # We undo the initialisation process qc.append(inverse_init_gate, [2]) # See the results, we only care about the state of qubit 2 qc.measure(2,0) # View the results: qc.draw() from qiskit import IBMQ IBMQ.save_account('### IMB TOKEN ') IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() from qiskit.providers.ibmq import least_busy backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and not b.configuration().simulator and b.status().operational==True)) job_exp = execute(qc, backend=backend, shots=8192) exp_result = job_exp.result() exp_measurement_result = exp_result.get_counts(qc) print(exp_measurement_result) plot_histogram(exp_measurement_result) error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \ * 100./ sum(list(exp_measurement_result.values())) print("The experimental error rate : ", error_rate_percent, "%")
https://github.com/SammithSB/virat-and-toss
SammithSB
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ from qiskit.visualization import plot_histogram, plot_bloch_multivector ### Creating 3 qubit and 2 classical bits in each separate register qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(1) teleportation_circuit = QuantumCircuit(qr, crz, crx) ### A third party eve helps to create an entangled state def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a, b) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, a, b): qc.cx(a, b) qc.h(a) teleportation_circuit.barrier() alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() def measure_and_send(qc, a, b): qc.barrier() qc.measure(a,0) qc.measure(b,1) teleportation_circuit.barrier() measure_and_send(teleportation_circuit, 0, 1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) qc.z(qubit).c_if(crz, 1) teleportation_circuit.barrier() bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() from qiskit.extensions import Initialize import math qc = QuantumCircuit(1) initial_state = [0,1] init_gate = Initialize(initial_state) # qc.append(initialize_qubit, [0]) qr = QuantumRegister(3) # Protocol uses 3 qubits crz = ClassicalRegister(1) # and 2 classical registers crx = ClassicalRegister(1) qc = QuantumCircuit(qr, crz, crx) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) # Bob decodes qubits bob_gates(qc, 2, crz, crx) qc.draw() backend = BasicAer.get_backend('statevector_simulator') out_vector = execute(qc, backend).result().get_statevector() plot_bloch_multivector(out_vector) inverse_init_gate = init_gate.gates_to_uncompute() qc.append(inverse_init_gate, [2]) qc.draw() cr_result = ClassicalRegister(1) qc.add_register(cr_result) qc.measure(2,2) qc.draw() backend = BasicAer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1024).result().get_counts() plot_histogram(counts) def bob_gates(qc, a, b, c): qc.cz(a, c) qc.cx(b, c) qc = QuantumCircuit(3,1) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) qc.barrier() # Alice sends classical bits to Bob bob_gates(qc, 0, 1, 2) # We undo the initialisation process qc.append(inverse_init_gate, [2]) # See the results, we only care about the state of qubit 2 qc.measure(2,0) # View the results: qc.draw() from qiskit import IBMQ IBMQ.save_account('### IMB TOKEN ') IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() from qiskit.providers.ibmq import least_busy backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and not b.configuration().simulator and b.status().operational==True)) job_exp = execute(qc, backend=backend, shots=8192) exp_result = job_exp.result() exp_measurement_result = exp_result.get_counts(qc) print(exp_measurement_result) plot_histogram(exp_measurement_result) error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \ * 100./ sum(list(exp_measurement_result.values())) print("The experimental error rate : ", error_rate_percent, "%")
https://github.com/sayana25/IQCQ-UPES-2023
sayana25
pip install qiskit !pip install pylatexenc pip install qiskit-aer pip install qiskit-ibm-runtime pip install qiskit-ibm-provider import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, Aer, IBMQ, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector from math import pi, sqrt sim = Aer.get_backend('aer_simulator') # Let's do an X-gate on a |0> qubit qc = QuantumCircuit(1) qc.x(0) qc.draw('mpl') # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) # Let's do an Y-gate on a |0> qubit qc = QuantumCircuit(1) #qc.x(0) qc.y(0) qc.draw('mpl') # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) # Let's do an Y-gate on a |1> qubit qc = QuantumCircuit(1) #In qiskit, the qubit is initialised at |0> qc.x(0) #prepares the |1> qubit qc.y(0) #Then y-gate is applied on y qc.draw('mpl') # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) # Let's do an Y-gate on a |1> qubit qc = QuantumCircuit(1) #In qiskit, the qubit is initialised at |0> qc.z(0) #z rotation on the |0> qubit, leaves it unchanged as seen below qc.draw('mpl') # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) # Let's do an Y-gate on a |1> qubit qc = QuantumCircuit(1) #In qiskit, the qubit is initialised at |0> qc.x(0) qc.z(0) #z rotation on the |1> qubit? qc.draw('mpl') # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) # Let's do an H-gate on a |0> qubit qc = QuantumCircuit(1) #In qiskit, the qubit is initialised at |0> qc.h(0) qc.draw('mpl') # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) # Let's do an H-gate on a |0> qubit followed by Z qc = QuantumCircuit(1) #In qiskit, the qubit is initialised at |0>, let's convert it to the |1> state qc.h(0) qc.z(0) # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) # Let's do an H-gate on a |0> qubit followed by X qc = QuantumCircuit(1) #In qiskit, the qubit is initialised at |0>, let's convert it to the |1> state qc.h(0) qc.x(0) #Does this make any difference? qc.z(0) #This flips # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) qc.h(2) qc.cp(pi/2, 1, 2) # CROT from qubit 1 to qubit 2 qc.cp(pi/4, 0, 2) # CROT from qubit 2 to qubit 0 qc.h(1) qc.cp(pi/2, 0, 1) # CROT from qubit 0 to qubit 1 qc.h(0) qc.swap(0,2) qc.draw('mpl') def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) # At the end of our function, we call the same function again on # the next qubits (we reduced n by one earlier in the function) qft_rotations(circuit, n) # Let's see how it looks: qc = QuantumCircuit(4) qft_rotations(qc,4) qc.draw('mpl') def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): """QFT on the first n qubits in circuit""" qft_rotations(circuit, n) swap_registers(circuit, n) return circuit # Let's see how it looks: qc = QuantumCircuit(4) qft(qc,4) qc.draw('mpl') bin(5) # Create the circuit qc = QuantumCircuit(3) # Encode the state 5 qc.x(0) qc.x(2) qc.draw('mpl') #Checking qubit states in the bloch vector representation using the Aer simulator 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('mpl') qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector) bin(4) # Create the circuit qc = QuantumCircuit(3) # Encode the state 4 qc.x(2) qc.draw('mpl') 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('mpl') qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector)
https://github.com/sayana25/IQCQ-UPES-2023
sayana25
pip install qiskit pip install qiskit-ibm-runtime pip install pylatexenc import qiskit from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister,execute,IBMQ, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_vector from math import sqrt, pi #qc = QuantumCircuit(1) # Create a quantum circuit with one qubit qc = QuantumCircuit(1) # Create a quantum circuit with one qubit initial_state = [0,1] # Define initial_state as |1> qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit qc.draw() # Let's view our circuit qc = QuantumCircuit(3,3) # Create a quantum circuit with 3 qubits, like in python qc.h(0) #hadamard gate qc.x(1) #Pauli-X gate qc.y(2) #Pauli-Y gate qc.draw() # Let's view our circuit
https://github.com/sayana25/IQCQ-UPES-2023
sayana25
pip install qiskit !pip install pylatexenc pip install qiskit-aer pip install git+https://github.com/Qiskit/qiskit-terra.git import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram, plot_histogram, plot_state_city Aer.backends() # Construct quantum circuit without measure circ = QuantumCircuit(2,2) circ.h(0) circ.cx(0, 1) #CNOT gate circ.measure([0,1], [0,1]) circ.draw('mpl') # Select the QasmSimulator from the Aer provider simulator = Aer.get_backend('qasm_simulator') # Execute and get memory result = execute(circ, simulator, shots=100, memory=True).result() memory = result.get_memory(circ) print(memory) # Select the StatevectorSimulator from the Aer provider simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(circ, simulator).result() statevector = result.get_statevector(circ) plot_state_city(statevector, title='Bell state') def psiplus(): qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement qc.h(0) qc.x(1) qc.cx(0,1) return qc qc = psiplus() qc.draw('mpl') # we draw the circuit qc.measure_all() # we measure all the qubits backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities #lets first construct the circuit for the GHZ state def GHZ(): circ = QuantumCircuit(3,3) circ.h(0) circ.cx(0,1) circ.cx(1,2) return circ circ = GHZ() circ.draw('mpl') # draw the circuit circ.measure_all() # measure all the qubits backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend counts = execute(circ, backend, shots = 2000).result().get_counts() # we run the simulation and get the counts plot_histogram(counts) # plot a histogram to see the possible outcomes and corresponding probabilities def GHZlike(): circ = QuantumCircuit(3,3) circ.h(0) circ.z(0) circ.x(1) circ.x(2) circ.cx(0,1) circ.cx(1,2) return circ circ = GHZlike() circ.draw('mpl') # draw the circuit circ.measure_all() # measure all the qubits backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend counts = execute(circ, backend, shots = 2000).result().get_counts() # we run the simulation and get the counts plot_histogram(counts) # plot a histogram to see the possible outcomes and corresponding probabilities def GHZlike(): circ = QuantumCircuit(3,3) circ.h(0) circ.z(0) circ.x(1) circ.x(2) circ.cx(0,1) circ.cx(1,2) return circ qc = GHZlike() qc.draw('mpl') # draw the circuit # Execute and get counts result = execute(qc, simulator).result() statevector = result.get_statevector(qc) plot_state_city(statevector, title='GHZ-like state') # Construct an empty quantum circuit which makes the first bell state qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) # Select the UnitarySimulator from the Aer provider simulator = Aer.get_backend('unitary_simulator') # Execute and get counts result = execute(qc, simulator).result() unitary = result.get_unitary(qc) print("Circuit unitary:\n", unitary)
https://github.com/sayana25/IQCQ-UPES-2023
sayana25
pip install qiskit # required imports: from qiskit.visualization import array_to_latex from qiskit.quantum_info import Statevector, random_statevector ket0 = [[1],[0]] #defining the ket |0> array_to_latex(ket0) ket1 = [[0],[1]] #defining the ket |1> array_to_latex(ket1) bra0 = [1,0] array_to_latex(bra0) bra1 = [0,1] array_to_latex(bra1) sv_bra0 = Statevector(bra0) sv_bra0 sv_bra1 = Statevector(bra1) sv_bra1 sv_ket1 = Statevector(ket1) sv_ket1 sv_ket0 = Statevector(ket0) sv_ket0 sv_eq = Statevector([1/2, 3/4, 4/5, 6/8]) sv_eq.draw('latex') sv_eq.is_valid() from qiskit.quantum_info.operators import Operator, Pauli op_bra0 = Operator(bra0) op_bra0 op_ket0 = Operator(ket0) op_bra0.tensor(op_ket0) pauli_x = Pauli('X') array_to_latex(pauli_x) pauli_y = Pauli('Y') array_to_latex(pauli_y) pauli_z = Pauli('Z') array_to_latex(pauli_z) import numpy as np test1 = np.dot(pauli_x,pauli_y) test2 = np.dot(pauli_y,pauli_x) array_to_latex(test1) array_to_latex(test1-test2) op_x = Operator(pauli_x) #operator representation of the Pauli X operator op_x op_y = Operator(pauli_y) #operator representation of the Pauli Y operator op_y op_z = Operator(pauli_z) #operator representation of the Pauli Y operator op_z op_new = np.dot(op_x,ket0) array_to_latex(op_new) op_new = np.dot(op_y,ket0) array_to_latex(op_new) op_new = np.dot(op_z,ket0) array_to_latex(op_new)
https://github.com/sayana25/IQCQ-UPES-2023
sayana25
pip install qiskit pip install qiskit-ibm-runtime !pip install pylatexenc !pip install matplotlib !pip install matplotlib-venn import qiskit from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister,execute,IBMQ, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_vector from math import sqrt, pi #qc = QuantumCircuit(1) # Create a quantum circuit with one qubit qc = QuantumCircuit(1) # Create a quantum circuit with one qubit initial_state = [0,1] # Define initial_state as |1> qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit qc.draw() # Let's view our circuit qc = QuantumCircuit(3,3) # Create a quantum circuit with 3 qubits, like in python qc.h(0) #hadamard gate qc.x(1) #Pauli-X gate qc.y(2) #Pauli-Y gate qc.draw() # Let's view our circuit qc = QuantumCircuit(3,3) # Create a quantum circuit with 3 qubits, like in python qc.h(0) #hadamard gate qc.x(1) #Pauli-X gate qc.y(2) #Pauli-Y gate qc.measure_all() # Let's view our circuit qc.draw('mpl') import qiskit from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister,execute,IBMQ, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_vector from math import sqrt, pi X = QuantumRegister(1, "Alice") #naming the qubit #naming the qubit circuit = QuantumCircuit(X) circuit.h(X) circuit.s(X) circuit.h(X) circuit.t(X) circuit.draw('mpl') from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister X = QuantumRegister(1, "x") Y = QuantumRegister(1, "y") A = ClassicalRegister(1, "a") B = ClassicalRegister(1, "b") circuit = QuantumCircuit(Y, X, B, A) circuit.h(Y) circuit.cx(Y, X) circuit.measure(Y, B) circuit.measure(X, A) display(circuit.draw('mpl')) qc = QuantumCircuit(4) qc.x(0) qc.y(1) # Qubit number inside the bracket, as in python the counting starts from 0 qc.z(2) qc.barrier qc.y(0) qc.z(0) qc.draw('mpl') bell = QuantumCircuit(2) bell.h(0) # apply an H gate to the circuit bell.cx(0,1) # apply a CNOT gate to the circuit bell.draw(output="mpl") import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram def bitflip(): qc = QuantumCircuit(1) qc.x(0) return qc state = Statevector.from_instruction(bitflip()) plot_bloch_multivector(state) def superposition(): qc = QuantumCircuit(1) qc.h(0) return qc state = Statevector.from_instruction(superposition()) plot_bloch_multivector(state) def antisuperposition(): qc = QuantumCircuit(1) qc.h(0) qc.z(0) #phase flip return qc state = Statevector.from_instruction(antisuperposition()) plot_bloch_multivector(state) def complex(): qc = QuantumCircuit(1) qc.h(0) qc.sdg(0) return qc state = Statevector.from_instruction(complex()) plot_bloch_multivector(state)
https://github.com/sayana25/IQCQ-UPES-2023
sayana25
import cirq import numpy as np from qiskit import QuantumCircuit, execute, Aer import seaborn as sns import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (15,10) q0, q1, q2 = [cirq.LineQubit(i) for i in range(3)] circuit = cirq.Circuit() #entagling the 2 quibits in different laboratories #and preparing the qubit to send circuit.append(cirq.H(q0)) circuit.append(cirq.H(q1)) circuit.append(cirq.CNOT(q1, q2)) #entangling the qubit we want to send to the one in the first laboratory circuit.append(cirq.CNOT(q0, q1)) circuit.append(cirq.H(q0)) #measurements circuit.append(cirq.measure(q0, q1)) #last transformations to obtain the qubit information circuit.append(cirq.CNOT(q1, q2)) circuit.append(cirq.CZ(q0, q2)) #measure of the qubit in the receiving laboratory along z axis circuit.append(cirq.measure(q2, key = 'Z')) circuit #starting simulation sim = cirq.Simulator() results = sim.run(circuit, repetitions=100) sns.histplot(results.measurements['Z'], discrete = True) 100 - np.count_nonzero(results.measurements['Z']), np.count_nonzero(results.measurements['Z']) #in qiskit the qubits are integrated in the circuit qc = QuantumCircuit(3, 1) #entangling qc.h(0) qc.h(1) qc.cx(1, 2) qc.cx(0, 1) #setting for measurment qc.h(0) qc.measure([0,1], [0,0]) #transformation to obtain qubit sent qc.cx(1, 2) qc.cz(0, 2) qc.measure(2, 0) print(qc) #simulation simulator = Aer.get_backend('qasm_simulator') job = execute(qc, simulator, shots=100) res = job.result().get_counts(qc) plt.bar(res.keys(), res.values()) res
https://github.com/yonahirakawa/qiskit-iniciantes
yonahirakawa
from qiskit.visualization import plot_bloch_vector plot_bloch_vector([1,0,0], title="Esfera de Bloch") from qiskit.visualization import plot_bloch_vector, bloch from matplotlib.pyplot import text from math import pi, cos, sin from qutip import * # angles that represent our state theta = pi/2 phi = 4*pi/3 # calculating the coordinates x = sin(theta)*cos(phi) y = sin(theta)*sin(phi) z = cos(theta) # preparing the sphere sphere = bloch sphere.Bloch b = Bloch() # preparing the lables b.ylpos = [1.1, -1.2] b.xlabel = ['$\\left|0\\right>+\\left|1\\right>$', '$\\left|0\\right>-\\left|1\\right>$'] b.ylabel = ['$\\left|0\\right>+i\\left|1\\right>$', '$\\left|0\\right>-i\\left|1\\right>$'] # first 6 drawn vectors will be blue, the 7th - red b.vector_color = ['b','b','b','b','b','b','r'] # drawing vectors of orthogonal states (most popular bases), note the coordinates of vectors, # they correspond to the according states. b.add_vectors([[0,0,1],[0,0,-1],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0]]) # drawing our state (as 7th vector) b.add_vectors([x,y,z]) # showing the Bloch sphere with all that we have prepared b.show()
https://github.com/yonahirakawa/qiskit-iniciantes
yonahirakawa
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer q = QuantumRegister(2,'q') c = ClassicalRegister(2,'c') def primeiroEstadoBell(): circuito = QuantumCircuit(q,c) circuito.h(q[0]) circuito.cx(q[0],q[1]) circuito.measure(q,c) display(circuito.draw(output='mpl')) job = execute(circuito, Aer.get_backend('qasm_simulator'), shots=8192) counts = job.result().get_counts(circuito) print(counts) def segundoEstadoBell(): circuito = QuantumCircuit(q,c) circuito.x(q[0]) circuito.h(q[0]) circuito.cx(q[0],q[1]) circuito.measure(q,c) display(circuito.draw(output='mpl')) job = execute(circuito, Aer.get_backend('qasm_simulator'), shots=8192) counts = job.result().get_counts(circuito) print(counts) def terceiroEstadoBell(): circuito = QuantumCircuit(q,c) circuito.x(q[1]) circuito.h(q[0]) circuito.cx(q[0],q[1]) circuito.measure(q,c) display(circuito.draw(output='mpl')) job = execute(circuito, Aer.get_backend('qasm_simulator'), shots=8192) counts = job.result().get_counts(circuito) print(counts) def quartoEstadoBell(): circuito = QuantumCircuit(q,c) circuito.x(q[1]) circuito.h(q[0]) circuito.z(q[0]) circuito.z(q[1]) circuito.cx(q[0],q[1]) circuito.measure(q,c) display(circuito.draw(output='mpl')) job = execute(circuito, Aer.get_backend('qasm_simulator'), shots=8192) counts = job.result().get_counts(circuito) print(counts) print("Criando primeiro estado de Bell:\n") primeiroEstadoBell() print("\nCriando segundo estado de Bell:\n") segundoEstadoBell() print("\nCriando terceiro estado de Bell:\n") terceiroEstadoBell() print("\nCriando quarto estado de Bell:\n") quartoEstadoBell()
https://github.com/yonahirakawa/qiskit-iniciantes
yonahirakawa
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qc = QuantumCircuit(1) qc.x(0) qc.draw(output='mpl') qc1 = QuantumCircuit(1) qc1.y(0) qc1.draw(output='mpl') qc2 = QuantumCircuit(1) qc2.z(0) qc2.draw(output='mpl') qc3 = QuantumCircuit(1) qc3.h(0) qc3.draw(output='mpl') from cmath import pi # Para aplicar este operador, precisamos especificar o Γ’ngulo para o qubit # Aqui vamos considerar a = 2*pi qc4 = QuantumCircuit(1) qc4.ry(2*pi,0) qc4.draw(output='mpl') qc5 = QuantumCircuit(2) qc5.cx(0,1) qc5.draw(output='mpl')
https://github.com/yonahirakawa/qiskit-iniciantes
yonahirakawa
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister q = QuantumRegister(1,"q0") c = ClassicalRegister(1,"c0") # Definindo nosso circuito quΓ’ntico qc = QuantumCircuit(q,c) # Aplicando o operador NOT, representado por um "x" qc.x(q[0]) # Fazendo a mediΓ§Γ£o do nosso cirtuito quΓ’ntico qc.measure(q[0],c[0]) print("Nosso circuito estΓ‘ pronto!") # Desenharemos nosso circuito utilizando o "draw" qc.draw() # Podemos melhorar essa visualizaΓ§Γ£o usando o matplotlib qc.draw(output='mpl') from qiskit import execute, Aer # TrΓͺs parΓ’metros # 1. mycircuit # 2. estrutura onde serΓ‘ executado: usaremos um simulador local # 3. quantas vezes serΓ‘ executado, por padrΓ£o Γ© 1024 job = execute(qc, Aer.get_backend('qasm_simulator'), shots=1024) counts = job.result().get_counts(qc) print(counts) from qiskit.visualization import plot_histogram plot_histogram(counts) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister q1 = QuantumRegister(1,"q1") c1 = ClassicalRegister(1,"c1") qc1 = QuantumCircuit(q1,c1) # Aplicando o operador Hadamard, representado por um "h" qc1.h(q1[0]) qc1.measure(q1[0],c1[0]) qc1.draw(output='mpl') job = execute(qc1, Aer.get_backend('qasm_simulator'), shots=10000) counts = job.result().get_counts(qc1) print(counts) print() n_zeros = counts['0'] n_ones = counts['1'] print("Estado 0 Γ© observado com uma frequΓͺncia %",100*n_zeros/(n_zeros+n_ones)) print("Estado 1 Γ© observado com uma frequΓͺncia %",100*n_ones/(n_zeros+n_ones)) print() plot_histogram(counts) q2 = QuantumRegister(2,"q") c2 = ClassicalRegister(2,"c") qc2 = QuantumCircuit(q2,c2) qc2.h(0) qc2.h(1) qc2.measure(0,0) qc2.measure(1,1) qc2.draw(output='mpl') job = execute(qc2,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(qc2) print(counts) print() plot_histogram(counts) q3 = QuantumRegister(4,"q") c3 = ClassicalRegister(4,"c") qc3 = QuantumCircuit(q3,c3) # aplicando x-gate ao primeiro qubit duas vezes qc3.x(q3[0]) qc3.x(q3[0]) # aplicando x-gate ao quarto qubit uma vez qc3.x(q3[3]) # aplicando x-gate ao terceiro qubit quatro vezes qc3.x(q3[2]) qc3.x(q3[2]) qc3.x(q3[2]) # aplicando x-gate ao segundo qubit quatro vezes qc3.x(q3[1]) qc3.x(q3[1]) qc3.x(q3[1]) qc3.x(q3[1]) # definindo uma barreira para uma melhor visualizaΓ§Γ£o qc3.barrier() # se o tamanho dos registradores quΓ’nticos e clΓ‘ssicos sΓ£o iguais, nΓ³s podemos definir mediΓ§Γ΅es em uma ΓΊnica linha de cΓ³digo qc3.measure(q3,c3) # os qubits e os bits clΓ‘ssicos sΓ£o associados de acordo com seus respectivos Γ­ndices qc3.draw(output='mpl') job = execute(qc3,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc3) print(counts) q4 = QuantumRegister(1,"qreg") c4 = ClassicalRegister(1,"creg") qc4 = QuantumCircuit(q4,c4) qc4.x(q4[0]) qc4.h(q4[0]) qc4.measure(q4,c4) qc4.draw(output='mpl') job = execute(qc4,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc4) print(counts) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # Por ser um circuito com 2 qubits, sabemos que todos os estados possΓ­veis sΓ£o dados por: todos_estados = ['00','01','10','11'] for estado in todos_estados: q = QuantumRegister(2,"q") c = ClassicalRegister(2,"c") qc = QuantumCircuit(q,c) # inicializando os inputs com respeito a ordem de leitura do Qiskit if estado[0]=='1': qc.x(q[0]) # configurando o estado do qubit 0 para |1> if estado[1]=='1': qc.x(q[1]) # configurando o estado do qubit 1 para |1> # aplicando o h-gate nos dois qubits qc.h(q[0]) qc.h(q[1]) # aplicando o cx(qubit 0,qubit 1) qc.cx(q[0],q[1]) # aplicando h-gate nos dois qubits qc.h(q[0]) qc.h(q[1]) # medindo ambos os qubits qc.barrier() qc.measure(q,c) display(qc.draw(output='mpl')) # execute the circuit 100 times in the local simulator job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc) print(estado,"Γ© mapeado para",counts) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer q_a = QuantumRegister(3, name='qa') q_b = QuantumRegister(5, name='qb') c_a = ClassicalRegister(3) c_b = ClassicalRegister(5) circuit = QuantumCircuit(q_a, q_b, c_a, c_b) circuit.x(q_a[1]) circuit.x(q_b[1]) circuit.x(q_b[2]) circuit.x(q_b[4]) circuit.barrier() circuit.h(q_a) circuit.barrier(q_a) circuit.h(q_b) circuit.cswap(q_b[0], q_b[1], q_b[2]) circuit.cswap(q_b[2], q_b[3], q_b[4]) circuit.cswap(q_b[3], q_b[4], q_b[0]) circuit.barrier(q_b) circuit.measure(q_a, c_a) circuit.measure(q_b, c_b) # Matplotlib Drawing circuit.draw(output='mpl')
https://github.com/vindem/quantumMD
vindem
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, transpile from VectorPreprocessor import VectorPreprocessor import numpy as np class CSWAPCircuit: def __init__(self, aux, qr1n, qr2n, crn, backend, shots): self._aux = aux self._qr1n = qr1n self._qr2n = qr2n self._crn = crn self._backend = backend self._shots = shots def _init_cswap_circuit(self, a, b, norm): q1 = QuantumRegister(self._aux, name='control_0') q2 = QuantumRegister(self._qr1n, name='qr_1') q3 = QuantumRegister(self._qr2n, name='qr_2') c = ClassicalRegister(self._crn, name='c') qc = QuantumCircuit(q1,q2,q3,c) qc.initialize(a, q2[0:self._qr1n]) qc.initialize(b, q3[0:self._qr2n]) qc.barrier() qc.h(q1[0]) qc.cswap(q1[0], q2[0], q3[0]) qc.h(q1[0]) qc.barrier() qc.measure(q1, c) job = execute(qc, self._backend, shots=self._shots, optimization_level=1) result = job.result() countsqd = result.get_counts(qc) qdsquared = abs((4 * norm ** 2 * ((countsqd['0'] / self._shots) - 0.5))) qd = np.sqrt(qdsquared) return qd def execute_swap_test(self, A, B): vector_preprocessor = VectorPreprocessor(A,B) return [self._init_cswap_circuit(vector_preprocessor.phi_reg()[i], vector_preprocessor.psi_reg()[i], vector_preprocessor.norm_factor()[i]) for i in range(len(vector_preprocessor.psi_reg()))]
https://github.com/vindem/quantumMD
vindem
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/vindem/quantumMD
vindem
from qiskit.circuit.library import RealAmplitudes, EfficientSU2 efficientSU2 = EfficientSU2(1, reps=1, entanglement='linear', insert_barriers=True) realAmplitudes = RealAmplitudes(1,reps=1) efficientSU2.draw(output='text') realAmplitudes.draw(output='text') import numpy as np rdist = np.random.rand(1, 1) rdistt = np.transpose(rdist) z1 = np.zeros((1, 1)) z2 = np.zeros((1, 1)) matrix = np.block([[z1, rdist], [rdistt, z2]]) from qiskit import IBMQ from qiskit.providers.ibmq import least_busy from qiskit.providers import JobStatus IBMQ.load_account() provider = IBMQ.get_provider('ibm-q-research-2','vienna-uni-tech-1','main') backend = least_busy( provider.backends( filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational and x.configuration().dynamic_reprate_enabled ) ) print(backend.name()) from qiskit.algorithms.optimizers import COBYLA from qiskit.opflow.primitive_ops import MatrixOp import time matrix_op = MatrixOp(matrix) vqe_inputs = { 'ansatz': realAmplitudes, 'operator': matrix_op, 'optimizer': COBYLA(max_iter=100, tol=0.00001), 'initial_point': np.random.random(realAmplitudes.num_parameters), 'measurement_error_mitigation': True, 'shots': 1024 } options = { 'backend_name': backend.name(), } job = provider.runtime.run(program_id='vqe', inputs=vqe_inputs, options=options) while job.status() != JobStatus.RUNNING: pass start = time.time() res = job.result() end = time.time() print("Runtime: "+str(end-start)) from qiskit.algorithms.optimizers import COBYLA from qiskit.opflow.primitive_ops import MatrixOp import time matrix_op = MatrixOp(matrix) vqe_inputs = { 'ansatz': efficientSU2, 'operator': matrix_op, 'optimizer': COBYLA(max_iter=100, tol=0.00001), 'initial_point': np.random.random(efficientSU2.num_parameters), 'measurement_error_mitigation': True, 'shots': 1024 } options = { 'backend_name': backend.name(), } job = provider.runtime.run(program_id='vqe', inputs=vqe_inputs, options=options) while job.status() != JobStatus.RUNNING: pass start = time.time() res = job.result() end = time.time() print("Runtime: "+str(end-start))
https://github.com/vindem/quantumMD
vindem
from qiskit import IBMQ, Aer from qiskit.aqua import QuantumInstance from qiskit.providers.aer.noise import NoiseModel from qiskit.ignis.mitigation.measurement import CompleteMeasFitter #Loading data about our backend quantum architecture IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend_sim = Aer.get_backend("qasm_simulator") backend_real = provider.get_backend("ibmq_lima") coupling_map = backend_real.configuration().coupling_map # Extracting noise model for error mitigation noise_model = NoiseModel.from_backend(backend_real) # Initializing quantum instance with error mitigation based on noise model of backend_real quantum_instance = QuantumInstance(backend=backend_sim, shots=20000, noise_model=noise_model, coupling_map=coupling_map, measurement_error_mitigation_cls=CompleteMeasFitter, cals_matrix_refresh_period=30) from qiskit.aqua.components.optimizers import COBYLA optimizer = COBYLA(maxiter=5000, tol=0.0001) from qiskit.aqua.operators import MatrixOperator, op_converter import numpy as np #Initialization of a 2x2 matrix in the same shape as MD program dimensions = 2 rdist = np.random.rand(dimensions,dimensions) rdist[0][0] = 1.0 rdist[0][1] = 2.0 rdist[1][0] = 1.0 rdist[1][1] = 3.0 rdistt = np.transpose(rdist) z1 = np.zeros((dimensions,dimensions)) z2 = np.zeros((dimensions,dimensions)) in_matrix = np.block([[z1,rdist],[rdistt,z2]]) #Converting matrix into operator hamiltonian = MatrixOperator(in_matrix) hamiltonian_qubit_op = op_converter.to_weighted_pauli_operator(hamiltonian) from qiskit.circuit.library import RealAmplitudes best_ansatz_ever = RealAmplitudes(2,reps=2) best_ansatz_ever.draw(output='text') from qiskit.aqua.algorithms import VQE vqe = VQE(operator=hamiltonian_qubit_op,var_form=best_ansatz_ever,quantum_instance=quantum_instance, optimizer=optimizer) vqe_result = np.real(vqe.run(backend_sim)['eigenvalue']) print(vqe_result) import math import scipy.linalg as lin_alg #storing values of, respectively, classic and quantum eigenvalues classic = [] quantum = [] for i in range(1,100): #Initializing random matrix rdist = np.random.rand(dimensions,dimensions) rdistt = np.transpose(rdist) z1 = np.zeros((dimensions,dimensions)) z2 = np.zeros((dimensions,dimensions)) in_matrix = np.block([[z1,rdist],[rdistt,z2]]) #Conversion of matrix into operator hamiltonian = MatrixOperator(in_matrix) hamiltonian_qubit_op = op_converter.to_weighted_pauli_operator(hamiltonian) #Calculation of Quantum eigenvalue vqe = VQE(operator=hamiltonian_qubit_op,var_form=best_ansatz_ever,quantum_instance=quantum_instance, optimizer=optimizer) vqe_result = np.real(vqe.run(backend_sim)['eigenvalue']) #Calculation of Classic eigenvalue classic_result = lin_alg.eigvalsh(in_matrix)[0] #Storing eigenvalues of current matrix classic.append(classic_result) quantum.append(vqe_result) #Calculating mean square error, root mean square error, root mean square error MSE = np.square(np.subtract(classic,quantum)).mean() RMSE = math.sqrt(MSE) print("RMSE: "+str(RMSE)) format_rmse = "{:.4f}".format((RMSE/(max(classic)-min(classic)))*100.0) print("NRMSE: "+format_rmse+ "%")
https://github.com/vindem/quantumMD
vindem
from qiskit.algorithms.minimum_eigen_solvers import VQE import numpy as np from qiskit.opflow import MatrixOp from CSWAPCircuit import CSWAPCircuit from qiskit.providers import JobStatus from qiskit import IBMQ import time from qiskit import IBMQ, Aer from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options from qiskit.primitives import Estimator from qiskit.providers.aer.noise import NoiseModel from qiskit_aqt_provider import AQTProvider from qiskit_aqt_provider.primitives import AQTEstimator from qiskit.quantum_info import Operator from scipy.optimize import minimize from config import Config from qiskit.algorithms.optimizers import COBYLA import math from qiskit.transpiler import PassManager from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime.transpiler.passes.scheduling import ALAPScheduleAnalysis, PadDynamicalDecoupling from qiskit.circuit.library import XGate from qiskit.circuit.library import * from JobPersistenceManager import JobPersistenceManager callback_dict = { "prev_vector": None, "iters": 0, "cost_history": [], } def setup_backend_for_task(task_name): task_setup = Config.execution_setup['execution_setup'][task_name][0] match task_setup['provider']: case 'Aer': return Aer.get_backend('aer_simulator') case 'AQT': provider = AQTProvider(task_setup['token']) backend = provider.get_backend(name=task_setup['name']) return backend case 'IBM': IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-research-2', group='vienna-uni-tech-1', project='main') backend = provider.get_backend(name=task_setup['name']) return backend case _: raise Exception("Unknown Provider!") def build_callback(ansatz, hamiltonian, estimator, callback_dict): """Return callback function that uses Estimator instance, and stores intermediate values into a dictionary. Parameters: ansatz (QuantumCircuit): Parameterized ansatz circuit hamiltonian (SparsePauliOp): Operator representation of Hamiltonian estimator (Estimator): Estimator primitive instance callback_dict (dict): Mutable dict for storing values Returns: Callable: Callback function object """ def callback(current_vector): """Callback function storing previous solution vector, computing the intermediate cost value, and displaying number of completed iterations and average time per iteration. Values are stored in pre-defined 'callback_dict' dictionary. Parameters: current_vector (ndarray): Current vector of parameters returned by optimizer """ # Keep track of the number of iterations callback_dict["iters"] += 1 # Set the prev_vector to the latest one callback_dict["prev_vector"] = current_vector # Compute the value of the cost function at the current vector # This adds an additional function evaluation current_cost = ( estimator.run(ansatz, hamiltonian, parameter_values=current_vector).result().values[0] ) callback_dict["cost_history"].append(current_cost) # Print to screen on single line print( "Iters. done: {} [Current cost: {}]".format(callback_dict["iters"], current_cost), end="\r", flush=True, ) return callback def calculate_distance_quantum(A, B): print("Starting SWAPTEST.") distance_configuration = Config.execution_setup['execution_setup']['dist_calc'][0] print("Target machine: "+distance_configuration['name']+ ", " + distance_configuration['type']) #IBMQ.load_account() #provider = IBMQ.get_provider(hub='ibm-q-research-2', group='vienna-uni-tech-1', project='main') #backend = Aer.get_backend('aer_simulator') #noise_model = NoiseModel.from_backend(provider.backend.ibmq_quito) #backend = provider.get_backend("ibex", workspace="hpqc") backend = setup_backend_for_task('dist_calc') cswap_circuit = CSWAPCircuit(backend, 200) quantum_ED = cswap_circuit.execute_swap_test(A, B) arr = np.array(quantum_ED) #print(arr.shape) return arr def calc_eigval_quantum(bpm, filename): print("Starting VQE.") eigenvalue_configuration = Config.execution_setup['execution_setup']['eigenvalues'][0] print("Target machine: " + eigenvalue_configuration['name'] + ", " + eigenvalue_configuration['type']) qubit_op = Operator(-bpm) #backend = Aer.get_backend('aer_simulator') backend = setup_backend_for_task('eigenvalues') #vqe = VQE(qubit_op, variational_form, optimizer=optimizer) def cost_function(params, ansatz, hamiltonian, estimator): try: if eigenvalue_configuration['persistence']: persistence_manager = JobPersistenceManager() job = estimator.run(ansatz, hamiltonian, parameter_values=params) if eigenvalue_configuration['persistence']: persistence_manager.add_id(job.job_id()) result = job.result() except TimeoutError: if eigenvalue_configuration['persistence']: job_ids = persistence_manager.active_jobs() for job_id in job_ids: restored_job = AQTJob.restore(job_id, access_token=eigenvalue_configuration['token']) result = restored_job.result() energy = result.values[0] return energy improved_ansatz = globals()[eigenvalue_configuration['ansatz']](int(math.log2(bpm.shape[0]))) num_params = improved_ansatz.num_parameters #x0 = - (np.max(qubit_op) - np.min(qubit_op)) * np.random.random(num_params) * 10.0 #x0 = np.max(np.real(qubit_op)) * np.random.random(num_params) x0 = [0] * num_params #x0 = np.random.random(num_params) #print("x0" + str(x0)) options = Options() #options.transpilation.skip_transpilation = True options.execution.shots = 200 options.optimization_level = 3 options.resilience_level = 3 #estimator = Estimator(options=options) #callback = build_callback(improved_ansatz, qubit_op, estimator, callback_dict) if eigenvalue_configuration['provider'] == 'AQT': from qiskit_aqt_provider.aqt_job import AQTJob estimator = AQTEstimator(backend=backend) elif eigenvalue_configuration['provider'] == 'IBM': estimator = Estimator(options={"optimization_level":3, "resilience_level": 3}) else: estimator = Estimator(options={"optimization_level": 3, "resilience_level": 3}) start = time.time() res = minimize( cost_function, x0, args=(improved_ansatz, qubit_op, estimator), method=eigenvalue_configuration['optimizer'], options={"maxiter": eigenvalue_configuration['opt_iters'], "tol":0.1} ) end = time.time() #print("FINAL: "+ str(np.real(-res.fun))) return [-(np.real(res.fun)), end - start]
https://github.com/vindem/quantumMD
vindem
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/vindem/quantumMD
vindem
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, transpile from VectorPreprocessor import VectorPreprocessor import numpy as np class CSWAPCircuit: def __init__(self, aux, qr1n, qr2n, crn, backend, shots): self._aux = aux self._qr1n = qr1n self._qr2n = qr2n self._crn = crn self._backend = backend self._shots = shots def _init_cswap_circuit(self, a, b, norm): q1 = QuantumRegister(self._aux, name='control_0') q2 = QuantumRegister(self._qr1n, name='qr_1') q3 = QuantumRegister(self._qr2n, name='qr_2') c = ClassicalRegister(self._crn, name='c') qc = QuantumCircuit(q1,q2,q3,c) qc.initialize(a, q2[0:self._qr1n]) qc.initialize(b, q3[0:self._qr2n]) qc.barrier() qc.h(q1[0]) qc.cswap(q1[0], q2[0], q3[0]) qc.h(q1[0]) qc.barrier() qc.measure(q1, c) job = execute(qc, self._backend, shots=self._shots, optimization_level=1) result = job.result() countsqd = result.get_counts(qc) qdsquared = abs((4 * norm ** 2 * ((countsqd['0'] / self._shots) - 0.5))) qd = np.sqrt(qdsquared) return qd def execute_swap_test(self, A, B): vector_preprocessor = VectorPreprocessor(A,B) return [self._init_cswap_circuit(vector_preprocessor.phi_reg()[i], vector_preprocessor.psi_reg()[i], vector_preprocessor.norm_factor()[i]) for i in range(len(vector_preprocessor.psi_reg()))]
https://github.com/vindem/quantumMD
vindem
from qiskit import IBMQ, Aer from CSWAPCircuit import CSWAPCircuit import random from scipy.spatial import distance from sklearn.metrics import mean_squared_error random.seed(42) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-research-2', group='vienna-uni-tech-1', project='main') backend_sim = provider.backend.ibmq_qasm_simulator def generate_random_vector(n_points): vec = [] for i in range(n_points): vec.append([random.uniform(0, 1) for j in range(3)]) return vec backend = Aer.get_backend('qasm_simulator') for num_qubits in range(0,5): quantum_distances = [] classic_distances = [] for i in range(10): A = generate_random_vector(2**num_qubits) B = generate_random_vector(2**num_qubits) cswap_circuit = CSWAPCircuit(1, 1, 3, 1, backend_sim, 8192) quantum_ED = cswap_circuit.execute_swap_test(A, B) classic_ED = [distance.euclidean(A[i], B[i]) for i in range(len(A))] quantum_distances.append(quantum_ED) classic_distances.append(classic_ED) mse = mean_squared_error(quantum_distances, classic_distances) print(mse)
https://github.com/vindem/quantumMD
vindem
import timeit from qiskit.circuit.library import EfficientSU2 from qiskit import IBMQ from qiskit.algorithms.optimizers import GradientDescent, COBYLA import numpy as np from qiskit.opflow import MatrixOp from qiskit.algorithms import VQE from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.test.mock import FakeJakarta, FakeManila, FakeLagos, FakeSantiago from qiskit import Aer from qiskit.utils import QuantumInstance from matplotlib import pyplot as plt import scipy.linalg as lin_alg from qiskit.utils.mitigation import CompleteMeasFitter import csv from sklearn.metrics import mean_squared_error, mean_absolute_error import math from main import generate_random_matrices, generate_ansaetze IBMQ.load_account() provider = IBMQ.get_provider('ibm-q-research-2', 'vienna-uni-tech-1', 'main') exponents = range(0,5) reps = range(1,6) #target_backend = [FakeJakarta(), FakeManila(), FakeSantiago(), FakeLagos()] target_backend = [FakeJakarta()] backend_sim = Aer.get_backend('aer_simulator') for num_reps in reps: for e in exponents: num_qubits = e + 1 matrices = generate_random_matrices(2 ** e, 2 ** e, 0, 10) ansaetze = generate_ansaetze(num_qubits, num_reps, 'circular') row = [] for a in ansaetze: row.append(a.__class__.__name__ + '-RT') row.append(a.__class__.__name__ + '-EIG') row.append("Classic-EIG") for backend in target_backend: print(backend.name()) vqe_times = [] vqe_res = [] classic_result = [] summary_fname = "VQE_" + backend.name() + '_' + str(num_qubits) + '_' + str(num_reps) + '_rt-nrmse.csv' rawdata_fname = "VQE_" + backend.name() + '_' + str(num_qubits) + '_' + str(num_reps) + '_raw-data.csv' summary = open(summary_fname, 'w') rawdata = open(rawdata_fname, 'w') summary_writer = csv.writer(summary) rawdata_writer = csv.writer(rawdata) results = {} results = dict.fromkeys(row) for r in row: results[r] = [] summary_writer.writerow(["PQC","AVG-RUNTIME", "MAE", "MSE", "RMSE", "NRMSE"]) rawdata_writer.writerow(row) noise_model = NoiseModel.from_backend(QasmSimulator.from_backend(backend)) quantum_instance = QuantumInstance(backend=backend_sim, noise_model=noise_model, measurement_error_mitigation_cls=CompleteMeasFitter) optimizer = COBYLA(maxiter=100) for matrix in matrices: # matrix_op = pauli_representation(matrix) operator = MatrixOp(matrix) results["Classic-EIG"].append(lin_alg.eigvalsh(matrix)[0]) for ansatz in ansaetze: initial_point = np.random.random(ansatz.num_parameters) local_vqe = VQE(ansatz=ansatz, optimizer=optimizer, initial_point=initial_point, quantum_instance=quantum_instance) key_rt = ansatz.__class__.__name__ + "-RT" key_eig = ansatz.__class__.__name__ + "-EIG" start = timeit.timeit() mde_eig_result = local_vqe.compute_minimum_eigenvalue(operator) end = timeit.timeit() eig = np.real(mde_eig_result.eigenvalue) rt = end - start results[key_eig].append(eig) results[key_rt].append(rt) row_results = [] for r in row: row_results.append(str(results[r][-1])) rawdata_writer.writerow(row_results) print(backend.name()) print("PQC \t RUNTIME \t MAE \t MSE \t RMSE \t NRMSE") for a in ansaetze: rt = a.__class__.__name__ + '-RT' avg_time = sum(results[rt]) / len(results[rt]) eig = a.__class__.__name__ + '-EIG' eig_mae = mean_absolute_error(results["Classic-EIG"], results[eig]) eig_mse = mean_squared_error(results["Classic-EIG"], results[eig]) eig_rmse = math.sqrt(mean_squared_error(results["Classic-EIG"], results[eig])) eig_nrmse = eig_rmse / (max(results["Classic-EIG"]) - min(results["Classic-EIG"])) print(a.__class__.__name__ + " \t" + str(avg_time) + "\t" + str(eig_mae) + "\t" + str(eig_mse) + "\t" + str(eig_rmse) + "\t" + str(eig_nrmse)) summary_writer.writerow( [a.__class__.__name__, str(avg_time), str(eig_mae), str(eig_mse), str(eig_rmse), str(eig_nrmse)]) summary.close() rawdata.close()
https://github.com/vindem/quantumMD
vindem
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/xtophe388/QISKIT
xtophe388
# This cell does some preparatory work to set QISKit up on the IBM Data Science Experience. # -------------------------------------------------------------------------------------------------- # IMPORTANT NOTES: # 1) Your QX API token can be found in the *Advanced* section of the *My Account* page of the QX. # Copy-Paste it into the QX_API_TOKEN variable below. BE SURE TO ENCLOSE IN QUOTES ("") # 2) If you are sharing any notebooks, MAKE SURE TO REMOVE the API token string before sharing! # 3) This both creates an IBMQE_API environment variable as well as a Qconfig.py file for connecting # to IBM QX. # -------------------------------------------------------------------------------------------------- import os, sys os.environ["IBMQE_API"] = "PUT_YOUR_API_TOKEN_HERE" # DO NOT CHANGE THE FOLLOWING assertions assert os.environ["IBMQE_API"] != "PUT_YOUR_API_TOKEN_HERE", "QX_API_TOKEN not updated!" # Install qiskit !pip install qiskit # Create Qconfig.py for connecting to QX import importlib import urllib.request home_dir = os.path.expanduser('~') qconfig_filepath = os.path.join(home_dir, 'Qconfig.py') qconfig_template_path = "https://raw.githubusercontent.com/QISKit/qiskit-tutorial/master/Qconfig.py.template" # We need visibility to Qconfig.py module. Add home dir in your sys.path just to be sure. if home_dir not in sys.path: sys.path.append(home_dir) # First check if the Qconfig module has already been loaded (may happen if you are executing this cell more than once) if 'Qconfig' in sys.modules: # The module has been imported already. Reload it to make sure we get the latest API token try: importlib.reload(Qconfig) Qconfig.update_token(os.environ["IBMQE_API"]) except AttributeError: print("Qconfig reload failed. This could be due to missing Qconfig.py file.") print("Try restarting the Jupyter notebook kernel!") raise except AssertionError: print("Have you set a valid APItoken?") raise except: print("Qconfig reload or API token update failed.") print("Try updating the token and restarting the Jupyter notebook kernel") raise else: # Try importing Qconfig module. If it doesn't exist, then download it from the qiskit-tutorials repo. try: import Qconfig except ImportError: urllib.request.urlretrieve ("{}".format(qconfig_template_path), "{}".format(qconfig_filepath)) # chmod the file. For Python 3, need to prefix the permission with 0o (zero and character small oh) os.chmod(qconfig_filepath , 0o664) import Qconfig except: print("Unexpected error!") raise # Trivial program to test if the QISKit setup was sucessful. from qiskit import * qp = QuantumProgram() qp.set_api(Qconfig.APItoken, Qconfig.config['url']) # Create a 2-qubit Quantum Register, "qr" qr = qp.create_quantum_register("qr", 2) # Create a Classical Register, "cr", with 2 bits cr = qp.create_classical_register("cr", 2) # Create the circuit qc = qp.create_circuit('Bell', [qr], [cr]) # add measure to see the state qc.measure(qr, cr) result = qp.execute('Bell', backend='ibmqx_qasm_simulator', shots=1, seed=88) # Show the results print(result) # Create IBMQE_API environment variable - remember to remove token if sharing any notebooks import os, sys os.environ["IBMQE_API"] = "PUT_YOUR_API_TOKEN_HERE" assert os.environ["IBMQE_API"] != "PUT_YOUR_API_TOKEN_HERE", "QX_API_TOKEN not updated!" assert sys.version_info[0:2] >= (3, 5) , "This code requires Python 3.5 or beyond!" # Add path to and import QConfig.py home_dir = os.path.expanduser('~') qconfig_filepath = os.path.join(home_dir, 'Qconfig.py') if home_dir not in sys.path: sys.path.append(home_dir) import Qconfig # NOTE: # If you ever change the value of environment variable os.environ["IBMQE_API"] AFTER executing this cell, # you can call the following code to update its value. # Qconfig.update_token(os.environ["IBMQE_API"]) # Or just set it as : Qconfig.APItoken = os.environ["IBMQE_API"]
https://github.com/xtophe388/QISKIT
xtophe388
import os import sys from IPython.display import Image from qiskit import QuantumProgram from qiskit.tools.visualization import plot_histogram def show_image(img_name): """Display an image in the notebook. This is set to the default path of the root of the tutorials repo images directory in the sub-folder 'intro_img'. Args: img_name (str): file name to display """ return Image(filename=os.path.join("..", "images", "intro_img", img_name)) def execute_and_plot(qp, circuits): """Execute and plot the histograms with default settings. Args: qp: QuantumProgram containing the circuits circuits (list): list of circuits to execute """ results = qp.execute(circuits) for circuit in circuits: print(circuit) plot_histogram(results.get_counts(circuit)) qp = QuantumProgram() n = 1 # number of qubits q = qp.create_quantum_register("q", n) c = qp.create_classical_register("c", n) show_image("single_q_x_gate.png") single_x = qp.create_circuit("single_x", [q], [c]) single_x.x(q[0]) single_x.measure(q[0], c[0]) execute_and_plot(qp, ["single_x"]) show_image("single_q_h_gate_0.png") single_h = qp.create_circuit("single_h", [q], [c]) single_h.h(q[0]) single_h.measure(q[0], c[0]) execute_and_plot(qp, ["single_h"]) show_image("single_q_h_gate_1.png") single_xh = qp.create_circuit("single_xh", [q], [c]) single_xh.x(q[0]) single_xh.h(q[0]) single_xh.measure(q[0], c[0]) execute_and_plot(qp, ["single_xh"]) show_image("single_q_h_gate_2.png") # This is the |+> state single_hh = qp.create_circuit("single_hh", [q], [c]) single_hh.h(q[0]) single_hh.h(q[0]) single_hh.measure(q[0], c[0]) execute_and_plot(qp, ["single_hh"]) show_image("single_q_h_gate_3.png") # This is the |-> state single_xhh = qp.create_circuit("single_xhh", [q], [c]) single_xhh.x(q[0]) single_xhh.h(q[0]) single_xhh.h(q[0]) single_xhh.measure(q[0],c[0]) execute_and_plot(qp, ["single_xhh"]) show_image("single_q_z_gate_0.png") single_z = qp.create_circuit("single_z", [q], [c]) single_z.z(q[0]) single_z.measure(q[0],c[0]) execute_and_plot(qp, ["single_z"]) show_image("single_q_z_gate_1.png") single_zh = qp.create_circuit("single_zh", [q], [c]) single_zh.h(q[0]) single_zh.z(q[0]) single_zh.measure(q[0],c[0]) execute_and_plot(qp, ["single_zh"]) show_image("single_q_z_gate_tbl.png") # 0 rotation around z, Pr(0) = 1.0 phs_0 = qp.create_circuit("phs_0", [q], [c]) phs_0.h(q[0]) phs_0.h(q[0]) # for x-basis measurement phs_0.measure(q[0], c[0]) # pi/4 rotation around z, Pr(0) = 0.85 phs_pi4 = qp.create_circuit("phs_pi4", [q], [c]) phs_pi4.h(q[0]) phs_pi4.t(q[0]) phs_pi4.h(q[0]) # for x-basis measurement phs_pi4.measure(q[0], c[0]) # pi/2 rotation around z, Pr(0) = 0.5 phs_pi2 = qp.create_circuit("phs_pi2", [q], [c]) phs_pi2.h(q[0]) phs_pi2.s(q[0]) # Alternate example gate: #phs_pi2.sdg(q[0]) #rotation -pi/2 using sdg instead of s phs_pi2.h(q[0]) # for x-basis measurement phs_pi2.measure(q[0], c[0]) # 3pi/4 rotation around z, Pr(0) = 0.15 phs_3pi4 = qp.create_circuit("phs_3pi4", [q], [c]) phs_3pi4.h(q[0]) phs_3pi4.s(q[0]) phs_3pi4.t(q[0]) phs_3pi4.h(q[0]) # for x-basis measurement phs_3pi4.measure(q[0], c[0]) # pi rotation around z, Pr(0) = 0 phs_pi = qp.create_circuit("phs_pi", [q], [c]) phs_pi.h(q[0]) phs_pi.z(q[0]) phs_pi.h(q[0]) # for measurement phs_pi.measure(q[0], c[0]) execute_and_plot(qp, ["phs_0", "phs_pi4", "phs_pi2", "phs_3pi4", "phs_pi"]) n = 2 # number of qubits q2 = qp.create_quantum_register("q2", n) c2 = qp.create_classical_register("c2", n) show_image("multi_q_0.png") # |00> -- |00> cnot_00 = qp.create_circuit("cnot_00", [q2], [c2]) cnot_00.cx(q2[0], q2[1]) cnot_00.measure(q2[0], c2[0]) cnot_00.measure(q2[1], c2[1]) execute_and_plot(qp, ["cnot_00"]) show_image("multi_q_1.png") # |01> -- |11> cnot_01 = qp.create_circuit("cnot_01", [q2], [c2]) cnot_01.x(q2[0]) cnot_01.cx(q2[0], q2[1]) cnot_01.measure(q2[0], c2[0]) cnot_01.measure(q2[1], c2[1]) execute_and_plot(qp, ["cnot_01"]) show_image("multi_q_2.png") # |10> -- |10> cnot_10 = qp.create_circuit("cnot_10", [q2], [c2]) cnot_10.x(q2[1]) cnot_10.cx(q2[0], q2[1]) cnot_10.measure(q2[0], c2[0]) cnot_10.measure(q2[1], c2[1]) execute_and_plot(qp, ["cnot_10"]) show_image("multi_q_3.png") # |11> -- |01> cnot_11 = qp.create_circuit("cnot_11", [q2], [c2]) cnot_11.x(q2[0]) cnot_11.x(q2[1]) cnot_11.cx(q2[0], q2[1]) cnot_11.measure(q2[0], c2[0]) cnot_11.measure(q2[1], c2[1]) execute_and_plot(qp, ["cnot_11"]) show_image("ent_q_0.png") e0 = qp.create_circuit("e0", [q2], [c2]) e0.h(q2[0]) # apply H-gate for superposition to q0 e0.cx(q2[0], q2[1]) # apply CNOT control from q0 to q1 e0.measure(q2[0], c2[0]) e0.measure(q2[1], c2[1]) execute_and_plot(qp, ["e0"]) show_image("ent_q_1.png") e1 = qp.create_circuit("e1", [q2], [c2]) e1.h(q2[0]) # apply H-gate on q0 for superposition e1.x(q2[1]) # apply x-gate on q1 e1.cx(q2[0], q2[1]) # apply CNOT control from q0 to q1 e1.measure(q2[0], c2[0]) e1.measure(q2[1], c2[1]) execute_and_plot(qp, ["e1"])
https://github.com/xtophe388/QISKIT
xtophe388
# Import the QuantumProgram and our configuration import math from pprint import pprint from qiskit import QuantumProgram import Qconfig qp = QuantumProgram() # quantum register for the first circuit q1 = qp.create_quantum_register('q1', 4) c1 = qp.create_classical_register('c1', 4) # quantum register for the second circuit q2 = qp.create_quantum_register('q2', 2) c2 = qp.create_classical_register('c2', 2) # making the first circuits qc1 = qp.create_circuit('GHZ', [q1], [c1]) qc2 = qp.create_circuit('superposition', [q2], [c2]) qc1.h(q1[0]) qc1.cx(q1[0], q1[1]) qc1.cx(q1[1], q1[2]) qc1.cx(q1[2], q1[3]) for i in range(4): qc1.measure(q1[i], c1[i]) # making the second circuits qc2.h(q2) for i in range(2): qc2.measure(q2[i], c2[i]) # printing the circuits print(qp.get_qasm('GHZ')) print(qp.get_qasm('superposition')) qobj = qp.compile(['GHZ','superposition'], backend='local_qasm_simulator') qp.get_execution_list(qobj) qp.get_execution_list(qobj, verbose=True) qp.get_compiled_configuration(qobj, 'GHZ', ) print(qp.get_compiled_qasm(qobj, 'GHZ')) # Coupling map coupling_map = {0: [1, 2, 3]} # Place the qubits on a triangle in the bow-tie initial_layout={("q1", 0): ("q", 0), ("q1", 1): ("q", 1), ("q1", 2): ("q", 2), ("q1", 3): ("q", 3)} qobj = qp.compile(['GHZ'], backend='local_qasm_simulator', coupling_map=coupling_map, initial_layout=initial_layout) print(qp.get_compiled_qasm(qobj,'GHZ')) # Define methods for making QFT circuits def input_state(circ, q, n): """n-qubit input state for QFT that produces output 1.""" for j in range(n): circ.h(q[j]) circ.u1(math.pi/float(2**(j)), q[j]).inverse() def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cu1(math.pi/float(2**(j-k)), q[j], q[k]) circ.h(q[j]) qp = QuantumProgram() q = qp.create_quantum_register("q", 3) c = qp.create_classical_register("c", 3) qft3 = qp.create_circuit("qft3", [q], [c]) input_state(qft3, q, 3) qft(qft3, q, 3) for i in range(3): qft3.measure(q[i], c[i]) print(qft3.qasm()) result = qp.execute(["qft3"], backend="local_qasm_simulator", shots=1024) result.get_counts("qft3") print(result.get_ran_qasm("qft3")) # Coupling map for ibmqx2 "bowtie" coupling_map = {0: [1, 2], 1: [2], 2: [], 3: [2, 4], 4: [2]} # Place the qubits on a triangle in the bow-tie initial_layout={("q", 0): ("q", 2), ("q", 1): ("q", 3), ("q", 2): ("q", 4)} result2 = qp.execute(["qft3"], backend="local_qasm_simulator", coupling_map=coupling_map, initial_layout=initial_layout) result2.get_counts("qft3") print(result2.get_ran_qasm("qft3")) # Place the qubits on a linear segment of the ibmqx3 coupling_map = {0: [1], 1: [2], 2: [3], 3: [14], 4: [3, 5], 6: [7, 11], 7: [10], 8: [7], 9: [8, 10], 11: [10], 12: [5, 11, 13], 13: [4, 14], 15: [0, 14]} initial_layout={("q", 0): ("q", 0), ("q", 1): ("q", 1), ("q", 2): ("q", 2)} result3 = qp.execute(["qft3"], backend="local_qasm_simulator", coupling_map=coupling_map, initial_layout=initial_layout) result3.get_counts("qft3") print(result3.get_ran_qasm("qft3"))
https://github.com/xtophe388/QISKIT
xtophe388
#initialization import sys import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing the QISKit from qiskit import QuantumProgram try: sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} except: qx_config = { "APItoken":"YOUR_TOKEN_HERE", "url":"https://quantumexperience.ng.bluemix.net/api"} # import basic plot tools from qiskit.tools.visualization import plot_histogram #set api from IBMQuantumExperience import IBMQuantumExperience api = IBMQuantumExperience(token=qx_config['APItoken'], config={'url': qx_config['url']}) #prepare backends from qiskit.backends import discover_local_backends, discover_remote_backends, get_backend_instance remote_backends = discover_remote_backends(api) #we have to call this to connect to remote backends local_backends = discover_local_backends() # Quantum program setup Q_program = QuantumProgram() #for plot with 16qubit import numpy as np from functools import reduce from scipy import linalg as la from collections import Counter import matplotlib.pyplot as plt def plot_histogram5(data, number_to_keep=False): """Plot a histogram of data. data is a dictionary of {'000': 5, '010': 113, ...} number_to_keep is the number of terms to plot and rest is made into a single bar called other values """ if number_to_keep is not False: data_temp = dict(Counter(data).most_common(number_to_keep)) data_temp["rest"] = sum(data.values()) - sum(data_temp.values()) data = data_temp labels = sorted(data) values = np.array([data[key] for key in labels], dtype=float) pvalues = values / sum(values) numelem = len(values) ind = np.arange(numelem) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() rects = ax.bar(ind, pvalues, width, color='seagreen') # add some text for labels, title, and axes ticks ax.set_ylabel('Probabilities', fontsize=12) ax.set_xticks(ind) ax.set_xticklabels(labels, fontsize=12, rotation=70) ax.set_ylim([0., min([1.2, max([1.2 * val for val in pvalues])])]) # attach some text labels for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height, '%f' % float(height), ha='center', va='bottom', fontsize=8) plt.show() q1_2 = Q_program.create_quantum_register("q1_2", 3) c1_2 = Q_program.create_classical_register("c1_2", 3) qw1_2 = Q_program.create_circuit("qw1_2", [q1_2], [c1_2]) t=8 #time qw1_2.x(q1_2[2]) qw1_2.u3(t, 0, 0, q1_2[1]) qw1_2.cx(q1_2[2], q1_2[1]) qw1_2.u3(t, 0, 0, q1_2[1]) qw1_2.cx(q1_2[2], q1_2[1]) qw1_2.measure(q1_2[0], c1_2[0]) qw1_2.measure(q1_2[1], c1_2[2]) qw1_2.measure(q1_2[2], c1_2[1]) print(qw1_2.qasm()) result = Q_program.execute(["qw1_2"], backend='local_qiskit_simulator', shots=1000) plot_histogram5(result.get_counts("qw1_2")) result = Q_program.execute(["qw1_2"], backend='ibmqx4', shots=1000, max_credits=3, wait=10, timeout=1024) plot_histogram5(result.get_counts("qw1_2")) q1 = Q_program.create_quantum_register("q1", 3) c1 = Q_program.create_classical_register("c1", 3) qw1 = Q_program.create_circuit("qw1", [q1], [c1]) t=8 #time qw1.x(q1[1]) qw1.cx(q1[2], q1[1]) qw1.u3(t, 0, 0, q1[2]) qw1.cx(q1[2], q1[0]) qw1.u3(t, 0, 0, q1[2]) qw1.cx(q1[2], q1[0]) qw1.cx(q1[2], q1[1]) qw1.u3(2*t, 0, 0, q1[2]) qw1.measure(q1[0], c1[0]) qw1.measure(q1[1], c1[1]) qw1.measure(q1[2], c1[2]) print(qw1.qasm()) result = Q_program.execute(["qw1"], backend='local_qiskit_simulator') plot_histogram5(result.get_counts("qw1")) result = Q_program.execute(["qw1"], backend='ibmqx4', shots=1000, max_credits=3, wait=10, timeout=600) plot_histogram5(result.get_counts("qw1"))
https://github.com/xtophe388/QISKIT
xtophe388
# useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np # useful math functions from math import pi, cos, acos, sqrt import random # importing the QISKit from qiskit import QuantumProgram import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram Q_program = QuantumProgram() Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url N = 4 # Creating registers qr = Q_program.create_quantum_register("qr", N) # for recording the measurement on qr cr = Q_program.create_classical_register("cr", N) circuitName = "sharedEntangled" sharedEntangled = Q_program.create_circuit(circuitName, [qr], [cr]) #Create uniform superposition of all strings of length 2 for i in range(2): sharedEntangled.h(qr[i]) #The amplitude is minus if there are odd number of 1s for i in range(2): sharedEntangled.z(qr[i]) #Copy the content of the fist two qubits to the last two qubits for i in range(2): sharedEntangled.cx(qr[i], qr[i+2]) #Flip the last two qubits for i in range(2,4): sharedEntangled.x(qr[i]) #we first define controlled-u gates required to assign phases from math import pi def ch(qProg, a, b): """ Controlled-Hadamard gate """ qProg.h(b) qProg.sdg(b) qProg.cx(a, b) qProg.h(b) qProg.t(b) qProg.cx(a, b) qProg.t(b) qProg.h(b) qProg.s(b) qProg.x(b) qProg.s(a) return qProg def cu1pi2(qProg, c, t): """ Controlled-u1(phi/2) gate """ qProg.u1(pi/4.0, c) qProg.cx(c, t) qProg.u1(-pi/4.0, t) qProg.cx(c, t) qProg.u1(pi/4.0, t) return qProg def cu3pi2(qProg, c, t): """ Controlled-u3(pi/2, -pi/2, pi/2) gate """ qProg.u1(pi/2.0, t) qProg.cx(c, t) qProg.u3(-pi/4.0, 0, 0, t) qProg.cx(c, t) qProg.u3(pi/4.0, -pi/2.0, 0, t) return qProg # dictionary for Alice's operations/circuits aliceCircuits = {} # Quantum circuits for Alice when receiving idx in 1, 2, 3 for idx in range(1, 4): circuitName = "Alice"+str(idx) aliceCircuits[circuitName] = Q_program.create_circuit(circuitName, [qr], [cr]) theCircuit = aliceCircuits[circuitName] if idx == 1: #the circuit of A_1 theCircuit.x(qr[1]) theCircuit.cx(qr[1], qr[0]) theCircuit = cu1pi2(theCircuit, qr[1], qr[0]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit = cu1pi2(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit = cu1pi2(theCircuit, qr[0], qr[1]) theCircuit = cu3pi2(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit = ch(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit.cx(qr[1], qr[0]) theCircuit.x(qr[1]) elif idx == 2: theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit = cu1pi2(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit = cu1pi2(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit.h(qr[0]) theCircuit.h(qr[1]) elif idx == 3: theCircuit.cz(qr[0], qr[1]) theCircuit.swap(qr[0], qr[1]) theCircuit.h(qr[0]) theCircuit.h(qr[1]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit.cz(qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) #measure the first two qubits in the computational basis theCircuit.measure(qr[0], cr[0]) theCircuit.measure(qr[1], cr[1]) # dictionary for Bob's operations/circuits bobCircuits = {} # Quantum circuits for Bob when receiving idx in 1, 2, 3 for idx in range(1,4): circuitName = "Bob"+str(idx) bobCircuits[circuitName] = Q_program.create_circuit(circuitName, [qr], [cr]) theCircuit = bobCircuits[circuitName] if idx == 1: theCircuit.x(qr[2]) theCircuit.x(qr[3]) theCircuit.cz(qr[2], qr[3]) theCircuit.x(qr[3]) theCircuit.u1(pi/2.0, qr[2]) theCircuit.x(qr[2]) theCircuit.z(qr[2]) theCircuit.cx(qr[2], qr[3]) theCircuit.cx(qr[3], qr[2]) theCircuit.h(qr[2]) theCircuit.h(qr[3]) theCircuit.x(qr[3]) theCircuit = cu1pi2(theCircuit, qr[2], qr[3]) theCircuit.x(qr[2]) theCircuit.cz(qr[2], qr[3]) theCircuit.x(qr[2]) theCircuit.x(qr[3]) elif idx == 2: theCircuit.x(qr[2]) theCircuit.x(qr[3]) theCircuit.cz(qr[2], qr[3]) theCircuit.x(qr[3]) theCircuit.u1(pi/2.0, qr[3]) theCircuit.cx(qr[2], qr[3]) theCircuit.h(qr[2]) theCircuit.h(qr[3]) elif idx == 3: theCircuit.cx(qr[3], qr[2]) theCircuit.x(qr[3]) theCircuit.h(qr[3]) #measure the third and fourth qubits in the computational basis theCircuit.measure(qr[2], cr[2]) theCircuit.measure(qr[3], cr[3]) a, b = random.randint(1,3), random.randint(1,3) #generate random integers print("The values of a and b are, resp.,", a,b) aliceCircuit = aliceCircuits["Alice"+str(a)] bobCircuit = bobCircuits["Bob"+str(b)] circuitName = "Alice"+str(a)+"Bob"+str(b) Q_program.add_circuit(circuitName, sharedEntangled+aliceCircuit+bobCircuit) backend = "local_qasm_simulator" ##backend = "ibmqx2" shots = 1 # We perform a one-shot experiment results = Q_program.execute([circuitName], backend=backend, shots=shots) answer = results.get_counts(circuitName) print(answer) for key in answer.keys(): aliceAnswer = [int(key[-1]), int(key[-2])] bobAnswer = [int(key[-3]), int(key[-4])] if sum(aliceAnswer) % 2 == 0:#the sume of Alice answer must be even aliceAnswer.append(0) else: aliceAnswer.append(1) if sum(bobAnswer) % 2 == 1:#the sum of Bob answer must be odd bobAnswer.append(0) else: bobAnswer.append(1) break print("Alice answer for a = ", a, "is", aliceAnswer) print("Bob answer for b = ", b, "is", bobAnswer) if(aliceAnswer[b-1] != bobAnswer[a-1]): #check if the intersection of their answers is the same print("Alice and Bob lost") else: print("Alice and Bob won") backend = "local_qasm_simulator" #backend = "ibmqx2" shots = 10 # We perform 10 shots of experiments for each round nWins = 0 nLost = 0 for a in range(1,4): for b in range(1,4): print("Asking Alice and Bob with a and b are, resp.,", a,b) rWins = 0 rLost = 0 aliceCircuit = aliceCircuits["Alice"+str(a)] bobCircuit = bobCircuits["Bob"+str(b)] circuitName = "Alice"+str(a)+"Bob"+str(b) Q_program.add_circuit(circuitName, sharedEntangled+aliceCircuit+bobCircuit) if backend == "ibmqx2": ibmqx2_backend = Q_program.get_backend_configuration('ibmqx2') ibmqx2_coupling = ibmqx2_backend['coupling_map'] results = Q_program.execute([circuitName], backend=backend, shots=shots, coupling_map=ibmqx2_coupling, max_credits=3, wait=10, timeout=240) else: results = Q_program.execute([circuitName], backend=backend, shots=shots) answer = results.get_counts(circuitName) for key in answer.keys(): kfreq = answer[key] #frequencies of keys obtained from measurements aliceAnswer = [int(key[-1]), int(key[-2])] bobAnswer = [int(key[-3]), int(key[-4])] if sum(aliceAnswer) % 2 == 0: aliceAnswer.append(0) else: aliceAnswer.append(1) if sum(bobAnswer) % 2 == 1: bobAnswer.append(0) else: bobAnswer.append(1) #print("Alice answer for a = ", a, "is", aliceAnswer) #print("Bob answer for b = ", b, "is", bobAnswer) if(aliceAnswer[b-1] != bobAnswer[a-1]): #print(a, b, "Alice and Bob lost") nLost += kfreq rLost += kfreq else: #print(a, b, "Alice and Bob won") nWins += kfreq rWins += kfreq print("\t#wins = ", rWins, "out of ", shots, "shots") print("Number of Games = ", nWins+nLost) print("Number of Wins = ", nWins) print("Winning probabilities = ", (nWins*100.0)/(nWins+nLost))
https://github.com/xtophe388/QISKIT
xtophe388
#Imports from itertools import product import matplotlib.pyplot as plt %matplotlib inline from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Result from qiskit import available_backends, get_backend, execute, register, least_busy from qiskit.tools.visualization import matplotlib_circuit_drawer, qx_color_scheme #require qiskit>0.5.5 %config InlineBackend.figure_format = 'svg' style = qx_color_scheme() style['compress'] = True style['cregbundle'] = True style['plotbarrier'] = True circuit_drawer = lambda circuit: matplotlib_circuit_drawer(circuit, style=style) # Creating registers qa = QuantumRegister(1, 'alice') qb = QuantumRegister(1, 'bob') c = ClassicalRegister(2, 'c') # Bell Measurement bell_measurement = QuantumCircuit(qa, qb, c) bell_measurement.cx(qa, qb) bell_measurement.h(qa) bell_measurement.measure(qa[0], c[0]) bell_measurement.measure(qb[0], c[1]) circuit_drawer(bell_measurement) alice = {} bob = {} # eigenvalue alice['+'] = QuantumCircuit(qa, qb, c) # do nothing alice['-'] = QuantumCircuit(qa, qb, c) alice['-'] .x(qa) bob['+'] = QuantumCircuit(qa, qb, c) # do nothing bob['-'] = QuantumCircuit(qa, qb, c) bob['-'].x(qb) # matrix alice['Z'] = QuantumCircuit(qa, qb, c) # do nothing alice['X'] = QuantumCircuit(qa, qb, c) alice['X'].h(qa) bob['W'] = QuantumCircuit(qa, qb, c) bob['W'].h(qb) bob['W'].t(qb) bob['W'].h(qb) bob['W'].s(qb) bob['V'] = QuantumCircuit(qa, qb, c) bob['V'].h(qb) bob['V'].tdg(qb) bob['V'].h(qb) bob['V'].s(qb) qc = alice['+'] + alice['Z'] + bob['+'] + bob['V'] circuit_drawer(qc) qc = alice['-'] + alice['X'] + bob['+'] + bob['W'] circuit_drawer(qc) backend = 'local_qasm_simulator' shots = 1024 circuits = {} for a_sign, a_basis, b_sign, b_basis in product(['+', '-'], ['Z', 'X'], ['+', '-'], ['V', 'W']): name = a_sign + a_basis + b_sign + b_basis circuits[name] = QuantumCircuit(qa, qb, c) circuits[name] += alice[a_sign] circuits[name] += alice[a_basis] circuits[name] += bob[b_sign] circuits[name] += bob[b_basis] circuits[name].barrier(qa) circuits[name].barrier(qb) circuits[name] += bell_measurement # Example print('A quantum circuit of -X+V.') circuit_drawer(circuits['-X+V']) job = execute(circuits.values(), backend=backend, shots=shots) result = job.result() completely_mixed = {'00': 0, '01': 0, '10': 0, '11': 0} for a_sign, a_basis, b_sign, b_basis in product(['+', '-'], ['Z', 'X'], ['+', '-'], ['V', 'W']): name = a_sign + a_basis + b_sign + b_basis completely_mixed['00'] += result.average_data(circuits[name], {'00': 1})/16 completely_mixed['01'] += result.average_data(circuits[name], {'01': 1})/16 completely_mixed['10'] += result.average_data(circuits[name], {'10': 1})/16 completely_mixed['11'] += result.average_data(circuits[name], {'11': 1})/16 plt.bar(completely_mixed.keys(), completely_mixed.values(), width=0.5) plt.xlabel('Outcome', fontsize=15) plt.ylabel('Probability for the completely mixed state', fontsize=10) plt.axhline(y=0.25, color='red', linewidth=1) def E(result: Result, observable: dict, a_basis: str, b_basis: str) -> float: val = 0 str2int = lambda x: 1 if x == '+' else -1 for a_sign, b_sign in product(['+', '-'], ['+', '-']): name = a_sign + a_basis + b_sign + b_basis sign = str2int(a_sign) * str2int(b_sign) val += sign * result.average_data(circuits[name], observable) return val def D(result: Result, outcome: str) -> float: val = 0 for a_basis, b_basis in product(['Z', 'X'], ['V', 'W']): if outcome[0] == outcome[1] and a_basis == 'X' and b_basis == 'V': sign = -1 elif outcome[0] != outcome[1] and a_basis == 'X' and b_basis == 'W': sign = -1 else: sign = 1 val += sign * E(result, {outcome: 1}, a_basis=a_basis, b_basis=b_basis) return val for outcome in ['00', '01', '10', '11']: if completely_mixed[outcome] <= 1/4: # check the condition print('D is equal to {} for the outcome {}.'.format(D(result, outcome), outcome)) # Connecting to the IBM Quantum Experience import sys, getpass try: sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} print('Qconfig loaded from %s.' % Qconfig.__file__) except: APItoken = getpass.getpass('Please input your token and hit enter: ') qx_config = { "APItoken": APItoken, "url":"https://quantumexperience.ng.bluemix.net/api"} print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.') register(qx_config['APItoken'], qx_config['url']) device_shots = 1024 device_name = least_busy(available_backends({'simulator': False, 'local': False})) device = get_backend(device_name) device_coupling = device.configuration['coupling_map'] print("the best backend is " + device_name + " with coupling " + str(device_coupling)) job = execute(circuits.values(), backend=device_name, shots=device_shots) result = job.result() completely_mixed = {'00': 0, '01': 0, '10': 0, '11': 0} for a_sign, a_basis, b_sign, b_basis in product(['+', '-'], ['Z', 'X'], ['+', '-'], ['V', 'W']): name = a_sign + a_basis + b_sign + b_basis completely_mixed['00'] += result.average_data(circuits[name], {'00': 1})/16 completely_mixed['01'] += result.average_data(circuits[name], {'01': 1})/16 completely_mixed['10'] += result.average_data(circuits[name], {'10': 1})/16 completely_mixed['11'] += result.average_data(circuits[name], {'11': 1})/16 plt.bar(completely_mixed.keys(), completely_mixed.values(), width=0.5) plt.xlabel('Outcome', fontsize=15) plt.ylabel('Probability for the completely mixed state', fontsize=10) plt.axhline(y=0.25, color='red', linewidth=1) for outcome in ['00', '01', '10', '11']: if completely_mixed[outcome] <= 1/4: # check the condition print('D is equal to {} for the outcome {}.'.format(D(result, outcome), outcome))
https://github.com/xtophe388/QISKIT
xtophe388
# Importing QISKit import math, sys from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister # Import basic plotting tools from qiskit.tools.visualization import plot_histogram # Import methods to connect with remote backends from qiskit import available_backends, execute, register, get_backend # Import token to use remote backends try: sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} except: qx_config = { "APItoken":"YOUR_TOKEN_HERE", "url":"https://quantumexperience.ng.bluemix.net/api"} #to enable sleep import time #connect to remote API to be able to use remote simulators and real devices register(qx_config['APItoken'], qx_config['url']) print("Available backends:", available_backends()) def input_state(circ, q, n): """n-qubit input state for QFT that produces output 1.""" for j in range(n): circ.h(q[j]) circ.u1(math.pi/float(2**(j)), q[j]).inverse() def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cu1(math.pi/float(2**(j-k)), q[j], q[k]) circ.h(q[j]) q = QuantumRegister(3) c = ClassicalRegister(3) qft3 = QuantumCircuit(q, c) input_state(qft3, q, 3) qft(qft3, q, 3) for i in range(3): qft3.measure(q[i], c[i]) print(qft3.qasm()) simulate = execute(qft3, backend="local_qasm_simulator", shots=1024).result() simulate.get_counts() backend = "ibmqx4" shots = 1024 if get_backend(backend).status["available"] is True: job_exp = execute(qft3, backend=backend, shots=shots) lapse = 0 interval = 10 while not job_exp.done: print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status) time.sleep(interval) lapse += 1 print(job_exp.status) results = job_exp.result() plot_histogram(results.get_counts())
https://github.com/xtophe388/QISKIT
xtophe388
from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit import register, available_backends, get_backend #import Qconfig and set APIToken and API url import sys sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} #set api register(qx_config['APItoken'], qx_config['url']) import math, scipy, copy, time import numpy as np def AddDelay (script,q,num,delay): for _ in range(delay): for address in range(num): script.iden(q[address]) def AddCnot(script,q,control,target,device): # set the coupling map # b in coupling_map[a] means a CNOT with control qubit a and target qubit b can be implemented # this is essentially just copy and pasted from # https://github.com/IBM/qiskit-qx-info/tree/master/backends/ibmqx3 # https://github.com/IBM/qiskit-qx-info/tree/master/backends/ibmqx5 # but with a few stylistic changes coupling_map = {} coupling_map['ibmqx3'] = {0: [1], 1: [2], 2: [3], 3: [14], 4: [3, 5], 5: [], 6: [7, 11], 7: [10], 8: [7], 9: [10, 8], 10:[], 11: [10], 12: [5, 11, 13], 13: [4, 14], 14:[], 15: [0, 14]} coupling_map['ibmqx5'] = {0:[],1:[0,2], 2:[3], 3:[4, 14], 4:[], 5:[4], 6:[5,7,11], 7:[10], 8:[7], 9:[8, 10], 10:[], 11:[10], 12:[5, 11, 13], 13:[4, 14], 14:[], 15:[0, 2, 14]} simulator = (device not in ['ibmqx3','ibmqx5']) # if simulator, just do the CNOT if simulator: script.cx(q[control], q[target]) # same if the coupling map allows it elif target in coupling_map[device][control]: script.cx(q[control], q[target]) # if it can be done the other way round we conjugate with Hadamards elif ( control in coupling_map[device][target] ): script.h(q[control]) script.h(q[target]) script.cx(q[target], q[control]) script.h(q[control]) script.h(q[target]) else: print('Qubits ' + str(control) + ' and ' + str(target) + ' cannot be entangled.') def GetAddress (codeQubit,offset,simulator): if (simulator): address = 2*codeQubit + offset else: address = (5-2*codeQubit-offset)%16 #address = (6+2*codeQubit+offset)%16 # this can be used to go clockwise instead return address def RunRepetition(bit,d,device,delay,totalRuns): # set the number of shots to use on the backend shots = 8192 # determine whether a simulator is used simulator = (device not in ['ibmqx3','ibmqx5']) # if the simulator is used, we declare the minimum number of qubits required if (simulator): num = 2*d # for the real device there are always 16 else: num = 16 repetitionScript = [] # we create a batch job of totalRuns identical runs for run in range(totalRuns): # set up registers and program q = QuantumRegister(num) c = ClassicalRegister(num) repetitionScript.append( QuantumCircuit(q, c) ) # now we insert all the quantum gates to be applied # a barrier is inserted between each section of the code to prevent the complilation doing things we don't want it to # the stored bit is initialized by repeating it across all code qubits same state # since qubits are automatically initialized as 0, we just need to do Xs if b=1 if (bit==1): for codeQubit in range(d): repetitionScript[run].x( q[GetAddress(codeQubit,0,simulator)] ) # also do it for the single qubit on the end for comparision repetitionScript[run].x( q[GetAddress(d-1,1,simulator)] ) repetitionScript[run].barrier() # if the code is simulated add rotations for error like effects (and a barrier) AddDelay(repetitionScript[run],q,num,delay) # we then start the syndrome measurements by doing CNOTs between each code qubit and the next ancilla along the line for codeQubit in range(d-1): AddCnot(repetitionScript[run],q,GetAddress(codeQubit,0,simulator),GetAddress(codeQubit,1,simulator),device) repetitionScript[run].barrier() # if the code is simulated add rotations for error like effects (and a barrier) AddDelay(repetitionScript[run],q,num,delay) # next we perform CNOTs between each code qubit and the previous ancilla along the line for codeQubit in range(1,d): AddCnot(repetitionScript[run],q,GetAddress(codeQubit,0,simulator),GetAddress(codeQubit,-1,simulator),device) repetitionScript[run].barrier() # if the code is simulated add rotations for error like effects (and a barrier) AddDelay(repetitionScript[run],q,num,delay) # all qubits are then measured for address in range(num): repetitionScript[run].measure(q[address], c[address]) # noise is turned on if simulator is used #repetitionScript[run].noise(int(simulator)) # run the job (if the device is available) backends = available_backends() backend = get_backend(device) print('Status of '+device+':',backend.status) dataNeeded = True while dataNeeded==True: if backend.status["available"] is True: print("\nThe device is available, so the following job is being submitted.\n") print(repetitionScript[1].qasm()) shots_device = 1000 job = execute(repetitionScript, backend, shots=shots, skip_translation=True) results = [] for run in range(totalRuns): results.append( job.result().get_counts(repetitionScript[run]) ) dataNeeded = False else: print("\nThe device is not available, so we will wait for a while.") time.sleep(600) # the raw data states the number of runs for which each outcome occurred # we convert this to fractions before output. for run in range(totalRuns): for key in results[run].keys(): results[run][key] = results[run][key]/shots # return the results return results def AddProbToResults(prob,string,results): if string not in results.keys(): results[string] = 0 results[string] += prob def CalculateError(encodedBit,results,table): # total prob of error will be caculated by looping over all strings # some will end up being ignored, so we'll also need to renormalize error = 0 renorm = 1 # all strings from our sample are looped over for string in results.keys(): # we find the probability P(string|encodedBit) from the lookup table right = 0 if string in table[encodedBit].keys(): right = table[encodedBit][string] # as is the probability P(string|!encodedBit) wrong = 0 if string in table[(encodedBit+1)%2].keys(): wrong = table[(encodedBit+1)%2][string] # if this is a string for which P(string|!encodedBit)>P(string|encodedBit), the decoding fails # the probabilty for this sample is then added to the error if (wrong>right): error += results[string] # if P(string|!encodedBit)=P(string|encodedBit)=0 we have no data to decode, so we should ignore this sample # otherwise if P(string|!encodedBit)=P(string|encodedBit), the decoder randomly chooses between them # P(failure|string) is therefore 0.5 in this case elif (wrong==right): if wrong==0: renorm -= results[string] else: error += 0.5*results[string] # otherwise the decoding succeeds, and we don't care about that if renorm==0: error = 1 else: error = error/renorm return error def GetData(device,minSize,maxSize,totalRuns,delay): # loop over code sizes that will fit on the chip (d=3 to d=8) for d in range(minSize,maxSize+1): print("\n\n**d = " + str(d) + "**") # get data for each encoded bit value for bit in range(2): # run the job and put results in resultsRaw results = RunRepetition(bit,d,device,delay,totalRuns) delayString = "" if delay>0: delayString = '_delay='+str(delay) for run in range(totalRuns): f = open('Repetition_Code_Results/'+device+'/results_d=' + str(d) + delayString + '_run=' + str(run) + '_bit=' + str(bit) + '.txt', 'w') f.write( str(results[run]) ) f.close() def ProcessData(device,encodedBit,minSize,maxSize,totalRuns,delay): # determine whether a simulator is used simulator = (device not in ['ibmqx3','ibmqx5']) # initialize list used to store the calculated means and variances for results from the codes codeResults = [[[0]*4 for _ in range(j)] for j in range(minSize,maxSize+1)] singleResults = [[[0]*2 for _ in range(16)] for _ in range(minSize,maxSize+1)] # singleResults[d-minSize][j][0] is the probability of state 1 for qubit j when used in a code of distance d # singleResults[d-minSize][j][1] is the variance for the above # the results will show that the case of partial decoding requires more analysis # for this reason we will also output combinedCodeResults, which is all runs of codeResults combined # here we initialize list of combined results from the code only case combinedResultsCode = [[{} for _ in range(minSize,maxSize+1) ] for _ in range(2)] for d in range(minSize,maxSize+1): # we loop over code sizes and runs to create the required dictionaries of data: # resultsFull, resultsCode and resultsSingle (and well as the things used to make them) # the results that come fresh from the backend resultsVeryRaw = [[{} for _ in range(2)] for run in range(0,totalRuns)] resultsRaw = [[{} for _ in range(2)] for run in range(0,totalRuns)] # the results from the full code (including ancillas) # resultsFull[k] gives results for the effective distance d-k code obtained by ignoring the last k code qubits and ancillas resultsFull = [[[{} for _ in range(d)] for _ in range(2)] for run in range(0,totalRuns)] # the same but with ancilla results excluded resultsCode = [[[{} for _ in range(d)] for _ in range(2)] for run in range(0,totalRuns)] # results each single bit resultsSingle = [[[{} for _ in range(16)] for _ in range(2)] for run in range(0,totalRuns)] for run in range(0,totalRuns): # we get results for both possible encoded bits for bit in range(2): delayString = "" if delay>0: delayString = '_delay='+str(delay) # get results for this run from file f = open('Repetition_Code_Results/'+device+'/results_d=' + str(d) + delayString + '_run=' + str(run) + '_bit=' + str(bit) + '.txt') resultsVeryRaw[run][bit] = eval(f.read()) f.close() # loop over all keys in the raw results and look at the ones without strings as values # since all such entries should have a bit string as a key, we call it stringVeryRaw for stringVeryRaw in resultsVeryRaw[run][bit].keys(): if resultsVeryRaw[run][bit][stringVeryRaw] is not str: # create a new dictionary in which each key is padded to a bit string of length 16 stringRaw = stringVeryRaw.rjust(16,'0') resultsRaw[run][bit][stringRaw] = resultsVeryRaw[run][bit][stringVeryRaw] # now stringRaw only has data in the correct format # let's loop over its entries and process stuff for stringRaw in resultsRaw[run][bit].keys(): # get the prob corresponding to this string probToAdd = resultsRaw[run][bit][stringRaw] # first we deal with resultsFull and resultsCode # loop over all truncated codes relevant for this d for k in range(d): # distance of this truncated code dd = d-k # extract the bit string relevant for resultsFull # from left to right this will alternate between code and ancilla qubits in increasing order stringFull = '' for codeQubit in range(dd): # add bit value for a code qubit... stringFull += stringRaw[15-GetAddress(codeQubit,0,simulator)] if (codeQubit!=(d-1)): #...and then the ancilla next to it (if we haven't reached the end of the code) stringFull += stringRaw[15-GetAddress(codeQubit,1,simulator)] # remove ancilla bits from this to get the string for resultsCode stringCode = "" for n in range(dd): stringCode += stringFull[2*n] AddProbToResults(probToAdd,stringFull,resultsFull[run][bit][k]) AddProbToResults(probToAdd,stringCode,resultsCode[run][bit][k]) # now we'll do results single # the qubits are listed in the order they are in the code # so for each code qubit for jj in range(8): # loop over it and its neighbour for offset in range(2): stringSingle = stringRaw[15-GetAddress(jj,offset,simulator)] AddProbToResults(probToAdd,stringSingle,resultsSingle[run][bit][2*jj+offset]) # combined this run's resultsCode with the total, using the k=0 values for stringCode in resultsCode[run][bit][0].keys(): probToAdd = resultsCode[run][bit][0][stringCode]/10 AddProbToResults(probToAdd,stringCode,combinedResultsCode[bit][d-minSize]) for run in range(0,totalRuns): # initialize list used to store the calculated means and variances for results from the codes codeSample = [[0]*2 for _ in range(d)] # here # codeSample gives the results # codeSample[0] gives results for the whole code # codeSample[k][0] is the error prob when decoding uses both code and ancilla qubits # codeSample[k][1] is the error prob when decoding uses only code qubits singleSample = [0]*16 # singleSample[j] is the probability of state 1 for qubit j when the required bit value is encoded # write results in for k in range(d): # calculate look up tables by averaging over all other runs fullTable = [{} for _ in range(2)] codeTable = [{} for _ in range(2)] for b in range(2): for r in [rr for rr in range(totalRuns) if rr!=run]: for string in resultsFull[r][b][k]: AddProbToResults(resultsFull[r][b][k][string]/(totalRuns-1),string,fullTable[b]) for string in resultsCode[r][b][k]: AddProbToResults(resultsCode[r][b][k][string]/(totalRuns-1),string,codeTable[b]) # then calculate corresponding errors codeSample[k][0] = CalculateError(encodedBit,resultsFull[run][encodedBit][k],fullTable) codeSample[k][1] = CalculateError(encodedBit,resultsCode[run][encodedBit][k],codeTable) for j in range(16): if '1' in resultsSingle[run][encodedBit][j].keys(): singleSample[j] = resultsSingle[run][encodedBit][j]['1'] # add results from this run to the overall means and variances for k in range(d): for l in range(2): codeResults[d-minSize][k][2*l] += codeSample[k][l] / totalRuns # means codeResults[d-minSize][k][2*l+1] += codeSample[k][l]**2 / totalRuns # variances for j in range(16): singleResults[d-minSize][j][0] += singleSample[j] / totalRuns singleResults[d-minSize][j][1] += singleSample[j]**2 / totalRuns # finish the variances by subtracting the square of the mean for k in range(d): for l in range(1,2,4): codeResults[d-minSize][k][l] -= codeResults[d-minSize][k][l-1]**2 for j in range(16): singleResults[d-minSize][j][1] -= singleResults[d-minSize][j][0]**2 # return processed results return codeResults, singleResults, combinedResultsCode def MakeGraph(X,Y,y,axisLabel,labels=[],legendPos='upper right',verbose=False,log=False,tall=False): from matplotlib import pyplot as plt plt.rcParams.update({'font.size': 30}) markers = ["o","^","h","D","*"] # if verbose, print the numbers to screen if verbose==True: print("\nX values") print(X) for j in range(len(Y)): print("\nY values for "+labels[j]) print(Y[j]) print("\nError bars") print(y[j]) print("") # convert the variances of varY into widths of error bars for j in range(len(y)): for k in range(len(y[j])): y[j][k] = math.sqrt(y[j][k]/2) if tall: plt.figure(figsize=(20,20)) else: plt.figure(figsize=(20,10)) # add in the series for j in range(len(Y)): marker = markers[j%len(markers)] if labels==[]: plt.errorbar(X, Y[j], marker = marker, markersize=20, yerr = y[j], linewidth=5) else: plt.errorbar(X, Y[j], label=labels[j], marker = marker, markersize=20, yerr = y[j], linewidth=5) plt.legend(loc=legendPos) # label the axes plt.xlabel(axisLabel[0]) plt.ylabel(axisLabel[1]) # make sure X axis is fully labelled plt.xticks(X) # logarithms if required if log==True: plt.yscale('log') # make the graph plt.show() plt.rcParams.update(plt.rcParamsDefault) # set device to use # this also sets the maximum d. We only go up to 6 on the simulator userInput = input("Do you want results for a real device? (input Y or N) If not, results will be from a simulator. \n").upper() if (userInput=="Y"): device = 'ibmqx3' else: device = 'ibmq_qasm_simulator' # determine the delay userInput = input("What value of the delay do you want results for? \n").upper() delay = 0 try: delay = int(userInput) except: pass # determine the code sizes to be considered userInput = input("What is the minimum size code you wish to consider? (input 3, 4, 5, 6, 7 or 8) \n").upper() if userInput in ['3','4','5','6','7','8']: minSize = int(userInput) else: minSize = 3 userInput = input("What is the maximum size code you wish to consider? (input a number no less than the minimum, but no larger than 8) \n").upper() if userInput in ['3','4','5','6','7','8']: maxSize = int(userInput) else: maxSize = 8 # determine whether data needs to be taken if device=='ibmqx5': dataAlready = True else: userInput = input("Do you want to process saved data? (Y/N) If not, new data will be obtained. \n").upper() if (userInput=="Y"): dataAlready = True else: dataAlready = False # set number of runs used for stats # totalRuns is for a repetition code of length d totalRuns = 10 # if we need data, we get it if (dataAlready==False): # get the required data for the desired number of runs GetData(device,minSize,maxSize,totalRuns,delay) codeResults = [[],[]] singleResults = [[],[]] for encodedBit in range(2): try: codeResults[encodedBit], singleResults[encodedBit], combinedResultsCode = ProcessData(device,encodedBit,minSize,maxSize,totalRuns,delay) except Exception as e: print(e) # plot for single qubit data for each code distance for d in range(minSize,maxSize+1): X = range(16) Y = [] y = [] # a series for each encoded bit for encodedBit in range(2): Y.append([singleResults[encodedBit][d-minSize][j][0] for j in range(16)]) y.append([singleResults[encodedBit][d-minSize][j][1] for j in range(16)]) # make graph print("\n\n***Final state of each qubit for code of distance d = " + str(d) + "***") MakeGraph(X,Y,y,['Qubit position in code','Probability of 1']) for encodedBit in range(2): # separate plots for each encoded bit X = range(minSize,maxSize+1) Y = [] y = [] for dec in range(2): # dec=0 corresponds to full decoding, and 1 to partial Y.append([codeResults[encodedBit][d-minSize][0][2*dec+0] for d in range(minSize,maxSize+1)]) y.append([codeResults[encodedBit][d-minSize][0][2*dec+1] for d in range(minSize,maxSize+1)]) # minimum error value for the single qubit memory is found and plotted as a comparsion (with max error bars) simulator = (device not in ['ibmqx3','ibmqx5']) minSingle = min([singleResults[encodedBit][d-minSize][GetAddress(d-1,1,simulator)][0] for d in range(minSize,maxSize+1)]) maxSingle = max([singleResults[encodedBit][d-minSize][GetAddress(d-1,1,simulator)][1] for d in range(minSize,maxSize+1)]) Y.append([minSingle]*(maxSize-minSize+1)) y.append([maxSingle]*(maxSize-minSize+1)) print("\n\n***Encoded " + str(encodedBit) + "***") MakeGraph(X,Y,y,['Code distance, d','Error probability, P'], labels=['Full decoding','Partial decoding','Single qubit memory'],legendPos='lower left',log=True,verbose=True) for encodedBit in range(2): # separate plots for each encoded bit for decoding in ['full','partial']: dec = (decoding=='partial') # this is treated as 0 if full and 1 if partial X = range(1,maxSize+1) Y = [] y = [] labels = [] for d in range(minSize,maxSize+1):# series for each code size seriesY = [math.nan]*(maxSize) seriesy = [math.nan]*(maxSize) for k in range(d): seriesY[d-k-1] = codeResults[encodedBit][d-minSize][k][2*dec+0] seriesy[d-k-1] = codeResults[encodedBit][d-minSize][k][2*dec+1] Y.append(seriesY) y.append(seriesy) labels.append('d='+str(d)) print("\n\n***Encoded " + str(encodedBit) + " with " + dec*"partial" + (1-dec)*"full" + " decoding***") MakeGraph(X,Y,y,['Effective code distance','Logical error probability'], labels=labels,legendPos = 'upper right') def MakeModelTables (q,d): # outputs an array of two dictionaries for the lookup table for a simple model of a distance d code # q[0] is prob of 0->1 noise, and q[1] is prob of 1->0 # no disinction is made between strings with the same number of errors # the prob for all are assigned to a single string, all with 0s on the left and 1s on the right modelResults = [{},{}] bit = ["0","1"] for encodedBit in range(2): for errors in range(d+1): if encodedBit==0: string = "0"*(d-errors)+"1"*errors else: string = "0"*errors+"1"*(d-errors) modelResults[encodedBit][string] = scipy.special.binom(d,errors) * q[encodedBit]**errors * (1-q[encodedBit])**(d-errors) return modelResults def TotalLogical (p0,d,p1=0): # outputs total logical error prob for a single or two round code P0 = CalculateError( encodedBit, MakeModelTables([p0,p0],d)[0], MakeModelTables([p0,p0],d) ) P1 = CalculateError( encodedBit, MakeModelTables([p0,p0],d)[1], MakeModelTables([p1,p1],d) ) return P0*(1-P1) + P1*(1-P0) for encodedBit in range(2): # separate plots for each encoded bit p = [0]*2 # here is where we'll put p_0 and p_1 bar = [0]*2 for dec in [1,0]: # dec=0 corresponds to full decoding, and 1 to partial # get the results we want to fit to realResults = [codeResults[encodedBit][d-minSize][0][2*dec] for d in range(minSize,maxSize+1)] # search possible values intul we find a minimum (assumed to be global) # first we do the partial decoding to get p (which is stored in p[0]) # then the full decoding to get p[1]=p_1 minimizing = True delta = 0.001 q = delta diff =[math.inf,math.inf] while minimizing: q += delta # set new q diff[0] = diff[1] # copy diff value for last p # calculate diff for new q diff[1] = 0 for d in range(minSize,maxSize+1): if dec==1: Q = TotalLogical(q,d) else: Q = TotalLogical(p[0]-q,d,p1=q) diff[1] += ( math.log( realResults[d-minSize] ) - math.log( Q ) )**2 # see if a minimum has been found minimizing = ( diff[0]>diff[1] ) # go back a step on p to get pSum p[1-dec] = q - delta # get diff per qubit bar[1-dec] = math.exp(math.sqrt( diff[0]/(maxSize-minSize+1) )) p[0] = p[0] - p[1] # put p_0 in p[0] (instead of p) print("\n\n***Encoded " + str(encodedBit) + "***\n" ) for j in [0,1]: print(" p_"+str(j)+" = " + str(p[j]) + " with fit values typically differing by a factor of " + str(bar[j]) + "\n") plottedMinSize = max(4,minSize) # we won't print results for d=3 for clarity X = range(plottedMinSize,maxSize+1) Y = [] y = [] # original plots for dec in range(2): # dec=0 corresponds to full decoding, and 1 to partial # results from the device Y.append([codeResults[encodedBit][d-minSize][0][2*dec+0] for d in range(plottedMinSize,maxSize+1)]) y.append([codeResults[encodedBit][d-minSize][0][2*dec+1] for d in range(plottedMinSize,maxSize+1)]) # fit lines for dec in range(2): if dec==1: Y.append([TotalLogical(p[0]+p[1],d) for d in range(plottedMinSize,maxSize+1)]) else: Y.append([TotalLogical(p[0],d,p1=p[1]) for d in range(plottedMinSize,maxSize+1)]) y.append([0]*(maxSize-plottedMinSize+1)) MakeGraph(X,Y,y,['Code distance, d','Error probability, P'], labels=['Full decoding','Partial decoding','Full decoding (model)','Partial decoding (model)'],legendPos='lower left',log=True) # for each code distance and each encoded bit value, we'll create a list of the probabilities for each possible number of errors # list is initialized with zeros errorNum = [[[0]*(d+1) for d in range(minSize,maxSize+1)] for _ in range(2)] for d in range(minSize,maxSize+1): for bit in range(2): # for each code distance and each encoded bit value we look at all possible result strings for string in combinedResultsCode[bit][d-minSize]: # count the number of errors in each string num = 0 for j in range(d): num += ( int( string[j] , 2 ) + bit )%2 # add prob to corresponding number of errors errorNum[bit][d-minSize][num] += combinedResultsCode[bit][d-minSize][string] # the we make a graph for each, and print a title Y0 = [y if y>0 else math.nan for y in errorNum[0][d-minSize]] Y1 = [y if y>0 else math.nan for y in errorNum[1][d-minSize]] print("\n\n***Probability of errors on code qubits for d = " + str(d) + "***") MakeGraph(range(d+1),[Y0,Y1],[[0]*(d+1)]*2,['Number of code qubit errors','Probability (log base 10)'], labels=['Encoded 0','Encoded 1'],legendPos='upper right',log=True) # actually, we make two graphs. This one plots the number of 1s rather than errors, and so the plot for encoded 1 is inverted # Y0 in this graph is as before Y1 = Y1[::-1] # but Y1 has its order inverted print("\n\n***Probability for number of 1s in code qubit result for d = " + str(d) + "***") MakeGraph(range(d+1),[Y0,Y1],[[0]*(d+1)]*2,['Number of 1s in code qubit result','Probability (log base 10)'], labels=['Encoded 0','Encoded 1'],legendPos='center right',log=True)
https://github.com/xtophe388/QISKIT
xtophe388
# useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from math import pi import sys # importing the QISKit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, register, get_backend # importing API token to access remote backends try: sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} except: qx_config = { "APItoken":"YOUR_TOKEN_HERE", "url":"https://quantumexperience.ng.bluemix.net/api"} # import basic plot tools from qiskit.tools.visualization import plot_histogram backend = 'local_qasm_simulator' # the device to run on shots = 1024 # the number of shots in the experiment #to record the rotation number for encoding 00, 10, 11, 01 rotationNumbers = {"00":1, "10":3, "11":5, "01":7} # Creating registers # qubit for encoding 2 bits of information qr = QuantumRegister(1) # bit for recording the measurement of the qubit cr = ClassicalRegister(1) # dictionary for encoding circuits encodingCircuits = {} # Quantum circuits for encoding 00, 10, 11, 01 for bits in ("00", "01", "10", "11"): circuitName = "Encode"+bits encodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName) encodingCircuits[circuitName].u3(rotationNumbers[bits]*pi/4.0, 0, 0, qr[0]) encodingCircuits[circuitName].barrier() # dictionary for decoding circuits decodingCircuits = {} # Quantum circuits for decoding the first and second bit for pos in ("First", "Second"): circuitName = "Decode"+pos decodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName) if pos == "Second": #if pos == "First" we can directly measure decodingCircuits[circuitName].h(qr[0]) decodingCircuits[circuitName].measure(qr[0], cr[0]) #combine encoding and decoding of QRACs to get a list of complete circuits circuitNames = [] circuits = [] for k1 in encodingCircuits.keys(): for k2 in decodingCircuits.keys(): circuitNames.append(k1+k2) circuits.append(encodingCircuits[k1]+decodingCircuits[k2]) print("List of circuit names:", circuitNames) #list of circuit names job = execute(circuits, backend=backend, shots=shots) results = job.result() print("Experimental Result of Encode01DecodeFirst") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode01DecodeFirst")])) #We should measure "0" with probability 0.85 print("Experimental Result of Encode01DecodeSecond") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode01DecodeSecond")])) #We should measure "1" with probability 0.85 print("Experimental Result of Encode11DecodeFirst") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode11DecodeFirst")])) #We should measure "1" with probability 0.85 print("Experimental Result of Encode11DecodeSecond") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode11DecodeSecond")])) #We should measure "1" with probability 0.85 #to enable sleep import time backend = "ibmqx4" #connect to remote API to be able to use remote simulators and real devices register(qx_config['APItoken'], qx_config['url']) print("Available backends:", available_backends()) if get_backend(backend).status["available"] is True: job_exp = execute(circuits, backend=backend, shots=shots) lapse = 0 interval = 50 while not job_exp.done: print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status) time.sleep(interval) lapse += 1 print(job_exp.status) results = job_exp.result() print("Experimental Result of Encode01DecodeFirst") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode01DecodeFirst")])) #We should measure "0" with probability 0.85 print("Experimental Result of Encode01DecodeSecond") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode01DecodeSecond")])) #We should measure "1" with probability 0.85 backend = 'local_qasm_simulator' # the device to run on shots = 1024 # the number of shots in the experiment from math import sqrt, cos, acos #compute the value of theta theta = acos(sqrt(0.5 + sqrt(3.0)/6.0)) #to record the u3 parameters for encoding 000, 010, 100, 110, 001, 011, 101, 111 rotationParams = {"000":(2*theta, pi/4, -pi/4), "010":(2*theta, 3*pi/4, -3*pi/4), "100":(pi-2*theta, pi/4, -pi/4), "110":(pi-2*theta, 3*pi/4, -3*pi/4), "001":(2*theta, -pi/4, pi/4), "011":(2*theta, -3*pi/4, 3*pi/4), "101":(pi-2*theta, -pi/4, pi/4), "111":(pi-2*theta, -3*pi/4, 3*pi/4)} # Creating registers # qubit for encoding 3 bits of information qr = QuantumRegister(1) # bit for recording the measurement of the qubit cr = ClassicalRegister(1) # dictionary for encoding circuits encodingCircuits = {} # Quantum circuits for encoding 000, ..., 111 for bits in rotationParams.keys(): circuitName = "Encode"+bits encodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName) encodingCircuits[circuitName].u3(*rotationParams[bits], qr[0]) encodingCircuits[circuitName].barrier() # dictionary for decoding circuits decodingCircuits = {} # Quantum circuits for decoding the first, second and third bit for pos in ("First", "Second", "Third"): circuitName = "Decode"+pos decodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName) if pos == "Second": #if pos == "First" we can directly measure decodingCircuits[circuitName].h(qr[0]) elif pos == "Third": decodingCircuits[circuitName].u3(pi/2, -pi/2, pi/2, qr[0]) decodingCircuits[circuitName].measure(qr[0], cr[0]) #combine encoding and decoding of QRACs to get a list of complete circuits circuitNames = [] circuits = [] for k1 in encodingCircuits.keys(): for k2 in decodingCircuits.keys(): circuitNames.append(k1+k2) circuits.append(encodingCircuits[k1]+decodingCircuits[k2]) print("List of circuit names:", circuitNames) #list of circuit names job = execute(circuits, backend=backend, shots=shots) results = job.result() print("Experimental Result of Encode010DecodeFirst") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeFirst")])) #We should measure "0" with probability 0.78 print("Experimental Result of Encode010DecodeSecond") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeSecond")])) #We should measure "1" with probability 0.78 print("Experimental Result of Encode010DecodeThird") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeThird")])) #We should measure "0" with probability 0.78 backend = "ibmqx4" #backend = "local_qasm_simulator" print("Available backends:", available_backends()) if get_backend(backend).status["available"] is True: job_exp = execute(circuits, backend=backend, shots=shots) lapse = 0 interval = 50 while not job_exp.done: print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status) time.sleep(interval) lapse += 1 print(job_exp.status) results = job_exp.result() print("Experimental Result of Encode010DecodeFirst") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeFirst")])) #We should measure "0" with probability 0.78 print("Experimental Result of Encode010DecodeSecond") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeSecond")])) #We should measure "1" with probability 0.78 print("Experimental Result of Encode010DecodeThird") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeThird")])) #We should measure "0" with probability 0.78
https://github.com/xtophe388/QISKIT
xtophe388
# useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing the QISKit from qiskit import QuantumProgram import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram backend = 'local_qasm_simulator' # the backend to run on shots = 1024 # the number of shots in the experiment Q_program = QuantumProgram() Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url # Creating registers qr = Q_program.create_quantum_register("qr", 1) cr = Q_program.create_classical_register("cr", 1) circuits = [] phase_vector = range(0,100) for phase_index in phase_vector: phase_shift = phase_index-50 phase = 2*np.pi*phase_shift/50 circuit_name = "phase_gate_%d"%phase_index qc_phase_gate = Q_program.create_circuit(circuit_name, [qr], [cr]) qc_phase_gate.h(qr) qc_phase_gate.u1(phase, qr) qc_phase_gate.h(qr) qc_phase_gate.measure(qr[0], cr[0]) circuits.append(circuit_name) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=3, wait=10, timeout=240) probz = [] phase_value = [] for phase_index in phase_vector: phase_shift = phase_index - 50 phase_value.append(2*phase_shift/50) if '0' in result.get_counts(circuits[phase_index]): probz.append(2*result.get_counts(circuits[phase_index]).get('0')/shots-1) else: probz.append(-1) plt.plot(phase_value, probz, 'b',0.25,1/np.sqrt(2),'ro',0.5,0,'ko',1,-1,'go',-0.25,1/np.sqrt(2),'rx',-0.5,0,'kx',-1,-1,'gx') plt.xlabel('Phase value (Pi)') plt.ylabel('Eigenvalue of X') plt.show() backend = 'local_qasm_simulator' # the backend to run on shots = 1024 # the number of shots in the experiment Q_program = QuantumProgram() Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url # Creating registers qr = Q_program.create_quantum_register("qr", 1) cr = Q_program.create_classical_register("cr", 1) circuits = [] phase_vector = range(0,100) for phase_index in phase_vector: phase_shift = phase_index-50 phase = 2*np.pi*phase_shift/50 circuit_name = "phase_gate_%d"%phase_index qc_phase_gate = Q_program.create_circuit(circuit_name, [qr], [cr]) qc_phase_gate.u3(phase,0,np.pi, qr) qc_phase_gate.measure(qr[0], cr[0]) circuits.append(circuit_name) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=3, wait=10, timeout=240) probz = [] phase_value = [] for phase_index in phase_vector: phase_shift = phase_index - 50 phase_value.append(2*phase_shift/50) if '0' in result.get_counts(circuits[phase_index]): probz.append(2*result.get_counts(circuits[phase_index]).get('0')/shots-1) else: probz.append(-1) plt.plot(phase_value, probz, 'b',0.5,0,'ko',1,-1,'go',-0.5,0,'kx',-1,-1,'gx') plt.xlabel('Phase value (Pi)') plt.ylabel('Eigenvalue of Z') plt.show()
https://github.com/xtophe388/QISKIT
xtophe388
# useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np # useful math functions from math import pi, cos, acos, sqrt import sys # importing the QISKit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, register, get_backend # importing API token to access remote backends try: sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} except: qx_config = { "APItoken":"YOUR_TOKEN_HERE", "url":"https://quantumexperience.ng.bluemix.net/api"} # import basic plot tools from qiskit.tools.visualization import plot_histogram def ch(qProg, a, b): """ Controlled-Hadamard gate """ qProg.h(b) qProg.sdg(b) qProg.cx(a, b) qProg.h(b) qProg.t(b) qProg.cx(a, b) qProg.t(b) qProg.h(b) qProg.s(b) qProg.x(b) qProg.s(a) return qProg def cu3(qProg, theta, phi, lambd, c, t): """ Controlled-u3 gate """ qProg.u1((lambd-phi)/2, t) qProg.cx(c, t) qProg.u3(-theta/2, 0, -(phi+lambd)/2, t) qProg.cx(c, t) qProg.u3(theta/2, phi, 0, t) return qProg #CHANGE THIS 7BIT 0-1 STRING TO PERFORM EXPERIMENT ON ENCODING 0000000, ..., 1111111 x1234567 = "0101010" if len(x1234567) != 7 or not("1" in x1234567 or "0" in x1234567): raise Exception("x1234567 is a 7-bit 0-1 pattern. Please set it to the correct pattern") #compute the value of rotation angle theta of (3,1)-QRAC theta = acos(sqrt(0.5 + sqrt(3.0)/6.0)) #to record the u3 parameters for encoding 000, 010, 100, 110, 001, 011, 101, 111 rotationParams = {"000":(2*theta, pi/4, -pi/4), "010":(2*theta, 3*pi/4, -3*pi/4), "100":(pi-2*theta, pi/4, -pi/4), "110":(pi-2*theta, 3*pi/4, -3*pi/4), "001":(2*theta, -pi/4, pi/4), "011":(2*theta, -3*pi/4, 3*pi/4), "101":(pi-2*theta, -pi/4, pi/4), "111":(pi-2*theta, -3*pi/4, 3*pi/4)} # Creating registers # qubits for encoding 7 bits of information with qr[0] kept by the sender qr = QuantumRegister(3) # bits for recording the measurement of the qubits qr[1] and qr[2] cr = ClassicalRegister(2) encodingName = "Encode"+x1234567 encodingCircuit = QuantumCircuit(qr, cr, name=encodingName) #Prepare superposition of mixing QRACs of x1...x6 and x7 encodingCircuit.u3(1.187, 0, 0, qr[0]) #Encoding the seventh bit seventhBit = x1234567[6] if seventhBit == "1": #copy qr[0] into qr[1] and qr[2] encodingCircuit.cx(qr[0], qr[1]) encodingCircuit.cx(qr[0], qr[2]) #perform controlled-Hadamard qr[0], qr[1], and toffoli qr[0], qr[1] , qr[2] encodingCircuit = ch(encodingCircuit, qr[0], qr[1]) encodingCircuit.ccx(qr[0], qr[1], qr[2]) #End of encoding the seventh bit #encode x1...x6 with two (3,1)-QRACS. To do that, we must flip q[0] so that the controlled encoding is executed encodingCircuit.x(qr[0]) #Encoding the first 3 bits 000, ..., 111 into the second qubit, i.e., (3,1)-QRAC on the second qubit firstThreeBits = x1234567[0:3] #encodingCircuit.cu3(*rotationParams[firstThreeBits], qr[0], qr[1]) encodingCircuit = cu3(encodingCircuit, *rotationParams[firstThreeBits], qr[0], qr[1]) #Encoding the second 3 bits 000, ..., 111 into the third qubit, i.e., (3,1)-QRAC on the third qubit secondThreeBits = x1234567[3:6] #encodingCircuit.cu3(*rotationParams[secondTreeBits], qr[0], qr[2]) encodingCircuit = cu3(encodingCircuit, *rotationParams[secondThreeBits], qr[0], qr[2]) #end of encoding encodingCircuit.barrier() # dictionary for decoding circuits decodingCircuits = {} # Quantum circuits for decoding the 1st to 6th bits for i, pos in enumerate(["First", "Second", "Third", "Fourth", "Fifth", "Sixth"]): circuitName = "Decode"+pos decodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName) if i < 3: #measure 1st, 2nd, 3rd bit if pos == "Second": #if pos == "First" we can directly measure decodingCircuits[circuitName].h(qr[1]) elif pos == "Third": decodingCircuits[circuitName].u3(pi/2, -pi/2, pi/2, qr[1]) decodingCircuits[circuitName].measure(qr[1], cr[1]) else: #measure 4th, 5th, 6th bit if pos == "Fifth": #if pos == "Fourth" we can directly measure decodingCircuits[circuitName].h(qr[2]) elif pos == "Sixth": decodingCircuits[circuitName].u3(pi/2, -pi/2, pi/2, qr[2]) decodingCircuits[circuitName].measure(qr[2], cr[1]) #Quantum circuits for decoding the 7th bit decodingCircuits["DecodeSeventh"] = QuantumCircuit(qr, cr, name="DecodeSeventh") decodingCircuits["DecodeSeventh"].measure(qr[1], cr[0]) decodingCircuits["DecodeSeventh"].measure(qr[2], cr[1]) #combine encoding and decoding of (7,2)-QRACs to get a list of complete circuits circuitNames = [] circuits = [] k1 = encodingName for k2 in decodingCircuits.keys(): circuitNames.append(k1+k2) circuits.append(encodingCircuit+decodingCircuits[k2]) print("List of circuit names:", circuitNames) #list of circuit names #Q_program.get_qasms(circuitNames) #list qasms codes backend = "local_qasm_simulator" #backend = "ibmqx2" shots = 1000 job = execute(circuits, backend=backend, shots=shots) results = job.result() for k in ["DecodeFirst", "DecodeSecond", "DecodeThird", "DecodeFourth", "DecodeFifth", "DecodeSixth"]: print("Experimental Result of ", encodingName+k) plot_histogram(results.get_counts(circuits[circuitNames.index(encodingName+k)])) print("Experimental result of ", encodingName+"DecodeSeventh") plot_histogram(results.get_counts(circuits[circuitNames.index(encodingName+"DecodeSeventh")]))
https://github.com/xtophe388/QISKIT
xtophe388
# useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from collections import Counter #Use this to convert results from list to dict for histogram # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram device = 'ibmqx2' # the device to run on #device = 'local_qasm_simulator' # uncomment to run on the simulator N = 50 # Number of bombs steps = 20 # Number of steps for the algorithm, limited by maximum circuit depth eps = np.pi / steps # Algorithm parameter, small QPS_SPECS = { "name": "IFM", "circuits": [{ "name": "IFM_gen", # Prototype circuit for bomb generation "quantum_registers": [{ "name":"q_gen", "size":1 }], "classical_registers": [{ "name":"c_gen", "size":1 }]}, {"name": "IFM_meas", # Prototype circuit for bomb measurement "quantum_registers": [{ "name":"q", "size":2 }], "classical_registers": [{ "name":"c", "size":steps+1 }]}] } Q_program = QuantumProgram(specs=QPS_SPECS) Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # Quantum circuits to generate bombs circuits = ["IFM_gen"+str(i) for i in range(N)] # NB: Can't have more than one measurement per circuit for circuit in circuits: q_gen = Q_program.get_quantum_register("q_gen") c_gen = Q_program.get_classical_register('c_gen') IFM = Q_program.create_circuit(circuit, [q_gen], [c_gen]) IFM.h(q_gen[0]) #Turn the qubit into |0> + |1> IFM.measure(q_gen[0], c_gen[0]) _ = Q_program.get_qasms(circuits) # Suppress the output result = Q_program.execute(circuits, device, shots=1, max_credits=5, wait=10, timeout=240) # Note that we only want one shot bombs = [] for circuit in circuits: for key in result.get_counts(circuit): # Hack, there should only be one key, since there was only one shot bombs.append(int(key)) #print(', '.join(('Live' if bomb else 'Dud' for bomb in bombs))) # Uncomment to print out "truth" of bombs plot_histogram(Counter(('Live' if bomb else 'Dud' for bomb in bombs))) #Plotting bomb generation results device = 'local_qasm_simulator' #Running on the simulator circuits = ["IFM_meas"+str(i) for i in range(N)] #Creating one measurement circuit for each bomb for i in range(N): bomb = bombs[i] q = Q_program.get_quantum_register("q") c = Q_program.get_classical_register('c') IFM = Q_program.create_circuit(circuits[i], [q], [c]) for step in range(steps): IFM.ry(eps, q[0]) #First we rotate the control qubit by epsilon if bomb: #If the bomb is live, the gate is a controlled X gate IFM.cx(q[0],q[1]) #If the bomb is a dud, the gate is a controlled identity gate, which does nothing IFM.measure(q[1], c[step]) #Now we measure to collapse the combined state IFM.measure(q[0], c[steps]) Q_program.get_qasms(circuits) result = Q_program.execute(circuits, device, shots=1, max_credits=5, wait=10, timeout=240) def get_status(counts): # Return whether a bomb was a dud, was live but detonated, or was live and undetonated # Note that registers are returned in reversed order for key in counts: if '1' in key[1:]: #If we ever measure a '1' from the measurement qubit (q1), the bomb was measured and will detonate return '!!BOOM!!' elif key[0] == '1': #If the control qubit (q0) was rotated to '1', the state never entangled because the bomb was a dud return 'Dud' else: #If we only measured '0' for both the control and measurement qubit, the bomb was live but never set off return 'Live' results = {'Live': 0, 'Dud': 0, "!!BOOM!!": 0} for circuit in circuits: status = get_status(result.get_counts(circuit)) results[status] += 1 plot_histogram(results)
https://github.com/xtophe388/QISKIT
xtophe388
# importing the QISKit from qiskit import QuantumCircuit, QuantumProgram import Qconfig # import tomography library import qiskit.tools.qcvv.tomography as tomo #visualization packages from qiskit.tools.visualization import plot_wigner_function, plot_wigner_data density_matrix = np.matrix([[0.5, 0, 0, 0.5],[0, 0, 0, 0],[0, 0, 0, 0],[0.5, 0, 0, 0.5]]) print(density_matrix) plot_wigner_function(density_matrix, res=200) import sympy as sym from sympy.physics.quantum import TensorProduct num = int(np.log2(len(density_matrix))) harr = sym.sqrt(3) Delta_su2 = sym.zeros(2) Delta = sym.ones(1) for qubit in range(num): phi = sym.Indexed('phi', qubit) theta = sym.Indexed('theta', qubit) costheta = harr*sym.cos(2*theta) sintheta = harr*sym.sin(2*theta) Delta_su2[0,0] = (1+costheta)/2 Delta_su2[0,1] = -(sym.exp(2j*phi)*sintheta)/2 Delta_su2[1,0] = -(sym.exp(-2j*phi)*sintheta)/2 Delta_su2[1,1] = (1-costheta)/2 Delta = TensorProduct(Delta,Delta_su2) W = sym.trace(density_matrix*Delta) print(sym.latex(W)) Q_program = QuantumProgram() number_of_qubits = 2 backend = 'local_qasm_simulator' shots = 1024 bell_qubits = [0, 1] qr = Q_program.create_quantum_register('qr',2) cr = Q_program.create_classical_register('cr',2) bell = Q_program.create_circuit('bell', [qr], [cr]) bell.h(qr[0]) bell.cx(qr[0],qr[1]) bell_tomo_set = tomo.state_tomography_set([0, 1]) bell_tomo_circuits = tomo.create_tomography_circuits(Q_program, 'bell', qr, cr, bell_tomo_set) bell_tomo_result = Q_program.execute(bell_tomo_circuits, backend=backend, shots=shots) bell_tomo_data = tomo.tomography_data(bell_tomo_result, 'bell', bell_tomo_set) rho_fit_sim = tomo.fit_tomography_data(bell_tomo_data) plot_wigner_function(np.matrix(rho_fit_sim),res=200) Delta_su2 = sym.zeros(2) Delta = sym.ones(1) for qubit in range(num): phi = sym.Indexed('phi', qubit) theta = sym.Indexed('theta', qubit) costheta = harr*sym.cos(2*theta) sintheta = harr*sym.sin(2*theta) Delta_su2[0,0] = (1+costheta)/2 Delta_su2[0,1] = -(sym.exp(2j*phi)*sintheta)/2 Delta_su2[1,0] = -(sym.exp(-2j*phi)*sintheta)/2 Delta_su2[1,1] = (1-costheta)/2 Delta = TensorProduct(Delta,Delta_su2) W = sym.trace(np.matrix(rho_fit_sim)*Delta) print(sym.latex(W)) Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) backend = 'ibmqx2' max_credits = 8 shots = 1024 bell_qubits = [0, 1] bell_tomo_set = tomo.state_tomography_set(bell_qubits) bell_tomo_circuits = tomo.create_tomography_circuits(Q_program, 'bell', qr, cr, bell_tomo_set) bell_tomo_result = Q_program.execute(bell_tomo_circuits, backend=backend, shots=shots, max_credits=max_credits, timeout=300) bell_tomo_data = tomo.tomography_data(bell_tomo_result, 'bell', bell_tomo_set) rho_fit_ibmqx = tomo.fit_tomography_data(bell_tomo_data) plot_wigner_function(np.matrix(rho_fit_ibmqx), res=100) print(rho_fit_ibmqx) Delta_su2 = sym.zeros(2) Delta = sym.ones(1) for qubit in range(num): phi = sym.Indexed('phi', qubit) theta = sym.Indexed('theta', qubit) costheta = harr*sym.cos(2*theta) sintheta = harr*sym.sin(2*theta) Delta_su2[0,0] = (1+costheta)/2 Delta_su2[0,1] = -(sym.exp(2j*phi)*sintheta)/2 Delta_su2[1,0] = -(sym.exp(-2j*phi)*sintheta)/2 Delta_su2[1,1] = (1-costheta)/2 Delta = TensorProduct(Delta,Delta_su2) W = sym.trace(np.matrix(rho_fit_ibmqx)*Delta) print(sym.latex(W)) theta1_points = 8 theta2_points = 8 number_of_points = theta1_points*theta2_points the1 = [0]*number_of_points the2 = [0]*number_of_points #initialize theta values phis = [[0]*number_of_points]*number_of_qubits #set phi values to 0 point = 0 for i in range(theta1_points): for k in range(theta2_points): the1[point] = 2*i*np.pi/theta1_points the2[point] = 2*k*np.pi/theta2_points #create the values of theta for all points on plot point += 1 thetas = np.vstack((the1,the2)) bell_circuits = tomo.build_wigner_circuits(Q_program, 'bell', phis, thetas, bell_qubits, qr, cr) backend = 'local_qasm_simulator' shots = 1024 bell_result = Q_program.execute(bell_circuits, backend=backend, shots=shots) print(bell_result) wdata = tomo.wigner_data(bell_result, bell_qubits, bell_circuits, shots=shots) wdata = np.matrix(wdata) wdata = wdata.reshape(theta1_points,theta2_points) plot_wigner_data(wdata, method='plaquette') equator_points = 64 theta = [np.pi/2]*equator_points phi = [0]*equator_points point = 0 for i in range(equator_points): phi[i] = 2*i*np.pi/equator_points thetas = np.vstack((theta,theta)) phis = np.vstack((phi,phi)) bell_eq_circuits = tomo.build_wigner_circuits(Q_program, 'bell', phis, thetas, bell_qubits, qr, cr) bell_eq_result = Q_program.execute(bell_eq_circuits, backend=backend, shots=shots) wdata_eq = tomo.wigner_data(bell_eq_result, bell_qubits, bell_eq_circuits, shots=shots) plot_wigner_data(wdata_eq, method='curve') Q_program = QuantumProgram() number_of_qubits = 5 backend = 'local_qasm_simulator' shots = 1024 ghz_qubits = [0, 1, 2, 3, 4] qr = Q_program.create_quantum_register('qr',5) cr = Q_program.create_classical_register('cr',5) ghz = Q_program.create_circuit('ghz', [qr], [cr]) ghz.h(qr[0]) ghz.h(qr[1]) ghz.x(qr[2]) ghz.h(qr[3]) ghz.h(qr[4]) ghz.cx(qr[0],qr[2]) ghz.cx(qr[1],qr[2]) ghz.cx(qr[3],qr[2]) ghz.cx(qr[4],qr[2]) ghz.h(qr[0]) ghz.h(qr[1]) ghz.h(qr[2]) ghz.h(qr[3]) ghz.h(qr[4]) equator_points = 64 thetas = [[np.pi/2]*equator_points]*number_of_qubits phi = [0]*equator_points point = 0 for i in range(equator_points): phi[i] = 2*i*np.pi/equator_points phis = np.vstack((phi,phi,phi,phi,phi)) ghz_eq_circuits = tomo.build_wigner_circuits(Q_program, 'ghz', phis, thetas, ghz_qubits, qr, cr) ghz_eq_result = Q_program.execute(ghz_eq_circuits, backend=backend, shots=shots, timeout = 300) wghzdata_eq = tomo.wigner_data(ghz_eq_result, ghz_qubits, ghz_eq_circuits, shots=shots) plot_wigner_data(wghzdata_eq, method='curve') import matplotlib.pyplot as plt plt.plot(phi, wghzdata_eq, 'o') plt.axis([0, 2*np.pi, -0.6, 0.6]) plt.show() density_matrix = np.zeros((32,32)) density_matrix[0][0] = 0.5 density_matrix[0][31] = -0.5 density_matrix[31][0] = -0.5 density_matrix[31][31] = 0.5 plot_wigner_function(density_matrix, res=200)
https://github.com/xtophe388/QISKIT
xtophe388
# You may need to trust this notebook before the button below works from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''') def cplayer_output(strategy, inp): if(strategy == 1): return inp elif(strategy == 2): return abs(inp-1) elif(strategy == 3): return 1 elif(strategy == 4): return 0 else: print("INVALID choice") return 100 # Pick Alice's classical strategy A_st = int(input('select the classical strategy for Alice, input 1,2,3 or 4 to pick one of the strategies listed above ')) # Pick Bob's classical strategy B_st = int(input('select the classical strategy for Bob, input 1,2,3 or 4 to pick one of the strategies listed above ')) # useful packages import numpy as np import random as rand # fixes the numbers of games to be played N=100 # initializes counters used to keep track of the numbers of games won and played by Alice an Bob cont_win = 0 # counts games won cont_tot = 0 # counts games played # play the game N times for i in range(N): # generates two random input from the refree, x and y, to be given to Alice and Bob random_num1 = rand.random() # first random number random_num2 = rand.random() # second random number if(random_num1 >= 1/2): # converts the first random number to 0 or 1 x = 0 else: x = 1 if(random_num2 >= 1/2): # converts the second random number to 0 or 1 y = 0 else: y = 1 # generates Alice's and Bob's output a = cplayer_output(A_st, x) # Alice's output b = cplayer_output(B_st, y) # Bob's output # check if the condition for winning the game is met if(x*y == a^b): cont_win += 1 # increase thes won games' counter if the condition to win the game is met cont_tot += 1 # increases the played games' counter Prob_win = cont_win/cont_tot # winning probability print('Alice and Bob won the game with probability: ', Prob_win*100, '%') def qAlice_output(strategy, inp): if(strategy == 1): return 0 elif(strategy == 2): return rand.uniform(0,2*np.pi) elif(strategy == 3): if(inp == 0): return 0 elif(inp == 1): return np.pi/2 else: print("INVALID choice") return 100 def qBob_output(strategy, inp): if(strategy == 1): return 0 elif(strategy == 2): return rand.uniform(0,2*np.pi) elif(strategy == 3): if(inp == 0): return np.pi/4 elif(inp == 1): return -np.pi/4 else: print("INVALID choice") return 100 # Alice's strategy qA_st = int(input('select the quantum strategy for Alice, input 1,2 or 3 to pick one of the strategies listed above: ')) # Bob's strategy qB_st = int(input('select the quantum strategy for Bob, input 1,2 or 3 to pick one of the strategies listed above: ')) # import packages from qiskit import * import numpy as np import random as rand # set parameters of the quantum run of the game shots = 1 # set how many times the circuit is run, accumulating statistics about the measurement outcomes backend = 'local_qasm_simulator' # set the machine where the quantum circuit is to be run #fixes the numbers of games to be played N=100 # initializes counters used to keep track of the numbers of games won and played by Alice an Bob cont_win = 0 # counts games won cont_tot = 0 # counts games played #play N games for i in range(N): #creates quantum program, which allows to specify the details of the circuit like the register and the gates used Q_program = QuantumProgram() # creates registers for qubits and bits q = Q_program.create_quantum_register('q', 2) # creates a quantum register, it specifies the qubits which are going to be used for the program c = Q_program.create_classical_register('c', 2) # creates a classical register, the results of the measurement of the qubits are stored here # creates quantum circuit, to write a quantum algorithm we will add gates to the circuit game = Q_program.create_circuit('game', [q], [c]) # These gates prepare the entangled Bell pair to be shared by Alice and Bob as part of their quantum strategy # Alice will have qubit 0 and Bob will have qubit 1 game.h(q[0]) # Hadamard gate on qubit 0 game.cx(q[0],q[1]) # CNOT gate on qubit 1 controlled by qubit 0 # generates two random input from the refree, x and y, to be given to Alice and Bob random_num1 = rand.random() # first random number random_num2 = rand.random() # second random number if(random_num1 >= 1/2): # converts the first random number to 0 or 1 x = 0 else: x = 1 if(random_num2 >= 1/2): # converts the second random number to 0 or 1 y = 0 else: y = 1 # The main part of Alice and Bob quantum strategy is to fix different rotation angles for their qubit according to the input x,y theta = qAlice_output(qA_st, x) # fixes Alice's rotation for her qubit phi = qBob_output(qB_st, y) # fixes Bob's rotation for his qubit # The following gates rotate Alice's qubit and Bob's qubit game.ry(theta,q[0]) #rotates Alice's qubit of an angle theta game.ry(phi,q[1]) ##rotates Bob's qubit of an angle phi # These gates are used to measure the value of the qubits game.measure(q[0], c[0]) # measure Alice's qubit and stores the result in a classical bit game.measure(q[1], c[1]) # measure Bob's qubit and stores the result in a classical bit # Assemble the gates in the circuit circuits = ['game'] # assemble circuit # executes circuit and store the output of the measurements result = Q_program.execute(circuits, backend=backend, shots=shots, wait=10, timeout=240) data = result.get_counts('game') # extract the outcomes and their statistics from the result of the execution # reads the result of the measurements of the quantum system for outcomes in data.keys(): out = outcomes # converts the result of the measurements contained in the classical register as string '00', '01', '10', '11', # which are the answers of Alice(a) and Bob (b), from a 'string' type to 'integer' type if(out == '00'): a = 0 b = 0 if(out == '01'): a = 1 b = 0 if(out == '10'): a = 0 b = 1 if(out == '11'): a = 1 b = 1 # check if the condition for winning the game is met if(x*y == a^b): cont_win += 1 # increase thes won games' counter if the condition to win the game is met cont_tot += 1 # increases the played games' counter qProb_win = cont_win/cont_tot print('Alice and Bob won the game with probability: ', qProb_win*100, '%') if Prob_win > qProb_win : print("The classical strategy gave Alice and Bob higher chances of winning") else: print("The quantum strategy gave Alice and Bob higher chances of winning")
https://github.com/xtophe388/QISKIT
xtophe388
# Checking the version of PYTHON; we only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # useful additional packages import numpy as np import random import re # regular expressions module # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram #import Qconfig # Quantum program setup Q_program = QuantumProgram() #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url # Creating registers qr = Q_program.create_quantum_register("qr", 2) cr = Q_program.create_classical_register("cr", 4) singlet = Q_program.create_circuit('singlet', [qr], [cr]) singlet.x(qr[0]) singlet.x(qr[1]) singlet.h(qr[0]) singlet.cx(qr[0],qr[1]) ## Alice's measurement circuits # measure the spin projection of Alice's qubit onto the a_1 direction (X basis) measureA1 = Q_program.create_circuit('measureA1', [qr], [cr]) measureA1.h(qr[0]) measureA1.measure(qr[0],cr[0]) # measure the spin projection of Alice's qubit onto the a_2 direction (W basis) measureA2 = Q_program.create_circuit('measureA2', [qr], [cr]) measureA2.s(qr[0]) measureA2.h(qr[0]) measureA2.t(qr[0]) measureA2.h(qr[0]) measureA2.measure(qr[0],cr[0]) # measure the spin projection of Alice's qubit onto the a_3 direction (standard Z basis) measureA3 = Q_program.create_circuit('measureA3', [qr], [cr]) measureA3.measure(qr[0],cr[0]) ## Bob's measurement circuits # measure the spin projection of Bob's qubit onto the b_1 direction (W basis) measureB1 = Q_program.create_circuit('measureB1', [qr], [cr]) measureB1.s(qr[1]) measureB1.h(qr[1]) measureB1.t(qr[1]) measureB1.h(qr[1]) measureB1.measure(qr[1],cr[1]) # measure the spin projection of Bob's qubit onto the b_2 direction (standard Z basis) measureB2 = Q_program.create_circuit('measureB2', [qr], [cr]) measureB2.measure(qr[1],cr[1]) # measure the spin projection of Bob's qubit onto the b_3 direction (V basis) measureB3 = Q_program.create_circuit('measureB3', [qr], [cr]) measureB3.s(qr[1]) measureB3.h(qr[1]) measureB3.tdg(qr[1]) measureB3.h(qr[1]) measureB3.measure(qr[1],cr[1]) ## Lists of measurement circuits aliceMeasurements = [measureA1, measureA2, measureA3] bobMeasurements = [measureB1, measureB2, measureB3] # Define the number of singlets N numberOfSinglets = 500 aliceMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b of Alice bobMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b' of Bob circuits = [] # the list in which the created circuits will be stored for i in range(numberOfSinglets): # create the name of the i-th circuit depending on Alice's and Bob's measurement choices circuitName = str(i) + ':A' + str(aliceMeasurementChoices[i]) + '_B' + str(bobMeasurementChoices[i]) # create the joint measurement circuit # add Alice's and Bob's measurement circuits to the singlet state curcuit Q_program.add_circuit(circuitName, singlet + # singlet state circuit aliceMeasurements[aliceMeasurementChoices[i]-1] + # measurement circuit of Alice bobMeasurements[bobMeasurementChoices[i]-1] # measurement circuit of Bob ) # add the created circuit to the circuits list circuits.append(circuitName) print(circuits[0]) result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240) print(result) result.get_counts(circuits[0]) abPatterns = [ re.compile('..00$'), # search for the '..00' output (Alice obtained -1 and Bob obtained -1) re.compile('..01$'), # search for the '..01' output re.compile('..10$'), # search for the '..10' output (Alice obtained -1 and Bob obtained 1) re.compile('..11$') # search for the '..11' output ] aliceResults = [] # Alice's results (string a) bobResults = [] # Bob's results (string a') for i in range(numberOfSinglets): res = list(result.get_counts(circuits[i]).keys())[0] # extract the key from the dict and transform it to str; execution result of the i-th circuit if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(-1) # Bob got the result -1 if abPatterns[1].search(res): aliceResults.append(1) bobResults.append(-1) if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(1) # Bob got the result 1 if abPatterns[3].search(res): aliceResults.append(1) bobResults.append(1) aliceKey = [] # Alice's key string k bobKey = [] # Bob's key string k' # comparing the stings with measurement choices for i in range(numberOfSinglets): # if Alice and Bob have measured the spin projections onto the a_2/b_1 or a_3/b_2 directions if (aliceMeasurementChoices[i] == 2 and bobMeasurementChoices[i] == 1) or (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 2): aliceKey.append(aliceResults[i]) # record the i-th result obtained by Alice as the bit of the secret key k bobKey.append(- bobResults[i]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k' keyLength = len(aliceKey) # length of the secret key abKeyMismatches = 0 # number of mismatching bits in Alice's and Bob's keys for j in range(keyLength): if aliceKey[j] != bobKey[j]: abKeyMismatches += 1 # function that calculates CHSH correlation value def chsh_corr(result): # lists with the counts of measurement results # each element represents the number of (-1,-1), (-1,1), (1,-1) and (1,1) results respectively countA1B1 = [0, 0, 0, 0] # XW observable countA1B3 = [0, 0, 0, 0] # XV observable countA3B1 = [0, 0, 0, 0] # ZW observable countA3B3 = [0, 0, 0, 0] # ZV observable for i in range(numberOfSinglets): res = list(result.get_counts(circuits[i]).keys())[0] # if the spins of the qubits of the i-th singlet were projected onto the a_1/b_1 directions if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 1): for j in range(4): if abPatterns[j].search(res): countA1B1[j] += 1 if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 3): for j in range(4): if abPatterns[j].search(res): countA1B3[j] += 1 if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 1): for j in range(4): if abPatterns[j].search(res): countA3B1[j] += 1 # if the spins of the qubits of the i-th singlet were projected onto the a_3/b_3 directions if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 3): for j in range(4): if abPatterns[j].search(res): countA3B3[j] += 1 # number of the results obtained from the measurements in a particular basis total11 = sum(countA1B1) total13 = sum(countA1B3) total31 = sum(countA3B1) total33 = sum(countA3B3) # expectation values of XW, XV, ZW and ZV observables (2) expect11 = (countA1B1[0] - countA1B1[1] - countA1B1[2] + countA1B1[3])/total11 # -1/sqrt(2) expect13 = (countA1B3[0] - countA1B3[1] - countA1B3[2] + countA1B3[3])/total13 # 1/sqrt(2) expect31 = (countA3B1[0] - countA3B1[1] - countA3B1[2] + countA3B1[3])/total31 # -1/sqrt(2) expect33 = (countA3B3[0] - countA3B3[1] - countA3B3[2] + countA3B3[3])/total33 # -1/sqrt(2) corr = expect11 - expect13 + expect31 + expect33 # calculate the CHSC correlation value (3) return corr corr = chsh_corr(result) # CHSH correlation value # CHSH inequality test print('CHSH correlation value: ' + str(round(corr, 3))) # Keys print('Length of the key: ' + str(keyLength)) print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n') # measurement of the spin projection of Alice's qubit onto the a_2 direction (W basis) measureEA2 = Q_program.create_circuit('measureEA2', [qr], [cr]) measureEA2.s(qr[0]) measureEA2.h(qr[0]) measureEA2.t(qr[0]) measureEA2.h(qr[0]) measureEA2.measure(qr[0],cr[2]) # measurement of the spin projection of Allice's qubit onto the a_3 direction (standard Z basis) measureEA3 = Q_program.create_circuit('measureEA3', [qr], [cr]) measureEA3.measure(qr[0],cr[2]) # measurement of the spin projection of Bob's qubit onto the b_1 direction (W basis) measureEB1 = Q_program.create_circuit('measureEB1', [qr], [cr]) measureEB1.s(qr[1]) measureEB1.h(qr[1]) measureEB1.t(qr[1]) measureEB1.h(qr[1]) measureEB1.measure(qr[1],cr[3]) # measurement of the spin projection of Bob's qubit onto the b_2 direction (standard Z measurement) measureEB2 = Q_program.create_circuit('measureEB2', [qr], [cr]) measureEB2.measure(qr[1],cr[3]) # lists of measurement circuits eveMeasurements = [measureEA2, measureEA3, measureEB1, measureEB2] # list of Eve's measurement choices # the first and the second elements of each row represent the measurement of Alice's and Bob's qubits by Eve respectively eveMeasurementChoices = [] for j in range(numberOfSinglets): if random.uniform(0, 1) <= 0.5: # in 50% of cases perform the WW measurement eveMeasurementChoices.append([0, 2]) else: # in 50% of cases perform the ZZ measurement eveMeasurementChoices.append([1, 3]) circuits = [] # the list in which the created circuits will be stored for j in range(numberOfSinglets): # create the name of the j-th circuit depending on Alice's, Bob's and Eve's choices of measurement circuitName = str(j) + ':A' + str(aliceMeasurementChoices[j]) + '_B' + str(bobMeasurementChoices[j] + 2) + '_E' + str(eveMeasurementChoices[j][0]) + str(eveMeasurementChoices[j][1] - 1) # create the joint measurement circuit # add Alice's and Bob's measurement circuits to the singlet state curcuit Q_program.add_circuit(circuitName, singlet + # singlet state circuit eveMeasurements[eveMeasurementChoices[j][0]-1] + # Eve's measurement circuit of Alice's qubit eveMeasurements[eveMeasurementChoices[j][1]-1] + # Eve's measurement circuit of Bob's qubit aliceMeasurements[aliceMeasurementChoices[j]-1] + # measurement circuit of Alice bobMeasurements[bobMeasurementChoices[j]-1] # measurement circuit of Bob ) # add the created circuit to the circuits list circuits.append(circuitName) result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240) print(result) print(str(circuits[0]) + '\t' + str(result.get_counts(circuits[0]))) ePatterns = [ re.compile('00..$'), # search for the '00..' result (Eve obtained the results -1 and -1 for Alice's and Bob's qubits) re.compile('01..$'), # search for the '01..' result (Eve obtained the results 1 and -1 for Alice's and Bob's qubits) re.compile('10..$'), re.compile('11..$') ] aliceResults = [] # Alice's results (string a) bobResults = [] # Bob's results (string a') # list of Eve's measurement results # the elements in the 1-st column are the results obtaned from the measurements of Alice's qubits # the elements in the 2-nd column are the results obtaned from the measurements of Bob's qubits eveResults = [] # recording the measurement results for j in range(numberOfSinglets): res = list(result.get_counts(circuits[j]).keys())[0] # extract a key from the dict and transform it to str # Alice and Bob if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(-1) # Bob got the result -1 if abPatterns[1].search(res): aliceResults.append(1) bobResults.append(-1) if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(1) # Bob got the result 1 if abPatterns[3].search(res): aliceResults.append(1) bobResults.append(1) # Eve if ePatterns[0].search(res): # check if the key is '00..' eveResults.append([-1, -1]) # results of the measurement of Alice's and Bob's qubits are -1,-1 if ePatterns[1].search(res): eveResults.append([1, -1]) if ePatterns[2].search(res): eveResults.append([-1, 1]) if ePatterns[3].search(res): eveResults.append([1, 1]) aliceKey = [] # Alice's key string a bobKey = [] # Bob's key string a' eveKeys = [] # Eve's keys; the 1-st column is the key of Alice, and the 2-nd is the key of Bob # comparing the strings with measurement choices (b and b') for j in range(numberOfSinglets): # if Alice and Bob measured the spin projections onto the a_2/b_1 or a_3/b_2 directions if (aliceMeasurementChoices[j] == 2 and bobMeasurementChoices[j] == 1) or (aliceMeasurementChoices[j] == 3 and bobMeasurementChoices[j] == 2): aliceKey.append(aliceResults[j]) # record the i-th result obtained by Alice as the bit of the secret key k bobKey.append(-bobResults[j]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k' eveKeys.append([eveResults[j][0], -eveResults[j][1]]) # record the i-th bits of the keys of Eve keyLength = len(aliceKey) # length of the secret skey abKeyMismatches = 0 # number of mismatching bits in the keys of Alice and Bob eaKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Alice ebKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Bob for j in range(keyLength): if aliceKey[j] != bobKey[j]: abKeyMismatches += 1 if eveKeys[j][0] != aliceKey[j]: eaKeyMismatches += 1 if eveKeys[j][1] != bobKey[j]: ebKeyMismatches += 1 eaKnowledge = (keyLength - eaKeyMismatches)/keyLength # Eve's knowledge of Bob's key ebKnowledge = (keyLength - ebKeyMismatches)/keyLength # Eve's knowledge of Alice's key corr = chsh_corr(result) # CHSH inequality test print('CHSH correlation value: ' + str(round(corr, 3)) + '\n') # Keys print('Length of the key: ' + str(keyLength)) print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n') print('Eve\'s knowledge of Alice\'s key: ' + str(round(eaKnowledge * 100, 2)) + ' %') print('Eve\'s knowledge of Bob\'s key: ' + str(round(ebKnowledge * 100, 2)) + ' %')
https://github.com/xtophe388/QISKIT
xtophe388
# checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram #import Qconfig # import basic plotting tools from qiskit.tools.visualization import plot_histogram from qiskit.tools.qcvv.tomography import marginal_counts # create a QuantumProgram object instance. q_program = QuantumProgram() #q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url # backend #backend = 'ibmqx2' backend = 'local_qasm_simulator' # quantum plain addition algorithm for 1-qubit numbers def addition_1bit(circuit, q): circuit.h(q[2]) circuit.cx(q[1], q[2]) circuit.tdg(q[2]) circuit.cx(q[0], q[2]) circuit.t(q[2]) circuit.cx(q[1], q[2]) circuit.tdg(q[2]) circuit.cx(q[0], q[2]) circuit.t(q[2]) circuit.h(q[2]) circuit.t(q[1]) circuit.cx(q[0], q[1]) circuit.t(q[0]) circuit.tdg(q[1]) # n-qubit number input state def number_state(circuit, q, a, b): if a == 1: circuit.x(q[0]) # q[0] contains the value of a if b == 1: circuit.x(q[1]) # q[1] contain the value of b # we define the values (0 or 1) a = 1 b = 1 # one single quantum register which contains 'a' (1 qubit) and 'b' (2 qubits) q = q_program.create_quantum_register("q", 3) # 3 qubits # clasical register c = q_program.create_classical_register("cr", 2) # 2 bits # quantum circuit involving the quantum register and the classical register add1bit_circuit = q_program.create_circuit("add", [q] ,[c]) # create the state containing a and b number_state(add1bit_circuit, q, a, b) # addition addition_1bit(add1bit_circuit, q) # measurements to see the result, which has been written in b (q[1]q[2]) add1bit_circuit.measure(q[1], c[0]) add1bit_circuit.measure(q[2], c[1]) # compile and execute the quantum program in the backend result = q_program.execute(["add"], backend=backend, shots=1024, max_credits=3, wait=10, timeout=999999) # show the results print(result) print(result.get_data("add")) counts = marginal_counts(result.get_counts("add"), [0, 1]) plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2))) # checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram # import basic plotting tools from qiskit.tools.visualization import plot_histogram # create a QuantumProgram object instance. q_program = QuantumProgram() # backend backend = 'local_qasm_simulator' def carry(circuit, q0, q1, q2, q3): "carry module" circuit.ccx(q1, q2, q3) circuit.cx(q1, q2) circuit.ccx(q0, q2, q3) def carry_inv(circuit, q0, q1, q2, q3): "carry module but running backwards" circuit.ccx(q0, q2, q3) circuit.cx(q1, q2) circuit.ccx(q1, q2, q3) def summation(circuit, q0, q1, q2): "summation module" circuit.cx(q1, q2) circuit.cx(q0, q2) # quantum plain addition algorithm for n-qubit numbers def addition_nbit(circuit, qa, qb, qcar, n): if n == 1: circuit.ccx(qa[0], qb[0], qb[1]) circuit.cx(qa[0], qb[0]) else: circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) circuit.cx(qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): summation(circuit, qcar[i-1], qa[i], qb[i]) carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1]) summation(circuit, qcar[0], qa[1], qb[1]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) # n-qubit number input state def number_state(circuit, q, x, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: circuit.x(q[i]) # we define the values a = 9 b = 14 # computing the number of qubits n needed n = len("{0:b}".format(a)) n2 = len("{0:b}".format(b)) if n2 > n: n = n2 # classical register with n+1 bits. c = q_program.create_classical_register("cr", n+1) # quantum registers qa = q_program.create_quantum_register("qa", n) # a qubits qb = q_program.create_quantum_register("qb", n+1) # b qubits # if n = 1, no need of carry register if n == 1: qcar = 0 # quantum circuit involving the quantum registers and the classical register addnbit_circuit = q_program.create_circuit("add", [qa, qb],[c]) else: qcar = q_program.create_quantum_register("qcar", n-1) # carry qubits # quantum circuit involving the quantum registers and the classical register addnbit_circuit = q_program.create_circuit("add", [qa, qb, qcar],[c]) # create the state containing a number_state(addnbit_circuit, qa, a, n) # create the state containing b number_state(addnbit_circuit, qb, b, n) # addition addition_nbit(addnbit_circuit, qa, qb, qcar, n) # measurements to see the result for i in range(n+1): addnbit_circuit.measure(qb[i], c[i]) # compile and execute the quantum program in the backend result = q_program.execute(["add"], backend=backend, shots=1024, timeout=999999) # show the results. print(result) print(result.get_data("add")) counts = result.get_counts("add") plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2))) # checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram # import basic plotting tools from qiskit.tools.visualization import plot_histogram # create a QuantumProgram object instance. q_program = QuantumProgram() # backend backend = 'local_qasm_simulator' def carry(circuit, q0, q1, q2, q3): "carry module" circuit.ccx(q1, q2, q3) circuit.cx(q1, q2) circuit.ccx(q0, q2, q3) def carry_inv(circuit, q0, q1, q2, q3): "carry module running backwards" circuit.ccx(q0, q2, q3) circuit.cx(q1, q2) circuit.ccx(q1, q2, q3) def summation(circuit, q0, q1, q2): "summation module" circuit.cx(q1, q2) circuit.cx(q0, q2) def summation_inv(circuit, q0, q1, q2): "summation module running backwards" circuit.cx(q0, q2) circuit.cx(q1, q2) # quantum plain addition algorithm for n-qubit numbers def addition_nbit(circuit, qa, qb, qcar, n): if n == 1: circuit.ccx(qa[0], qb[0], qb[1]) circuit.cx(qa[0], qb[0]) else: circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) circuit.cx(qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): summation(circuit, qcar[i-1], qa[i], qb[i]) carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1]) summation(circuit, qcar[0], qa[1], qb[1]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) # quantum plain substraction algorithm for n-qubit numbers def subs_nbit(circuit, qa, qb, qcar, n): "same circuit as the plain addition but going backwards" if n == 1: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qb[1]) else: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) summation_inv(circuit, qcar[0], qa[1], qb[1]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2]) circuit.cx(qa[n-1], qb[n-1]) carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) for i in range(n-2, 0, -1): carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) def cond_toffoli(circuit, qcond, q1, q2, q3): "toffoli gate conditioned by an external qubit" circuit.h(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.h(q3) circuit.t(q2) circuit.ccx(qcond, q1, q2) circuit.t(q1) circuit.tdg(q2) circuit.ccx(qcond, q1, q2) def cond_carry(circuit, q0, q1, q2, q3, qcond): "conditional carry module" cond_toffoli(circuit, qcond, q1, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q0, q2, q3) def cond_carry_inv(circuit, q0, q1, q2, q3, qcond): "conditional carry module running backwards" cond_toffoli(circuit, qcond, q0, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q1, q2, q3) def cond_summation(circuit, q0, q1, q2, qcond): "conditional summation module" circuit.ccx(qcond, q1, q2) circuit.ccx(qcond, q0, q2) def cond_summation_inv(circuit, q0, q1, q2, qcond): "conditional summation module running backwards" circuit.ccx(qcond, q0, q2) circuit.ccx(qcond, q1, q2) # quantum conditional plain addition algorithm for n-qubit numbers def cond_addition_nbit(circuit, qa, qb, qcar, qcond, n): "plain addition algorithm conditioned by an external qubit" if n == 1: cond_toffoli(circuit, qcond[0], qa[0], qb[0], qb[1]) circuit.ccx(qcond[0], qa[0], qb[0]) else: cond_toffoli(circuit, qcond[0], qa[0], qb[0], qcar[0]) circuit.ccx(qcond[0], qa[0], qb[0]) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond[0]) cond_carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond[0]) circuit.ccx(qcond[0], qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): cond_summation(circuit, qcar[i-1], qa[i], qb[i], qcond[0]) cond_carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1], qcond[0]) cond_summation(circuit, qcar[0], qa[1], qb[1], qcond[0]) circuit.ccx(qcond[0], qa[0], qb[0]) cond_toffoli(circuit, qcond[0], qa[0], qb[0], qcar[0]) circuit.ccx(qcond[0], qa[0], qb[0]) # quantum conditional plain substraction algorithm for n-qubit numbers def cond_subs_nbit(circuit, qa, qb, qcar, qcond, n): "same circuit as the conditional plain addition but going backwards" if n == 1: circuit.ccx(qcond[0], qa[0], qb[0]) cond_toffoli(circuit, qcond[0], qa[0], qb[0], qb[1]) else: circuit.ccx(qcond[0], qa[0], qb[0]) cond_toffoli(circuit, qcond[0], qa[0], qb[0], qcar[0]) circuit.ccx(qcond[0], qa[0], qb[0]) cond_summation_inv(circuit, qcar[0], qa[1], qb[1], qcond[0]) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond[0]) cond_summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2], qcond[0]) circuit.ccx(qcond[0], qa[n-1], qb[n-1]) cond_carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond[0]) for i in range(n-2, 0, -1): cond_carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i], qcond[0]) circuit.ccx(qcond[0], qa[0], qb[0]) cond_toffoli(circuit, qcond[0], qa[0], qb[0], qcar[0]) # quantum modular addition algorithm for n-qubit numbers def mod_addition_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, n): addition_nbit(circuit, qa, qb, qcar, n) subs_nbit(circuit, qN, qb, qcar, n) circuit.x(qb[n]) circuit.cx(qb[n], qtemp[0]) circuit.x(qb[n]) cond_subs_nbit(circuit, qNtemp, qN, qcar, qtemp, n) addition_nbit(circuit, qN, qb, qcar, n) cond_addition_nbit(circuit, qNtemp, qN, qcar, qtemp, n) subs_nbit(circuit, qa, qb, qcar, n) circuit.cx(qb[n], qtemp[0]) addition_nbit(circuit, qa, qb, qcar, n) # n-qubit number input state def number_state(circuit, q, x, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: circuit.x(q[i]) # we define the values a = 2 b = 3 N = 3 # computing number of qubits n needed n = len("{0:b}".format(a)) n2 = len("{0:b}".format(b)) n3 = len("{0:b}".format(N)) if n2 > n: n = n2 if n3 > n: n = n3 # classical register with n+1 bits. c = q_program.create_classical_register("cr", n+1) # quantum registers qa = q_program.create_quantum_register("qa", n) # a qubits qb = q_program.create_quantum_register("qb", n+1) # b qubits qN = q_program.create_quantum_register("qN", n+1) # N qubits qNtemp = q_program.create_quantum_register("qNtemp", n) # temporary N qubits qtemp = q_program.create_quantum_register("qtemp", 1) # temporary qubit # if n = 1, no need of carry register if n == 1: qcar = 0 # quantum circuit involving the quantum registers and the classical register mod_add_circuit = q_program.create_circuit("mod_add", [qa, qb, qN, qNtemp, qtemp],[c]) else: qcar = q_program.create_quantum_register("qcar", n-1) # carry qubits # quantum circuit involving the quantum registers and the classical register mod_add_circuit = q_program.create_circuit("mod_add", [qa, qb, qN, qcar, qNtemp, qtemp],[c]) # create the state containing 'a' number_state(mod_add_circuit, qa, a, n) # create the state containing 'b' number_state(mod_add_circuit, qb, b, n) # create the state containing 'N' number_state(mod_add_circuit, qN, N, n) # create the temporary state containing 'N' number_state(mod_add_circuit, qNtemp, N, n) # modular addition mod_addition_nbit(mod_add_circuit, qa, qb, qN, qNtemp, qcar, qtemp, n) # measurements to see the result for i in range(n+1): mod_add_circuit.measure(qb[i], c[i]) # compile and execute the quantum program in the backend result = q_program.execute(["mod_add"], backend=backend, shots=1024, max_credits=3, wait=10, timeout=999999) # show the results. print(result) print(result.get_data("mod_add")) counts = result.get_counts("mod_add") plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2))) # checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram # import basic plotting tools from qiskit.tools.visualization import plot_histogram # create a QuantumProgram object instance. q_program = QuantumProgram() # backend backend = 'local_qasm_simulator' def carry(circuit, q0, q1, q2, q3): "carry module" circuit.ccx(q1, q2, q3) circuit.cx(q1, q2) circuit.ccx(q0, q2, q3) def carry_inv(circuit, q0, q1, q2, q3): "carry module running backwards" circuit.ccx(q0, q2, q3) circuit.cx(q1, q2) circuit.ccx(q1, q2, q3) def summation(circuit, q0, q1, q2): "summation module" circuit.cx(q1, q2) circuit.cx(q0, q2) def summation_inv(circuit, q0, q1, q2): "summation module running backwards" circuit.cx(q0, q2) circuit.cx(q1, q2) # quantum plain addition algorithm for n-qubit numbers def addition_nbit(circuit, qa, qb, qcar, n): if n == 1: circuit.ccx(qa[0], qb[0], qb[1]) circuit.cx(qa[0], qb[0]) else: circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) circuit.cx(qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): summation(circuit, qcar[i-1], qa[i], qb[i]) carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1]) summation(circuit, qcar[0], qa[1], qb[1]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) # quantum plain substraction algorithm for n-qubit numbers def subs_nbit(circuit, qa, qb, qcar, n): "same circuit as the addition but going backwards" if n == 1: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qb[1]) else: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) summation_inv(circuit, qcar[0], qa[1], qb[1]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2]) circuit.cx(qa[n-1], qb[n-1]) carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) for i in range(n-2, 0, -1): carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) def cond_toffoli(circuit, qcond, q1, q2, q3): "toffoli gate conditioned by an external qubit" circuit.h(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.h(q3) circuit.t(q2) circuit.ccx(qcond, q1, q2) circuit.t(q1) circuit.tdg(q2) circuit.ccx(qcond, q1, q2) def cond_carry(circuit, q0, q1, q2, q3, qcond): "conditional carry module" cond_toffoli(circuit, qcond, q1, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q0, q2, q3) def cond_carry_inv(circuit, q0, q1, q2, q3, qcond): "conditional carry module running backwards" cond_toffoli(circuit, qcond, q0, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q1, q2, q3) def cond_summation(circuit, q0, q1, q2, qcond): "conditional summation module" circuit.ccx(qcond, q1, q2) circuit.ccx(qcond, q0, q2) def cond_summation_inv(circuit, q0, q1, q2, qcond): "conditional summation module running backwards" circuit.ccx(qcond, q0, q2) circuit.ccx(qcond, q1, q2) # quantum conditional plain addition algorithm for n-qubit numbers def cond_addition_nbit(circuit, qa, qb, qcar, qcond, n): if n == 1: cond_toffoli(circuit, qcond, qa[0], qb[0], qb[1]) circuit.ccx(qcond, qa[0], qb[0]) else: cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond) cond_carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond) circuit.ccx(qcond, qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): cond_summation(circuit, qcar[i-1], qa[i], qb[i], qcond) cond_carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1], qcond) cond_summation(circuit, qcar[0], qa[1], qb[1], qcond) circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) # quantum conditional plain substraction algorithm for n-qubit numbers def cond_subs_nbit(circuit, qa, qb, qcar, qcond, n): "same circuit as the conditional plain addition but going backwards" if n == 1: circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qb[1]) else: circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) cond_summation_inv(circuit, qcar[0], qa[1], qb[1], qcond) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond) cond_summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2], qcond) circuit.ccx(qcond, qa[n-1], qb[n-1]) cond_carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond) for i in range(n-2, 0, -1): cond_carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i], qcond) circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) # quantum modular addition algorithm for n-qubit numbers def mod_addition_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, n): addition_nbit(circuit, qa, qb, qcar, n) subs_nbit(circuit, qN, qb, qcar, n) circuit.x(qb[n]) circuit.cx(qb[n], qtemp) circuit.x(qb[n]) cond_subs_nbit(circuit, qNtemp, qN, qcar, qtemp, n) addition_nbit(circuit, qN, qb, qcar, n) cond_addition_nbit(circuit, qNtemp, qN, qcar, qtemp, n) subs_nbit(circuit, qa, qb, qcar, n) circuit.cx(qb[n], qtemp) addition_nbit(circuit, qa, qb, qcar, n) # quantum controlled modular multiplication algorithm for n-qubit numbers def cont_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, qX, qext, N, n): for i in range(n): for j in range(n): classical_mod = (2**(i+j))%N cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) mod_addition_nbit(circuit, qtempst, qb, qN, qNtemp, qcar, qtemp, n) cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) circuit.x(qext) cond_addition_nbit(circuit, qX, qb, qcar, qext, n) circuit.x(qext) # n-qubit number input state def number_state(circuit, q, x, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: circuit.x(q[i]) # n-qubit number input state, controlled by 2 control qubits def cond_number_state(circuit, q, x, ext, control1, control2, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: cond_toffoli(circuit, ext, control1, control2, q[i]) # we define the values a = 1 x = 1 N = 1 # computing number of qubits n needed n = len("{0:b}".format(a)) n2 = len("{0:b}".format(x)) n3 = len("{0:b}".format(N)) if n2 > n: n = n2 if n3 > n: n = n3 # classical register with n+1 bits. c = q_program.create_classical_register("cr", n+1) # quantum registers qa = q_program.create_quantum_register("qa", n) # a qubits qb = q_program.create_quantum_register("qb", n+1) # result register qN = q_program.create_quantum_register("qN", n+1) # N qubits qNtemp = q_program.create_quantum_register("qNtemp", n) # temporary N qubits qtemp = q_program.create_quantum_register("qtemp", 1) # temporary qubit qtempst = q_program.create_quantum_register("qtempst", n) # temporary register qX = q_program.create_quantum_register("qX", n) # x register qext = q_program.create_quantum_register("qext", 1) # if n = 1, no need of carry register if n == 1: qcar = 0 # quantum circuit involving the quantum registers and the classical register mod_mult_circuit = q_program.create_circuit("mod_mult", [qa, qb, qN, qNtemp, qtemp, qtempst, qX, qext],[c]) else: qcar = q_program.create_quantum_register("qcar", n-1) # carry qubits # quantum circuit involving the quantum register and the classical register mod_mult_circuit = q_program.create_circuit("mod_mult", [qa, qb, qN, qcar, qNtemp, qtemp, qtempst, qX, qext],[c]) # create the state containing 'a' number_state(mod_mult_circuit, qa, a, n) # create the state containing 'b' number_state(mod_mult_circuit, qX, x, n) # create the state containing 'N' number_state(mod_mult_circuit, qN, N, n+1) # create a temporary state containing 'N' number_state(mod_mult_circuit, qNtemp, N, n) mod_mult_circuit.x(qext[0]) # we set the control qubit to |1> # controlled modular multiplication cont_mod_mult_nbit(mod_mult_circuit, qa, qb, qN, qNtemp, qcar, qtemp[0], qtempst, qX, qext[0], N, n) # measurements to see the result for i in range(n+1): mod_mult_circuit.measure(qb[i], c[i]) # compile and execute the quantum program in the backend result = q_program.execute(["mod_mult"], backend=backend, shots=1024, max_credits=3, wait=10, timeout=999999) # show the results. print(result) print(result.get_data("mod_mult")) counts = result.get_counts("mod_mult") plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2))) # checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram # import basic plotting tools from qiskit.tools.visualization import plot_histogram # create a QuantumProgram object instance. q_program = QuantumProgram() # backend backend = 'local_qasm_simulator' def carry(circuit, q0, q1, q2, q3): "carry module" circuit.ccx(q1, q2, q3) circuit.cx(q1, q2) circuit.ccx(q0, q2, q3) def carry_inv(circuit, q0, q1, q2, q3): "carry module running backwards" circuit.ccx(q0, q2, q3) circuit.cx(q1, q2) circuit.ccx(q1, q2, q3) def summation(circuit, q0, q1, q2): "summation module" circuit.cx(q1, q2) circuit.cx(q0, q2) def summation_inv(circuit, q0, q1, q2): "summation module running backwards" circuit.cx(q0, q2) circuit.cx(q1, q2) # quantum plain addition algorithm for n-qubit numbers def addition_nbit(circuit, qa, qb, qcar, n): if n == 1: circuit.ccx(qa[0], qb[0], qb[1]) circuit.cx(qa[0], qb[0]) else: circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) circuit.cx(qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): summation(circuit, qcar[i-1], qa[i], qb[i]) carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1]) summation(circuit, qcar[0], qa[1], qb[1]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) # quantum plain substraction algorithm for n-qubit numbers def subs_nbit(circuit, qa, qb, qcar, n): "same as the plain addition but running backwards" if n == 1: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qb[1]) else: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) summation_inv(circuit, qcar[0], qa[1], qb[1]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2]) circuit.cx(qa[n-1], qb[n-1]) carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) for i in range(n-2, 0, -1): carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) def cond_toffoli(circuit, qcond, q1, q2, q3): "conditional toffoli gate" circuit.h(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.h(q3) circuit.t(q2) circuit.ccx(qcond, q1, q2) circuit.t(q1) circuit.tdg(q2) circuit.ccx(qcond, q1, q2) def cond_carry(circuit, q0, q1, q2, q3, qcond): "conditional carry module" cond_toffoli(circuit, qcond, q1, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q0, q2, q3) def cond_carry_inv(circuit, q0, q1, q2, q3, qcond): "conditional carry module running backwards" cond_toffoli(circuit, qcond, q0, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q1, q2, q3) def cond_summation(circuit, q0, q1, q2, qcond): "conditional summation" circuit.ccx(qcond, q1, q2) circuit.ccx(qcond, q0, q2) def cond_summation_inv(circuit, q0, q1, q2, qcond): "conditional summation running backwards" circuit.ccx(qcond, q0, q2) circuit.ccx(qcond, q1, q2) # quantum conditional plain addition algorithm for n-qubit numbers def cond_addition_nbit(circuit, qa, qb, qcar, qcond, n): if n == 1: cond_toffoli(circuit, qcond, qa[0], qb[0], qb[1]) circuit.ccx(qcond, qa[0], qb[0]) else: cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond) cond_carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond) circuit.ccx(qcond, qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): cond_summation(circuit, qcar[i-1], qa[i], qb[i], qcond) cond_carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1], qcond) cond_summation(circuit, qcar[0], qa[1], qb[1], qcond) circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) # quantum conditional plain substraction algorithm for n-qubit numbers def cond_subs_nbit(circuit, qa, qb, qcar, qcond, n): "same as conditional plain addition but running backwards" if n == 1: circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qb[1]) else: circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) cond_summation_inv(circuit, qcar[0], qa[1], qb[1], qcond) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond) cond_summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2], qcond) circuit.ccx(qcond, qa[n-1], qb[n-1]) cond_carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond) for i in range(n-2, 0, -1): cond_carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i], qcond) circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) # quantum modular addition algorithm for n-qubit numbers def mod_addition_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, n): addition_nbit(circuit, qa, qb, qcar, n) subs_nbit(circuit, qN, qb, qcar, n) circuit.x(qb[n]) circuit.cx(qb[n], qtemp) circuit.x(qb[n]) cond_subs_nbit(circuit, qNtemp, qN, qcar, qtemp, n) addition_nbit(circuit, qN, qb, qcar, n) cond_addition_nbit(circuit, qNtemp, qN, qcar, qtemp, n) subs_nbit(circuit, qa, qb, qcar, n) circuit.cx(qb[n], qtemp) addition_nbit(circuit, qa, qb, qcar, n) # quantum modular substraction algorithm for n-qubit numbers def mod_subs_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, n): "same as modular addition but running backwards" subs_nbit(circuit, qa, qb, qcar, n) circuit.cx(qb[n], qtemp) addition_nbit(circuit, qa, qb, qcar, n) cond_subs_nbit(circuit, qNtemp, qN, qcar, qtemp, n) subs_nbit(circuit, qN, qb, qcar, n) cond_addition_nbit(circuit, qNtemp, qN, qcar, qtemp, n) circuit.x(qb[n]) circuit.cx(qb[n], qtemp) circuit.x(qb[n]) addition_nbit(circuit, qN, qb, qcar, n) subs_nbit(circuit, qa, qb, qcar, n) # quantum controlled modular multiplication algorithm for n-qubit numbers def cont_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, qX, qext, N, n): for i in range(n): for j in range(n): classical_mod = (2**(i+j))%N cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) mod_addition_nbit(circuit, qtempst, qb, qN, qNtemp, qcar, qtemp, n) cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) circuit.x(qext) cond_addition_nbit(circuit, qX, qb, qcar, qext, n) circuit.x(qext) def cont_inv_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, qX, qext, N, n): "same as the controlled modular multiplication but running backwards" circuit.x(qext) cond_subs_nbit(circuit, qX, qb, qcar, qext, n) circuit.x(qext) for i in range(n): for j in range(n): classical_mod = (2**(i+j))%N cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) mod_subs_nbit(circuit, qtempst, qb, qN, qNtemp, qcar, qtemp, n) cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) # quantum modular exponentiation algorithm for n-qubit numbers def mod_exp_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, q1, qX, N, a, n): for k in range(len(qX)): clas_value = (a**(2**(k)))%N if k % 2 == 0: number_state(circuit, qa, clas_value, n) cont_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, q1, qX[k], N, n) number_state(circuit, qa, clas_value, n) clas_value = modinv(a**(2**(k)), N) number_state(circuit, qa, clas_value, n) cont_inv_mod_mult_nbit(circuit, qa, q1, qN, qNtemp, qcar, qtemp, qtempst, qb, qX[k], N, n) number_state(circuit, qa, clas_value, n) else: number_state(circuit, qa, clas_value, n) cont_mod_mult_nbit(circuit, qa, q1, qN, qNtemp, qcar, qtemp, qtempst, qb, qX[k], N, n) number_state(circuit, qa, clas_value, n) clas_value = modinv(a**(2**(k)), N) number_state(circuit, qa, clas_value, n) cont_inv_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, q1, qX[k], N, n) number_state(circuit, qa, clas_value, n) # n-qubit number input state def number_state(circuit, q, x, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: circuit.x(q[i]) # n-qubit number input state, controlled by 2 control qubits def cond_number_state(circuit, q, x, ext, control1, control2, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: cond_toffoli(circuit, ext, control1, control2, q[i]) # efficient algorithm for computing the modular multiplicative inverse a^-1 mod m def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m # we define the values, a and N must be coprimes a = 1 x = 1 N = 1 # computing number of qubits n needed n = len("{0:b}".format(a)) n2 = len("{0:b}".format(x)) n3 = len("{0:b}".format(N)) if n3 > n: n = n3 # classical register with n+1 bits. c = q_program.create_classical_register("cr", n+1) # quantum registers qa = q_program.create_quantum_register("qa", n) # a qubits qb = q_program.create_quantum_register("qb", n+1) # initial state |0> qN = q_program.create_quantum_register("qN", n+1) # N qubits qNtemp = q_program.create_quantum_register("qNtemp", n) # temporary N qubits qtemp = q_program.create_quantum_register("qtemp", 1) # temporary qubit qtempst = q_program.create_quantum_register("qtempst", n) # temporary register q1 = q_program.create_quantum_register("q1", n+1) # initial state |1> qX = q_program.create_quantum_register("qX", n2) # x register # if n = 1, no need of carry register if n == 1: qcar = 0 # quantum circuit involving the quantum registers and the classical register mod_exp_circuit = q_program.create_circuit("mod_exp", [qa, qb, qN, qNtemp, qtemp, qtempst, q1, qX],[c]) else: qcar = q_program.create_quantum_register("qcar", n-1) # carry qubits # quantum circuit involving the quantum registers and the classical register mod_exp_circuit = q_program.create_circuit("mod_exp", [qa, qb, qN, qcar, qNtemp, qtemp, qtempst, q1, qX],[c]) # create the initial state |1>. If N = 1, initial state is |0> if N != 1: number_state(mod_exp_circuit, q1, 1, 1) # create the state containing 'x' number_state(mod_exp_circuit, qX, x, n2) # create the state containing 'N' number_state(mod_exp_circuit, qN, N, n+1) # create a temporary state containing 'N' number_state(mod_exp_circuit, qNtemp, N, n) # modular exponentiation mod_exp_nbit(mod_exp_circuit, qa, qb, qN, qNtemp, qcar, qtemp[0], qtempst, q1, qX, N, a, n) # measurements to see the result, the result would be in one of those registers, q1 or qb if n2 % 2 == 0: for i in range(n+1): mod_exp_circuit.measure(q1[i], c[i]) else: for i in range(n+1): mod_exp_circuit.measure(qb[i], c[i]) # compile and execute the quantum program in the backend result = q_program.execute(["mod_exp"], backend=backend, shots=1024, max_credits=3, wait=10, timeout=9999999) # show the results. print(result) print(result.get_data("mod_exp")) counts = result.get_counts("mod_exp") plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2)))
https://github.com/xtophe388/QISKIT
xtophe388
def digit_sum(n): num_str = str(n) sum = 0 for i in range(0, len(num_str)): sum += int(num_str[i]) return sum # CZ (Controlled-Z) # control qubit: q0 # target qubit: q1 def CZ(qp,q0,q1): qp.h(q1) qp.cx(q0,q1) qp.h(q1) # f-SWAP # taking into account the one-directionality of CNOT gates in the available devices def fSWAP(qp,q0,q1): qp.cx(q0,q1) qp.h(q0) qp.h(q1) qp.cx(q0,q1) qp.h(q0) qp.h(q1) qp.cx(q0,q1) CZ(qp,q0,q1) # CH (Controlled-Haddamard) # control qubit: q1 # target qubit: q0 def CH2(qp,q0,q1): qp.sdg(q0) qp.h(q0) qp.tdg(q0) qp.h(q0) qp.h(q1) qp.cx(q0,q1) qp.h(q0) qp.h(q1) qp.t(q0) qp.h(q0) qp.s(q0) # Fourier transform gates def F2(qp,q0,q1): qp.cx(q0,q1) CH2(qp,q0,q1) qp.cx(q0,q1) CZ(qp,q0,q1) def F0(qp,q0,q1): F2(qp,q0,q1) def F1(qp,q0,q1): F2(qp,q0,q1) qp.sdg(q0) from math import pi # ROTATIONAL GATES def RZ(qp,th,q0): qp.u1(-th,q0) def RY(qp,th,q0): qp.u3(th,0.,0.,q0) def RX(qp,th,q0): qp.u3(th,0.,pi,q0) # CRX (Controlled-RX) # control qubit: q0 # target qubit: q1 def CRX(qp,th,q0,q1): RZ(qp,pi/2.0,q1) RY(qp,th/2.0,q1) qp.cx(q0,q1) RY(qp,-th/2.0,q1) qp.cx(q0,q1) RZ(qp,-pi/2.0,q1) # Bogoliubov B_1 def B(qp,thk,q0,q1): qp.x(q1) qp.cx(q1,q0) CRX(qp,thk,q0,q1) qp.cx(q1,q0) qp.x(q1) # This circuit can be implemented in ibmqx5 using qubits (q0,q1,q2,q3)=(6,7,11,10) # It can also be implemented between other qubits or in ibqmx2 and ibqmx4 using fermionic SWAPS # For instance, the lines commented correspond to the implementations: # ibmqx2 (q0,q1,q2,q3)=(4,2,0,1) # ibmqx4 (q0,q1,q2,q3)=(3,2,1,0) def Udisg(qc,lam,q0,q1,q2,q3): k=1 n=4 th1=-np.arccos((lam-np.cos(2*pi*k/n))/np.sqrt((lam-np.cos(2*pi*k/n))**2+np.sin(2*pi*k/n)**2)) B(Udis,th1,q0,q1) F1(Udis,q0,q1) F0(Udis,q2,q3) #fSWAP(Udis,q2,q1) # for ibmqx2 #fSWAP(Udis,q1,q2) # for ibmqx4 F0(Udis,q0,q2) F0(Udis,q1,q3) #fSWAP(Udis,q2,q1) # for ibmqx2 #fSWAP(Udis,q1,q2) # for ibmqx4 def Initial(qc,lam,q0,q1,q2,q3): if lam <1: qc.x(q3) def Ising(qc,ini,udis,mes,lam,q0,q1,q2,q3,c0,c1,c2,c3): Initial(ini,lam,q0,q1,q2,q3) Udisg(udis,lam,q0,q1,q2,q3) mes.measure(q0,c0) mes.measure(q1,c1) mes.measure(q2,c2) mes.measure(q3,c3) qc.add_circuit("Ising",ini+udis+mes) #import sys #sys.path.append("../../") # importing the QISKit from qiskit import QuantumCircuit,QuantumProgram #import Qconfig # useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from scipy import linalg as la # Simulator shots = 1024 backend ='ibmqx_qasm_simulator' coupling_map = None mag_sim = [] for i in range(8): Isex = QuantumProgram() q = Isex.create_quantum_register("q",4) c = Isex.create_classical_register("c", 4) Udis = Isex.create_circuit("Udis", [q], [c]) ini = Isex.create_circuit("ini",[q],[c]) mes = Isex.create_circuit("mes",[q],[c]) lam=i*0.25 Ising(Isex,ini,Udis,mes,lam,q[0],q[1],q[2],q[3],c[0],c[1],c[2],c[3]) # Isex.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url result = Isex.execute(["Ising"], backend=backend, coupling_map=coupling_map, shots=shots,timeout=240000) res=result.get_counts("Ising") r1=list(res.keys()) r2=list(res.values()) M=0 for j in range(0,len(r1)): M=M+(4-2*digit_sum(r1[j]))*r2[j]/shots #print("$\lambda$: ",lam,", $<\sigma_{z}>$: ",M/4) mag_sim.append(M/4) # Real device shots = 1024 #backend ='ibmqx5' max_credits = 5 mag=[] for i in range(8): Isex = QuantumProgram() q = Isex.create_quantum_register("q",12) c = Isex.create_classical_register("c", 4) Udis = Isex.create_circuit("Udis", [q], [c]) ini = Isex.create_circuit("ini",[q],[c]) mes = Isex.create_circuit("mes",[q],[c]) lam=i*0.25 Ising(Isex,ini,Udis,mes,lam,q[6],q[7],q[11],q[10],c[0],c[1],c[2],c[3]) # Isex.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url result = Isex.execute(["Ising"], backend=backend, max_credits=max_credits, wait=10, shots=shots,timeout=240000) res=result.get_counts("Ising") r1=list(res.keys()) r2=list(res.values()) M=0 for j in range(0,len(r1)): M=M+(4-2*digit_sum(r1[j]))*r2[j]/shots #print("$\lambda$: ",lam,", $<\sigma_{z}>$: ",M/4) mag.append(M/4) # As it is a system of only 4 particles, we can easily compute the exact result def exact(lam): if lam <1: return lam/(2*np.sqrt(1+lam**2)) if lam >1: return 1/2+lam/(2*np.sqrt(1+lam**2)) return None vexact = np.vectorize(exact) l=np.arange(0.0,2.0,0.01) l1=np.arange(0.0,2.0,0.25) plt.figure(figsize=(9,5)) plt.plot(l,vexact(l),'k',label='exact') plt.plot(l1, mag_sim, 'bo',label='simulation') plt.plot(l1, mag, 'r*',label='ibmqx5') plt.xlabel('$\lambda$') plt.ylabel('$<\sigma_{z}>$') plt.legend() plt.title('Magnetization of the ground state of n=4 Ising spin chain') plt.show() #This was the result when the real device is used: def Initial_time(qc,t,lam,q0,q1,q2,q3): qc.u3(np.arccos(lam/np.sqrt(1+lam**2)),pi/2.+4*t*np.sqrt(1+lam**2),0.,q0) qc.cx(q0,q1) def Ising_time(qc,ini,udis,mes,lam,t,q0,q1,q2,q3,c0,c1,c2,c3): Initial_time(ini,t,lam,q0,q1,q2,q3) Udisg(udis,lam,q0,q1,q2,q3) mes.measure(q0,c0) mes.measure(q1,c1) mes.measure(q2,c2) mes.measure(q3,c3) qc.add_circuit("Ising_time",ini+udis+mes) #Simulation shots = 1024 backend = 'ibmqx_qasm_simulator' coupling_map = None # We compute the time evolution for lambda=0.5,0.9 and 1.8 nlam=3 magt_sim=[[] for _ in range(nlam)] lam0=[0.5,0.9,1.8] for j in range(nlam): lam=lam0[j] for i in range(9): Isex_time = QuantumProgram() q = Isex_time.create_quantum_register("q",4) c = Isex_time.create_classical_register("c", 4) Udis = Isex_time.create_circuit("Udis", [q], [c]) ini = Isex_time.create_circuit("ini",[q],[c]) mes = Isex_time.create_circuit("mes",[q],[c]) t=i*0.25 Ising_time(Isex_time,ini,Udis,mes,lam,t,q[0],q[1],q[2],q[3],c[0],c[1],c[2],c[3]) Isex_time.set_api(Qconfig.APItoken, Qconfig.config["url"]) result = Isex_time.execute(["Ising_time"], backend=backend, coupling_map=coupling_map, shots=shots,timeout=240000) res=result.get_counts("Ising_time") r1=list(res.keys()) r2=list(res.values()) M=0 for k in range(0,len(r1)): M=M+(4-2*digit_sum(r1[k]))*r2[k]/shots magt_sim[j].append(M/4) shots = 1024 backend = 'ibmqx5' max_credits = 5 # We compute the time evolution for lambda=0.5,0.9 and 1.8 nlam=3 magt=[[] for _ in range(nlam)] lam0=[0.5,0.9,1.8] for j in range(nlam): lam=lam0[j] for i in range(9): Isex_time = QuantumProgram() q = Isex_time.create_quantum_register("q",12) c = Isex_time.create_classical_register("c", 4) Udis = Isex_time.create_circuit("Udis", [q], [c]) ini = Isex_time.create_circuit("ini",[q],[c]) mes = Isex_time.create_circuit("mes",[q],[c]) t=i*0.25 Ising_time(Isex_time,ini,Udis,mes,lam,t,q[6],q[7],q[11],q[10],c[0],c[1],c[2],c[3]) Isex_time.set_api(Qconfig.APItoken, Qconfig.config["url"]) result = Isex_time.execute(["Ising_time"], backend=backend, max_credits=max_credits, wait=10, shots=shots,timeout=240000) res=result.get_counts("Ising_time") r1=list(res.keys()) r2=list(res.values()) M=0 for k in range(0,len(r1)): M=M+(4-2*digit_sum(r1[k]))*r2[k]/shots magt[j].append(M/4) def exact_time(lam,tt): Mt=(1 + 2*lam**2 + np.cos(4*tt*np.sqrt(1 + lam**2)))/(2 + 2*lam**2) return Mt vexact_t = np.vectorize(exact_time) t=np.arange(0.0,2.0,0.01) tt=np.arange(0.0,2.25,0.25) plt.figure(figsize=(10,5)) plt.plot(t,vexact_t(0.5,t),'b',label='$\lambda=0.5$') plt.plot(t,vexact_t(0.9,t),'r',label='$\lambda=0.9$') plt.plot(t,vexact_t(1.8,t),'g',label='$\lambda=1.8$') #plt.plot(tt, magt_sim[0], 'bo',label='simulation') #plt.plot(tt, magt_sim[1], 'ro') #plt.plot(tt, magt_sim[2], 'go') plt.plot(tt, magt[0], 'b*',label='ibmqx5') plt.plot(tt, magt[1], 'r*') plt.plot(tt, magt[2], 'g*') plt.plot(tt, magt[0], 'b--') plt.plot(tt, magt[1], 'r--') plt.plot(tt, magt[2], 'g--') plt.xlabel('time') plt.ylabel('$<\sigma_{z}>$') plt.legend() plt.title('Time evolution |↑↑↑↑> state') plt.show() plt.figure(figsize=(13,3)) plt.subplot(1,3,1) plt.plot(t,vexact_t(0.5,t),'b',label='$\lambda=0.5$') plt.plot(tt, magt[0], 'b*',label='ibmqx5') plt.plot(tt, magt[0], 'b--',label='ibmqx5') plt.xlabel('time') plt.ylabel('$<\sigma_{z}>$') plt.title('$\lambda=0.5$') plt.subplot(132) plt.plot(t,vexact_t(0.9,t),'r',label='$\lambda=0.9$') plt.plot(tt, magt[1], 'r*',label='ibmqx5') plt.plot(tt, magt[1], 'r--',label='ibmqx5') plt.xlabel('time') plt.ylabel('$<\sigma_{z}>$') plt.title('$\lambda=0.9$') plt.subplot(133) plt.plot(t,vexact_t(1.8,t),'g',label='$\lambda=1.8$') plt.plot(tt, magt[2], 'g*',label='ibmqx5') plt.plot(tt, magt[2], 'g--',label='ibmqx5') plt.xlabel('time') plt.ylabel('$<\sigma_{z}>$') plt.title('$\lambda=1.8$') plt.tight_layout() plt.show()
https://github.com/xtophe388/QISKIT
xtophe388
import numpy as np # These column vectors can be stored in numpy arrays so that we can operate # on them with the circuit diagram's corresponding matrix (which is to be evaluated) # as follows: zero_zero = np.array([[1],[0],[0],[0]]) zero_one = np.array([[0],[1],[0],[0]]) one_zero = np.array([[0],[0],[1],[0]]) one_one = np.array([[0],[0],[0],[1]]) Psi = {'zero_zero': zero_zero, 'zero_one': zero_one, 'one_zero': one_zero, 'one_one': one_one} # ^We can conveniently store all possible input states in a dictionary and then print to check the representations: for key, val in Psi.items(): print(key, ':', '\n', val) # storing CNOT as a numpy array: CNOT_1 = np.matrix([[1, 0, 0, 0],[0, 1, 0, 0],[0, 0, 0, 1],[0, 0, 1, 0]]) print(CNOT_1) print('FINAL STATE OF i):') #Apply CNOT to each possible state for |Psi> to find --> |Psi'> for key, val in Psi.items(): print(key, 'becomes..\n', CNOT_1*val) # storing this in a numpy array: H_2 = .5*np.matrix([[1, 1, 1, 1],[1, -1, 1, -1],[1, 1, -1, -1],[1, -1, -1, 1]]) print('H_2:') print(H_2) # storing this in a numpy array: CNOT_2 = np.matrix([[1, 0, 0, 0],[0, 0, 0, 1],[0, 0, 1, 0],[0, 1, 0, 0]]) A = H_2*CNOT_2*H_2 print(A) print(CNOT_1) for key, val in Psi.items(): print(key, 'becomes...\n', A*val)
https://github.com/xtophe388/QISKIT
xtophe388
# import necessary libraries import numpy as np from pprint import pprint from qiskit import QuantumProgram from qiskit.tools.visualization import plot_histogram #import Qconfig # When working worth external backends (more on this below), # be sure that the working directory has a # Qconfig.py file for importing your APIToken from # your IBM Q Experience account. # An example file has been provided, so for working # in this notebook you can simply set # the variable values to your credentials and rename # this file as 'Qconfig.py' # This initial state register # can be realized in python by creating an instance of the # QISKit QuantumProgram Class with a quantum register of 2 qubits # and 2 classical ancilla bits for measuring the states i = QuantumProgram() n = 2 i_q = i.create_quantum_register("i_q", n) i_c = i.create_classical_register("i_c", n) #i.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url i.available_backends() #check backends - if you've set up your APIToken properly you #should be able to see the quantum chips and simulators at IBM for backend in i.available_backends(): #check backend status print(backend) pprint(i.get_backend_status(backend)) def execute_and_plot(qp, circuits, backend = "local_qasm_simulator"): """Executes circuits and plots the final state histograms the for each circuit. Adapted from 'execute_and_plot' function in the beginners_guide_composer_examples notebook provided in IBM's QISKit tutorial library on GitHub. Args: qp: QuantumProgram containing the circuits circuits (list): list of circuits to execute backend (string): allows for specifying the backend to execute on. Defaults to local qasm simulator downloaded with QISKit library, but can be specified to run on an actual quantum chip by using the string names of the available backends at IBM. """ # Store the results of the circuit implementation # using the .execute() method results = qp.execute(circuits, backend = backend) for circuit in circuits: plot_histogram(results.get_counts(circuit)) # .get_counts() # method returns a dictionary that maps each possible # final state to the number of instances of # said state over n evaluations # (n defaults to 1024 for local qasm simulator), # where multiple evaluations are a necessity since # quantum computation outputs are statistically # informed # Initialize circuit: cnot_i_00 = i.create_circuit("cnot_i_00", [i_q], [i_c]) # Note: qubits are assumed by QISKit # to be initialized in the |0> state # Apply gates according to diagram: cnot_i_00.cx(i_q[0], i_q[1]) # Apply CNOT on line 2 controlled by line 1 # Measure final state: cnot_i_00.measure(i_q[0], i_c[0]) # Write qubit 1 state onto classical ancilla bit 1 cnot_i_00.measure(i_q[1], i_c[1]) # Write qubit 2 state onto classical ancilla bit 2 # Display final state probabilities: execute_and_plot(i, ["cnot_i_00"]) print(i.get_qasm('cnot_i_00')) # Initialize circuit: cnot_i_01 = i.create_circuit("cnot_i_01", [i_q], [i_c]) cnot_i_01.x(i_q[0]) # Set the 1st qubit to |1> by flipping # the initialized |0> with an X gate before implementing # the circuit # Apply gates according to diagram: cnot_i_01.cx(i_q[0], i_q[1]) # Apply CNOT controlled by line 1 # Measure final state: cnot_i_01.measure(i_q[0], i_c[0]) cnot_i_01.measure(i_q[1], i_c[1]) # Display final state probabilities: execute_and_plot(i, ["cnot_i_01"]) # Initialize circuit: cnot_i_10 = i.create_circuit("cnot_i_10", [i_q], [i_c]) cnot_i_10.x(i_q[1]) # Set the 2nd qubit to |1> # Apply gates according to diagram: cnot_i_10.cx(i_q[0], i_q[1]) # Apply CNOT controlled by line 1 # Measure final state: cnot_i_10.measure(i_q[0], i_c[0]) cnot_i_10.measure(i_q[1], i_c[1]) # Display final state probabilities: execute_and_plot(i, ["cnot_i_10"]) # Initialize circuit: cnot_i_11 = i.create_circuit("cnot_i_11", [i_q], [i_c]) cnot_i_11.x(i_q[0]) # Set the 1st qubit to |1> cnot_i_11.x(i_q[1]) # Set the 2nd qubit to |1> # Apply gates according to diagram: cnot_i_11.cx(i_q[0], i_q[1]) # Apply CNOT controlled by line 1 # Measure final states: cnot_i_11.measure(i_q[0], i_c[0]) cnot_i_11.measure(i_q[1], i_c[1]) # Display final state probabilities: execute_and_plot(i, ["cnot_i_11"]) # For circuit ii, we can again create a QuantumProgram instance to # realize a quantum register of size 2 with 2 classical ancilla bits # for measurement ii = QuantumProgram() n = 2 ii_q = ii.create_quantum_register("ii_q", n) ii_c = ii.create_classical_register("ii_c", n) #ii.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url ii.available_backends() #check backends - if you've set up your APIToken properly you #should be able to see the quantum chips and simulators at IBM for backend in ii.available_backends(): #check backend status print(backend) pprint(ii.get_backend_status(backend)) # Initialize circuit: cnot_ii_00 = ii.create_circuit("cnot_ii_00", [ii_q], [ii_c]) # Apply gates according to diagram: cnot_ii_00.h(ii_q) # Apply hadamards in parallel, note that specifying # a register a a gate method argument applies the operation to all # qubits in the register cnot_ii_00.cx(ii_q[1], ii_q[0]) #apply CNOT controlled by line 2 cnot_ii_00.h(ii_q) # Apply hadamards in parallel # Measure final state: cnot_ii_00.measure(ii_q[0], ii_c[0]) cnot_ii_00.measure(ii_q[1], ii_c[1]) # Display final state probabilities execute_and_plot(ii, ["cnot_ii_00"]) # Initialize circuit: cnot_ii_01 = ii.create_circuit("cnot_ii_01", [ii_q], [ii_c]) cnot_ii_01.x(ii_q[0]) # Set the 1st qubit to |1> # Apply gates according to diagram: cnot_ii_00.h(ii_q) # Apply hadamards in parallel cnot_ii_01.cx(ii_q[1], ii_q[0]) # Apply CNOT controlled by line 2 cnot_ii_00.h(ii_q) # Apply hadamards in parallel # Measure final state: cnot_ii_01.measure(ii_q[0], ii_c[0]) cnot_ii_01.measure(ii_q[1], ii_c[1]) # Display final state probabilities: execute_and_plot(ii, ["cnot_ii_01"]) # Initialize circuits cnot_ii_10 = ii.create_circuit("cnot_ii_10", [ii_q], [ii_c]) cnot_ii_10.x(ii_q[1]) # Set the 2nd qubit to |1> # Apply gates according to diagram: cnot_ii_00.h(ii_q) # Apply hadamards in parallel cnot_ii_10.cx(ii_q[1], ii_q[0]) # Apply CNOT controlled by line 2 cnot_ii_00.h(ii_q) # Apply hadamards in parallel # Measure final state: cnot_ii_10.measure(ii_q[0], ii_c[0]) cnot_ii_10.measure(ii_q[1], ii_c[1]) # Display final state probabilities: execute_and_plot(ii, ["cnot_ii_10"]) # Initialize circuits: cnot_ii_11 = ii.create_circuit("cnot_ii_11", [ii_q], [ii_c]) cnot_ii_11.x(ii_q[0]) # Set the 1st qubit to |1> cnot_ii_11.x(ii_q[1]) # Set the 2nd qubit to |1> # Apply gates according to diagram: cnot_ii_00.h(ii_q) # Apply hadamards in parallel cnot_ii_11.cx(ii_q[1], ii_q[0]) # Apply CNOT controlled by line 2 cnot_ii_00.h(ii_q) # Apply hadamards in parallel # Measure final state cnot_ii_11.measure(ii_q[0], ii_c[0]) cnot_ii_11.measure(ii_q[1], ii_c[1]) # Display final state probabilities execute_and_plot(ii, ["cnot_ii_11"]) def circuit_i(): i = QuantumProgram() i_q = i.create_quantum_register('i_q', 2) i_c = i.create_classical_register('i_c', 2) initial_states = ['00','01','10','11'] initial_circuits = {state: i.create_circuit('%s'%(state), [i_q], [i_c]) \ for state in initial_states} final_circuits = {} for state in initial_states: if state[0] is '1': initial_circuits[state].x(i_q[0]) if state[1] is '1': initial_circuits[state].x(i_q[1]) initial_circuits[state].cx(i_q[0], i_q[1]) initial_circuits[state].measure(i_q[0], i_c[0]) initial_circuits[state].measure(i_q[1], i_c[1]) final_circuits[state] = initial_circuits[state] return i def circuit_ii(): ii = QuantumProgram() ii_q = ii.create_quantum_register('ii_q', 2) ii_c = ii.create_classical_register('ii_c', 2) initial_states = ['00','01','10','11'] circuits = {state: ii.create_circuit('%s'%(state), [ii_q], [ii_c]) \ for state in initial_states} for state in initial_states: if state[0] is '1': circuits[state].x(ii_q[0]) if state[1] is '1': circuits[state].x(ii_q[1]) circuits[state].h(ii_q) circuits[state].cx(ii_q[1], ii_q[0]) circuits[state].h(ii_q) circuits[state].measure(ii_q[0], ii_c[0]) circuits[state].measure(ii_q[1], ii_c[1]) return ii i = circuit_i() ii = circuit_ii() #i.set_api(Qconfig.APItoken, Qconfig.config['url']) #ii.set_api(Qconfig.APItoken, Qconfig.config['url']) results_i = i.execute(list(i.get_circuit_names())) results_ii = ii.execute(list(ii.get_circuit_names())) results_i_mapping = {circuit: results_i.get_counts(circuit) for circuit in list(i.get_circuit_names())} results_ii_mapping = {circuit: results_ii.get_counts(circuit) for circuit in list(ii.get_circuit_names())} print(results_i_mapping) print(results_ii_mapping)
https://github.com/xtophe388/QISKIT
xtophe388
#import all the packages # Checking the version of PYTHON import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') #append to system path so qiskit and Qconfig can be found from home directory sys.path.append('../qiskit-sdk-py/') # Import the QuantumProgram and configuration from qiskit import QuantumProgram #import Qconfig #other useful packages import math #Super secret message mes = 'hello world' print('Your super secret message: ',mes) #initial size of key n = len(mes)*3 #break up message into smaller parts if length > 10 nlist = [] for i in range(int(n/10)): nlist.append(10) if n%10 != 0: nlist.append(n%10) print('Initial key length: ',n) # Make random strings of length string_length def randomStringGen(string_length): #output variables used to access quantum computer results at the end of the function output_list = [] output = '' #start up your quantum program qp = QuantumProgram() backend = 'local_qasm_simulator' circuits = ['rs'] #run circuit in batches of 10 qubits for fastest results. The results #from each run will be appended and then clipped down to the right n size. n = string_length temp_n = 10 temp_output = '' for i in range(math.ceil(n/temp_n)): #initialize quantum registers for circuit q = qp.create_quantum_register('q',temp_n) c = qp.create_classical_register('c',temp_n) rs = qp.create_circuit('rs',[q],[c]) #create temp_n number of qubits all in superpositions for i in range(temp_n): rs.h(q[i]) #the .h gate is the Hadamard gate that makes superpositions rs.measure(q[i],c[i]) #execute circuit and extract 0s and 1s from key result = qp.execute(circuits, backend, shots=1) counts = result.get_counts('rs') result_key = list(result.get_counts('rs').keys()) temp_output = result_key[0] output += temp_output #return output clipped to size of desired string length return output[:n] key = randomStringGen(n) print('Initial key: ',key) #generate random rotation strings for Alice and Bob Alice_rotate = randomStringGen(n) Bob_rotate = randomStringGen(n) print("Alice's rotation string:",Alice_rotate) print("Bob's rotation string: ",Bob_rotate) #start up your quantum program backend = 'local_qasm_simulator' shots = 1 circuits = ['send_over'] Bob_result = '' for ind,l in enumerate(nlist): #define temp variables used in breaking up quantum program if message length > 10 if l < 10: key_temp = key[10*ind:10*ind+l] Ar_temp = Alice_rotate[10*ind:10*ind+l] Br_temp = Bob_rotate[10*ind:10*ind+l] else: key_temp = key[l*ind:l*(ind+1)] Ar_temp = Alice_rotate[l*ind:l*(ind+1)] Br_temp = Bob_rotate[l*ind:l*(ind+1)] #start up the rest of your quantum program qp2 = QuantumProgram() q = qp2.create_quantum_register('q',l) c = qp2.create_classical_register('c',l) send_over = qp2.create_circuit('send_over',[q],[c]) #prepare qubits based on key; add Hadamard gates based on Alice's and Bob's #rotation strings for i,j,k,n in zip(key_temp,Ar_temp,Br_temp,range(0,len(key_temp))): i = int(i) j = int(j) k = int(k) if i > 0: send_over.x(q[n]) #Look at Alice's rotation string if j > 0: send_over.h(q[n]) #Look at Bob's rotation string if k > 0: send_over.h(q[n]) send_over.measure(q[n],c[n]) #execute quantum circuit result_so = qp2.execute(circuits, backend, shots=shots) counts_so = result_so.get_counts('send_over') result_key_so = list(result_so.get_counts('send_over').keys()) Bob_result += result_key_so[0][::-1] print("Bob's results: ", Bob_result) def makeKey(rotation1,rotation2,results): key = '' count = 0 for i,j in zip(rotation1,rotation2): if i == j: key += results[count] count += 1 return key Akey = makeKey(Bob_rotate,Alice_rotate,key) Bkey = makeKey(Bob_rotate,Alice_rotate,Bob_result) print("Alice's key:",Akey) print("Bob's key: ",Bkey) #make key same length has message shortened_Akey = Akey[:len(mes)] encoded_m='' #encrypt message mes using encryption key final_key for m,k in zip(mes,shortened_Akey): encoded_c = chr(ord(m) + 2*ord(k) % 256) encoded_m += encoded_c print('encoded message: ',encoded_m) #make key same length has message shortened_Bkey = Bkey[:len(mes)] #decrypt message mes using encryption key final_key result = '' for m,k in zip(encoded_m,shortened_Bkey): encoded_c = chr(ord(m) - 2*ord(k) % 256) result += encoded_c print('recovered message:',result) #start up your quantum program backend = 'local_qasm_simulator' shots = 1 circuits = ['Eve'] Eve_result = '' for ind,l in enumerate(nlist): #define temp variables used in breaking up quantum program if message length > 10 if l < 10: key_temp = key[10*ind:10*ind+l] Ar_temp = Alice_rotate[10*ind:10*ind+l] else: key_temp = key[l*ind:l*(ind+1)] Ar_temp = Alice_rotate[l*ind:l*(ind+1)] #start up the rest of your quantum program qp3 = QuantumProgram() q = qp3.create_quantum_register('q',l) c = qp3.create_classical_register('c',l) Eve = qp3.create_circuit('Eve',[q],[c]) #prepare qubits based on key; add Hadamard gates based on Alice's and Bob's #rotation strings for i,j,n in zip(key_temp,Ar_temp,range(0,len(key_temp))): i = int(i) j = int(j) if i > 0: Eve.x(q[n]) if j > 0: Eve.h(q[n]) Eve.measure(q[n],c[n]) #execute result_eve = qp3.execute(circuits, backend, shots=shots) counts_eve = result_eve.get_counts('Eve') result_key_eve = list(result_eve.get_counts('Eve').keys()) Eve_result += result_key_eve[0][::-1] print("Eve's results: ", Eve_result) #start up your quantum program backend = 'local_qasm_simulator' shots = 1 circuits = ['Eve2'] Bob_badresult = '' for ind,l in enumerate(nlist): #define temp variables used in breaking up quantum program if message length > 10 if l < 10: key_temp = key[10*ind:10*ind+l] Eve_temp = Eve_result[10*ind:10*ind+l] Br_temp = Bob_rotate[10*ind:10*ind+l] else: key_temp = key[l*ind:l*(ind+1)] Eve_temp = Eve_result[l*ind:l*(ind+1)] Br_temp = Bob_rotate[l*ind:l*(ind+1)] #start up the rest of your quantum program qp4 = QuantumProgram() q = qp4.create_quantum_register('q',l) c = qp4.create_classical_register('c',l) Eve2 = qp4.create_circuit('Eve2',[q],[c]) #prepare qubits for i,j,n in zip(Eve_temp,Br_temp,range(0,len(key_temp))): i = int(i) j = int(j) if i > 0: Eve2.x(q[n]) if j > 0: Eve2.h(q[n]) Eve2.measure(q[n],c[n]) #execute result_eve = qp4.execute(circuits, backend, shots=shots) counts_eve = result_eve.get_counts('Eve2') result_key_eve = list(result_eve.get_counts('Eve2').keys()) Bob_badresult += result_key_eve[0][::-1] print("Bob's previous results (w/o Eve):",Bob_result) print("Bob's results from Eve:\t\t ",Bob_badresult) #make keys for Alice and Bob Akey = makeKey(Bob_rotate,Alice_rotate,key) Bkey = makeKey(Bob_rotate,Alice_rotate,Bob_badresult) print("Alice's key: ",Akey) print("Bob's key: ",Bkey) check_key = randomStringGen(len(Akey)) print('spots to check:',check_key) #find which values in rotation string were used to make the key Alice_keyrotate = makeKey(Bob_rotate,Alice_rotate,Alice_rotate) Bob_keyrotate = makeKey(Bob_rotate,Alice_rotate,Bob_rotate) # Detect Eve's interference #extract a subset of Alice's key sub_Akey = '' sub_Arotate = '' count = 0 for i,j in zip(Alice_rotate,Akey): if int(check_key[count]) == 1: sub_Akey += Akey[count] sub_Arotate += Alice_keyrotate[count] count += 1 #extract a subset of Bob's key sub_Bkey = '' sub_Brotate = '' count = 0 for i,j in zip(Bob_rotate,Bkey): if int(check_key[count]) == 1: sub_Bkey += Bkey[count] sub_Brotate += Bob_keyrotate[count] count += 1 print("subset of Alice's key:",sub_Akey) print("subset of Bob's key: ",sub_Bkey) #compare Alice and Bob's key subsets secure = True for i,j in zip(sub_Akey,sub_Bkey): if i == j: secure = True else: secure = False break; if not secure: print('Eve detected!') else: print('Eve escaped detection!') #sub_Akey and sub_Bkey are public knowledge now, so we remove them from Akey and Bkey if secure: new_Akey = '' new_Bkey = '' for index,i in enumerate(check_key): if int(i) == 0: new_Akey += Akey[index] new_Bkey += Bkey[index] print('new A and B keys: ',new_Akey,new_Bkey) if(len(mes)>len(new_Akey)): print('Your new key is not long enough.') #!!! you may need to execute this cell twice in order to see the output due to an problem with matplotlib import matplotlib.pyplot as plt import numpy as np x = np.arange(0., 30.0) y = 1-(3/4)**x plt.plot(y) plt.title('Probablity of detecting Eve') plt.xlabel('# of key bits compared') plt.ylabel('Probablity of detecting Eve') plt.show()
https://github.com/xtophe388/QISKIT
xtophe388
from IPython.display import Image Image(filename="error_correction_files/error_correction_1_0.png", width=450, height=300) Image(filename="error_correction_files/error_correction_3_0.png", width=450, height=300) Image(filename="error_correction_files/error_correction_5_0.png", width=450, height=300) Image(filename="error_correction_files/error_correction_7_0.png", width=450, height=300) import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') from qiskit import QuantumProgram #import Qconfig # Needed to visualize quantum circuits import os import shutil from qiskit.tools.visualization import latex_drawer import pdf2image from IPython.display import Image # Initialize quantum program qp = QuantumProgram() #qp.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url # Circuit requires 5 qubits and 5 classical bits qr = qp.create_quantum_register('qr', 5) cr = qp.create_classical_register('cr',5) qc = qp.create_circuit('Circuit', [qr], [cr]) circuit = qp.get_circuit('Circuit') # get the Quantum Register by Name quantum_r = qp.get_quantum_register('qr') # get the Classical Register by Name classical_r = qp.get_classical_register('cr') def circuitImage(circuit, filename, basis="u1,u2,u3,cx"): """ Obtain the circuit in image format Note: Requires pdflatex installed (to compile Latex) Note: Required pdf2image Python package (to display pdf as image) """ tmpdir='tmp/' if not os.path.exists(tmpdir): os.makedirs(tmpdir) latex_drawer(circuit, tmpdir+filename+".tex", basis=basis) os.system("pdflatex -output-directory {} {}".format(tmpdir, filename+".tex")) images = pdf2image.convert_from_path(tmpdir+filename+".pdf") shutil.rmtree(tmpdir) return images[0] def toffoli(circuit,quantum_r,a,b,c): """ Creates toffoli gate in existing circuit with a and b as the test points and c as the affected point """ circuit.iden(quantum_r[c]) circuit.h(quantum_r[c]) circuit.cx(quantum_r[b],quantum_r[c]) circuit.tdg(quantum_r[c]) circuit.cx(quantum_r[a],quantum_r[c]) circuit.t(quantum_r[c]) circuit.cx(quantum_r[b],quantum_r[c]) circuit.tdg(quantum_r[c]) circuit.cx(quantum_r[a],quantum_r[c]) circuit.t(quantum_r[c]) circuit.t(quantum_r[b]) circuit.h(quantum_r[c]) circuit.cx(quantum_r[b],quantum_r[c]) circuit.h(quantum_r[c]) circuit.h(quantum_r[b]) circuit.cx(quantum_r[b],quantum_r[c]) circuit.h(quantum_r[c]) circuit.h(quantum_r[b]) circuit.cx(quantum_r[b],quantum_r[c]) circuit.cx(quantum_r[a],quantum_r[c]) circuit.t(quantum_r[a]) circuit.tdg(quantum_r[c]) circuit.cx(quantum_r[a],quantum_r[c]) circuit.cx(quantum_r[b],quantum_r[c]) circuit.cx(quantum_r[c],quantum_r[b]) circuit.cx(quantum_r[b],quantum_r[c]) #circuit.x(quantum_r[2]) circuit.x(quantum_r[3]) circuit.x(quantum_r[4]) circuit.cx(quantum_r[2],quantum_r[0]) circuit.cx(quantum_r[3],quantum_r[0]) circuit.cx(quantum_r[3],quantum_r[1]) circuit.cx(quantum_r[4],quantum_r[1]) circuit.cx(quantum_r[0],quantum_r[2]) circuit.cx(quantum_r[1],quantum_r[4]) toffoli(circuit,quantum_r,0,1,2) toffoli(circuit,quantum_r,0,1,3) toffoli(circuit,quantum_r,0,1,4) circuit.measure(quantum_r[0], classical_r[0]) circuit.measure(quantum_r[1], classical_r[1]) circuit.measure(quantum_r[2], classical_r[2]) circuit.measure(quantum_r[3], classical_r[3]) circuit.measure(quantum_r[4], classical_r[4]) """ Image of the final circuit. Becuase it contains three Toffoli gates where each gate is made up of many basis gates, this circuit is unfortunately very hard to visualize. """ basis="u1,u2,u3,cx,x,y,z,h,s,t,rx,ry,rz" circuitImage(circuit,'circuit',basis) #!!! for better visibility plot using the now built-in code from qiskit.tools.visualization import circuit_drawer circuit_drawer(circuit) """ Results of the computation. Note that the states of the five qubits from up to down in the circuit are shown from right to left in the result. """ backend = 'ibmqx_qasm_simulator' circuits = ['Circuit'] # Group of circuits to execute qobj=qp.compile(circuits, backend, shots=1024, max_credits=3) result = qp.run(qobj, wait=2, timeout=240) print(result.get_counts('Circuit')) Image(filename="error_correction_files/error_correction_27_0.png", width=250, height=300) Image(filename="error_correction_files/error_correction_30_0.png", width=450, height=300) Image(filename="error_correction_files/error_correction_33_0.png", width=450, height=300) Image(filename="error_correction_files/error_correction_36_0.png", width=450, height=300) Image(filename="error_correction_files/error_correction_39_0.png", width=900, height=600) Image(filename="error_correction_files/error_correction_40_0.png", width=900, height=600) Image(filename="error_correction_files/error_correction_43_0.png", width=900, height=450)
https://github.com/xtophe388/QISKIT
xtophe388
from utils import version; version.version_information()
https://github.com/xtophe388/QISKIT
xtophe388
# Checking the version of PYTHON; we only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') #Importing qiskit and math lib from qiskit import QuantumProgram import math #import Qconfig pi = math.pi theta_list = [0.01, 0.02, 0.03, 0.04, 0.05, 1.31, 1.32, 1.33, 1.34, 1.35] Q_program = QuantumProgram() #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) def k_means(): # create Quantum Register called "qr" with 5 qubits qr = Q_program.create_quantum_register("qr", 5) # create Classical Register called "cr" with 5 bits cr = Q_program.create_classical_register("cr", 5) # Creating Quantum Circuit called "qc" involving your Quantum Register "qr" # and your Classical Register "cr" qc = Q_program.create_circuit("k_means", [qr], [cr]) #Define a loop to compute the distance between each pair of points for i in range(9): for j in range(1,10-i): # Set the parament theta about different point theta_1 = theta_list[i] theta_2 = theta_list[i+j] #Achieve the quantum circuit via qiskit qc.h(qr[2]) qc.h(qr[1]) qc.h(qr[4]) qc.u3(theta_1, pi, pi, qr[1]) qc.u3(theta_2, pi, pi, qr[4]) qc.cswap(qr[2], qr[1], qr[4]) qc.h(qr[2]) qc.measure(qr[2], cr[2]) qc.reset(qr) result = Q_program.execute("k_means", backend = 'local_qasm_simulator') print(result) print('theta_1:' + str(theta_1)) print('theta_2:' + str(theta_2)) print( result.get_data("k_means")) #result = Q_program.execute(["reset"], backend='ibmqx4', shots=1024, timeout=600) if __name__ == "__main__": k_means() %run "../version.ipynb"
https://github.com/xtophe388/QISKIT
xtophe388
# Checking the version of PYTHON; we only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') from qiskit import QuantumProgram import math #import Qconfig #Define a QuantumProgram object Q_program = QuantumProgram() #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) pi = math.pi def solve_linear_sys(): #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # create Quantum Register called "qr" with 4 qubits qr = Q_program.create_quantum_register("qr", 4) # create Quantum Register called "cr" with 4 qubits cr = Q_program.create_classical_register("cr", 4) # Creating Quantum Circuit called "qc" involving your Quantum Register "qr" # and your Classical Register "cr" qc = Q_program.create_circuit("solve_linear_sys", [qr], [cr]) # Initialize times that we get the result vector n0 = 0 n1 = 0 for i in range(10): #Set the input|b> state" qc.x(qr[2]) #Set the phase estimation circuit qc.h(qr[0]) qc.h(qr[1]) qc.u1(pi, qr[0]) qc.u1(pi/2, qr[1]) qc.cx(qr[1], qr[2]) #The quantum inverse Fourier transform qc.h(qr[0]) qc.cu1(-pi/2, qr[0], qr[1]) qc.h(qr[1]) #R(lamda^-1οΌ‰ Rotation qc.x(qr[1]) qc.cu3(pi/16, 0, 0, qr[0], qr[3]) qc.cu3(pi/8, 0, 0, qr[1], qr[3]) #Uncomputation qc.x(qr[1]) qc.h(qr[1]) qc.cu1(pi/2, qr[0], qr[1]) qc.h(qr[0]) qc.cx(qr[1], qr[2]) qc.u1(-pi/2, qr[1]) qc.u1(-pi, qr[0]) qc.h(qr[1]) qc.h(qr[0]) # To measure the whole quantum register qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) qc.measure(qr[3], cr[3]) result = Q_program.execute("solve_linear_sys", shots=8192, backend='local_qasm_simulator') # Get the sum og all results n0 = n0 + result.get_data("solve_linear_sys")['counts']['1000'] n1 = n1 + result.get_data("solve_linear_sys")['counts']['1100'] # print the result print(result) print(result.get_data("solve_linear_sys")) # Reset the circuit qc.reset(qr) # calculate the scale of the elements in result vectot and print it. p = n0/n1 print(n0) print(n1) print(p) # The test function if __name__ == "__main__": solve_linear_sys() %run "../version.ipynb"
https://github.com/xtophe388/QISKIT
xtophe388
%run ../version.ipynb
https://github.com/xtophe388/QISKIT
xtophe388
import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') from pprint import pprint import math # importing the QISKit from qiskit import QuantumProgram # To use API #import Qconfig # Definition of matchgate def gate_mu3(qcirc,theta,phi,lam,a,b): qcirc.cx(a,b) qcirc.cu3(theta,phi,lam,b,a) qcirc.cx(a,b) # Number of qubits (should be odd) n_nodes = 5 # Number of steps n_step = 2 # Histogram hist = True # Quantum Sphere #hist = False # Creating Programs qp = QuantumProgram() # Creating Registers qr = qp.create_quantum_register('qr', n_nodes) cr = qp.create_classical_register('cr', n_nodes) # Creating Circuits qc = qp.create_circuit('QWalk', [qr], [cr]) # Initial state qc.x(qr[0]) # Creating of two partitions with M1' and M2 # Repeating that n_step times for k in range(0,n_step): for i in range(0,n_nodes-1,2): gate_mu3(qc,math.pi, math.pi, 0, qr[i], qr[i+1]) for i in range(1,n_nodes,2): gate_mu3(qc,math.pi/2, 0, 0, qr[i], qr[i+1]) if hist: for i in range(0,n_nodes): qc.measure(qr[i], cr[i]) # To print the circuit # QASM_source = qp.get_qasm('QWalk') # print(QASM_source) # To use API # qp.set_api(Qconfig.APItoken, Qconfig.config['url']) backend = 'local_qasm_simulator' if hist: shots = 4096 else: shots = 1 # backend 'trick': produces amplitudes instead of probabilities qobj=qp.compile(['QWalk'], backend = backend, shots = shots ) # Compile quantum walk result = qp.run(qobj) print(result) # execute this cell twice to see the result due to an issue with matplotlib # import state tomography functions from qiskit.tools.visualization import plot_histogram, plot_state import numpy as np if hist: plot_histogram(result.get_counts('QWalk')) else: data_ampl = result.get_data('QWalk') state_walk = data_ampl['quantum_state'] rho_walk = np.outer(state_walk,state_walk.conj()) plot_state(rho_walk,'qsphere')
https://github.com/xtophe388/QISKIT
xtophe388
# execute this cell twice to see the output due to an issue with matplotlib import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') from pprint import pprint import math # importing the QISKit from qiskit import QuantumProgram # To use API #import Qconfig def gate_mu3(qcirc,theta,phi,lam,a,b): qcirc.cx(a,b) qcirc.cu3(theta,phi,lam,b,a) qcirc.cx(a,b) n_nodes = 5 n_step = 3 # Creating Programs qp = QuantumProgram() # Creating Registers qr = qp.create_quantum_register('qr', n_nodes) cr = qp.create_classical_register('cr', n_nodes) # Creating Circuits qc = qp.create_circuit('QWalk', [qr], [cr]) # Creating of two partitions with M1' and M2 for i in range(0,n_nodes-1,2): gate_mu3(qc,math.pi, math.pi, 0, qr[i], qr[i+1]) for i in range(1,n_nodes,2): gate_mu3(qc,math.pi/2, 0, 0, qr[i], qr[i+1]) # import state tomography functions from qiskit.tools.visualization import plot_histogram, plot_state import numpy as np # execute the quantum circuit backend = 'local_unitary_simulator' # the device to run on qobj = qp.compile(['QWalk'], backend=backend) result = qp.run(qobj) initial_state = np.zeros(2**n_nodes) initial_state[1]=1.0 # state 0 = ....0000, state 1 = ...000001 QWalk = result.get_data('QWalk')['unitary'] #Applying QWalk n_step times for i in range(0,n_step): if i > 0: initial_state = np.copy(state_QWalk) # Copy previous state state_QWalk = np.dot(QWalk,initial_state) # Multiply on QWalk matrix rho_QWalk=np.outer(state_QWalk, state_QWalk.conj()) # Calculate density matrix print('step = ',i+1) # print number plot_state(rho_QWalk,'qsphere') # draw Quantum Sphere
https://github.com/xtophe388/QISKIT
xtophe388
import math import numpy as np from scipy import linalg import matplotlib.pyplot as plt # swap is 2x2 matrix swap = np.array([[0, 1], [1, 0]], dtype=complex) # Hadamard coin c_Hadamard = (1/math.sqrt(2))*np.array([[1, 1], [1, -1]], dtype=complex) # Balanced coin (not used) c_bal = (1/math.sqrt(2))*np.array([[1, 1j], [1j, 1]], dtype=complex) # step with swap and coin s_coin = c_Hadamard.dot(swap) # Number of nodes (should be odd) n_nodes = 15 # Step 1 includes swap and coin for first partition Step1 = np.identity(n_nodes, dtype=complex) for i in range(0,n_nodes-1,2): for i1 in range(0,2): for i2 in range(0,2): Step1[i+i1,i+i2] = s_coin[i1,i2] # Step 2 includes swap for second partition Step2 = np.identity(n_nodes, dtype=complex) for i in range(1,n_nodes,2): for i1 in range(0,2): for i2 in range(0,2): Step2[i+i1,i+i2] = swap[i1,i2] # Vector with chain nodes ch = np.zeros(n_nodes, dtype=complex) # Initial distribution for symmetric walk with Hadamard coin # two central nodes n_pos = n_nodes//2 ch[n_pos] = 1/math.sqrt(2) ch[n_pos+1] = 1j/math.sqrt(2) # Alternative initial distribution also could be used #ch[0] = 1 # Probability from complex amplitude def abs2(x): return x.real**2 + x.imag**2 # Vector with probabilities ch2 = np.zeros(n_nodes, dtype = float) # Number of steps n_step=12 for i in range(0,n_step): if i > 0: # step = 0 doing nothing, only draw if i%2 == 1 : ch = Step1.dot(ch) # odd steps 1 3 5 ... else: ch = Step2.dot(ch) # even steps 2 4 6 ... ch2 = abs2(ch) # calculate probabilities print(ch2) if i%2 == 0 : # plot for even steps 0 2 4 ... plt.plot(ch2) plt.show()
https://github.com/xtophe388/QISKIT
xtophe388
# Checking the version of PYTHON; we only support 3 at the moment import sys if sys.version_info < (3,0): raise Exception('Please use Python version 3 or greater.') # useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np import time from pprint import pprint # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram #import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram QPS_SPECS = { 'circuits': [{ 'name': 'W_states', 'quantum_registers': [{ 'name':'q', 'size':5 }], 'classical_registers': [{ 'name':'c', 'size':5 }]}], } Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) "Choice of the backend" # The flag_qx2 must be "True" for using the ibmqx2. # "True" is also better when using the simulator (shorter circuit) #backend = 'ibmqx2' #backend = 'ibmqx4' backend = 'local_qasm_simulator' #backend = 'ibmqx_hpc_qasm_simulator' flag_qx2 = True if backend == 'ibmqx4': flag_qx2 = False print("Your choice for the backend is: ", backend, "flag_qx2 is: ", flag_qx2) # Here, two useful routine # Define a F_gate def F_gate(circ,q,i,j,n,k) : theta = np.arccos(np.sqrt(1/(n-k+1))) circ.ry(-theta,q[j]) circ.cz(q[i],q[j]) circ.ry(theta,q[j]) circ.barrier(q[i]) # Define the cxrv gate which uses reverse CNOT instead of CNOT def cxrv(circ,q,i,j) : circ.h(q[i]) circ.h(q[j]) circ.cx(q[j],q[i]) circ.h(q[i]) circ.h(q[j]) circ.barrier(q[i],q[j]) # 3-qubit W state Step 1 Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[2]) #start is |100> F_gate(W_states,q,2,1,3,1) # Applying F12 for i in range(3) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 3-qubit (step 1) on', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 3-qubit (step 1) on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states')) # 3-qubit W state, first and second steps Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[2]) #start is |100> F_gate(W_states,q,2,1,3,1) # Applying F12 F_gate(W_states,q,1,0,3,2) # Applying F23 for i in range(3) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 3-qubit (steps 1 + 2) on', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 3-qubit (steps 1 + 2) on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states')) # 3-qubit W state Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[2]) #start is |100> F_gate(W_states,q,2,1,3,1) # Applying F12 F_gate(W_states,q,1,0,3,2) # Applying F23 if flag_qx2 : # option ibmqx2 W_states.cx(q[1],q[2]) # cNOT 21 W_states.cx(q[0],q[1]) # cNOT 32 else : # option ibmqx4 cxrv(W_states,q,1,2) cxrv(W_states,q,0,1) for i in range(3) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 3-qubit on', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 3-qubit on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states')) # 4-qubit W state Q_program = QuantumProgram(specs=QPS_SPECS) # Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[3]) #start is |1000> F_gate(W_states,q,3,2,4,1) # Applying F12 F_gate(W_states,q,2,1,4,2) # Applying F23 F_gate(W_states,q,1,0,4,3) # Applying F34 cxrv(W_states,q,2,3) # cNOT 21 if flag_qx2 : # option ibmqx2 W_states.cx(q[1],q[2]) # cNOT 32 W_states.cx(q[0],q[1]) # cNOT 43 else : # option ibmqx4 cxrv(W_states,q,1,2) cxrv(W_states,q,0,1) for i in range(4) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 4-qubit ', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 4-qubit on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states')) # 5-qubit W state Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[4]) #start is |10000> F_gate(W_states,q,4,3,5,1) # Applying F12 F_gate(W_states,q,3,2,5,2) # Applying F23 F_gate(W_states,q,2,1,5,3) # Applying F34 F_gate(W_states,q,1,0,5,4) # Applying F45 W_states.cx(q[3],q[4]) # cNOT 21 cxrv(W_states,q,2,3) # cNOT 32 if flag_qx2 : # option ibmqx2 W_states.cx(q[1],q[2]) # cNOT 43 W_states.cx(q[0],q[1]) # cNOT 54 else : # option ibmqx4 cxrv(W_states,q,1,2) cxrv(W_states,q,0,1) for i in range(5) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 5-qubit on', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=1200) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 5-qubit on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states'))
https://github.com/xtophe388/QISKIT
xtophe388
# Checking the version of PYTHON; we only support 3 at the moment import sys if sys.version_info < (3,0): raise Exception('Please use Python version 3 or greater.') # useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np import time from pprint import pprint # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram #import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram QPS_SPECS = { 'circuits': [{ 'name': 'W_states', 'quantum_registers': [{ 'name':'q', 'size':5 }], 'classical_registers': [{ 'name':'c', 'size':5 }]}], } "Choice of the backend" # The flag_qx2 must be "True" for using the ibmqx2. # "True" is also better when using the simulator #backend = 'ibmqx2' # not advisable if other pending jobs! #backend = 'ibmqx4' # not advisable if other pending jobs! backend = 'local_qasm_simulator' #OK #backend = 'ibmqx_hpc_qasm_simulator' #OK flag_qx2 = True if backend == 'ibmqx4': flag_qx2 = False print("Your choice for the backend is: ", backend, "flag_qx2 is: ", flag_qx2) # Here, two useful routine # Define a F_gate def F_gate(circ,q,i,j,n,k) : theta = np.arccos(np.sqrt(1/(n-k+1))) circ.ry(-theta,q[j]) circ.cz(q[i],q[j]) circ.ry(theta,q[j]) circ.barrier(q[i]) # Define the cxrv gate which uses reverse CNOT instead of CNOT def cxrv(circ,q,i,j) : circ.h(q[i]) circ.h(q[j]) circ.cx(q[j],q[i]) circ.h(q[i]) circ.h(q[j]) circ.barrier(q[i],q[j]) # 3-qubit W state Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[2]) #start is |100> F_gate(W_states,q,2,1,3,1) # Applying F12 F_gate(W_states,q,1,0,3,2) # Applying F23 if flag_qx2 : # option ibmqx2 W_states.cx(q[1],q[2]) # cNOT 21 W_states.cx(q[0],q[1]) # cNOT 32 else : # option ibmqx4 cxrv(W_states,q,1,2) cxrv(W_states,q,0,1) # Coin tossing W_states.h(q[3]) W_states.h(q[4]) for i in range(5) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] "Dotted alphabet" top_bottom = "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" blank = "β–ˆ β–ˆ" chosen = [] chosen = chosen + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = [] here_left = here_left + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = [] here_center = here_center + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_right = [] here_right = here_right + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] goa=["β–ˆ β–ˆ","β–ˆ ( ) β–ˆ","β–ˆ ( ) β–ˆ","β–ˆ / O O \ β–ˆ","β–ˆ )|( β–ˆ","β–ˆ @ β–ˆ","β–ˆ = β–ˆ","β–ˆ Y β–ˆ","β–ˆ β–ˆ"] car=["β–ˆ β–ˆ","β–ˆ _______ β–ˆ","β–ˆ / \ β–ˆ","β–ˆ Β° _______ Β° β–ˆ","β–ˆ / \ β–ˆ","β–ˆ (O) ### (O) β–ˆ","β–ˆ =+=====+= β–ˆ","β–ˆ || || β–ˆ","β–ˆ β–ˆ"] "(RE)INITIATES STATISTICS" nb_randomnb = 0 nb_left = 0 nb_center = 0 nb_right = 0 nb_switches = 0 nb_stays = 0 nb_won_switching = 0 nb_won_sticking = 0 nb_games = 0 n_won = 0 "HERE START THE GAME" "Hiding the car and the two goats behind the three doors" Label = ["left", "central", "right"] shots = 1 repeat = "Y" while repeat == "Y": nb_of_cars = 4 while nb_of_cars != 1: result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) c5str = str(result.get_counts('W_states')) nb_of_cars = int(c5str[4]) + int(c5str[5]) + int(c5str[6]) #this is for checking results from the real computer: if nb_of_cars == 0: print("They managed to hide three goats and no car behind the doors! Restarting the hiding process...") if nb_of_cars >= 2: print("They managed to hide", nb_of_cars, "cars behind the doors! Restarting the hiding process...") print(top_bottom," ",top_bottom," ",top_bottom) for i in range(9): print(here_left[i]," ",here_center[i]," ",here_right[i]) print(top_bottom," ",top_bottom," ",top_bottom,"\n") door = input("Game master: Your choice? letter l: left door, c: central door, r: right door + enter\n").upper() picl = here_left picc = here_center picr = here_right if (door == "L"): Doorchosen = 1 nb_left = nb_left + 1 picl = chosen else: if (door == "C"): Doorchosen = 2 nb_center = nb_center + 1 picc=chosen else: Doorchosen = 3 nb_right = nb_right + 1 picr = chosen print('Game master: Your choice was the',Label[Doorchosen-1], "door") "AN OPPORTUNITY TO CHANGE YOUR MIND" c5str = str(result.get_counts('W_states')) randomnb = (int(c5str[2]) + int(c5str[3])) %2 if c5str[4] == "1": #car behind left door Doorwinning = 1 if Doorchosen == 1: Dooropen = 2 + randomnb Doorswitch = 3 - randomnb if Doorchosen == 2: Dooropen = 3 Doorswitch = 1 if Doorchosen == 3: Dooropen = 2 Doorswitch = 1 if c5str[5] == "1": #car behind central door Doorwinning = 2 if Doorchosen == 2: Dooropen = 1 + 2*randomnb Doorswitch = 3 - 2*randomnb if Doorchosen == 1: Dooropen = 3 Doorswitch = 2 if Doorchosen == 3: Dooropen = 1 Doorswitch = 2 if c5str[6] == "1": #car behind right door Doorwinning = 3 if Doorchosen == 3: Dooropen = randomnb + 1 Doorswitch = 2 - randomnb if Doorchosen == 1: Dooropen = 2 Doorswitch = 3 if Doorchosen == 2: Dooropen = 1 Doorswitch = 3 if Dooropen == 1: picl = goa if Dooropen == 2: picc = goa if Dooropen == 3: picr = goa print(top_bottom," ",top_bottom," ",top_bottom) for i in range(9): print(picl[i]," ",picc[i]," ",picr[i]) print(top_bottom," ",top_bottom," ",top_bottom,"\n") print('I opened the', Label[Dooropen-1], 'door and you see a goat') print('You get now an opportunity to change your choice!') print("Do you want to switch for the ",Label[Doorswitch-1], " door?") I_switch = input(" Answer by (y/n) + enter\n").upper() if (I_switch == "Y"): Doorfinal = Doorswitch else: Doorfinal = Doorchosen "FINAL ANNOUNCE" if Doorfinal == Doorwinning: if Doorfinal == 1: picl = car if Doorfinal == 2: picc = car if Doorfinal == 3: picr = car endmessage = 'won the car! Congratulations!' else: if Doorfinal == 1: picl = goa if Doorfinal == 2: picc = goa if Doorfinal == 3: picr = goa endmessage = 'won a goat! Sorry!' print(top_bottom," ",top_bottom," ",top_bottom) for i in range(9): print(picl[i]," ",picc[i]," ",picr[i]) print(top_bottom," ",top_bottom," ",top_bottom,"\n") print('Game master: You opened the',Label[Doorfinal-1],'door and', endmessage) "STATISTICS" nb_games = nb_games + 1 nb_randomnb = nb_randomnb + randomnb if Doorfinal == Doorswitch: nb_switches = nb_switches +1 if c5str[Doorfinal+3] == "1": nb_won_switching = nb_won_switching + 1 else: nb_stays = nb_stays+1 if c5str[Doorfinal+3] == "1": nb_won_sticking = nb_won_sticking + 1 n_won = nb_won_switching + nb_won_sticking print() print("YOUR STATS") print("nb of games: ", nb_games," total nb won:", n_won, " first choice: left",nb_left," center", nb_center,"right", nb_right) print("nb sticking: ",nb_stays," nb won when sticking: ",nb_won_sticking,"nb switching:",nb_switches," nb won when switching:",nb_won_switching) repeat = input("Another game? Answer by (y/n) + enter\n").upper() print("Game over") %run "../version.ipynb"
https://github.com/xtophe388/QISKIT
xtophe388
# Checking the version of PYTHON; we only support 3 at the moment import sys if sys.version_info < (3,0): raise Exception('Please use Python version 3 or greater.') # useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np import time from pprint import pprint # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram #import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram Q_program = QuantumProgram() #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) "Choice of the backend" backend = 'local_qasm_simulator' #can be very slow when number of shoots increases #backend = 'ibmqx_hpc_qasm_simulator' print("Your choice for the backend is: ", backend) # Define a F_gate def F_gate(circ,q,i,j,n,k) : theta = np.arccos(np.sqrt(1/(n-k+1))) circ.ry(-theta,q[j]) circ.cz(q[i],q[j]) circ.ry(theta,q[j]) circ.barrier(q[i]) # Define the cxrv gate which uses reverse CNOT instead of CNOT def cxrv(circ,q,i,j) : circ.h(q[i]) circ.h(q[j]) circ.cx(q[j],q[i]) circ.h(q[i]) circ.h(q[j]) circ.barrier(q[i],q[j]) #"CIRCUITS" q = Q_program.create_quantum_register("q", 16) c = Q_program.create_classical_register("c", 16) twin = Q_program.create_circuit("twin", [q], [c]) # First W state twin.x(q[14]) F_gate(twin,q,14,3,3,1) F_gate(twin,q,3,2,3,2) twin.cx(q[3],q[14]) twin.cx(q[2],q[3]) #Second W state twin.x(q[12]) F_gate(twin,q,12,5,3,1) F_gate(twin,q,5,6,3,2) cxrv(twin,q,5,12) twin.cx(q[6],q[5]) #Coin tossing twin.h(q[0]) twin.h(q[1]) switch1 = Q_program.create_circuit('switch1',[q],[c]) #Stick or switch switch1.h(q[13]) for i in range (4) : switch1.measure(q[i] , c[i]); for i in range (5,7) : switch1.measure(q[i] , c[i]); for i in range (12,15) : switch1.measure(q[i] , c[i]); Q_program.add_circuit("AliceBob", twin+switch1) Label = ["left", "central", "right"] wstates = 0 while wstates != 1: time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print("Alice vs Bob", "backend=", backend, "starting time", time_exp) result = Q_program.execute("AliceBob", backend=backend, shots=1, max_credits=5, wait=5, timeout=120) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print("Alice vs Bob", "backend=", backend, " end time", time_exp) cstr = str(result.get_counts("AliceBob")) nb_of_cars = int(cstr[3]) + int(cstr[14]) + int(cstr[15]) nb_of_doors = int(cstr[12]) + int(cstr[11]) + int(cstr[5]) wstates = nb_of_cars * nb_of_doors print(" ") print('Alice: One car and two goats are now hidden behind these doors.') print(' Which door do you choose?') print(" ") "Chosing the left door" if int(cstr[5]) == 1: Doorchosen = 1 "Chosing the center door" if int(cstr[11]) == 1: Doorchosen = 2 "Chosing the right door" if int(cstr[12]) == 1: Doorchosen = 3 time.sleep(2) print('Bob: My choice is the',Label[Doorchosen-1], "door") print(" ") randomnb = int(cstr[16]) + int(cstr[17]) %2 if cstr[3] == "1": #car behind left door Doorwinning = 1 if Doorchosen == 1: Dooropen = 2 + randomnb Doorswitch = 3 - randomnb if Doorchosen == 2: Dooropen = 3 Doorswitch = 1 if Doorchosen == 3: Dooropen = 2 Doorswitch = 1 if cstr[14] == "1": #car behind central door Doorwinning = 2 if Doorchosen == 2: Dooropen = 1 + 2*randomnb Doorswitch = 3 - 2*randomnb if Doorchosen == 1: Dooropen = 3 Doorswitch = 2 if Doorchosen == 3: Dooropen = 1 Doorswitch = 2 if cstr[15] == "1": #car behind right door Doorwinning = 3 if Doorchosen == 3: Dooropen = randomnb + 1 Doorswitch = 2 - randomnb if Doorchosen == 1: Dooropen = 2 Doorswitch = 3 if Doorchosen == 2: Dooropen = 1 Doorswitch = 3 time.sleep(2) print('Alice: Now I open the', Label[Dooropen-1], 'door and you see a goat') time.sleep(2) print(' You get an opportunity to change your choice!') time.sleep(2) print(' Do you want to switch for the',Label[Doorswitch-1], "door?") print(" ") time.sleep(2) switch_flag = int(cstr[4]) "BOB STICKS WITH HIS FIRST CHOICE!" if switch_flag == 0: Doorfinal = Doorchosen print('Bob: I stick with my first choice, the',Label[Doorfinal-1], "door") "BOB CHANGES HIS MIND!" if switch_flag == 1: Doorfinal = Doorswitch print('Bob: I change my mind and choose the',Label[Doorfinal-1], "door") "FINAL ANNOUNCE" if Doorfinal == Doorwinning: endmessage = 'won the car! Congratulations!' else: endmessage = 'won a goat! Sorry!' time.sleep(2) print() print('Alice: You opened the',Label[Doorfinal-1],'door and', endmessage) print("Game over") #Toffoli gates Toffoli = Q_program.create_circuit('Toffoli',[q],[c]) Toffoli.ccx(q[3], q[5], q[4]) Toffoli.swap(q[2],q[3]) Toffoli.swap(q[6],q[5]) Toffoli.ccx(q[3], q[5], q[4]) Toffoli.swap(q[3],q[14]) Toffoli.swap(q[12],q[5]) Toffoli.ccx(q[3], q[5], q[4]) # A general solution with 50% switching strategy switch_fifty_percent = Q_program.create_circuit('switch_fifty_percent',[q],[c]) #switch flag switch_fifty_percent.h(q[13]) switch_fifty_percent.cx(q[13],q[4]) switch_fifty_percent.measure(q[4] , c[4]); switch_fifty_percent.measure(q[13] , c[13]); Q_program.add_circuit("general_solution", twin+Toffoli+switch_fifty_percent) circuits = ['general_solution'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print(backend, "shots", shots, "starting time", time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=30, timeout=600) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print(backend, "shots", shots, "end time", time_exp) plot_histogram(result.get_counts("general_solution")) print(result.get_counts("general_solution")) observable_stickwon = {'0000000000010000': 1, '0010000000010000': 0, '0010000000000000': 0, '0000000000000000': 0} observable_switchwon = {'0000000000010000': 0, '0010000000010000': 1, '0010000000000000': 0, '0000000000000000': 0} observable_stickall = {'0000000000010000': 1, '0010000000010000': 0, '0010000000000000': 0, '0000000000000000': 1} observable_switchall = {'0000000000010000': 0, '0010000000010000': 1, '0010000000000000': 1, '0000000000000000': 0} stickwon = result.average_data("general_solution",observable_stickwon) switchwon = result.average_data("general_solution",observable_switchwon) stickall = result.average_data("general_solution",observable_stickall) switchall = result.average_data("general_solution",observable_switchall) print("Proportion sticking: %6.2f " % stickall) print("Proportion switching: %6.2f " % switchall) stickwon_stickall = stickwon/stickall switchwon_switchall = switchwon/switchall print("Proportion winning when sticking: %6.2f " % stickwon_stickall) print("Proportion winning when switching: %6.2f " % switchwon_switchall) # Illustrating different strategies xdat = [] ydat = [] observable = {'0000000000000000': 0, '0000000000010000': 1} shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print(backend, "shots", shots, "starting time", time_exp) for i in range(9) : strategies = Q_program.create_circuit('strategies',[q],[c]) Prob = i/8 lambda_s = 2*np.arcsin(np.sqrt(Prob)) strategies.rx(lambda_s,q[13]) strategies.cx(q[13],q[4]) strategies.measure(q[4] , c[4]); statploti = "statplot"+str(i) Q_program.create_circuit("statploti",[q],[c]) Q_program.add_circuit("statploti",twin+Toffoli+strategies) result = Q_program.execute("statploti", backend=backend, shots=shots, max_credits=5, wait=30, timeout=600) loop_average=(result.average_data("statploti",observable)) print(statploti," Proportion switching: %6.3f" % Prob, " Proportion winning: %6.2f" % loop_average) ydat.append(loop_average) xdat.append(Prob) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print(backend, "shots", shots, "end time", time_exp) plt.plot(xdat, ydat, 'ro') plt.grid() plt.ylabel('Probability of Winning', fontsize=12) plt.xlabel(r'Probability of Switching', fontsize=12) plt.show() print("Our Advice: \n") y_aver = [] for j in range(0,7,3) : y_aver.append((ydat[j] + ydat[j+1] +ydat[j+2])/3) if y_aver[0] == max(y_aver) : print(" Thou Shalt Not Switch") elif y_aver[2] == max(y_aver) : print(" Thou Shalt Not Stick") else: print(" Just follow the intuition of the moment") %run "../version.ipynb"
https://github.com/xtophe388/QISKIT
xtophe388
from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram #Set up the quantum and classical registers, and combine them into a circuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) #Create a superposition on the single quantum bit qc.measure(qr[0], cr[0]) #Measure the single bit, and store its value in the clasical bit from qiskit import register, available_backends, get_backend #Import the config file (Qconfig.py) to retrieve the API token and API url try: import sys sys.path.append('../') #Parent directory import Qconfig qx_config = { 'APItoken': Qconfig.APItoken, 'url': Qconfig.config['url']} except Exception as e: print(e) qx_config = { 'APItoken':'YOUR_TOKEN_HERE', 'url':'https://quantumexperience.ng.bluemix.net/api'} #Setup API register(qx_config['APItoken'], qx_config['url']) backend = 'ibmq_qasm_simulator' #Replace 'ibmq_qasm_simulator' with 'ibmqx5' to run on the quantum computer shots_sim = 100 #Adjust this number as desired, with effects as described above job_sim = execute(qc, backend, shots=shots_sim) #Run job on chosen backend for chosen number of shots stats_sim = job_sim.result().get_counts() #Retrieve results #Select '0' to represent 'laurel' if '0' not in stats_sim.keys(): stats_sim['laurel'] = 0 else: stats_sim['laurel'] = stats_sim.pop('0') #Which leaves '1' to represent 'yanny' if '1' not in stats_sim.keys(): stats_sim['yanny'] = 0 else: stats_sim['yanny'] = stats_sim.pop('1') plot_histogram(stats_sim) from pydub import AudioSegment from pydub.playback import play #Import two tracks laurel = AudioSegment.from_wav('laurel_or_yanny_audio_files/laurel.wav') yanny = AudioSegment.from_wav('laurel_or_yanny_audio_files/yanny.wav') play(laurel) #Listen to the laurel-specific track play(yanny) #Listen to the yanny-specific track #Modify the volumes based on the results of the experiment laurel = laurel + ((100*stats_sim['laurel']/shots_sim)-50) #Laurel yanny = yanny + ((100*stats_sim['yanny']/shots_sim)-50) #Yanny #Mix the two together and play the result mixed = laurel.overlay(yanny) play(mixed) mixed.export('laurel_or_yanny_audio_files/quantumLaurelYanny.wav', format='wav') print("Installed packages are as the following") !python --version print() !conda list 'qiskit|IBMQuantumExperience|numpy|scipy'
https://github.com/xtophe388/QISKIT
xtophe388
from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram # set up registers and program qr = QuantumRegister(16) cr = ClassicalRegister(16) qc = QuantumCircuit(qr, cr) # rightmost eight (qu)bits have ')' = 00101001 qc.x(qr[0]) qc.x(qr[3]) qc.x(qr[5]) # second eight (qu)bits have superposition of # '8' = 00111000 # ';' = 00111011 # these differ only on the rightmost two bits qc.h(qr[9]) # create superposition on 9 qc.cx(qr[9],qr[8]) # spread it to 8 with a CNOT qc.x(qr[11]) qc.x(qr[12]) qc.x(qr[13]) # measure for j in range(16): qc.measure(qr[j], cr[j]) from qiskit import register, available_backends, get_backend #import Qconfig and set APIToken and API url try: import sys sys.path.append("../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} except Exception as e: print(e) qx_config = { "APItoken":"YOUR_TOKEN_HERE", "url":"https://quantumexperience.ng.bluemix.net/api"} #set api register(qx_config['APItoken'], qx_config['url']) backend = "ibmq_qasm_simulator" shots_sim = 128 job_sim = execute(qc, backend, shots=shots_sim) stats_sim = job_sim.result().get_counts() plot_histogram(stats_sim) import matplotlib.pyplot as plt %matplotlib inline plt.rc('font', family='monospace') def plot_smiley (stats, shots): for bitString in stats: char = chr(int( bitString[0:8] ,2)) # get string of the leftmost 8 bits and convert to an ASCII character char += chr(int( bitString[8:16] ,2)) # do the same for string of rightmost 8 bits, and add it to the previous character prob = stats[bitString] / shots # fraction of shots for which this result occurred # create plot with all characters on top of each other with alpha given by how often it turned up in the output plt.annotate( char, (0.5,0.5), va="center", ha="center", color = (0,0,0, prob ), size = 300) if (prob>0.05): # list prob and char for the dominant results (occurred for more than 5% of shots) print(str(prob)+"\t"+char) plt.axis('off') plt.show() plot_smiley(stats_sim, shots_sim) backends = available_backends() backend = get_backend('ibmqx5') print('Status of ibmqx5:',backend.status) if backend.status["operational"] is True: print("\nThe device is operational, so we'll submit the job.") shots_device = 1000 job_device = execute(qc, backend, shots=shots_device) stats_device = job_device.result().get_counts() else: print("\nThe device is not operational. Try again later.") plot_smiley(stats_device, shots_device)
https://github.com/xtophe388/QISKIT
xtophe388
import getpass, time from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import available_backends, execute, register, least_busy # import basic plot tools from qiskit.tools.visualization import plot_histogram, circuit_drawer APItoken = getpass.getpass('Please input your token and hit enter: ') qx_config = { "APItoken": APItoken, "url":"https://quantumexperience.ng.bluemix.net/api"} try: register(qx_config['APItoken'], qx_config['url']) print('\nYou have access to great power!') print(available_backends({'local': False, 'simulator': False})) except: print('Something went wrong.\nDid you enter a correct token?') backend = least_busy(available_backends({'simulator': False, 'local': False})) print("The least busy backend is " + backend) q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) job_exp = execute(qc, backend=backend, shots=1024, max_credits=3) lapse = 0 interval = 30 while not job_exp.done: print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status) time.sleep(interval) lapse += 1 print(job_exp.status) plot_histogram(job_exp.result().get_counts(qc)) print('You have made entanglement!') circuit_drawer(qc)
https://github.com/xtophe388/QISKIT
xtophe388
# useful additional packages import matplotlib.pyplot as plt import matplotlib.axes as axes %matplotlib inline import numpy as np import networkx as nx from qiskit.tools.visualization import plot_histogram from qiskit_acqua import Operator, run_algorithm, get_algorithm_instance from qiskit_acqua.input import get_input_instance from qiskit_acqua.ising import maxcut import logging logger = logging.getLogger() # logger.setLevel(logging.DEBUG) # uncomment it to see detailed logging ################# import Qconfig and set APIToken and API url and prepare backends ############ try: import sys sys.path.append("../../") # go to parent dir import Qconfig except Exception as e: print(e) from qiskit import register, available_backends #set api APItoken=getattr(Qconfig, 'APItoken', None) url = Qconfig.config.get('url', None) hub = Qconfig.config.get('hub', None) group = Qconfig.config.get('group', None) project = Qconfig.config.get('project', None) try: register(APItoken, url, hub, group, project) except Exception as e: print(e) print("Backends: {}".format(available_backends())) # Generating a graph of 4 nodes n=4 # Number of nodes in graph G=nx.Graph() G.add_nodes_from(np.arange(0,n,1)) elist=[(0,1,1.0),(0,2,1.0),(0,3,1.0),(1,2,1.0),(2,3,1.0)] # tuple is (i,j,weight) where (i,j) is the edge G.add_weighted_edges_from(elist) colors = ['r' for node in G.nodes()] pos = nx.spring_layout(G) default_axes = plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos) # Computing the weight matrix from the random graph w = np.zeros([n,n]) for i in range(n): for j in range(n): temp = G.get_edge_data(i,j,default=0) if temp != 0: w[i,j] = temp['weight'] print(w) best_cost_brute = 0 for b in range(2**n): x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))] cost = 0 for i in range(n): for j in range(n): cost = cost + w[i,j]*x[i]*(1-x[j]) if best_cost_brute < cost: best_cost_brute = cost xbest_brute = x print('case = ' + str(x)+ ' cost = ' + str(cost)) colors = ['r' if xbest_brute[i] == 0 else 'b' for i in range(n)] nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos) print('\nBest solution = ' + str(xbest_brute) + ' cost = ' + str(best_cost_brute)) qubitOp, offset = maxcut.get_maxcut_qubitops(w) algo_input = get_input_instance('EnergyInput') algo_input.qubit_op = qubitOp #Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) x = maxcut.sample_most_likely(len(w), np.array(result['eigvecs'])) print('energy:', result['energy']) print('maxcut objective:', result['energy'] + offset) print('solution:', maxcut.get_graph_solution(x)) print('solution objective:', maxcut.maxcut_value(x, w)) colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)] nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'SPSA', 'max_trials': 300 } var_form_cfg = { 'name': 'RY', 'depth': 5, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising', 'random_seed': 10598}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg, 'backend': {'name': 'local_statevector_simulator'} } result = run_algorithm(params, algo_input) x = maxcut.sample_most_likely(len(w), result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('maxcut objective:', result['energy'] + offset) print('solution:', maxcut.get_graph_solution(x)) print('solution objective:', maxcut.maxcut_value(x, w)) colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)] nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos) # run quantum algorithm with shots params['backend']['name'] = 'local_qasm_simulator' params['backend']['shots'] = 1024 result = run_algorithm(params, algo_input) x = maxcut.sample_most_likely(len(w), result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('maxcut objective:', result['energy'] + offset) print('solution:', maxcut.get_graph_solution(x)) print('solution objective:', maxcut.maxcut_value(x, w)) plot_histogram(result['eigvecs'][0]) colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)] nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos)
https://github.com/xtophe388/QISKIT
xtophe388
# useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit_acqua_chemistry import ACQUAChemistry import warnings warnings.filterwarnings('ignore') import logging logger = logging.getLogger() # logger.setLevel(logging.DEBUG) # uncomment it to see detailed logging ################# import Qconfig and set APIToken and API url and prepare backends ############ try: import sys sys.path.append("../../") # go to parent dir import Qconfig except Exception as e: print(e) from qiskit import register, available_backends #set api APItoken=getattr(Qconfig, 'APItoken', None) url = Qconfig.config.get('url', None) hub = Qconfig.config.get('hub', None) group = Qconfig.config.get('group', None) project = Qconfig.config.get('project', None) try: register(APItoken, url, hub, group, project) except Exception as e: print(e) print("Backends: {}".format(available_backends())) # First, we use classical eigendecomposition to get ground state energy (including nuclear repulsion energy) as reference. acqua_chemistry_dict = { 'driver': {'name': 'HDF5'}, 'HDF5': {'hdf5_input': 'H2/H2_equilibrium_0.735_sto-3g.hdf5'}, 'operator': {'name':'hamiltonian', 'qubit_mapping': 'parity', 'two_qubit_reduction': True}, 'algorithm': {'name': 'ExactEigensolver'} } solver = ACQUAChemistry() result = solver.run(acqua_chemistry_dict) print('Ground state energy (classical): {:.12f}'.format(result['energy'])) # Second, we use variational quantum eigensolver (VQE) acqua_chemistry_dict['algorithm']['name'] = 'VQE' acqua_chemistry_dict['optimizer'] = {'name': 'SPSA', 'max_trials': 350} acqua_chemistry_dict['variational_form'] = {'name': 'RYRZ', 'depth': 3, 'entanglement':'full'} acqua_chemistry_dict['backend'] = {'name': 'local_statevector_simulator'} solver = ACQUAChemistry() result = solver.run(acqua_chemistry_dict) print('Ground state energy (quantum) : {:.12f}'.format(result['energy'])) print("====================================================") # You can also print out other info in the field 'printable' for line in result['printable']: print(line) # select H2 or LiH to experiment with molecule='H2' acqua_chemistry_dict = { 'driver': {'name': 'HDF5'}, 'HDF5': {'hdf5_input': ''}, 'operator': {'name':'hamiltonian', 'qubit_mapping': 'parity', 'two_qubit_reduction': True}, 'algorithm': {'name': ''}, 'optimizer': {'name': 'SPSA', 'max_trials': 350}, 'variational_form': {'name': 'RYRZ', 'depth': 3, 'entanglement':'full'} } # choose which backend want to use # backend = {'name': 'local_statevector_simulator'} backend = {'name': 'local_qasm_simulator', 'shots': 1024} algos = ['ExactEigensolver', 'VQE'] if molecule == 'LiH': mol_distances = np.arange(0.6, 5.1, 0.1) acqua_chemistry_dict['operator']['freeze_core'] = True acqua_chemistry_dict['operator']['orbital_reduction'] = [-3, -2] acqua_chemistry_dict['optimizer']['max_trials'] = 2500 acqua_chemistry_dict['variational_form']['depth'] = 5 else: mol_distances = np.arange(0.2, 4.1, 0.1) energy = np.zeros((len(algos), len(mol_distances))) for j, algo in enumerate(algos): acqua_chemistry_dict['algorithm']['name'] = algo if algo == 'ExactEigensolver': acqua_chemistry_dict.pop('backend', None) elif algo == 'VQE': acqua_chemistry_dict['backend'] = backend print("Using {}".format(algo)) for i, dis in enumerate(mol_distances): print("Processing atomic distance: {:1.1f} Angstrom".format(dis), end='\r') acqua_chemistry_dict['HDF5']['hdf5_input'] = "{}/{:1.1f}_sto-3g.hdf5".format(molecule, dis) result = solver.run(acqua_chemistry_dict) energy[j][i] = result['energy'] print("\n") for i, algo in enumerate(algos): plt.plot(mol_distances, energy[i], label=algo) plt.xlabel('Atomic distance (Angstrom)') plt.ylabel('Energy') plt.legend() plt.show()
https://github.com/xtophe388/QISKIT
xtophe388
from svm_datasets import * from qiskit_acqua.svm.data_preprocess import * from qiskit_acqua.input import get_input_instance from qiskit_acqua import run_algorithm import logging logger = logging.getLogger() # logger.setLevel(logging.DEBUG) # uncomment it to see detailed logging ################# import Qconfig and set APIToken and API url and prepare backends ############ try: import sys sys.path.append("../../") # go to parent dir import Qconfig except Exception as e: print(e) from qiskit import register, available_backends #set api APItoken=getattr(Qconfig, 'APItoken', None) url = Qconfig.config.get('url', None) hub = Qconfig.config.get('hub', None) group = Qconfig.config.get('group', None) project = Qconfig.config.get('project', None) try: register(APItoken, url, hub, group, project) except Exception as e: print(e) print("Backends: {}".format(available_backends())) feature_dim=2 # we support feature_dim 2 or 3 sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=20, test_size=10, n=feature_dim, gap=0.3, PLOT_DATA=True) total_array, label_to_labelclass = get_points(test_input, class_labels) params = { 'problem': {'name': 'svm_classification'}, 'backend': {'name': 'local_qasm_simulator', 'shots':1000}, 'algorithm': { 'name': 'SVM_QKernel', 'print_info' : True } } algo_input = get_input_instance('SVMInput') algo_input.training_dataset = training_input algo_input.test_dataset = test_input algo_input.datapoints = total_array result = run_algorithm(params,algo_input) print("testing success ratio: ", result['test_success_ratio']) print("predicted labels:", result['predicted_labels']) print("kernel matrix of the training data:") kernel_matrix = result['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r') plt.show() sample_Total, training_input, test_input, class_labels = Breast_cancer(training_size=20, test_size=10, n=feature_dim, PLOT_DATA=True) algo_input = get_input_instance('SVMInput') algo_input.training_dataset = training_input algo_input.test_dataset = test_input algo_input.datapoints = total_array result = run_algorithm(params, algo_input) print("testing success ratio: ", result['test_success_ratio']) print("predicted labels:", result['predicted_labels']) print("kernel matrix of the training data:") kernel_matrix = result['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r') plt.show()
https://github.com/xtophe388/QISKIT
xtophe388
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/xtophe388/QISKIT
xtophe388
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)