repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) ghz.draw(output='mpl')
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,BasicAer,Aer,transpile qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') backend.name() job=backend.run(qc) result=job.result() sv=result.get_statevector() sv sv.draw(output='latex') backend=Aer.get_backend('statevector_simulator') qc_transpile=transpile(qc,backend) job=backend.run(qc_transpile) result=job.result() sv=result.get_statevector() print(sv) sv.draw(output='latex') qc=QuantumCircuit(2) qc.h(0) qc.x(1) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') qc_transpile=transpile(qc,backend) job=backend.run(qc_transpile) result=job.result() sv=result.get_statevector() print(sv) sv.draw(output='latex') # get the raw data of the experiment sv.data
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import IBMQ, transpile from qiskit import QuantumCircuit from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram from qiskit.providers.fake_provider import FakeVigo device_backend = FakeVigo() # Construct quantum circuit circ = QuantumCircuit(3, 3) circ.h(0) circ.cx(0, 1) circ.cx(1, 2) circ.measure([0, 1, 2], [0, 1, 2]) sim_ideal = AerSimulator() # Execute and get counts result = sim_ideal.run(transpile(circ, sim_ideal)).result() counts = result.get_counts(0) plot_histogram(counts, title='Ideal counts for 3-qubit GHZ state') sim_vigo = AerSimulator.from_backend(device_backend) # Transpile the circuit for the noisy basis gates tcirc = transpile(circ, sim_vigo) # Execute noisy simulation and get counts result_noise = sim_vigo.run(tcirc).result() counts_noise = result_noise.get_counts(0) plot_histogram(counts_noise, title="Counts for 3-qubit GHZ state with device noise model") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
from tsp_qaoa import test_solution from qiskit.visualization import plot_histogram import networkx as nx import numpy as np import json import csv # Array of JSON Objects header = ['p', 'state', 'probability', 'mean'] length_p = 10 with open('qaoa_multiple_p.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) # write the header writer.writerow(header) first_p = False for p in range(length_p): p = p+1 if first_p == False: job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p) first_p = True else: job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p) # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"]) mean = UNIFORM_CONVERGENCE_SAMPLE[0]["mean"] print(mean) state = 0 for probability in UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"]: state += 1 writer.writerow([p,state, probability,mean])
https://github.com/1chooo/Quantum-Oracle
1chooo
""" Constant: Output equal 0. """ """ Create the quantum Circuit. """ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qrx = QuantumRegister(1, 'q0') qry = QuantumRegister(1, 'q1') cr = ClassicalRegister(1, 'c') qc = QuantumCircuit(qrx, qry, cr) qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() qc.i(qry) qc.barrier() qc.h(qrx) qc.h(qry) qc.measure(qrx, cr) qc.draw("mpl") """ Proof through histogram. """ from qiskit import execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram sim = AerSimulator() job = execute(qc, backend = sim, shots = 1000) result = job.result() counts = result.get_counts(qc) print("Counts: ", counts) plot_histogram(counts) """ Also in Quantum Computer. """ from qiskit import QuantumCircuit, IBMQ, execute from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram IBMQ.save_account('your_token') IBMQ.load_account() IBMQ.providers() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') qcomp = provider.get_backend('ibmq_manila') job = execute(qc, backend = qcomp, shots = 1000) job_monitor(job) result = job.result() counts = result.get_counts(qc) print("Total counts for qubit states are:", counts) plot_histogram(counts)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": ### removed z gate ### pass return qc def decode_message(qc): ### removed cx gate ### qc.h(1) return qc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can set a color for all the bars. from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Useful additional packages import matplotlib.pyplot as plt import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer backend = BasicAer.get_backend('unitary_simulator') q = QuantumRegister(1) qc = QuantumCircuit(q) qc.u(pi/2,pi/4,pi/8,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.p(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.id(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.x(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.y(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.z(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.h(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.s(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.sdg(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.t(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.tdg(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.rx(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ry(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.rz(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cx(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cy(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cz(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ch(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.crz(pi/2,q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cp(pi/2,q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cu(pi/2, pi/2, pi/2, 0, q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.swap(q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.ccx(q[0], q[1], q[2]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cswap(q[0], q[1], q[2]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.measure(q, c) qc.draw() backend = BasicAer.get_backend('qasm_simulator') job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.reset(q[0]) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.reset(q[0]) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.x(q[0]).c_if(c, 0) qc.measure(q,c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q,c) qc.x(q[0]).c_if(c, 0) qc.measure(q,c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) # Initializing a three-qubit quantum state import math desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0] q = QuantumRegister(3) qc = QuantumCircuit(q) qc.initialize(desired_vector, [q[0],q[1],q[2]]) qc.draw() backend = BasicAer.get_backend('statevector_simulator') job = backend.run(transpile(qc, backend)) qc_state = job.result().get_statevector(qc) qc_state state_fidelity(desired_vector,qc_state) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.circuit.library import MCXGate gate = MCXGate(4) from qiskit import QuantumCircuit circuit = QuantumCircuit(5) circuit.append(gate, [0, 1, 4, 2, 3]) circuit.draw('mpl')
https://github.com/Chibikuri/qwopt
Chibikuri
import pennylane as qml import numpy as np import tensorflow as tf qml.about() # simulator on cirq dev = qml.device('cirq.simulator', wires=3) def real(angles, **kwargs): qml.Hadamard(wires=0) qml.Rot(*angles, wires=0) def generator(w, **kwargs): qml.Hadamard(wires=0) qml.RX(w[0], wires=0) qml.RX(w[1], wires=1) qml.RY(w[2], wires=0) qml.RY(w[3], wires=1) qml.RZ(w[4], wires=0) qml.RZ(w[5], wires=1) qml.CNOT(wires=[0, 1]) qml.RX(w[6], wires=0) qml.RY(w[7], wires=0) qml.RZ(w[8], wires=0) def discriminator(w): qml.Hadamard(wires=0) qml.RX(w[0], wires=0) qml.RX(w[1], wires=2) qml.RY(w[2], wires=0) qml.RY(w[3], wires=2) qml.RZ(w[4], wires=0) qml.RZ(w[5], wires=2) qml.CNOT(wires=[0, 2]) qml.RX(w[6], wires=2) qml.RY(w[7], wires=2) qml.RZ(w[8], wires=2) def real_disc_circuit(phi, theta, omega, disc_weights): real([phi, theta, omega]) discriminator(disc_weights) return qml.expval(qml.PauliZ(2)) @qml.qnode(dev, interface="tf") def gen_disc_circuit(gen_weights, disc_weights): generator(gen_weights) discriminator(disc_weights) return qml.expval(qml.PauliZ(2)) def prob_real_true(disc_weights): true_disc_output = real_disc_circuit(phi, theta, omega, disc_weights) # convert to probability prob_real_true = (true_disc_output + 1) / 2 return prob_real_true def prob_fake_true(gen_weights, disc_weights): fake_disc_output = gen_disc_circuit(gen_weights, disc_weights) # convert to probability prob_fake_true = (fake_disc_output + 1) / 2 return prob_fake_true def disc_cost(disc_weights): cost = prob_fake_true(gen_weights, disc_weights) - prob_real_true(disc_weights) return cost def gen_cost(gen_weights): return -prob_fake_true(gen_weights, disc_weights) phi = np.pi / 6 theta = np.pi / 2 omega = np.pi / 7 np.random.seed(0) eps = 1e-2 init_gen_weights = np.array([np.pi] + [0] * 8) + \ np.random.normal(scale=eps, size=(9,)) init_disc_weights = np.random.normal(size=(9,)) gen_weights = tf.Variable(init_gen_weights) disc_weights = tf.Variable(init_disc_weights) opt = tf.keras.optimizers.SGD(0.4) cost = lambda: disc_cost(disc_weights) print(cost) for step in range(50): opt.minimize(cost, disc_weights) if step % 5 == 0: cost_val = cost().numpy() print("Step {}: cost = {}".format(step, cost_val))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.drivers.second_quantization import GaussianForcesDriver from qiskit_nature.problems.second_quantization import VibrationalStructureProblem from qiskit_nature.settings import settings settings.dict_aux_operators = True driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2) # Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so: second_q_ops = problem.second_q_ops() hamiltonian = second_q_ops["VibrationalEnergy"] print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) # this is now done explicitly and already requires the basis problem = driver.run(basis=basis) problem.hamiltonian.truncation_order = 2 hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers.second_quantization import GaussianLogResult from qiskit_nature.properties.second_quantization.vibrational.bases import HarmonicBasis from qiskit_nature.settings import settings settings.dict_aux_operators = True log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log") hamiltonian = log_result.get_vibrational_energy() print(hamiltonian) hamiltonian.basis = HarmonicBasis([2, 2, 3, 4]) op = hamiltonian.second_q_ops()["VibrationalEnergy"] print("\n".join(str(op).splitlines()[:10] + ["..."])) from qiskit_nature.second_q.drivers import GaussianLogResult from qiskit_nature.second_q.formats import watson_to_problem from qiskit_nature.second_q.problems import HarmonicBasis log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log") watson = log_result.get_watson_hamiltonian() print(watson) basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) problem = watson_to_problem(watson, basis) hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers.second_quantization import GaussianForcesDriver from qiskit_nature.problems.second_quantization import VibrationalStructureProblem driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2) # we trigger driver.run() implicitly like so: second_q_ops = problem.second_q_ops() hamiltonian_op = second_q_ops.pop("VibrationalEnergy") aux_ops = second_q_ops from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) problem = driver.run(basis=basis) problem.hamiltonian.truncation_order = 2 hamiltonian_op, aux_ops = problem.second_q_ops() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from IPython.display import display, clear_output from qiskit.primitives import Estimator from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.observables_evaluator import estimate_observables from qiskit.algorithms.optimizers import COBYLA, SLSQP from qiskit.circuit import QuantumCircuit, Parameter from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.utils import algorithm_globals from qiskit_nature.second_q.operators import FermionicOp from qiskit_nature.second_q.mappers import JordanWignerMapper def kronecker_delta_function(n: int, m: int) -> int: """An implementation of the Kronecker delta function. Args: n (int): The first integer argument. m (int): The second integer argument. Returns: Returns 1 if n = m, else returns 0. """ return int(n == m) def create_deuteron_hamiltonian( N: int, hbar_omega: float = 7.0, V_0: float = -5.68658111 ) -> SparsePauliOp: """Creates a version of the Deuteron Hamiltonian as a qubit operator. Args: N (int): An integer number that represents the dimension of the basis. hbar_omega (float, optional): The value of the product of hbar and omega. Defaults to 7.0. V_0 (float, optional): The value of the potential energy. Defaults to -5.68658111. Returns: SparsePauliOp: The qubit-space Hamiltonian that represents the Deuteron. """ hamiltonian_terms = {} for m in range(N): for n in range(N): label = "+_{} -_{}".format(str(n), str(m)) coefficient_kinect = (hbar_omega / 2) * ( (2 * n + 3 / 2) * kronecker_delta_function(n, m) - np.sqrt(n * (n + (1 / 2))) * kronecker_delta_function(n, m + 1) - np.sqrt((n + 1) * (n + (3 / 2)) * kronecker_delta_function(n, m - 1)) ) hamiltonian_terms[label] = coefficient_kinect coefficient_potential = ( V_0 * kronecker_delta_function(n, 0) * kronecker_delta_function(n, m) ) hamiltonian_terms[label] += coefficient_potential hamiltonian = FermionicOp(hamiltonian_terms, num_spin_orbitals=N) mapper = JordanWignerMapper() qubit_hamiltonian = mapper.map(hamiltonian) if not isinstance(qubit_hamiltonian, SparsePauliOp): qubit_hamiltonian = qubit_hamiltonian.primitive return qubit_hamiltonian deuteron_hamiltonians = [create_deuteron_hamiltonian(i) for i in range(1, 5)] for i, hamiltonian in enumerate(deuteron_hamiltonians): print("Deuteron Hamiltonian: H_{}".format(i + 1)) print(hamiltonian) print("\n") theta = Parameter(r"$\theta$") eta = Parameter(r"$\eta$") wavefunction = QuantumCircuit(1) wavefunction.ry(theta, 0) wavefunction.draw("mpl") wavefunction2 = QuantumCircuit(2) wavefunction2.x(0) wavefunction2.ry(theta, 1) wavefunction2.cx(1, 0) wavefunction2.draw("mpl") wavefunction3 = QuantumCircuit(3) wavefunction3.x(0) wavefunction3.ry(eta, 1) wavefunction3.ry(theta, 2) wavefunction3.cx(2, 0) wavefunction3.cx(0, 1) wavefunction3.ry(-eta, 1) wavefunction3.cx(0, 1) wavefunction3.cx(1, 0) wavefunction3.draw("mpl") ansatz = [wavefunction, wavefunction2, wavefunction3] reference_values = [] print("Exact binding energies calculated through numpy.linalg.eigh \n") for i, hamiltonian in enumerate(deuteron_hamiltonians): eigenvalues, eigenstates = np.linalg.eigh(hamiltonian.to_matrix()) reference_values.append(eigenvalues[0]) print("Exact binding energy for H_{}: {}".format(i + 1, eigenvalues[0])) print( "Results using Estimator for H_1, H_2 and H_3 with the ansatz given in the reference paper \n" ) for i in range(3): seed = 42 algorithm_globals.random_seed = seed vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=SLSQP()) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) binding_energy = vqe_result.optimal_value print("Binding energy for H_{}: {} MeV".format(i + 1, binding_energy)) def callback(eval_count, parameters, mean, std): # Overwrites the same line when printing display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std)) clear_output(wait=True) counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) plots = [] for i in range(3): counts = [] values = [] params = [] deviation = [] seed = 42 algorithm_globals.random_seed = seed vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=COBYLA(), callback=callback) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) plots.append([counts, values]) fig, ax = plt.subplots(nrows=3, ncols=1) fig.set_size_inches((12, 12)) for i, plot in enumerate(plots): ax[i].plot(plot[0], plot[1], "o-", label="COBYLA") ax[i].axhline( y=reference_values[i], color="k", linestyle="--", label=f"Reference Value: {reference_values[i]}", ) ax[i].legend() ax[i].set_xlabel("Cost Function Evaluations", fontsize=15) ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15) plt.show() twolocal_ansatzes = [] for i in range(1, 5): ansatz = TwoLocal( deuteron_hamiltonians[i - 1].num_qubits, ["rz", "ry"], "cx", entanglement="full", reps=i, initial_state=None, ) twolocal_ansatzes.append(ansatz) print("Results using Estimator for H_1, H_2, H_3 and H_4 with TwoLocal ansatz \n") seed = 42 algorithm_globals.random_seed = seed for i in range(4): vqe = VQE(Estimator(), ansatz=twolocal_ansatzes[i], optimizer=SLSQP()) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) binding_energy = vqe_result.optimal_value print("Binding energy for H_{}:".format(i + 1), binding_energy, "MeV") seed = 42 algorithm_globals.random_seed = seed plots_tl = [] for i in range(4): counts = [] values = [] params = [] deviation = [] vqe = VQE( Estimator(), ansatz=twolocal_ansatzes[i], optimizer=SLSQP(), callback=callback, ) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) plots_tl.append([counts, values]) fig, ax = plt.subplots(nrows=4, ncols=1) fig.set_size_inches((15, 15)) for i, plot in enumerate(plots_tl): ax[i].plot(plot[0], plot[1], "o-", label="COBYLA") ax[i].axhline( y=reference_values[i], color="k", linestyle="--", label=f"Reference Value: {reference_values[i]}", ) ax[i].legend() ax[i].set_xlabel("Cost Function Evaluations", fontsize=15) ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15) plt.show() def calculate_observables_exp_values( quantum_circuit: QuantumCircuit, observables: list, angles: list ) -> list: """Calculate the expectation value of an observable given the quantum circuit that represents the wavefunction and a list of parameters. Args: quantum_circuit (QuantumCircuit): A parameterized quantum circuit that represents the wavefunction of the system. observables (list): A list containing the observables that we want to know the expectation values. angles (list): A list with the values that will be used in the 'bind_parameters' method. Returns: list_exp_values (list): A list containing the expectation values of the observables given as input. """ list_exp_values = [] for observable in observables: exp_values = [] for angle in angles: qc = quantum_circuit.bind_parameters({theta: angle}) result = estimate_observables( Estimator(), quantum_state=qc, observables=[observable], ) exp_values.append(result[0][0]) list_exp_values.append(exp_values) return list_exp_values angles = list(np.linspace(-np.pi, np.pi, 100)) observables = [ Pauli("IZ"), Pauli("ZI"), Pauli("XX"), Pauli("YY"), deuteron_hamiltonians[1], ] h2_observables_exp_values = calculate_observables_exp_values(wavefunction2, observables, angles) fig, ax = plt.subplots(nrows=2, ncols=1) fig.set_size_inches((12, 12)) ax[0].plot(angles, h2_observables_exp_values[0], "o", label=r"$Z_0$") ax[0].plot(angles, h2_observables_exp_values[1], "o", label=r"$Z_1$") ax[0].plot(angles, h2_observables_exp_values[2], "o", label=r"$X_0X_1$") ax[0].plot(angles, h2_observables_exp_values[3], "o", label=r"$Y_0Y_1$") ax[0].axhline( y=1, color="k", linestyle="--", ) ax[0].axhline(y=-1, color="k", linestyle="--") ax[0].legend() ax[0].set_xlabel(r"Theta - $\theta$", fontsize=15) ax[0].set_ylabel(r"$\langle O \rangle $ - Operator Expectation Value", fontsize=15) ax[0].set_xticks( [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"], ) ax[0].set_title( r"Expectation value of the observables $Z_0$, $Z_1$, $X_0X_1$ and $Y_0Y_1$ when we vary $\theta$ in the ansatz.", fontsize=15, ) ax[1].plot(angles, h2_observables_exp_values[4], "o") ax[1].axhline( y=reference_values[1], color="k", linestyle="--", label="Binding Energy: {} MeV".format(np.round(reference_values[1], 3)), ) ax[1].legend() ax[1].set_xlabel(r"Theta - $\theta$", fontsize=15) ax[1].set_ylabel(r"$\langle H_2 \rangle $ - Energy (MeV)", fontsize=15) ax[1].set_xticks( [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"], ) ax[1].set_title( r"Behavior of the expectation value of $H_2$ when we vary $\theta$ in the ansatz.", fontsize=15 ) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import datetime import numpy as np from matplotlib import pyplot as plt import qiskit from qiskit import * from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') device = provider.backend.ibmq_rome print(device) #backend = device backend = qiskit.providers.aer.AerSimulator.from_backend(device) coupling_map = device.configuration().coupling_map noise_model = qiskit.providers.aer.noise.NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates #aqua_globals.random_seed = seed qi = qiskit.utils.QuantumInstance(backend=backend, # , seed_simulator=seed, seed_transpiler=seed coupling_map=coupling_map, noise_model=noise_model, measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1): result = [] nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in range(num_trash): circ.ry(thetas[L-i-1], L-i-1) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=True)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = init_vqe(init_state,L=L) + circ else: circ.initialize(init_state, qreg) return circ, qreg def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas backend_sim = backend def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100): circ, qreg = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) # Execute the circuit on the qasm simulator. job_sim = execute(circ, backend_sim, shots=shots, seed_simulator=123, seed_transpiler=234) # fix seed to make it reproducible # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(circ) # print(counts) # mems = result_sim.get_memory(circ) # print(mems) return counts L = 5 num_trash = 2 phi = np.random.rand(40) thetas = np.random.uniform(0, 2*np.pi, 2*L+2) run_circuit(thetas, L, num_trash, phi)['11'] from qiskit.ignis.mitigation.measurement import complete_meas_cal circ, qreg = prepare_circuit(thetas, L, num_trash, phi) qubit_list = [L-i-1 for i in range(num_trash)] # only need to calibrate the trash qubits meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qreg, circlabel='mcal') job = qiskit.execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') print(meas_fitter.cal_matrix) meas_fitter.plot_calibration() job_sim = execute(circ, backend, shots=1000) # fix seed to make it reproducible result = job_sim.result() # Results without mitigation raw_counts = result.get_counts() # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) mitigated_counts = mitigated_results.get_counts(0) from qiskit.tools.visualization import * plot_histogram([raw_counts, mitigated_counts], legend=['raw', 'mitigated'])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can choose different colors for the real and imaginary parts of the density matrix. from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = DensityMatrix(qc) plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
https://github.com/ankitkmisra/Quantum-Computing-and-Cryptography
ankitkmisra
%matplotlib inline # Importing standard Qiskit libraries import random from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * #Get the library to check the answers %pip install -I git+https://github.com/mnp-club/MnP_QC_Workshop.git from mnp_qc_workshop_2020.bb84 import * # Configuring account provider = IBMQ.load_account() backend = provider.get_backend('ibmq_qasm_simulator') # with this simulator it wouldn't work \ # Initial setup random.seed(64) # do not change this seed, otherwise you will get a different key random.seed(64) # This is your 'random' bit string that determines your bases numqubits = 16 bob_bases = str('{0:016b}'.format(random.getrandbits(numqubits))) def bb84(): print('Bob\'s bases:', bob_bases) # Now Alice will send her bits one by one... all_qubit_circuits = [] for qubit_index in range(numqubits): # This is Alice creating the qubit thisqubit_circuit = alice_prepare_qubit(qubit_index) # This is Bob finishing the protocol below bob_measure_qubit(bob_bases, qubit_index, thisqubit_circuit) # We collect all these circuits and put them in an array all_qubit_circuits.append(thisqubit_circuit) # Now execute all the circuits for each qubit results = execute(all_qubit_circuits, backend=backend, shots=1).result() # And combine the results bits = '' for qubit_index in range(numqubits): bits += [measurement for measurement in results.get_counts(qubit_index)][0] return bits # Here is your task def bob_measure_qubit(bob_bases, qubit_index, qubit_circuit): if bob_bases[qubit_index] == '1': qubit_circuit.h(0) qubit_circuit.measure(0, 0) bits = bb84() print('Bob\'s bits: ', bits) check_bits(bits) alice_bases = '0100000101011100' # Alice's bases bits key = '' for i in range(16): if bob_bases[i] == alice_bases[i]: key += bits[i] print(key) check_key(key) message = get_message()# encrypted message decrypted = '' for i in range(len(message)): x = key[-(i%len(key))-1] y = message[-i-1] if x == y: decrypted = '0' + decrypted else: decrypted = '1' + decrypted print(decrypted) check_decrypted(decrypted) decrypted_to_string_ASCII = '' i = 0 while i < 43: decrypted_to_string_ASCII += decrypted[] check_message(decrypted_to_string_ASCII)
https://github.com/samihatashin/QC-Algorithms-with-Qiskit
samihatashin
# Importing standard Qiskit libraries: from qiskit import * from qiskit.providers.ibmq import least_busy from qiskit.tools.jupyter import * from qiskit.visualization import * %matplotlib inline circuit = QuantumCircuit(7+1,7) circuit.draw("mpl") circuit.h([0,1,2,3,4,5,6]) circuit.x(7) circuit.h(7) circuit.barrier() circuit.draw("mpl") circuit.cx(6,7) circuit.cx(3,7) circuit.cx(2,7) circuit.cx(0,7) circuit.barrier() circuit.draw("mpl") circuit.h([0,1,2,3,4,5,6]) circuit.barrier() circuit.measure([0,1,2,3,4,5,6],[0,1,2,3,4,5,6]) circuit.draw("mpl") simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend = simulator, shots = 1).result() counts = result.get_counts() print(counts) plot_histogram(counts) secret_number = input("Input a Binary String of your choice ") ## Not more than 4 bits if you want to run on a real quantum device later on bv_circ = QuantumCircuit(len(secret_number)+1,len(secret_number)) bv_circ.h(range(len(secret_number))) bv_circ.x(len(secret_number)) bv_circ.h(len(secret_number)) bv_circ.barrier() bv_circ.draw("mpl") for digit, query in enumerate(reversed(secret_number)): if query == "1": bv_circ.cx(digit, len(secret_number)) bv_circ.barrier() bv_circ.draw("mpl") bv_circ.h(range(len(secret_number))) bv_circ.barrier() bv_circ.measure(range(len(secret_number)),range(len(secret_number))) bv_circ.draw("mpl") simulator = Aer.get_backend("qasm_simulator") result = execute(bv_circ, backend = simulator, shots = 1).result() counts = result.get_counts() print(counts) plot_histogram(counts) # Enabling our IBMQ accounts to get the least busy backend device with less than or equal to 5 qubits IBMQ.enable_account('IBM Q API Token') provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) exp = execute(bv_circ, backend, shots = 1024) result_exp = exp.result() counts_exp = result_exp.get_counts() plot_histogram([counts_exp,counts])
https://github.com/Axect/QuantumAlgorithms
Axect
import pennylane as qml from pennylane import numpy as np import matplotlib.pyplot as plt from enum import Enum qml.drawer.use_style('sketch') class ReOrIm(Enum): real = 0 imag = 1 dev = qml.device('default.qubit', wires=2) @qml.qnode(dev) def hadamard_test_circuit(theta, phi, re_or_im=ReOrIm.real): # Prepare the superposition state |psi> = (|0>|a> + |1>|b>)/sqrt(2) # 1. Apply the Hadamard gate to the first qubit qml.Hadamard(wires=0) # 2. Apply S^dagger to the first qubit if we are measuring the imaginary part if re_or_im == ReOrIm.imag: qml.adjoint(qml.S)(wires=0) # 3. Apply the controlled unitary U where U|0> = |a> and U|1> = |b> qml.RY(2 * theta, wires=1) # |a> = Ry(theta)|0> qml.CRY(2 * (phi-theta), wires=[0, 1]) # 4. Apply the Hadamard gate to the first qubit qml.Hadamard(wires=0) return qml.probs(wires=0) qml.draw_mpl(hadamard_test_circuit)(np.pi/4, np.pi/3) plt.show() qml.draw_mpl(hadamard_test_circuit)(np.pi/4, np.pi/3, re_or_im=ReOrIm.imag) plt.show() p_0_real = hadamard_test_circuit(np.pi/4, np.pi/3, re_or_im=ReOrIm.real)[0] p_0_imag = hadamard_test_circuit(np.pi/4, np.pi/3, re_or_im=ReOrIm.imag)[0] print(f"Probability of measuring |0> when measuring the real part: {p_0_real:.4f}") print(f"Probability of measuring |0> when measuring the imaginary part: {p_0_imag:.4f}") inner_prod_real = 2 * p_0_real - 1 inner_prod_imag = 1 - 2 * p_0_imag print(f"Real part of the inner product: {inner_prod_real:.4f}") print(f"Imaginary part of the inner product: {inner_prod_imag:.4f}") # The inner product of the two states is the sum of the real and imaginary parts inner_prod = inner_prod_real + 1j * inner_prod_imag print(f"Inner product of the two states: {inner_prod:.4f}")
https://github.com/Innanov/Qiskit-Global-Summer-School-2022
Innanov
from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=2, reps=1, entanglement='linear') ansatz.draw('mpl', style='iqx') from qiskit.opflow import Z, I hamiltonian = Z ^ Z from qiskit.opflow import StateFn expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) import numpy as np point = np.random.random(ansatz.num_parameters) index = 2 from qiskit import Aer from qiskit.utils import QuantumInstance backend = Aer.get_backend('qasm_simulator') q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 2718, seed_transpiler = 2718) from qiskit.circuit import QuantumCircuit from qiskit.opflow import Z, X H = X ^ X U = QuantumCircuit(2) U.h(0) U.cx(0, 1) # YOUR CODE HERE expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U) matmult_result =expectation.eval() from qc_grader import grade_lab4_ex1 # Note that the grading function is expecting a complex number grade_lab4_ex1(matmult_result) from qiskit.opflow import CircuitSampler, PauliExpectation sampler = CircuitSampler(q_instance) # YOUR CODE HERE sampler = CircuitSampler(q_instance) # q_instance is the QuantumInstance from the beginning of the notebook expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U) in_pauli_basis = PauliExpectation().convert(expectation) shots_result = sampler.convert(in_pauli_basis).eval() from qc_grader import grade_lab4_ex2 # Note that the grading function is expecting a complex number grade_lab4_ex2(shots_result) from qiskit.opflow import PauliExpectation, CircuitSampler expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) in_pauli_basis = PauliExpectation().convert(expectation) sampler = CircuitSampler(q_instance) def evaluate_expectation(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(in_pauli_basis, params=value_dict).eval() return np.real(result) eps = 0.2 e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0 plus = point + eps * e_i minus = point - eps * e_i finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps) print(finite_difference) from qiskit.opflow import Gradient expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient('fin_diff', analytic=False, epsilon=eps) grad = shifter.convert(expectation, params=ansatz.parameters[index]) print(grad) value_dict = dict(zip(ansatz.parameters, point)) sampler.convert(grad, value_dict).eval().real eps = np.pi / 2 e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0 plus = point + eps * e_i minus = point - eps * e_i finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / 2 print(finite_difference) expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient() # parameter-shift rule is the default grad = shifter.convert(expectation, params=ansatz.parameters[index]) sampler.convert(grad, value_dict).eval().real expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient('lin_comb') # parameter-shift rule is the default grad = shifter.convert(expectation, params=ansatz.parameters[index]) sampler.convert(grad, value_dict).eval().real # initial_point = np.random.random(ansatz.num_parameters) initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341]) expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz)) gradient = Gradient().convert(expectation) gradient_in_pauli_basis = PauliExpectation().convert(gradient) sampler = CircuitSampler(q_instance) def evaluate_gradient(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() # add parameters in here! return np.real(result) # Note: The GradientDescent class will be released with Qiskit 0.28.0 and can then be imported as: # from qiskit.algorithms.optimizers import GradientDescent from qc_grader.gradient_descent import GradientDescent gd_loss = [] def gd_callback(nfevs, x, fx, stepsize): gd_loss.append(fx) gd = GradientDescent(maxiter=300, learning_rate=0.01, callback=gd_callback) x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, # number of parameters evaluate_expectation, # function to minimize gradient_function=evaluate_gradient, # function to evaluate the gradient initial_point=initial_point) # initial point import matplotlib import matplotlib.pyplot as plt matplotlib.rcParams['font.size'] = 14 plt.figure(figsize=(12, 6)) plt.plot(gd_loss, label='vanilla gradient descent') plt.axhline(-1, ls='--', c='tab:red', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend(); from qiskit.opflow import NaturalGradient expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz)) natural_gradient = NaturalGradient(regularization='ridge').convert(expectation) natural_gradient_in_pauli_basis = PauliExpectation().convert(natural_gradient) sampler = CircuitSampler(q_instance, caching="all") def evaluate_natural_gradient(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(natural_gradient, params=value_dict).eval() return np.real(result) print('Vanilla gradient:', evaluate_gradient(initial_point)) print('Natural gradient:', evaluate_natural_gradient(initial_point)) qng_loss = [] def qng_callback(nfevs, x, fx, stepsize): qng_loss.append(fx) qng = GradientDescent(maxiter=300, learning_rate=0.01, callback=qng_callback) x_opt, fx_opt, nfevs = qng.optimize(initial_point.size, evaluate_expectation, gradient_function=evaluate_natural_gradient, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() from qc_grader.spsa import SPSA spsa_loss = [] def spsa_callback(nfev, x, fx, stepsize, accepted): spsa_loss.append(fx) spsa = SPSA(maxiter=300, learning_rate=0.01, perturbation=0.01, callback=spsa_callback) x_opt, fx_opt, nfevs = spsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() # Note: The QNSPSA class will be released with Qiskit 0.28.0 and can then be imported as: # from qiskit.algorithms.optimizers import QNSPSA from qc_grader.qnspsa import QNSPSA qnspsa_loss = [] def qnspsa_callback(nfev, x, fx, stepsize, accepted): qnspsa_loss.append(fx) fidelity = QNSPSA.get_fidelity(ansatz, q_instance, expectation=PauliExpectation()) qnspsa = QNSPSA(fidelity, maxiter=300, learning_rate=0.01, perturbation=0.01, callback=qnspsa_callback) x_opt, fx_opt, nfevs = qnspsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() autospsa_loss = [] def autospsa_callback(nfev, x, fx, stepsize, accepted): autospsa_loss.append(fx) autospsa = SPSA(maxiter=300, learning_rate=None, perturbation=None, callback=autospsa_callback) x_opt, fx_opt, nfevs = autospsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA') plt.plot(autospsa_loss, 'tab:red', label='Powerlaw SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() H_tfi = -(Z^Z^I)-(I^Z^Z)-(X^I^I)-(I^X^I)-(I^I^X) from qc_grader import grade_lab4_ex3 # Note that the grading function is expecting a Hamiltonian grade_lab4_ex3(H_tfi) from qiskit.circuit.library import EfficientSU2 efficient_su2 = EfficientSU2(3, entanglement="linear", reps=2) tfi_sampler = CircuitSampler(q_instance) def evaluate_tfi(parameters): exp = StateFn(H_tfi, is_measurement=True).compose(StateFn(efficient_su2)) value_dict = dict(zip(efficient_su2.parameters, parameters)) result = tfi_sampler.convert(PauliExpectation().convert(exp), params=value_dict).eval() return np.real(result) # target energy tfi_target = -3.4939592074349326 # initial point for reproducibility tfi_init = np.array([0.95667807, 0.06192812, 0.47615196, 0.83809827, 0.89022282, 0.27140831, 0.9540853 , 0.41374024, 0.92595507, 0.76150126, 0.8701938 , 0.05096063, 0.25476016, 0.71807858, 0.85661325, 0.48311132, 0.43623886, 0.6371297 ]) tfi_result = SPSA(maxiter=300, learning_rate=None, perturbation=None) tfi_result = tfi_result.optimize(tfi_init.size, evaluate_tfi, initial_point=tfi_init) tfi_minimum = tfi_result[1] print("Error:", np.abs(tfi_result[1] - tfi_target)) from qc_grader import grade_lab4_ex4 # Note that the grading function is expecting a floating point number grade_lab4_ex4(tfi_minimum) from qiskit_machine_learning.datasets import ad_hoc_data training_features, training_labels, test_features, test_labels = ad_hoc_data( training_size=20, test_size=10, n=2, one_hot=False, gap=0.5 ) # the training labels are in {0, 1} but we'll use {-1, 1} as class labels! training_labels = 2 * training_labels - 1 test_labels = 2 * test_labels - 1 def plot_sampled_data(): from matplotlib.patches import Patch from matplotlib.lines import Line2D import matplotlib.pyplot as plt plt.figure(figsize=(12,6)) for feature, label in zip(training_features, training_labels): marker = 'o' color = 'tab:green' if label == -1 else 'tab:blue' plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) for feature, label in zip(test_features, test_labels): marker = 's' plt.scatter(feature[0], feature[1], marker=marker, s=100, facecolor='none', edgecolor='k') legend_elements = [ Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15), Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15), Line2D([0], [0], marker='s', c='w', mfc='none', mec='k', label='test features', ms=10) ] plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.6)) plt.title('Training & test data') plt.xlabel('$x$') plt.ylabel('$y$') plot_sampled_data() from qiskit.circuit.library import ZZFeatureMap dim = 2 feature_map = ZZFeatureMap(dim, reps=1) # let's keep it simple! feature_map.draw('mpl', style='iqx') ansatz = RealAmplitudes(num_qubits=dim, entanglement='linear', reps=1) # also simple here! ansatz.draw('mpl', style='iqx') circuit = feature_map.compose(ansatz) circuit.draw('mpl', style='iqx') hamiltonian = Z ^ Z # global Z operators gd_qnn_loss = [] def gd_qnn_callback(*args): gd_qnn_loss.append(args[2]) gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=gd_qnn_callback) from qiskit_machine_learning.neural_networks import OpflowQNN qnn_expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit) qnn = OpflowQNN(qnn_expectation, input_params=list(feature_map.parameters), weight_params=list(ansatz.parameters), exp_val=PauliExpectation(), gradient=Gradient(), # <-- Parameter-Shift gradients quantum_instance=q_instance) from qiskit_machine_learning.algorithms import NeuralNetworkClassifier #initial_point = np.array([0.2, 0.1, 0.3, 0.4]) classifier = NeuralNetworkClassifier(qnn, optimizer=gd) classifier.fit(training_features, training_labels); predicted = classifier.predict(test_features) def plot_predicted(): from matplotlib.lines import Line2D plt.figure(figsize=(12, 6)) for feature, label in zip(training_features, training_labels): marker = 'o' color = 'tab:green' if label == -1 else 'tab:blue' plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) for feature, label, pred in zip(test_features, test_labels, predicted): marker = 's' color = 'tab:green' if pred == -1 else 'tab:blue' if label != pred: # mark wrongly classified plt.scatter(feature[0], feature[1], marker='o', s=500, linewidths=2.5, facecolor='none', edgecolor='tab:red') plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) legend_elements = [ Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15), Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15), Line2D([0], [0], marker='s', c='w', mfc='tab:green', label='predict A', ms=10), Line2D([0], [0], marker='s', c='w', mfc='tab:blue', label='predict B', ms=10), Line2D([0], [0], marker='o', c='w', mfc='none', mec='tab:red', label='wrongly classified', mew=2, ms=15) ] plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.7)) plt.title('Training & test data') plt.xlabel('$x$') plt.ylabel('$y$') plot_predicted() qng_qnn_loss = [] def qng_qnn_callback(*args): qng_qnn_loss.append(args[2]) gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=qng_qnn_callback) qnn = OpflowQNN(qnn_expectation, input_params=list(feature_map.parameters), weight_params=list(ansatz.parameters), gradient=NaturalGradient(regularization='ridge'), # <-- using Natural Gradients! quantum_instance=q_instance) classifier = NeuralNetworkClassifier(qnn, optimizer=gd)#, initial_point=initial_point) classifier.fit(training_features, training_labels); def plot_losses(): plt.figure(figsize=(12, 6)) plt.plot(gd_qnn_loss, 'tab:blue', marker='o', label='vanilla gradients') plt.plot(qng_qnn_loss, 'tab:green', marker='o', label='natural gradients') plt.xlabel('iterations') plt.ylabel('loss') plt.legend(loc='best') plot_losses() from qiskit.opflow import I def sample_gradients(num_qubits, reps, local=False): """Sample the gradient of our model for ``num_qubits`` qubits and ``reps`` repetitions. We sample 100 times for random parameters and compute the gradient of the first RY rotation gate. """ index = num_qubits - 1 # you can also exchange this for a local operator and observe the same! if local: operator = Z ^ Z ^ (I ^ (num_qubits - 2)) else: operator = Z ^ num_qubits # real amplitudes ansatz ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps) # construct Gradient we want to evaluate for different values expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz)) grad = Gradient().convert(expectation, params=ansatz.parameters[index]) # evaluate for 100 different, random parameter values num_points = 100 grads = [] for _ in range(num_points): # points are uniformly chosen from [0, pi] point = np.random.uniform(0, np.pi, ansatz.num_parameters) value_dict = dict(zip(ansatz.parameters, point)) grads.append(sampler.convert(grad, value_dict).eval()) return grads num_qubits = list(range(2, 13)) reps = num_qubits # number of layers = numbers of qubits gradients = [sample_gradients(n, r) for n, r in zip(num_qubits, reps)] fit = np.polyfit(num_qubits, np.log(np.var(gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='measured variance') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); from qiskit.opflow import NaturalGradient def sample_natural_gradients(num_qubits, reps): index = num_qubits - 1 operator = Z ^ num_qubits ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps) expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz)) grad = # TODO: ``grad`` should be the natural gradient for the parameter at index ``index``. # Hint: Check the ``sample_gradients`` function, this one is almost the same. grad = NaturalGradient().convert(expectation, params=ansatz.parameters[index]) num_points = 100 grads = [] for _ in range(num_points): point = np.random.uniform(0, np.pi, ansatz.num_parameters) value_dict = dict(zip(ansatz.parameters, point)) grads.append(sampler.convert(grad, value_dict).eval()) return grads num_qubits = list(range(2, 13)) reps = num_qubits # number of layers = numbers of qubits natural_gradients = [sample_natural_gradients(n, r) for n, r in zip(num_qubits, reps)] fit = np.polyfit(num_qubits, np.log(np.var(natural_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='vanilla gradients') plt.semilogy(num_qubits, np.var(natural_gradients, axis=1), 's-', label='natural gradients') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {float(fit[0]):.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) fixed_depth_global_gradients = [sample_gradients(n, 1) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_global_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) linear_depth_local_gradients = [sample_gradients(n, n, local=True) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(linear_depth_local_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) fixed_depth_local_gradients = [sample_gradients(n, 1, local=True) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_local_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_local_gradients, axis=1), 'o-', label='local cost, constant depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = 6 operator = Z ^ Z ^ (I ^ (num_qubits - 4)) def minimize(circuit, optimizer): initial_point = np.random.random(circuit.num_parameters) exp = StateFn(operator, is_measurement=True) @ StateFn(circuit) grad = Gradient().convert(exp) # pauli basis exp = PauliExpectation().convert(exp) grad = PauliExpectation().convert(grad) sampler = CircuitSampler(q_instance, caching="all") def loss(x): values_dict = dict(zip(circuit.parameters, x)) return np.real(sampler.convert(exp, values_dict).eval()) def gradient(x): values_dict = dict(zip(circuit.parameters, x)) return np.real(sampler.convert(grad, values_dict).eval()) return optimizer.optimize(circuit.num_parameters, loss, gradient, initial_point=initial_point) circuit = RealAmplitudes(4, reps=1, entanglement='linear') circuit.draw('mpl', style='iqx') circuit.reps = 5 circuit.draw('mpl', style='iqx') def layerwise_training(ansatz, max_num_layers, optimizer): optimal_parameters = [] fopt = None for reps in range(1, max_num_layers): ansatz.reps = reps # bind already optimized parameters values_dict = dict(zip(ansatz.parameters, optimal_parameters)) partially_bound = ansatz.bind_parameters(values_dict) xopt, fopt, _ = minimize(partially_bound, optimizer) print('Circuit depth:', ansatz.depth(), 'best value:', fopt) optimal_parameters += list(xopt) return fopt, optimal_parameters ansatz = RealAmplitudes(4, entanglement='linear') optimizer = GradientDescent(maxiter=50) np.random.seed(12) fopt, optimal_parameters = layerwise_training(ansatz, 4, optimizer)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw()
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
JessicaJohnBritto
# Importing Packages from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble, QuantumRegister, ClassicalRegister from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle bb = input("Enter the input string:\n") ### Using in-built "simon_oracle" from QISKIT # importing Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle n = len(bb) simon_circuit = QuantumCircuit(n*2, n) # Apply Hadamard gates before querying the oracle simon_circuit.h(range(n)) # Apply barrier for visual separation simon_circuit.barrier() simon_circuit += simon_oracle(b) # Apply barrier for visual separation simon_circuit.barrier() # Apply Hadamard gates to the input register simon_circuit.h(range(n)) # Measure qubits simon_circuit.measure(range(n), range(n)) simon_circuit.draw(output="mpl") # use local simulator aer_sim = Aer.get_backend('aer_simulator') shots = 500 qobj = assemble(simon_circuit, shots=shots) results = aer_sim.run(qobj).result() counts = results.get_counts() print(counts) plot_histogram(counts) # Calculate the dot product of the results def bdotz(b, z): accum = 0 for i in range(len(b)): accum += int(b[i]) * int(z[i]) return (accum % 2) for z in counts: print( '{}.{} = {} (mod 2)'.format(b, z, bdotz(b,z)) ) b = input("Enter a binary string:\n") # Actual b = 011 b_rev = b[::-1] flagbit = b_rev.find('1') n=len(b) q1=QuantumRegister(n,'q1') q2=QuantumRegister(n,'q2') c1=ClassicalRegister(n) qc = QuantumCircuit(q1,q2,c1) qc.barrier() qc.h(q1) qc.barrier() for i in range(n): qc.cx(q1[i],q2[i]) qc.barrier() if flagbit != -1: # print("test1") for ind, bit in enumerate(b_rev): # print("test2") if bit == "1": # print("test3") qc.cx(flagbit, q2[ind]) qc.barrier() qc.h(q1) qc.barrier() qc.measure(q1,c1) qc.draw("mpl") aer_sim = Aer.get_backend('aer_simulator') shots = 500 qobj = assemble(qc, shots=shots) results = aer_sim.run(qobj).result() counts = results.get_counts() print(counts) plot_histogram(counts) # Actual b = 011 b="1" b_rev = "1" flagbit = b_rev.find('1') n=len(b) q1=QuantumRegister(n,'q1') q2=QuantumRegister(n,'q2') c1=ClassicalRegister(n) qc = QuantumCircuit(q1,q2,c1) qc.barrier() qc.h(q1) qc.barrier() for i in range(n): qc.cx(q1[i],q2[i]) qc.barrier() if flagbit != -1: # print("test1") for ind, bit in enumerate(b_rev): # print("test2") if bit == "1": # print("test3") qc.cx(flagbit, q2[ind]) qc.barrier() qc.h(q1) qc.barrier() # qc.measure(q1,c1) # qc.draw("mpl") # Simulate the unitary usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() # Display the results: array_to_latex(unitary, prefix="\\text{Circuit = } ")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_aer.utils import approximate_quantum_error, approximate_noise_model import numpy as np # Import Aer QuantumError functions that will be used from qiskit_aer.noise import amplitude_damping_error, reset_error, pauli_error from qiskit.quantum_info import Kraus gamma = 0.23 error = amplitude_damping_error(gamma) results = approximate_quantum_error(error, operator_string="reset") print(results) p = (1 + gamma - np.sqrt(1 - gamma)) / 2 q = 0 print("") print("Expected results:") print("P(0) = {}".format(1-(p+q))) print("P(1) = {}".format(p)) print("P(2) = {}".format(q)) gamma = 0.23 K0 = np.array([[1,0],[0,np.sqrt(1-gamma)]]) K1 = np.array([[0,np.sqrt(gamma)],[0,0]]) results = approximate_quantum_error(Kraus([K0, K1]), operator_string="reset") print(results) reset_to_0 = Kraus([np.array([[1,0],[0,0]]), np.array([[0,1],[0,0]])]) reset_to_1 = Kraus([np.array([[0,0],[1,0]]), np.array([[0,0],[0,1]])]) reset_kraus = [reset_to_0, reset_to_1] gamma = 0.23 error = amplitude_damping_error(gamma) results = approximate_quantum_error(error, operator_list=reset_kraus) print(results) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits to represent the uncertainty num_uncertainty_qubits = 3 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # construct circuit for uncertainty model uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high) ) # plot probability distribution x = uncertainty_model.values y = uncertainty_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.show() # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 1.438 strike_price_2 = 2.584 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, strike_price_2 - strike_price_1] f_min = 0 f_max = strike_price_2 - strike_price_1 bull_spread_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective bull_spread = bull_spread_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value (normalized to the [0, 1] interval) exact_value = np.dot(uncertainty_model.probabilities, y) exact_delta = sum( uncertainty_model.probabilities[np.logical_and(x >= strike_price_1, x <= strike_price_2)] ) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread, objective_qubits=[num_uncertainty_qubits], post_processing=bull_spread_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 0, 0] offsets = [0, 1, 0] f_min = 0 f_max = 1 bull_spread_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # no approximation necessary, hence no rescaling factor # construct the A operator by stacking the uncertainty model and payoff function together bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval) print("Exact delta: \t%.4f" % exact_delta) print("Estimated value:\t%.4f" % result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Tojarieh97/VQE
Tojarieh97
from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import SLSQP, L_BFGS_B from qiskit.circuit.library import TwoLocal num_qubits = 2 ansatz = TwoLocal(num_qubits, 'ry', 'cz') opt = SLSQP(maxiter=60) bfgs_optimizer = L_BFGS_B(maxiter=60) vqe = VQE(ansatz, optimizer=opt) ansatz.draw() from qiskit import Aer backend = Aer.get_backend('aer_simulator_statevector') from qiskit.utils import QuantumInstance backend = Aer.get_backend('aer_simulator') quantum_instance = QuantumInstance(backend=backend, shots=800, seed_simulator=99) from qiskit.opflow import X, Z, I print(I.to_matrix()) print((Z^I).to_matrix()) H2_op = (-1.052373245772859 * I ^ I) + \ (0.39793742484318045 * I ^ Z) + \ (-0.39793742484318045 * Z ^ I) + \ (-0.01128010425623538 * Z ^ Z) + \ (0.18093119978423156 * X ^ X) print(H2_op.to_matrix()) from qiskit.utils import algorithm_globals seed = 50 algorithm_globals.random_seed = seed qi = QuantumInstance(Aer.get_backend('statevector_simulator'), seed_transpiler=seed, seed_simulator=seed) ansatz = TwoLocal(rotation_blocks='ry', entanglement_blocks='cz') slsqp = SLSQP(maxiter=1000) vqe = VQE(ansatz, optimizer=bfgs_optimizer, quantum_instance=qi) result = vqe.compute_minimum_eigenvalue(H2_op) print(result) from qiskit.circuit.library import EfficientSU2 entanglements = ["linear", "full"] for entanglement in entanglements: ansatz = EfficientSU2(num_qubits=4, entanglement=entanglement) if entanglement == "linear": print("=============Linear Entanglement:=============") vqe = VQE(ansatz, optimizer=bfgs_optimizer, quantum_instance=qi) result = vqe.compute_minimum_eigenvalue(H2_op) print(result) print() else: print("=============Full Entanglement:=============") vqe = VQE(ansatz, optimizer=bfgs_optimizer, quantum_instance=qi) result = vqe.compute_minimum_eigenvalue(H2_op) print(result) print()
https://github.com/ctuning/ck-qiskit
ctuning
"""The following is python code utilizing the qiskit library that can be run on extant quantum hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding, for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1, results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>). To find the factor, use the equivalence a^r mod 15. From this: (a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15 Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients, gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15, so the result of running shors algorithm to find the prime factors of an integer using quantum hardware are demonstrated. Note, this is not the same as the technical implementation of shor's algorithm described in this section for breaking the discrete log hardness assumption, though the proof of concept remains.""" # Import libraries from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from numpy import pi from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram # Initialize qubit registers qreg_q = QuantumRegister(5, 'q') creg_c = ClassicalRegister(5, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.reset(qreg_q[3]) circuit.reset(qreg_q[4]) # Apply Hadamard transformations to qubit registers circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) # Apply first QFT, modular exponentiation, and another QFT circuit.h(qreg_q[1]) circuit.cx(qreg_q[2], qreg_q[3]) circuit.crx(pi/2, qreg_q[0], qreg_q[1]) circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run the circuit on available quantum hardware and plot histogram from qiskit.tools.monitor import job_monitor job = execute(circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(circuit) plot_histogram(answer) #largest amplitude results correspond with r values used to find the prime factor of N.
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # 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. """Commutation analysis and transformation pass testing""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import PropertySet from qiskit.transpiler.passes import CommutationAnalysis from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestCommutationAnalysis(QiskitTestCase): """Test the Commutation pass.""" def setUp(self): self.pass_ = CommutationAnalysis() self.pset = self.pass_.property_set = PropertySet() def assertCommutationSet(self, result, expected): """ Compares the result of propertyset["commutation_set"] with a dictionary of the form {'q[0]': [ [node_id, ...], [node_id, ...] ]} """ result_to_compare = {} for qbit_str, sets in result.items(): if not isinstance(qbit_str, str): continue result_to_compare[qbit_str] = [] for commutation_set in sets: result_to_compare[qbit_str].append( sorted([node._node_id for node in commutation_set])) for qbit_str, sets in expected.items(): for commutation_set in sets: commutation_set.sort() self.assertDictEqual(result_to_compare, expected) def test_commutation_set_property_is_created(self): """Test property is created""" qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.h(qr) dag = circuit_to_dag(circuit) self.assertIsNone(self.pset['commutation_set']) self.pass_.run(dag) self.assertIsNotNone(self.pset['commutation_set']) def test_all_gates(self): """Test all gates on 1 and 2 qubits qr0:----[H]---[x]---[y]---[t]---[s]---[rz]---[u1]---[u2]---[u3]---.---.---.-- | | | qr1:-------------------------------------------------------------(+)-(Y)--.-- """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.x(qr[0]) circuit.y(qr[0]) circuit.t(qr[0]) circuit.s(qr[0]) circuit.rz(0.5, qr[0]) circuit.u1(0.5, qr[0]) circuit.u2(0.5, 0.6, qr[0]) circuit.u3(0.5, 0.6, 0.7, qr[0]) circuit.cx(qr[0], qr[1]) circuit.cy(qr[0], qr[1]) circuit.cz(qr[0], qr[1]) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [5], [6], [7], [8, 9, 10, 11], [12], [13], [14], [15], [16], [2]], 'qr[1]': [[3], [14], [15], [16], [4]]} self.assertCommutationSet(self.pset["commutation_set"], expected) def test_non_commutative_circuit(self): """A simple circuit where no gates commute qr0:---[H]--- qr1:---[H]--- qr2:---[H]--- """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.h(qr) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [7], [2]], 'qr[1]': [[3], [8], [4]], 'qr[2]': [[5], [9], [6]]} self.assertCommutationSet(self.pset["commutation_set"], expected) def test_non_commutative_circuit_2(self): """A simple circuit where no gates commute qr0:----.------------- | qr1:---(+)------.----- | qr2:---[H]-----(+)---- """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[2]) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [7], [2]], 'qr[1]': [[3], [7], [9], [4]], 'qr[2]': [[5], [8], [9], [6]]} self.assertCommutationSet(self.pset["commutation_set"], expected) def test_commutative_circuit(self): """A simple circuit where two CNOTs commute qr0:----.------------ | qr1:---(+)-----(+)--- | qr2:---[H]------.---- """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[2]) circuit.cx(qr[2], qr[1]) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [7], [2]], 'qr[1]': [[3], [7, 9], [4]], 'qr[2]': [[5], [8], [9], [6]]} self.assertCommutationSet(self.pset["commutation_set"], expected) def test_commutative_circuit_2(self): """A simple circuit where a CNOT and a Z gate commute, and a CNOT and a CNOT commute qr0:----.-----[Z]----- | qr1:---(+)----(+)---- | qr2:---[H]-----.---- """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.z(qr[0]) circuit.h(qr[2]) circuit.cx(qr[2], qr[1]) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [7, 8], [2]], 'qr[1]': [[3], [7, 10], [4]], 'qr[2]': [[5], [9], [10], [6]]} self.assertCommutationSet(self.pset["commutation_set"], expected) def test_commutative_circuit_3(self): """A simple circuit where multiple gates commute qr0:----.-----[Z]-----.----[z]----- | | qr1:---(+)----(+)----(+)----.------ | | qr2:---[H]-----.-----[x]---(+)----- """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[2]) circuit.z(qr[0]) circuit.cx(qr[2], qr[1]) circuit.cx(qr[0], qr[1]) circuit.x(qr[2]) circuit.z(qr[0]) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [7, 9, 11, 13], [2]], 'qr[1]': [[3], [7, 10, 11], [14], [4]], 'qr[2]': [[5], [8], [10], [12, 14], [6]]} self.assertCommutationSet(self.pset["commutation_set"], expected) def test_jordan_wigner_type_circuit(self): """A Jordan-Wigner type circuit where consecutive CNOTs commute qr0:----.-------------------------------------------------------------.---- | | qr1:---(+)----.-------------------------------------------------.----(+)--- | | qr2:---------(+)----.-------------------------------------.----(+)--------- | | qr3:---------------(+)----.-------------------------.----(+)--------------- | | qr4:---------------------(+)----.-------------.----(+)--------------------- | | qr5:---------------------------(+)----[z]----(+)--------------------------- """ qr = QuantumRegister(6, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[4], qr[5]) circuit.z(qr[5]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [13, 23], [2]], 'qr[1]': [[3], [13], [14, 22], [23], [4]], 'qr[2]': [[5], [14], [15, 21], [22], [6]], 'qr[3]': [[7], [15], [16, 20], [21], [8]], 'qr[4]': [[9], [16], [17, 19], [20], [10]], 'qr[5]': [[11], [17], [18], [19], [12]]} self.assertCommutationSet(self.pset["commutation_set"], expected) def test_all_commute_circuit(self): """Test circuit with that all commute""" qr = QuantumRegister(5, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[1]) circuit.cx(qr[4], qr[3]) circuit.cx(qr[2], qr[3]) circuit.z(qr[0]) circuit.z(qr[4]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[1]) circuit.cx(qr[4], qr[3]) circuit.cx(qr[2], qr[3]) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [11, 15, 17], [2]], 'qr[1]': [[3], [11, 12, 17, 18], [4]], 'qr[2]': [[5], [12, 14, 18, 20], [6]], 'qr[3]': [[7], [13, 14, 19, 20], [8]], 'qr[4]': [[9], [13, 16, 19], [10]]} self.assertCommutationSet(self.pset["commutation_set"], expected) if __name__ == '__main__': unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_circuit_layout from qiskit.tools.monitor import job_monitor from qiskit.providers.fake_provider import FakeVigoV2 import matplotlib.pyplot as plt ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) backend = FakeVigoV2() new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # 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=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
""" Test Script """ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qrx = QuantumRegister(1, 'q0') qry = QuantumRegister(1, 'q1') cr = ClassicalRegister(1, 'c') qc = QuantumCircuit(qrx, qry, cr) qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() qc.x(qry) qc.barrier() qc.h(qrx) qc.h(qry) qc.measure(qrx, cr) qc.draw("mpl") from qiskit import execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram sim = AerSimulator() job = execute(qc, backend = sim, shots = 1000) result = job.result() counts = result.get_counts(qc) print("Counts: ", counts) plot_histogram(counts)
https://github.com/1chooo/Quantum-Oracle
1chooo
""" Balanced: Input not equal Output. """ """ Create the quantum Circuit. """ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qrx = QuantumRegister(1, 'q0') qry = QuantumRegister(1, 'q1') cr = ClassicalRegister(1, 'c') qc = QuantumCircuit(qrx, qry, cr) qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() qc.x(qry) qc.cx(qrx, qry) qc.barrier() qc.h(qrx) qc.h(qry) qc.measure(qrx, cr) qc.draw("mpl") """ Proof through histogram. """ from qiskit import execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram sim = AerSimulator() job = execute(qc, backend = sim, shots = 1000) result = job.result() counts = result.get_counts(qc) print("Counts: ", counts) plot_histogram(counts) """ Also in Quantum Computer. """ from qiskit import QuantumCircuit, IBMQ, execute from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram IBMQ.save_account('your_token') IBMQ.load_account() IBMQ.providers() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') qcomp = provider.get_backend('ibmq_manila') job = execute(qc, backend = qcomp, shots = 1000) job_monitor(job) result = job.result() counts = result.get_counts(qc) print("Total counts for qubit states are:", counts) plot_histogram(counts)
https://github.com/danieljaffe/quantum-algorithms-qiskit
danieljaffe
from qiskit import QuantumCircuit from QCLG_lvl3.oracles.secret_number_oracle import SecretNUmberOracle class BernsteinVazirani: @classmethod def bernstein_vazirani(cls, random_binary, eval_mode: bool) -> QuantumCircuit: # Construct secret number oracle secret_number_oracle = SecretNUmberOracle.create_secret_number_oracle(random_binary=random_binary, eval_mode=eval_mode) num_of_qubits = secret_number_oracle.num_qubits # Construct circuit according to the length of the number dj_circuit = QuantumCircuit(num_of_qubits, num_of_qubits - 1) dj_circuit_before_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1) # Apply H-gates for qubit in range(num_of_qubits - 1): dj_circuit_before_oracle.h(qubit) # Put output qubit in state |-> dj_circuit_before_oracle.x(num_of_qubits - 1) dj_circuit_before_oracle.h(num_of_qubits - 1) dj_circuit += dj_circuit_before_oracle # Add oracle dj_circuit += secret_number_oracle dj_circuit_after_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1) # Repeat H-gates for qubit in range(num_of_qubits - 1): dj_circuit_after_oracle.h(qubit) dj_circuit_after_oracle.barrier() # Measure for i in range(num_of_qubits - 1): dj_circuit_after_oracle.measure(i, i) dj_circuit += dj_circuit_after_oracle if not eval_mode: print("Circuit before the oracle\n") print(QuantumCircuit.draw(dj_circuit_before_oracle)) print("Circuit after the oracle\n") print(QuantumCircuit.draw(dj_circuit_after_oracle)) print(dj_circuit) return dj_circuit
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 42 from qiskit.circuit import Parameter from qiskit import QuantumCircuit params1 = [Parameter("input1"), Parameter("weight1")] qc1 = QuantumCircuit(1) qc1.h(0) qc1.ry(params1[0], 0) qc1.rx(params1[1], 0) qc1.draw("mpl") from qiskit.quantum_info import SparsePauliOp observable1 = SparsePauliOp.from_list([("Y" * qc1.num_qubits, 1)]) from qiskit_machine_learning.neural_networks import EstimatorQNN estimator_qnn = EstimatorQNN( circuit=qc1, observables=observable1, input_params=[params1[0]], weight_params=[params1[1]] ) estimator_qnn from qiskit.circuit import 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 estimator_qnn_input = algorithm_globals.random.random(estimator_qnn.num_inputs) estimator_qnn_weights = algorithm_globals.random.random(estimator_qnn.num_weights) print( f"Number of input features for EstimatorQNN: {estimator_qnn.num_inputs} \nInput: {estimator_qnn_input}" ) print( f"Number of trainable weights for EstimatorQNN: {estimator_qnn.num_weights} \nWeights: {estimator_qnn_weights}" ) 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}" ) estimator_qnn_forward = estimator_qnn.forward(estimator_qnn_input, estimator_qnn_weights) print( f"Forward pass result for EstimatorQNN: {estimator_qnn_forward}. \nShape: {estimator_qnn_forward.shape}" ) 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}" ) estimator_qnn_forward_batched = estimator_qnn.forward( [estimator_qnn_input, estimator_qnn_input], estimator_qnn_weights ) print( f"Forward pass result for EstimatorQNN: {estimator_qnn_forward_batched}. \nShape: {estimator_qnn_forward_batched.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}" ) estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward( estimator_qnn_input, estimator_qnn_weights ) print( f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad}" ) print( f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.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}" ) estimator_qnn.input_gradients = True sampler_qnn.input_gradients = True estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward( estimator_qnn_input, estimator_qnn_weights ) print( f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad.shape}" ) print( f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.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.shape}" ) print( f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}" ) observable2 = SparsePauliOp.from_list([("Z" * qc1.num_qubits, 1)]) estimator_qnn2 = EstimatorQNN( circuit=qc1, observables=[observable1, observable2], input_params=[params1[0]], weight_params=[params1[1]], ) estimator_qnn_forward2 = estimator_qnn2.forward(estimator_qnn_input, estimator_qnn_weights) estimator_qnn_input_grad2, estimator_qnn_weight_grad2 = estimator_qnn2.backward( estimator_qnn_input, estimator_qnn_weights ) print(f"Forward output for EstimatorQNN1: {estimator_qnn_forward.shape}") print(f"Forward output for EstimatorQNN2: {estimator_qnn_forward2.shape}") print(f"Backward output for EstimatorQNN1: {estimator_qnn_weight_grad.shape}") print(f"Backward output for EstimatorQNN2: {estimator_qnn_weight_grad2.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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.quantumcircuitdata import CircuitInstruction from qiskit.circuit import Measure from qiskit.circuit.library import HGate, CXGate qr = QuantumRegister(2) cr = ClassicalRegister(2) instructions = [ CircuitInstruction(HGate(), [qr[0]], []), CircuitInstruction(CXGate(), [qr[0], qr[1]], []), CircuitInstruction(Measure(), [qr[0]], [cr[0]]), CircuitInstruction(Measure(), [qr[1]], [cr[1]]), ] circuit = QuantumCircuit.from_instructions(instructions) circuit.draw("mpl")
https://github.com/derivation/quantum_image_edge_detection
derivation
import numpy as np from numpy import pi import matplotlib.pyplot as plt import matplotlib.image as mpimg filename = './schrodin_yang.png' im = mpimg.imread(filename) fig, ax = plt.subplots() ax.imshow(im) from skimage.transform import resize n_pixels = 2**5 im = resize(im, (n_pixels, n_pixels)) fig, ax = plt.subplots() ax.imshow(im) data = im[:,:,0].ravel() from qiskit_aqua.components.initial_states import Custom n_qubits = np.int_(np.log2(len(data))) init_state = Custom(n_qubits, state_vector=data) circ = init_state.construct_circuit('circuit') qr = circ.qregs from copy import deepcopy circ_init = deepcopy(circ) circ.h(qr[0][0]) from qiskit import BasicAer, execute simulator = BasicAer.get_backend('statevector_simulator') result = execute(circ, simulator).result() final_state_vector = result.get_statevector(circ) edge_even = np.real(final_state_vector) n_rows = int(np.sqrt(len(edge_even))) edge_even = edge_even.reshape(n_rows, -1) edge_even[:,::2] = 0 fig, ax = plt.subplots(1,2) ax[0].imshow(edge_even) ax[1].imshow(im) def qft(c, q, n): """n-qubit QFT on q in c.""" for j in range(n): for k in range(j): c.cu1(pi/float(2**(j-k)), q[j], q[k]) c.h(q[j]) def iqft(c, q, n): """n-qubit IQFT on q in c.""" for j in range(n): for k in range(j): c.cu1(-pi/float(2**(j-k)), q[int(n-j-1)], q[int(n-k-1)]) c.h(q[int(n-j-1)]) def shiftBases(c, q, n, p): """Shift the register q by p positions""" iqft(c,q,n) for k in range(n): c.u1(-p*2*pi/float(2**(n-k)), q[int(n-k-1)]) qft(c,q,n) from qiskit import QuantumRegister, QuantumCircuit n = 2 q = QuantumRegister(n,'q') c = QuantumCircuit(q) iqft(c,q,n) shiftBases(c,q,n,1) qft(c,q,n) c.draw(output='mpl') circ = deepcopy(circ_init) qr = circ.qregs shiftBases(circ,qr[0],n_qubits,1) circ.h(qr[0][0]) shiftBases(circ,qr[0],n_qubits,-1) simulator = BasicAer.get_backend('statevector_simulator') result = execute(circ, simulator).result() final_state_vector = result.get_statevector(circ) edge_odd = np.real(final_state_vector) n_rows = np.int_(np.sqrt(len(edge_odd))) edge_odd = edge_odd.reshape(n_rows, -1) edge_odd[:,1::2] = 0 fig, ax = plt.subplots(1,2) ax[0].imshow(edge_odd) ax[1].imshow(im) edge = edge_even + edge_odd fig, ax = plt.subplots(1,2) ax[0].imshow(edge) ax[1].imshow(im)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Monte Carlo Sampling Benchmark Program via Amplitude Estimation- QSim """ import copy import functools import sys import time import numpy as np from numpy.polynomial.polynomial import Polynomial from numpy.polynomial.polynomial import polyfit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.library.standard_gates.ry import RYGate sys.path[1:1] = ["_common", "_common/qsim", "monte-carlo/_common", "quantum-fourier-transform/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../monte-carlo/_common", "../../quantum-fourier-transform/qsim"] import execute as ex import mc_utils as mc_utils import metrics as metrics from qft_benchmark import inv_qft_gate from execute import BenchmarkResult # Benchmark Name benchmark_name = "Monte Carlo Sampling" np.random.seed(0) # default function is f(x) = x^2 f_of_X = functools.partial(mc_utils.power_f, power=2) # default distribution is gaussian distribution p_distribution = mc_utils.gaussian_dist verbose = False # saved circuits and subcircuits for display A_ = None Q_ = None cQ_ = None QC_ = None R_ = None F_ = None QFTI_ = None ############### Circuit Definition def MonteCarloSampling(target_dist, f, num_state_qubits, num_counting_qubits, epsilon=0.05, degree=2, method=2): A_qr = QuantumRegister(num_state_qubits+1) A = QuantumCircuit(A_qr, name=f"A") num_qubits = num_state_qubits + 1 + num_counting_qubits # initialize R and F circuits R_qr = QuantumRegister(num_state_qubits+1) F_qr = QuantumRegister(num_state_qubits+1) R = QuantumCircuit(R_qr, name=f"R") F = QuantumCircuit(F_qr, name=f"F") # method 1 takes in the abitrary function f and arbitrary dist if method == 1: state_prep(R, R_qr, target_dist, num_state_qubits) f_on_objective(F, F_qr, f, epsilon=epsilon, degree=degree) # method 2 chooses to have lower circuit depth by choosing specific f and dist elif method == 2: uniform_prep(R, R_qr, num_state_qubits) square_on_objective(F, F_qr) # append R and F circuits to A A.append(R.to_gate(), A_qr) A.append(F.to_gate(), A_qr) # run AE subroutine given our A composed of R and F qc = AE_Subroutine(num_state_qubits, num_counting_qubits, A, method) # save smaller circuit example for display global QC_, R_, F_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc if (R_ and F_) == None or num_state_qubits <= 3: if num_state_qubits < 5: R_ = R; F_ = F return qc ############### def f_on_objective(qc, qr, f, epsilon=0.05, degree=2): """ Assume last qubit is the objective. Function f is evaluated on first n-1 qubits """ num_state_qubits = qc.num_qubits - 1 c_star = (2*epsilon)**(1/(degree+1)) f_ = functools.partial(f, num_state_qubits=num_state_qubits) zeta_ = functools.partial(mc_utils.zeta_from_f, func=f_, epsilon=epsilon, degree=degree, c=c_star) x_eval = np.linspace(0.0, 2**(num_state_qubits) - 1, num= degree+1) poly = Polynomial(polyfit(x_eval, zeta_(x_eval), degree)) b_exp = mc_utils.binary_expansion(num_state_qubits, poly) for controls in b_exp.keys(): theta = 2*b_exp[controls] controls = list(controls) if len(controls)==0: qc.ry(-theta, qr[num_state_qubits]) else: # define a MCRY gate: # this does the same thing as qc.mcry, but is clearer in the circuit printing MCRY = RYGate(-theta).control(len(controls)) qc.append(MCRY, [*(qr[i] for i in controls), qr[num_state_qubits]]) def square_on_objective(qc, qr): """ Assume last qubit is the objective. Shifted square wave function: if x is even, f(x) = 0; if x i s odd, f(x) = 1 """ num_state_qubits = qc.num_qubits - 1 for control in range(num_state_qubits): qc.cx(control, num_state_qubits) def state_prep(qc, qr, target_dist, num_state_qubits): """ Use controlled Ry gates to construct the superposition Sum \sqrt{p_i} |i> """ r_probs = mc_utils.region_probs(target_dist, num_state_qubits) regions = r_probs.keys() r_norm = {} for r in regions: num_controls = len(r) - 1 super_key = r[:num_controls] if super_key=='': r_norm[super_key] = 1 elif super_key == '1': r_norm[super_key] = r_probs[super_key] r_norm['0'] = 1-r_probs[super_key] else: try: r_norm[super_key] = r_probs[super_key] except KeyError: r_norm[super_key] = r_norm[super_key[:num_controls-1]] - r_probs[super_key[:num_controls-1] + '1'] norm = r_norm[super_key] p = 0 if norm != 0: p = r_probs[r] / norm theta = 2*np.arcsin(np.sqrt(p)) if r == '1': qc.ry(-theta, num_state_qubits-1) else: controls = [qr[num_state_qubits-1 - i] for i in range(num_controls)] # define a MCRY gate: # this does the same thing as qc.mcry, but is clearer in the circuit printing MCRY = RYGate(-theta).control(num_controls, ctrl_state=r[:-1]) qc.append(MCRY, [*controls, qr[num_state_qubits-1 - num_controls]]) def uniform_prep(qc, qr, num_state_qubits): """ Generates a uniform distribution over all states """ for i in range(num_state_qubits): qc.h(i) def AE_Subroutine(num_state_qubits, num_counting_qubits, A_circuit, method): num_qubits = num_state_qubits + num_counting_qubits qr_state = QuantumRegister(num_state_qubits+1) qr_counting = QuantumRegister(num_counting_qubits) cr = ClassicalRegister(num_counting_qubits) qc = QuantumCircuit(qr_state, qr_counting, cr, name=f"qmc({method})-{num_qubits}-{0}") A = A_circuit cQ, Q = Ctrl_Q(num_state_qubits, A) # save small example subcircuits for visualization global A_, Q_, cQ_, QFTI_ if (cQ_ and Q_) == None or num_state_qubits <= 6: if num_state_qubits < 9: cQ_ = cQ; Q_ = Q if A_ == None or num_state_qubits <= 3: if num_state_qubits < 5: A_ = A if QFTI_ == None or num_counting_qubits <= 3: if num_counting_qubits < 4: QFTI_ = inv_qft_gate(num_counting_qubits) # Prepare state from A, and counting qubits with H transform qc.append(A, qr_state) for i in range(num_counting_qubits): qc.h(qr_counting[i]) repeat = 1 for j in reversed(range(num_counting_qubits)): for _ in range(repeat): qc.append(cQ, [qr_counting[j]] + [qr_state[l] for l in range(num_state_qubits+1)]) repeat *= 2 qc.barrier() # inverse quantum Fourier transform only on counting qubits qc.append(inv_qft_gate(num_counting_qubits), qr_counting) qc.barrier() qc.measure([qr_counting[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits))) return qc ############################### # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qc = QuantumCircuit(num_state_qubits+1, name=f"Q") temp_A = copy.copy(A_circ) A_gate = temp_A.to_gate() A_gate_inv = temp_A.inverse().to_gate() ### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ # -S_chi qc.x(num_state_qubits) qc.z(num_state_qubits) qc.x(num_state_qubits) # A_circ_inverse qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)]) # S_0 for i in range(num_state_qubits+1): qc.x(i) qc.h(num_state_qubits) qc.mcx([x for x in range(num_state_qubits)], num_state_qubits) qc.h(num_state_qubits) for i in range(num_state_qubits+1): qc.x(i) # A_circ qc.append(A_gate, [i for i in range(num_state_qubits+1)]) # Create a gate out of the Q operator qc.to_gate(label='Q') # and also a controlled version of it Ctrl_Q_ = qc.control(1) # and return both return Ctrl_Q_, qc ######################################### # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result(qc, result, num_counting_qubits, mu, num_shots, method, num_state_qubits): # generate exact value for the expectation value given our function and dist target_dist = p_distribution(num_state_qubits, mu) f = functools.partial(f_of_X, num_state_qubits=num_state_qubits) if method == 1: exact = mc_utils.estimated_value(target_dist, f) elif method == 2: exact = 0.5 # hard coded exact value from uniform dist and square function if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts # calculate the expected output histogram correct_dist = a_to_bitstring(exact, num_counting_qubits) # generate thermal_dist with amplitudes instead, to be comparable to correct_dist thermal_dist = metrics.uniform_dist(num_counting_qubits) # convert counts, expectation, and thermal_dist to app form for visibility # app form of correct distribution is measuring the input a 100% of the time # convert bit_counts into expectation values counts according to Quantum Risk Analysis paper app_counts = expectation_from_bits(probs, num_counting_qubits, num_shots, method) app_correct_dist = mc_utils.mc_dist(num_counting_qubits, exact, c_star, method) app_thermal_dist = expectation_from_bits(thermal_dist, num_counting_qubits, num_shots, method) if verbose: print(f"For expected value {exact}, expected: {correct_dist} measured: {probs}") print(f" ... For expected value {exact} thermal_dist: {thermal_dist}") print(f"For expected value {exact}, app expected: {app_correct_dist} measured: {app_counts}") print(f" ... For expected value {exact} app_thermal_dist: {app_thermal_dist}") # use polarization fidelity with rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist, thermal_dist) #fidelity = metrics.polarization_fidelity(app_counts, app_correct_dist, app_thermal_dist) hf_fidelity = metrics.hellinger_fidelity_with_expected(probs, correct_dist) ########################################################################### # NOTE: in this benchmark, we are testing how well the amplitude estimation routine # works according to theory, and we do not measure the difference between # the reported answer and the correct answer; the below code just helps # demonstrate that we do approximate the expectation value accurately. # the max in the counts is what the algorithm would report as the correct answer a, _ = mc_utils.value_and_max_prob_from_dist(probs) if verbose: print(f"For expected value {exact} measured: {a}") ########################################################################### if verbose: print(f"Solution counts: {probs}") if verbose: print(f" ... fidelity: {fidelity} hf_fidelity: {hf_fidelity}") return probs, fidelity def a_to_bitstring(a, num_counting_qubits): m = num_counting_qubits # solution 1 num1 = round(np.arcsin(np.sqrt(a)) / np.pi * 2**m) num2 = round( (np.pi - np.arcsin(np.sqrt(a))) / np.pi * 2**m) if num1 != num2 and num2 < 2**m and num1 < 2**m: counts = {format(num1, "0"+str(m)+"b"): 0.5, format(num2, "0"+str(m)+"b"): 0.5} else: counts = {format(num1, "0"+str(m)+"b"): 1} return counts def expectation_from_bits(bits, num_qubits, num_shots, method): amplitudes = {} for b in bits.keys(): precision = int(num_qubits / (np.log2(10))) + 2 r = bits[b] a_meas = pow(np.sin(np.pi*int(b,2)/pow(2,num_qubits)),2) if method == 1: a = ((a_meas - 0.5)/c_star) + 0.5 if method == 2: a = a_meas a = round(a, precision) if a not in amplitudes.keys(): amplitudes[a] = 0 amplitudes[a] += r return amplitudes ################ Benchmark Loop MIN_QUBITS = 4 # must be at least MIN_STATE_QUBITS + 3 MIN_STATE_QUBITS = 1 # set minimums for method 1 MIN_QUBITS_M1 = 5 # must be at least MIN_STATE_QUBITS + 3 MIN_STATE_QUBITS_M1 = 2 # Because circuit size grows significantly with num_qubits # limit the max_qubits here ... MAX_QUBITS=10 # Execute program with default parameters def run(min_qubits=MIN_QUBITS, max_qubits=7, skip_qubits=1, max_circuits=1, num_shots=100, epsilon=0.05, degree=2, num_state_qubits=MIN_STATE_QUBITS, method = 2, # default, not exposed to users backend_id='dm_simulator', provider_backend=None, # hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} ({method}) Benchmark Program - QSim") # Clamp the maximum number of qubits if max_qubits > MAX_QUBITS: print(f"INFO: {benchmark_name} benchmark is limited to a maximum of {MAX_QUBITS} qubits.") max_qubits = MAX_QUBITS if (method == 2): if max_qubits < MIN_QUBITS: print(f"INFO: {benchmark_name} benchmark method ({method}) requires a minimum of {MIN_QUBITS} qubits.") return if min_qubits < MIN_QUBITS: min_qubits = MIN_QUBITS elif (method == 1): if max_qubits < MIN_QUBITS_M1: print(f"INFO: {benchmark_name} benchmark method ({method}) requires a minimum of {MIN_QUBITS_M1} qubits.") return if min_qubits < MIN_QUBITS_M1: min_qubits = MIN_QUBITS_M1 if (method == 1) and (num_state_qubits == MIN_STATE_QUBITS): num_state_qubits = MIN_STATE_QUBITS_M1 skip_qubits = max(1, skip_qubits) ### TODO: need to do more validation of arguments, e.g. min_state_qubits and min_qubits # create context identifier if context is None: context = f"{benchmark_name} ({method}) Benchmark" ########## # Initialize metrics module metrics.init_metrics() global c_star c_star = (2*epsilon)**(1/(degree+1)) # Define custom result handler def execution_handler(qc, result, num_qubits, mu, num_shots): # determine fidelity of result set num_counting_qubits = int(num_qubits) - num_state_qubits -1 counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, float(mu), num_shots, method=method, num_state_qubits=num_state_qubits) metrics.store_metric(num_qubits, mu, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, #hub=hub, group=group, project=project, exec_options=exec_options, context=context) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) input_size = num_qubits - 1 # TODO: keep using inputsize? only used in num_circuits # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (input_size), max_circuits) #print(num_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of circuits to loop over for method 1 if 2**(input_size) <= max_circuits: mu_range = [i/2**(input_size) for i in range(num_circuits)] else: mu_range = [i/2**(input_size) for i in np.random.choice(2**(input_size), num_circuits, False)] #print(mu_range) # loop over limited # of mu values for this for mu in mu_range: target_dist = p_distribution(num_state_qubits, mu) f_to_estimate = functools.partial(f_of_X, num_state_qubits=num_state_qubits) #print(mu) # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = MonteCarloSampling(target_dist, f_to_estimate, num_state_qubits, num_counting_qubits, epsilon, degree, method=method).reverse_bits() # reverse_bits() is applying to handle the change in endianness metrics.store_metric(num_qubits, mu, 'create_time', time.time() - ts) # collapse the 4 sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose().decompose().decompose().decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, mu, num_shots) # if method is 2, we only have one type of circuit, so break out of loop #if method == 2: # break # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nControlled Quantum Operator 'cQ' ="); print(cQ_ if cQ_ != None else " ... too large!") print("\nQuantum Operator 'Q' ="); print(Q_ if Q_ != None else " ... too large!") print("\nAmplitude Generator 'A' ="); print(A_ if A_ != None else " ... too large!") print("\nDistribution Generator 'R' ="); print(R_ if R_ != None else " ... too large!") print("\nFunction Generator 'F' ="); print(F_ if F_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim") # if main, execute method if __name__ == '__main__': ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks) run()
https://github.com/usamisaori/quantum-expressibility-entangling-capability
usamisaori
import sys sys.path.append('../') from expressibility import expressibility from entanglement import Ent import numpy as np import kaleidoscope.qiskit from kaleidoscope import bloch_sphere import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix def getDensityMatrix(circuit): return DensityMatrix(circuit).data import warnings warnings.filterwarnings('ignore') def sampleI(layer=1, qubits=1): circuit = QuantumCircuit(1) circuit.i(0) return circuit def sampleHU1(layer=1, qubits=1): circuit = QuantumCircuit(1) circuit.h(0) circuit.u1(np.random.uniform(0, np.pi * 2), 0) return circuit def sampleHU2(layer=1, qubits=1): circuit = QuantumCircuit(1) circuit.h(0) circuit.u2(np.random.uniform(0, np.pi * 2), np.random.uniform(0, np.pi * 2), 0) return circuit def sampleHU3(layer=1, qubits=1): circuit = QuantumCircuit(1) circuit.h(0) circuit.u3(np.random.uniform(0, np.pi * 2), np.random.uniform(0, np.pi * 2), np.random.uniform(0, np.pi * 2), 0) return circuit X = np.matrix([ [0, 1], [1, 0] ]) Y = np.matrix([ [0, -1j], [1j, 0] ]) Z = np.matrix([ [1, 0], [0, -1] ]) def point(sample): rou = getDensityMatrix(sample()) return [ np.trace(rou @ X).real, np.trace(rou @ Y).real, np.trace(rou @ Z).real ] color = "#FF9933" bins = 100 sampleI().draw(output='mpl') pointsI = [ point(sampleI) for i in range(100) ] bloch_sphere(points=pointsI, points_color=color) h_i, p_i = expressibility(1, sampleI, bins=bins, return_detail=True) fig, ax = plt.subplots() plt.bar([ i/100 for i in range(bins) ], h_i, color="#9999FF", label="Haar", width=0.01) plt.bar([ i/100 for i in range(bins) ], p_i, color="#FF9933AA", label="VQC", width=0.01) plt.ylabel("Probability", fontsize=15) plt.xlabel("Fidelity", fontsize=15) plt.title("Expr") ax.legend(loc="upper center") sampleHU1().draw(output='mpl') pointsHU1 = [ point(sampleHU1) for i in range(2000) ] bloch_sphere(points=pointsHU1, points_color=color) h_hu1, p_hu1 = expressibility(1, sampleHU1, bins=bins, return_detail=True) fig, ax = plt.subplots() plt.bar([ i/100 for i in range(bins) ], h_hu1, color="#9999FF", label="Haar", width=0.01) plt.bar([ i/100 for i in range(bins) ], p_hu1, color="#FF9933AA", label="VQC", width=0.01) plt.ylabel("Probability", fontsize=15) plt.xlabel("Fidelity", fontsize=15) plt.title("Expr") ax.legend(loc="upper center") sampleHU2().draw(output='mpl') pointsHU2 = [ point(sampleHU2) for i in range(2000) ] bloch_sphere(points=pointsHU2, points_color=color) h_hu2, p_hu2 = expressibility(1, sampleHU2, bins=bins, return_detail=True) fig, ax = plt.subplots() plt.bar([ i/100 for i in range(bins) ], h_hu2, color="#9999FF", label="Haar", width=0.01) plt.bar([ i/100 for i in range(bins) ], p_hu2, color="#FF9933AA", label="VQC", width=0.01) plt.ylabel("Probability", fontsize=15) plt.xlabel("Fidelity", fontsize=15) plt.title("Expr") ax.legend(loc="upper center") sampleHU3().draw(output='mpl') pointsHU3 = [ point(sampleHU3) for i in range(2000) ] bloch_sphere(points=pointsHU3, points_color=color) h_hu3, p_hu3 = expressibility(1, sampleHU3, bins=bins, return_detail=True) fig, ax = plt.subplots() plt.bar([ i/100 for i in range(bins) ], h_hu3, color="#9999FF", label="Haar", width=0.01) plt.bar([ i/100 for i in range(bins) ], p_hu3, color="#FF9933AA", label="VQC", width=0.01) plt.ylabel("Probability", fontsize=15) plt.xlabel("Fidelity", fontsize=15) plt.title("Expr") ax.legend(loc="upper center")
https://github.com/quantumjim/Qiskit-PyConDE
quantumjim
%matplotlib notebook import pew # setting up tools for the pewpew pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # fill the screen with medium brightness pixels for X in range(8): for Y in range(8): screen.pixel(X,Y,2) B = 3 # set brightness screen.pixel(6,6,B) # put a bright pixel at (6,6) pew.show(screen) # update screen to display the above changes pew.tick(5) # pause for 5 seconds before quitting import pew # setting up tools for the pewpew pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # fill the screen with medium brightness pixels for X in range(8): for Y in range(8): screen.pixel(X,Y,2) B = 3 # set initial brightness pressing = False while True: # loop which checks for user input and responds keys = pew.keys() # get current key presses if not pressing: if keys&pew.K_X: # pressing X turns off the program break if keys&pew.K_UP: # if UP is pressed, increase brightness of pixel at at (6,6) B = min(B+1,3) if keys&pew.K_DOWN: # if DOWN is pressed, decrease brightness of pixel at at (6,6) B = max(B-1,0) if keys: pressing = True else: if not keys: pressing = False screen.pixel(6,6,B) # put a pixel at (6,6) with current brightness pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # fill the screen with dim pixels for X in range(8): for Y in range(8): screen.pixel(X,Y,2) pew.show(screen) # update screen to display the above changes qc = QuantumCircuit(1,1) # create an empty single qubit circuit # create a circuit that measures the qubit in the z basis m_z = QuantumCircuit(1,1) m_z.measure(0,0) pressing = False while True: # loop which checks for user input and responds keys = pew.keys() # get current key presses if not pressing: if keys&pew.K_X: # pressing X turns off the program break if keys&pew.K_UP: # if UP is pressed, add an x gate qc.x(0) if keys&pew.K_DOWN: # if DOWN is pressed, add an h gate qc.h(0) if keys: pressing = True else: if not keys: pressing = False # get the output from the current circuit full_circuit = qc + m_z bit = simulate(full_circuit,shots=1,get='memory')[0] # set the brightness of 6,6 according to the output if bit=='1': B = 3 else: B = 0 screen.pixel(6,6,B) # put a pixel at (6,1) with current brightness pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum from math import pi pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # fill the screen with dim pixels for X in range(8): for Y in range(8): screen.pixel(X,Y,2) pew.show(screen) # update screen to display the above changes qc = QuantumCircuit(1,1) # create an empty single qubit circuit # create a circuit that measures the qubit in the z basis m_z = QuantumCircuit(1,1) m_z.measure(0,0) # create a circuit that measures the qubit in the x basis m_x = QuantumCircuit(1,1) m_x.h(0) m_x.measure(0,0) basis = 'z' # set initial measurement basis pressing = False while True: # loop which checks for user input and responds keys = pew.keys() # get current key presses if not pressing: if keys&pew.K_X: # pressing X turns off the program break if keys&pew.K_UP: # if UP is pressed, add an x gate qc.x(0) if keys&pew.K_DOWN: # if DOWN is pressed, add an h gate qc.h(0) if keys&pew.K_O: basis = (basis=='z')*'x' + (basis=='x')*'z' if keys: pressing = True else: if not keys: pressing = False # get the output from the current circuit if basis=='z': full_circuit = qc + m_z elif basis=='x': full_circuit = qc + m_x bit = simulate(full_circuit,shots=1,get='memory')[0] # set the brightness of 6,6 according to the output if bit=='1': B = 3 else: B = 0 if basis=='z': screen.pixel(6,6,B) screen.pixel(1,1,2) elif basis=='x': screen.pixel(6,6,2) screen.pixel(1,1,B) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum from math import pi pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # fill the screen with dim pixels for X in range(8): for Y in range(8): screen.pixel(X,Y,2) pew.show(screen) # update screen to display the above changes qc = QuantumCircuit(1,1) # create an empty single qubit circuit # create a circuit that measures the qubit in the z basis m_z = QuantumCircuit(1,1) m_z.measure(0,0) # create a circuit that measures the qubit in the x basis m_x = QuantumCircuit(1,1) m_x.h(0) m_x.measure(0,0) # create a circuit that measures the qubit in the y basis m_y = QuantumCircuit(1,1) m_y.rx(pi/2,0) m_y.measure(0,0) basis = 'z' # set initial measurement basis pressing = False while True: # loop which checks for user input and responds keys = pew.keys() # get current key presses if not pressing: if keys&pew.K_X: # pressing X turns off the program break if keys&pew.K_UP: # if UP is pressed, add an x gate qc.x(0) if keys&pew.K_DOWN: # if DOWN is pressed, add an h gate qc.h(0) if keys&pew.K_LEFT: # if LEFT is pressed, add a sqrt(x) gate qc.rx(pi/2,0) if keys&pew.K_O: basis = (basis=='z')*'x' + (basis=='x')*'y'+ (basis=='y')*'z' if keys: pressing = True else: if not keys: pressing = False # get the output from the current circuit if basis=='z': full_circuit = qc + m_z elif basis=='x': full_circuit = qc + m_x elif basis=='y': full_circuit = qc + m_y bit = simulate(full_circuit,shots=1,get='memory')[0] # set the brightness of 6,6 according to the output if bit=='1': B = 3 else: B = 0 if basis=='z': screen.pixel(6,6,B) screen.pixel(6,1,2) screen.pixel(1,1,2) elif basis=='x': screen.pixel(6,6,2) screen.pixel(6,1,2) screen.pixel(1,1,B) elif basis=='y': screen.pixel(6,6,2) screen.pixel(6,1,B) screen.pixel(1,1,2) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second %matplotlib inline from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Set up tools for visualizing the Bloch sphere from math import pi def get_bloch(qc): # create a circuit that measures the qubit in the z basis m_z = QuantumCircuit(1,1) m_z.measure(0,0) # create a circuit that measures the qubit in the x basis m_x = QuantumCircuit(1,1) m_x.h(0) m_x.measure(0,0) # create a circuit that measures the qubit in the y basis m_y = QuantumCircuit(1,1) m_y.rx(pi/2,0) m_y.measure(0,0) shots = 2**14 # number of samples used for statistics bloch_vector = [] # look at each possible measurement for measure_circuit in [m_x, m_y, m_z]: # run the circuit with a the selected measurement and get the number of samples that output each bit value counts = execute(qc+measure_circuit,Aer.get_backend('qasm_simulator'),shots=shots).result().get_counts() # calculate the probabilities for each bit value probs = {} for output in ['0','1']: if output in counts: probs[output] = counts[output]/shots else: probs[output] = 0 # the bloch vector needs the different between these values bloch_vector.append( probs['0'] - probs['1'] ) return bloch_vector qc = QuantumCircuit(1,1) plot_bloch_vector(get_bloch(qc)) qc = QuantumCircuit(1,1) qc.x(0) plot_bloch_vector(get_bloch(qc)) qc = QuantumCircuit(1,1) qc.h(0) plot_bloch_vector(get_bloch(qc)) qc = QuantumCircuit(1,1) qc.x(0) qc.h(0) plot_bloch_vector(get_bloch(qc)) qc = QuantumCircuit(1,1) qc.rx(-pi/2,0) plot_bloch_vector(get_bloch(qc)) qc = QuantumCircuit(1,1) qc.rx(pi/2,0) plot_bloch_vector(get_bloch(qc)) qc = QuantumCircuit(1,1) qc.rx(pi*1/8,0) plot_bloch_vector(get_bloch(qc)) qc = QuantumCircuit(1,1) qc.rx(pi*2/8,0) plot_bloch_vector(get_bloch(qc)) qc = QuantumCircuit(1,1) qc.rx(pi*3/8,0) plot_bloch_vector(get_bloch(qc)) qc = QuantumCircuit(1,1) qc.rx(pi*4/8,0) plot_bloch_vector(get_bloch(qc)) qc = QuantumCircuit(1,1) qc.rx(pi*4/8,0) qc.rz(pi*1/8,0) plot_bloch_vector(get_bloch(qc)) qc = QuantumCircuit(1,1) qc.rx(pi*4/8,0) qc.rz(pi*2/8,0) plot_bloch_vector(get_bloch(qc)) qc = QuantumCircuit(1,1) qc.rx(pi*4/8,0) qc.rz(pi*3/8,0) plot_bloch_vector(get_bloch(qc)) qc = QuantumCircuit(1,1) qc.rx(pi*4/8,0) qc.rz(pi*4/8,0) plot_bloch_vector(get_bloch(qc)) qc = QuantumCircuit(1,1) qc.rx(pi*4/8,0) qc.rz(pi*4/8,0) qc.ry(-pi*1/8,0) plot_bloch_vector(get_bloch(qc))
https://github.com/BryceFuller/qiskit_camp
BryceFuller
# Python import logging from copy import deepcopy from functools import partial from contextlib import contextmanager import time from multideterminant_prep import PrepareMultiDeterminantState as pmds # Local # External import pandas as pd import numpy as np import xarray as xr import xyzpy as xy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, tools from qiskit.aqua.components.optimizers import SPSA, SLSQP def build_model_from_parameters(circuit, theta): layers, num_qubits, rotations = theta.shape assert rotations == 3, "Expected a 3-sized vector for each theta." # Combine all the qubits in the circuit into one flat list all_qubits = [(reg, qubit) for register in circuit.qregs for reg, qubit in register] assert len(all_qubits) == num_qubits, \ "There are {} qubits but expected same as parameter's shape ({})!".format(len(all_qubits), num_qubits) for l in range(layers): # Add layer of (pseudo)random single qubit rotations for n, (reg, qubit_idx) in enumerate(all_qubits): circuit.u3(theta[l][n][0], theta[l][n][1], theta[l][n][2], reg[qubit_idx]) # Pattern with 2-qubit gates # change the step size in range to affect density of cx layer for n in range(0, num_qubits, 2): if (n + 1) + (l % 2) < num_qubits: # Out-of-bounds check reg_1, qubit_idx_1 = all_qubits[n + (l % 2)] reg_2, qubit_idx_2 = all_qubits[(n + 1) + (l % 2)] circuit.cx(reg_1[qubit_idx_1], reg_2[qubit_idx_2]) def build_compression_model(registers, model_parameters): """ Given a set of input registers, builds a parametrised model of random gate operations which seek to approximate some other (equally-sized) target circuit. Returns: QuantumCircuit: a circuit consisting of random operations on the given registers. """ model_circuit = QuantumCircuit(*registers) # Reshape model parameters so they make sense n_layers = int(len(model_parameters) / 3 / model_circuit.width()) model_parameters = np.array(model_parameters).reshape((n_layers, model_circuit.width(), 3)) # TODO: Store some internal parametrization that can be optimised over. # TODO: Create random set of gate operations based on parametrization. build_model_from_parameters(model_circuit, model_parameters) return model_circuit def swap_test_with_compression_model(target_circuit, model_parameters): """ Given a circuit, builds a parametrised sub-circuit that runs in parallel with and approximately models (with compression) the original circuit. Return: QuantumCircuit: new combined circuit consisting of the original circuit and the model circuit. """ # We assume all quantum registers of the original circuit are to be # modelled. new_registers = [reg.__class__(reg.size, '{}_model'.format(reg.name)) for reg in target_circuit.qregs] # TODO: Build the model's compression circuit here. model_circuit = build_compression_model(new_registers, model_parameters) # Append the two circuits together. top_circuit = target_circuit + model_circuit # Synchronisation barrier just so we know where the original circuits ends. top_circuit.barrier() # Performs a swap test between the compression model and original circuit. # ------------------------------------------------------------------------ # Firstly, create an ancillary in superposition to store the swap test result. swap_tester = QuantumRegister(1, 'swap_tester') top_circuit.add_register(swap_tester) top_circuit.h(swap_tester) # Next, we perform controlled SWAPs using the swap tester. for orig_reg, model_reg in zip(target_circuit.qregs, model_circuit.qregs): for i in range(orig_reg.size): top_circuit.cswap(swap_tester[0], orig_reg[i], model_reg[i]) # Finally, we re-interfere the branches and measure the swap tester. top_circuit.h(swap_tester) top_circuit.x(swap_tester) # Make it so test measurement is P(model == target). swap_test_result = ClassicalRegister(1, 'swap_test_result') top_circuit.add_register(swap_test_result) top_circuit.measure(swap_tester, swap_test_result) return top_circuit def compute_approximation_fidelity(target_circuit, backend='qasm_simulator', n_shots=1000, results_fidelity_list=[], model_parameters=[]): """ Performs a set of runs on the target circuit and an approximation model to compute the approximation's fidelity. Returns: float: a measure of fidelity in [0, 1], where 1 represents the maximum achievable approximation of the target circuit. """ final_circuit = swap_test_with_compression_model(target_circuit, model_parameters) # Execute the SWAP test circuit simulator = Aer.get_backend(backend) job = execute(final_circuit, backend=simulator, shots=n_shots) # Return a measurement of fidelity result_counts = job.result().get_counts(final_circuit) fidelity = result_counts.get('1', n_shots) / n_shots results_fidelity_list.append(fidelity) logging.critical("Fidelity: {}".format(fidelity)) return fidelity def cross_validate_qnn_depth(target_circuit, n_shots, n_iters, n_layers, run=0): """ Runs a single cross-validation experiment with the given parameters. Returns: xr.Dataset: an xarray Dataset consisting of any number of DataArrays of data regarding the results of this experiment. This Dataset will be merged with all other experiment datasets, so in theory every experiment should return a fairly consistent set of data. """ # TODO: Compile the circuit to determine a measure of optimised circuit depth # tools.compiler.compile(target_circuit, backend) # logging.critical("Circuit depth (compiled): {}".format(compiled_depth)) # Configuration n_params = target_circuit.width() * n_layers * 3 # Build variable bounds variable_bounds_single = (0., 2*np.pi) variable_bounds = [variable_bounds_single] * n_params initial_point = np.random.uniform(low=variable_bounds_single[0], high=variable_bounds_single[1], size=(n_params,)).tolist() # logging.critical("Initial point: {}".format(initial_point)) # Store resulting information results_fidelity_list = [] # Partially define the objective function maximisation_function = partial(compute_approximation_fidelity, target_circuit, "qasm_simulator", n_shots, results_fidelity_list) minimization_function = lambda params: -maximisation_function(params) # Call the optimiser optimizer = SPSA(max_trials=n_iters, save_steps=1) result = optimizer.optimize(n_params, minimization_function, variable_bounds=variable_bounds, initial_point=initial_point) last_params, last_score, _ = result logging.critical("FINAL SCORE: {}".format(-last_score)) # Ignore the first set of fidelities (calibration) and very last one (equal to last_score) results_fidelity_list = results_fidelity_list[-((n_iters * 2) + 1):-1] # TODO calculate compiled depth (for simulator this is always 2*l) # Output results return xr.Dataset({ "fidelity": xr.DataArray(np.array(results_fidelity_list).reshape((n_iters, 2)), coords={"iteration": range(n_iters), "plusminus": range(2)}, dims=["iteration", "plusminus"]), "last_theta": xr.DataArray(np.array(last_params).reshape((n_layers, target_circuit.width(), 3)), coords={"layer": range(n_layers), "qubit": range(target_circuit.width()), "angle": ["theta", "phi", "lambda"]}, dims=["layer", "qubit", "angle"]), "uncompiled_target_depth": xr.DataArray(target_circuit.depth()), # "compiled_target_depth": xr.DataArray(compiled_depth), "uncompiled_model_depth": xr.DataArray(2 * n_layers), }) @contextmanager def experiment_crop(fn, experiment_name): """ Defines how to run a crop of experiments (i.e. all the experiments in the grid) in parallel and store results in a file. """ experiment_runner = xy.Runner(fn, var_names=None) timestr = time.strftime("%Y%m%d-%H%M%S") filename = "experiment_results/{}_{}.h5".format(experiment_name, timestr) logging.critical("Running experiments: {}".format(filename)) experiment_harvester = xy.Harvester(experiment_runner, data_name=filename) experiment = experiment_harvester.Crop() yield experiment experiment.grow_missing(parallel=True) results = experiment.reap(wait=True, overwrite=True) logging.critical(results) logging.critical("Saved experiments: {}".format(filename)) if __name__ == "__main__": """ Example which defines a circuit and then runs a set of experiments, defined by the grid_search parameters, across a parallel set of processes. """ logging.critical("Creating the circuit...") in_strings = ["0101", "0011"] in_weights = [4, 7] target_circuit = pmds(in_weights, in_strings, mode='noancilla') logging.critical("Circuit depth (uncompiled): {}".format(target_circuit.depth())) logging.critical("Running the experiments...") with experiment_crop(cross_validate_qnn_depth, "experiments") as experiment: grid_search = { 'n_shots': [1000], 'n_iters': [200], 'n_layers': [2, 3, 4, 5], 'run': range(50), } constants = { 'target_circuit': target_circuit } experiment.sow_combos(grid_search, constants=constants)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # 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=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc)
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram # Create a quantum circuit with 2 qubits # The default initial state of qubits will be |0> or [1,0] qc = QuantumCircuit(2) # Apply h gate to the control and target qubits qc.x(0) qc.h(0) qc.h(1) #Applying the CNOT gate #qc.cx(0,1) #Draw the circuit # qc.draw() qc.draw('mpl') #Get the backend for the circuit to display unitary matrix backend = Aer.get_backend('unitary_simulator') #execute the circuit using the backend out = execute(qc,backend).result().get_unitary() #import qiskit_textbook and display the combined unitary matrix from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ") #Get the backend for the circuit (simulator or realtime system) backend = Aer.get_backend('statevector_simulator') #execute the circuit using the backend out = execute(qc,backend).result().get_statevector() #import qiskit_textbook and display the statevector #from qiskit.tools import array_to_latex array_to_latex(out, pretext = "\\text{Statevector} = ") #execute the circuit and get the plain result out = execute(qc,backend).result() #getting the count of the result counts = out.get_counts() #plotting the histogram plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) def udd10_pos(j): return np.sin(np.pi*j/(2*10 + 2))**2 with pulse.build() as udd_sched: pulse.play(x90, d0) with pulse.align_func(duration=300, func=udd10_pos): for _ in range(10): pulse.play(x180, d0) pulse.play(x90, d0) udd_sched.draw()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) es_problem = driver.run() from qiskit_nature.second_q.mappers import JordanWignerMapper mapper = JordanWignerMapper() from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver numpy_solver = NumPyMinimumEigensolver() from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD ansatz = UCCSD( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, initial_state=HartreeFock( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, ), ) vqe_solver = VQE(Estimator(), ansatz, SLSQP()) vqe_solver.initial_point = [0.0] * ansatz.num_parameters from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.circuit.library import TwoLocal tl_circuit = TwoLocal( rotation_blocks=["h", "rx"], entanglement_blocks="cz", entanglement="full", reps=2, parameter_prefix="y", ) another_solver = VQE(Estimator(), tl_circuit, SLSQP()) from qiskit_nature.second_q.algorithms import GroundStateEigensolver calc = GroundStateEigensolver(mapper, vqe_solver) res = calc.solve(es_problem) print(res) calc = GroundStateEigensolver(mapper, numpy_solver) res = calc.solve(es_problem) print(res) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.mappers import DirectMapper from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis([2, 2, 2, 2]) vib_problem = driver.run(basis=basis) vib_problem.hamiltonian.truncation_order = 2 mapper = DirectMapper() solver_without_filter = NumPyMinimumEigensolver() solver_with_filter = NumPyMinimumEigensolver( filter_criterion=vib_problem.get_default_filter_criterion() ) gsc_wo = GroundStateEigensolver(mapper, solver_without_filter) result_wo = gsc_wo.solve(vib_problem) gsc_w = GroundStateEigensolver(mapper, solver_with_filter) result_w = gsc_w.solve(vib_problem) print(result_wo) print("\n\n") print(result_w) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/qiskit-community/qiskit-dell-runtime
qiskit-community
import itertools import json import numpy as np from numpy.random import RandomState from qiskit import QuantumCircuit, QuantumRegister from qiskit.compiler import transpile from cvxopt import matrix, solvers # pylint: disable=import-error from .qka import QKA class FeatureMap: def __init__(self, feature_dimension, entangler_map=None): if isinstance(feature_dimension, int): if feature_dimension % 2 == 0: self._feature_dimension = feature_dimension else: raise ValueError("Feature dimension must be an even integer.") else: raise ValueError("Feature dimension must be an even integer.") self._num_qubits = int(feature_dimension / 2) if entangler_map is None: self._entangler_map = [ [i, j] for i in range(self._feature_dimension) for j in range(i + 1, self._feature_dimension) ] else: self._entangler_map = entangler_map self._num_parameters = self._num_qubits def construct_circuit(self, x=None, parameters=None, q=None, inverse=False, name=None): if parameters is not None: if isinstance(parameters, (int, float)): raise ValueError("Parameters must be a list.") if len(parameters) == 1: parameters = parameters * np.ones(self._num_qubits) else: if len(parameters) != self._num_parameters: raise ValueError( "The number of feature map parameters must be {}.".format( self._num_parameters ) ) if len(x) != self._feature_dimension: raise ValueError( "The input vector must be of length {}.".format(self._feature_dimension) ) if q is None: q = QuantumRegister(self._num_qubits, name="q") circuit = QuantumCircuit(q, name=name) for i in range(self._num_qubits): circuit.ry(-parameters[i], q[i]) for source, target in self._entangler_map: circuit.cz(q[source], q[target]) for i in range(self._num_qubits): circuit.rz(-2 * x[2 * i + 1], q[i]) circuit.rx(-2 * x[2 * i], q[i]) if inverse: return circuit.inverse() else: return circuit def to_json(self): return json.dumps( {"feature_dimension": self._feature_dimension, "entangler_map": self._entangler_map} ) @classmethod def from_json(cls, data): return cls(**json.loads(data))
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumCircuit qc = QuantumCircuit(3) qc.ccx(0, 1, 2) qc.draw("mpl")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
p = 0.2 import numpy as np from qiskit.circuit import QuantumCircuit class BernoulliA(QuantumCircuit): """A circuit representing the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(theta_p, 0) class BernoulliQ(QuantumCircuit): """A circuit representing the Bernoulli Q operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit self._theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self._theta_p, 0) def power(self, k): # implement the efficient power of Q q_k = QuantumCircuit(1) q_k.ry(2 * k * self._theta_p, 0) return q_k A = BernoulliA(p) Q = BernoulliQ(p) from qiskit.algorithms import EstimationProblem problem = EstimationProblem( state_preparation=A, # A operator grover_operator=Q, # Q operator objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) from qiskit.primitives import Sampler sampler = Sampler() from qiskit.algorithms import AmplitudeEstimation ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy sampler=sampler, ) ae_result = ae.estimate(problem) print(ae_result.estimation) import matplotlib.pyplot as plt # plot estimated values gridpoints = list(ae_result.samples.keys()) probabilities = list(ae_result.samples.values()) plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities)) plt.axvline(p, color="r", ls="--") plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title("Estimated Values", size=15) plt.ylabel("Probability", size=15) plt.xlabel(r"Amplitude $a$", size=15) plt.ylim((0, 1)) plt.grid() plt.show() print("Interpolated MLE estimator:", ae_result.mle) ae_circuit = ae.construct_circuit(problem) ae_circuit.decompose().draw( "mpl", style="iqx" ) # decompose 1 level: exposes the Phase estimation circuit! from qiskit import transpile basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"] transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx") from qiskit.algorithms import IterativeAmplitudeEstimation iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval sampler=sampler, ) iae_result = iae.estimate(problem) print("Estimate:", iae_result.estimation) iae_circuit = iae.construct_circuit(problem, k=3) iae_circuit.draw("mpl", style="iqx") from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation mlae = MaximumLikelihoodAmplitudeEstimation( evaluation_schedule=3, # log2 of the maximal Grover power sampler=sampler, ) mlae_result = mlae.estimate(problem) print("Estimate:", mlae_result.estimation) from qiskit.algorithms import FasterAmplitudeEstimation fae = FasterAmplitudeEstimation( delta=0.01, # target accuracy maxiter=3, # determines the maximal power of the Grover operator sampler=sampler, ) fae_result = fae.estimate(problem) print("Estimate:", fae_result.estimation) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0) plot_circuit_layout(new_circ_lv0, backend)
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
PacktPublishing
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created Nov 2020 Updated Aug 2021 @author: hassi """ from qiskit import IBMQ, QuantumCircuit, execute from qiskit.tools.monitor import job_monitor print("Ch 5: Identifying backends") print("--------------------------") print("Getting provider...") if not IBMQ.active_account(): IBMQ.load_account() provider = IBMQ.get_provider() print("\nAvailable backends:") print(provider.backends(operational=True, simulator=False)) select_backend=input("Type in the name of a backend: ") backend = provider.get_backend(select_backend) print("\nSelected backend:", backend.name()) # Create a quantum circuit to test qc = QuantumCircuit(2,2) qc.h(0) qc.cx(0,1) qc.measure([0,1],[0,1]) print("\nQuantum circuit:") print(qc) job = execute(qc, backend, shots=1000) job_monitor(job) result = job.result() counts = result.get_counts(qc) print("\nResults:", counts) print("\nAvailable simulator backends:") print(provider.backends(operational=True, simulator=True)) backend = provider.get_backend('ibmq_qasm_simulator') job = execute(qc, backend, shots=1000) job_monitor(job) result = job.result() counts = result.get_counts(qc) print("\nSimulator results:", counts)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Hamiltonian-Simulation Benchmark Program - QSim """ import json import os import sys import time import numpy as np from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister sys.path[1:1] = ["_common", "_common/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim"] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "Hamiltonian Simulation" np.random.seed(0) verbose = False # saved circuits and subcircuits for display QC_ = None XX_ = None YY_ = None ZZ_ = None XXYYZZ_ = None # for validating the implementation of XXYYZZ operation _use_XX_YY_ZZ_gates = False # import precalculated data to compare against filename = os.path.join(os.path.dirname(__file__), os.path.pardir, "_common", "precalculated_data.json") # filename = os.path.join(os.path.pardir, "_common", "precalculated_data.json") with open(filename, 'r') as file: data = file.read() precalculated_data = json.loads(data) ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z): ''' Construct a Qiskit circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :return: return a Qiskit circuit for this Hamiltonian ''' num_qubits = n_spins secret_int = f"{K}-{t}" # allocate qubits qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins); qc = QuantumCircuit(qr, cr, name=f"hamsim-{num_qubits}-{secret_int}") tau = t / K # start with initial state of 1010101... for k in range(0, n_spins, 2): qc.x(qr[k]) qc.barrier() # loop over each trotter step, adding gates to the circuit defining the hamiltonian for k in range(K): # the Pauli spin vector product [qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)] [qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)] qc.barrier() # Basic implementation of exp(i * t * (XX + YY + ZZ)) if _use_XX_YY_ZZ_gates: # XX operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # YY operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # Use an optimal XXYYZZ combined operator # See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf else: # optimized XX + YY + ZZ operator on each pair of qubits in linear chain for j in range(2): for i in range(j % 2, n_spins - 1, 2): qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) qc.barrier() # measure all the qubits used in the circuit for i_qubit in range(n_spins): qc.measure(qr[i_qubit], cr[i_qubit]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 6: if n_spins < 9: QC_ = qc return qc ############### XX, YY, ZZ Gate Implementations # Simple XX gate on q0 and q1 with angle 'tau' def xx_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate") qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) # save circuit example for display global XX_ XX_ = qc return qc # Simple YY gate on q0 and q1 with angle 'tau' def yy_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate") qc.s(qr[0]) qc.s(qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.sdg(qr[0]) qc.sdg(qr[1]) # save circuit example for display global YY_ YY_ = qc return qc # Simple ZZ gate on q0 and q1 with angle 'tau' def zz_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate") qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) # save circuit example for display global ZZ_ ZZ_ = qc return qc # Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau' def xxyyzz_opt_gate(tau): alpha = tau; beta = tau; gamma = tau qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt") qc.rz(3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(3.1416*gamma - 3.1416/2, qr[0]) qc.ry(3.1416/2 - 3.1416*alpha, qr[1]) qc.cx(qr[0], qr[1]) qc.ry(3.1416*beta - 3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(-3.1416/2, qr[0]) # save circuit example for display global XXYYZZ_ XXYYZZ_ = qc return qc ############### Result Data Analysis # Analyze and print measured results # Compute the quality of the result based on operator expectation for each state def analyze_and_print_result(qc, result, num_qubits, type, num_shots): if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts if verbose: print(f"For type {type} measured: {probs}") # we have precalculated the correct distribution that a perfect quantum computer will return # it is stored in the json file we import at the top of the code correct_dist = precalculated_data[f"Qubits - {num_qubits}"] if verbose: print(f"Correct dist: {correct_dist}") correct_dist_reversed = {key[::-1]: value for key, value in correct_dist.items()} # print(f"correct_dist_reversed ===== {correct_dist_reversed}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist_reversed) # print(f"fidelity ===== {fidelity}") # # use our polarization fidelity rescaling # fidelity = metrics.polarization_fidelity(counts, correct_dist) return probs, fidelity ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=2, max_qubits=6, max_circuits=3, skip_qubits=1, num_shots=100, use_XX_YY_ZZ_gates = False, backend_id='dm_simulator', provider_backend=None, #hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # create context identifier #if context is None: context = f"{benchmark_name} ({method}) Benchmark" if context is None: context = f"{benchmark_name} Benchmark" # set the flag to use an XX YY ZZ shim if given global _use_XX_YY_ZZ_gates _use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates if _use_XX_YY_ZZ_gates: print("... using unoptimized XX YY ZZ gates") ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, expectation_a = analyze_and_print_result(qc, result, num_qubits, type, num_shots) metrics.store_metric(num_qubits, type, 'fidelity', expectation_a) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options, context=context) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # determine number of circuits to execute for this group num_circuits = max(1, max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # parameters of simulation #### CANNOT BE MODIFIED W/O ALSO MODIFYING PRECALCULATED DATA ######### w = precalculated_data['w'] # strength of disorder k = precalculated_data['k'] # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. t = precalculated_data['t'] # time of simulation ####################################################################### # loop over only 1 circuit for circuit_id in range(num_circuits): #print(circuit_id) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() h_x = precalculated_data['h_x'][:num_qubits] # precalculated random numbers between [-1, 1] h_z = precalculated_data['h_z'][:num_qubits] qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z) metrics.store_metric(num_qubits, circuit_id, 'create_time', time.time() - ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, circuit_id, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if _use_XX_YY_ZZ_gates: print("\nXX, YY, ZZ =") print(XX_); print(YY_); print(ZZ_) else: print("\nXXYYZZ_opt =") print(XXYYZZ_) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks) run()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # 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. """Tests for visualization tools.""" import os import logging import unittest from inspect import signature import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.visualization import utils from qiskit.visualization import circuit_drawer from qiskit.test import QiskitTestCase logger = logging.getLogger(__name__) class TestLatexSourceGenerator(QiskitTestCase): """Qiskit latex source generator tests.""" def random_circuit(self, width=3, depth=3, max_operands=3): """Generate random circuit of arbitrary size. Note: the depth is the layers of independent operation. true depth in the image may be more for visualization purposes, if gates overlap. Args: width (int): number of quantum wires depth (int): layers of operations max_operands (int): maximum operands of each gate Returns: QuantumCircuit: constructed circuit """ qr = QuantumRegister(width, "q") qc = QuantumCircuit(qr) one_q_ops = "iden,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz" two_q_ops = "cx,cy,cz,ch,crz,cu1,cu3,swap" three_q_ops = "ccx" seed = np.random.randint(0, np.iinfo(np.int32).max) logger.debug("random_circuit RandomState seeded with seed=%s", seed) rng = np.random.RandomState(seed) # apply arbitrary random operations at every depth for _ in range(depth): # choose either 1, 2, or 3 qubits for the operation remaining_qubits = list(range(width)) while remaining_qubits: max_possible_operands = min(len(remaining_qubits), max_operands) num_operands = rng.choice(range(max_possible_operands)) + 1 rng.shuffle(remaining_qubits) operands = remaining_qubits[:num_operands] remaining_qubits = [q for q in remaining_qubits if q not in operands] if num_operands == 1: operation = rng.choice(one_q_ops.split(',')) elif num_operands == 2: operation = rng.choice(two_q_ops.split(',')) elif num_operands == 3: operation = rng.choice(three_q_ops.split(',')) # every gate is defined as a method of the QuantumCircuit class # the code below is so we can call a gate by its name gate = getattr(QuantumCircuit, operation) op_args = list(signature(gate).parameters.keys()) num_angles = len(op_args) - num_operands - 1 # -1 for the 'self' arg angles = [rng.uniform(0, 3.14) for x in range(num_angles)] register_operands = [qr[i] for i in operands] gate(qc, *angles, *register_operands) return qc def test_tiny_circuit(self): """Test draw tiny circuit.""" filename = self._get_resource_path('test_tiny.tex') qc = self.random_circuit(1, 1, 1) try: circuit_drawer(qc, filename=filename, output='latex_source') self.assertNotEqual(os.path.exists(filename), False) finally: if os.path.exists(filename): os.remove(filename) def test_normal_circuit(self): """Test draw normal size circuit.""" filename = self._get_resource_path('test_normal.tex') qc = self.random_circuit(5, 5, 3) try: circuit_drawer(qc, filename=filename, output='latex_source') self.assertNotEqual(os.path.exists(filename), False) finally: if os.path.exists(filename): os.remove(filename) def test_wide_circuit(self): """Test draw wide circuit.""" filename = self._get_resource_path('test_wide.tex') qc = self.random_circuit(100, 1, 1) try: circuit_drawer(qc, filename=filename, output='latex_source') self.assertNotEqual(os.path.exists(filename), False) finally: if os.path.exists(filename): os.remove(filename) def test_deep_circuit(self): """Test draw deep circuit.""" filename = self._get_resource_path('test_deep.tex') qc = self.random_circuit(1, 100, 1) try: circuit_drawer(qc, filename=filename, output='latex_source') self.assertNotEqual(os.path.exists(filename), False) finally: if os.path.exists(filename): os.remove(filename) def test_huge_circuit(self): """Test draw huge circuit.""" filename = self._get_resource_path('test_huge.tex') qc = self.random_circuit(40, 40, 1) try: circuit_drawer(qc, filename=filename, output='latex_source') self.assertNotEqual(os.path.exists(filename), False) finally: if os.path.exists(filename): os.remove(filename) def test_teleport(self): """Test draw teleport circuit.""" filename = self._get_resource_path('test_teleport.tex') qr = QuantumRegister(3, 'q') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, cr) # Prepare an initial state qc.u3(0.3, 0.2, 0.1, qr[0]) # Prepare a Bell pair qc.h(qr[1]) qc.cx(qr[1], qr[2]) # Barrier following state preparation qc.barrier(qr) # Measure in the Bell basis qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) # Apply a correction qc.z(qr[2]).c_if(cr, 1) qc.x(qr[2]).c_if(cr, 2) qc.measure(qr[2], cr[2]) try: circuit_drawer(qc, filename=filename, output='latex_source') self.assertNotEqual(os.path.exists(filename), False) finally: if os.path.exists(filename): os.remove(filename) class TestVisualizationUtils(QiskitTestCase): """ Tests for visualizer utilities. Since the utilities in qiskit/tools/visualization/_utils.py are used by several visualizers the need to be check if the interface or their result changes.""" def setUp(self): self.qr1 = QuantumRegister(2, 'qr1') self.qr2 = QuantumRegister(2, 'qr2') self.cr1 = ClassicalRegister(2, 'cr1') self.cr2 = ClassicalRegister(2, 'cr2') self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2) self.circuit.cx(self.qr2[0], self.qr2[1]) self.circuit.measure(self.qr2[0], self.cr2[0]) self.circuit.cx(self.qr2[1], self.qr2[0]) self.circuit.measure(self.qr2[1], self.cr2[1]) self.circuit.cx(self.qr1[0], self.qr1[1]) self.circuit.measure(self.qr1[0], self.cr1[0]) self.circuit.cx(self.qr1[1], self.qr1[0]) self.circuit.measure(self.qr1[1], self.cr1[1]) def test_get_layered_instructions(self): """ _get_layered_instructions without reverse_bits """ (qregs, cregs, layered_ops) = utils._get_layered_instructions(self.circuit) exp = [[('cx', [(QuantumRegister(2, 'qr2'), 0), (QuantumRegister(2, 'qr2'), 1)], []), ('cx', [(QuantumRegister(2, 'qr1'), 0), (QuantumRegister(2, 'qr1'), 1)], [])], [('measure', [(QuantumRegister(2, 'qr2'), 0)], [(ClassicalRegister(2, 'cr2'), 0)])], [('measure', [(QuantumRegister(2, 'qr1'), 0)], [(ClassicalRegister(2, 'cr1'), 0)])], [('cx', [(QuantumRegister(2, 'qr2'), 1), (QuantumRegister(2, 'qr2'), 0)], []), ('cx', [(QuantumRegister(2, 'qr1'), 1), (QuantumRegister(2, 'qr1'), 0)], [])], [('measure', [(QuantumRegister(2, 'qr2'), 1)], [(ClassicalRegister(2, 'cr2'), 1)])], [('measure', [(QuantumRegister(2, 'qr1'), 1)], [(ClassicalRegister(2, 'cr1'), 1)])] ] self.assertEqual([(self.qr1, 0), (self.qr1, 1), (self.qr2, 0), (self.qr2, 1)], qregs) self.assertEqual([(self.cr1, 0), (self.cr1, 1), (self.cr2, 0), (self.cr2, 1)], cregs) self.assertEqual(exp, [[(op.name, op.qargs, op.cargs) for op in ops]for ops in layered_ops]) def test_get_layered_instructions_reverse_bits(self): """ _get_layered_instructions with reverse_bits=True """ (qregs, cregs, layered_ops) = utils._get_layered_instructions(self.circuit, reverse_bits=True) exp = [[('cx', [(QuantumRegister(2, 'qr2'), 0), (QuantumRegister(2, 'qr2'), 1)], []), ('cx', [(QuantumRegister(2, 'qr1'), 0), (QuantumRegister(2, 'qr1'), 1)], [])], [('measure', [(QuantumRegister(2, 'qr2'), 0)], [(ClassicalRegister(2, 'cr2'), 0)])], [('measure', [(QuantumRegister(2, 'qr1'), 0)], [(ClassicalRegister(2, 'cr1'), 0)])], [('cx', [(QuantumRegister(2, 'qr2'), 1), (QuantumRegister(2, 'qr2'), 0)], []), ('cx', [(QuantumRegister(2, 'qr1'), 1), (QuantumRegister(2, 'qr1'), 0)], [])], [('measure', [(QuantumRegister(2, 'qr2'), 1)], [(ClassicalRegister(2, 'cr2'), 1)])], [('measure', [(QuantumRegister(2, 'qr1'), 1)], [(ClassicalRegister(2, 'cr1'), 1)])] ] self.assertEqual([(self.qr2, 1), (self.qr2, 0), (self.qr1, 1), (self.qr1, 0)], qregs) self.assertEqual([(self.cr2, 1), (self.cr2, 0), (self.cr1, 1), (self.cr1, 0)], cregs) self.assertEqual(exp, [[(op.name, op.qargs, op.cargs) for op in ops]for ops in layered_ops]) if __name__ == '__main__': unittest.main(verbosity=2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# load necessary Runtime libraries from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session backend = "ibmq_qasm_simulator" # use the simulator from qiskit.circuit import Parameter from qiskit.opflow import I, X, Z mu = Parameter('$\\mu$') ham_pauli = mu * X cc = Parameter('$c$') ww = Parameter('$\\omega$') ham_res = -(1/2)*ww*(I^Z) + cc*(X^X) + (ham_pauli^I) tt = Parameter('$t$') U_ham = (tt*ham_res).exp_i() from qiskit import transpile from qiskit.circuit import ClassicalRegister from qiskit.opflow import PauliTrotterEvolution, Suzuki import numpy as np num_trot_steps = 5 total_time = 10 cr = ClassicalRegister(1, 'c') spec_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=num_trot_steps)).convert(U_ham) spec_circ = spec_op.to_circuit() spec_circ_t = transpile(spec_circ, basis_gates=['sx', 'rz', 'cx']) spec_circ_t.add_register(cr) spec_circ_t.measure(0, cr[0]) spec_circ_t.draw('mpl') # fixed Parameters fixed_params = { cc: 0.3, mu: 0.7, tt: total_time } # Parameter value for single circuit param_keys = list(spec_circ_t.parameters) # run through all the ww values to create a List of Lists of Parameter value num_pts = 101 wvals = np.linspace(-2, 2, num_pts) param_vals = [] for wval in wvals: all_params = {**fixed_params, **{ww: wval}} param_vals.append([all_params[key] for key in param_keys]) with Session(backend=backend): sampler = Sampler() job = sampler.run( circuits=[spec_circ_t]*num_pts, parameter_values=param_vals, shots=1e5 ) result = job.result() Zexps = [] for dist in result.quasi_dists: if 1 in dist: Zexps.append(1 - 2*dist[1]) else: Zexps.append(1) from qiskit.opflow import PauliExpectation, Zero param_bind = { cc: 0.3, mu: 0.7, tt: total_time } init_state = Zero^2 obsv = I^Z Zexp_exact = (U_ham @ init_state).adjoint() @ obsv @ (U_ham @ init_state) diag_meas_op = PauliExpectation().convert(Zexp_exact) Zexact_values = [] for w_set in wvals: param_bind[ww] = w_set Zexact_values.append(np.real(diag_meas_op.bind_parameters(param_bind).eval())) import matplotlib.pyplot as plt plt.style.use('dark_background') fig, ax = plt.subplots(dpi=100) ax.plot([-param_bind[mu], -param_bind[mu]], [0, 1], ls='--', color='purple') ax.plot([param_bind[mu], param_bind[mu]], [0, 1], ls='--', color='purple') ax.plot(wvals, Zexact_values, label='Exact') ax.plot(wvals, Zexps, label=f"{backend}") ax.set_xlabel(r'$\omega$ (arb)') ax.set_ylabel(r'$\langle Z \rangle$ Expectation') ax.legend() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() from qiskit.tools.jupyter import * %qiskit_version_table
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
VedDharkar
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 import * # Loading your IBM Q account(s) #provider = IBMQ.load_account() q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.draw('mpl') sim = Aer.get_backend('statevector_simulator') qobj = assemble(qc) final_state = sim.run(qobj).result().get_statevector() plot_state_qsphere(final_state)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) # plot using a DensityMatrix state = DensityMatrix(qc) plot_state_city(state)
https://github.com/MonitSharma/qiskit-projects
MonitSharma
import numpy as np import matplotlib.pyplot as plt from docplex.mp.model import Model from qiskit import BasicAer from qiskit.algorithms import QAOA, NumPyMinimumEigensolver from qiskit_optimization.algorithms import CplexOptimizer, MinimumEigenOptimizer from qiskit_optimization.algorithms.admm_optimizer import ADMMParameters, ADMMOptimizer from qiskit_optimization import QuadraticProgram from qiskit_optimization.converters import QuadraticProgramToQubo from qiskit.algorithms.optimizers import COBYLA %matplotlib inline np.random.seed(1) num_items = 3 # number of items num_bins = num_items # maximum number of bins max_weight = 15 # max weight of a bin weights = np.random.randint(1, max_weight, num_items) # Randomly picking the item weight # Construct model using docplex mdl = Model("BinPacking") y = mdl.binary_var_list(num_bins, name="y") # list of variables that represent the bins x = mdl.binary_var_matrix(num_items, num_bins, "x") # variables that represent the items on the specific bin objective = mdl.sum(y) mdl.minimize(objective) for i in range(num_items): # First set of constraints: the items must be in any bin mdl.add_constraint(mdl.sum(x[i, j] for j in range(num_bins)) == 1) for j in range(num_bins): # Second set of constraints: weight constraints mdl.add_constraint(mdl.sum(weights[i] * x[i, j] for i in range(num_items)) <= max_weight * y[j]) # Load quadratic program from docplex model qp = QuadraticProgram() qp.from_docplex(mdl) qubo = QuadraticProgramToQubo().convert(qp)# Create a converter from quadratic program to qubo representation print(f"The number of variables prior converting to QUBO is {qp.get_num_vars()}") print(f"The number of variables after converting to QUBO is {qubo.get_num_vars()}") plt.figure() plt.bar(0, qp.get_num_vars(), label="Prior QUBO") plt.bar(1, qubo.get_num_vars(), label="QUBO") plt.xticks(range(2), 2 * [""]) plt.xlim((-1,2)) plt.legend() plt.ylabel("Num. vars") plt.title(f"Num. vars for {num_items} items") def BinPacking(num_items, num_bins, weights, max_weight, simplification=False): # Construct model using docplex mdl = Model("BinPacking") y = mdl.binary_var_list(num_bins, name="y") # list of variables that represent the bins x = mdl.binary_var_matrix(num_items, num_bins, "x") # variables that represent the items on the specific bin objective = mdl.sum(y) mdl.minimize(objective) for i in range(num_items): # First set of constraints: the items must be in any bin mdl.add_constraint(mdl.sum(x[i, j] for j in range(num_bins)) == 1) for j in range(num_bins): # Second set of constraints: weight constraints mdl.add_constraint(mdl.sum(weights[i] * x[i, j] for i in range(num_items)) <= max_weight * y[j]) # Load quadratic program from docplex model qp = QuadraticProgram() qp.from_docplex(mdl) if simplification: l = int(np.ceil(np.sum(weights)/max_weight)) qp = qp.substitute_variables({f"y_{_}":1 for _ in range(l)}) # First simplification qp = qp.substitute_variables({"x_0_0":1}) # Assign the first item into the first bin qp = qp.substitute_variables({f"x_0_{_}":0 for _ in range(1, num_bins)}) # as the first item is in the first #bin it couldn't be in the other bins qubo = QuadraticProgramToQubo().convert(qp)# Create a converter from quadratic program to qubo representation return qubo qubo_simp = BinPacking(num_items, num_bins, weights, max_weight, simplification=True) print(f"After the simplification, the number of variables is {qubo_simp.get_num_vars()}") plt.figure() plt.bar(0, qp.get_num_vars(), label="Prior QUBO") plt.bar(1, qubo.get_num_vars(), label="QUBO") plt.bar(2, qubo_simp.get_num_vars(), label="QUBO Simplifications") plt.xticks(range(3), 3 * [""]) plt.xlim((-1,3)) plt.legend() plt.ylabel("Num. vars") plt.title(f"Num. vars for {num_items} items") from qiskit import Aer backend = Aer.get_backend("qasm_simulator") def interpret(results, weights, num_items, num_bins, simplify=False): """ Save the results as a list of list where each sublist represent a bin and the sublist elements represent the items weights Args: results: results of the optimization weights (list): weights of the items num_items: (int) number of items num_bins: (int) number of bins """ if simplify: l = int(np.ceil(np.sum(weights)/max_weight)) bins = l * [1] + list(results[:num_bins - l]) items = results[num_bins - l: (num_bins - l) + num_bins * (num_items - 1)].reshape(num_items - 1, num_bins) items_in_bins = [[i+1 for i in range(num_items-1) if bins[j] and items[i, j]] for j in range(num_bins)] items_in_bins[0].append(0) else: bins = results[:num_bins] items = results[num_bins:(num_bins + 1) * num_items].reshape((num_items, num_bins)) items_in_bins = [[i for i in range(num_items) if bins[j] and items[i, j]] for j in range(num_bins)] return items_in_bins def get_figure(items_in_bins, weights, max_weight, title=None): """Get plot of the solution of the Bin Packing Problem. Args: result : The calculated result of the problem Returns: fig: A plot of the solution, where x and y represent the bins and sum of the weights respectively. """ colors = plt.cm.get_cmap("jet", len(weights)) num_bins = len(items_in_bins) fig, axes = plt.subplots() for _, bin_i in enumerate(items_in_bins): sum_items = 0 for item in bin_i: axes.bar(_, weights[item], bottom=sum_items, label=f"Item {item}", color=colors(item)) sum_items += weights[item] axes.hlines(max_weight, -0.5, num_bins - 0.5, linestyle="--", color="tab:red", label="Max Weight") axes.set_xticks(np.arange(num_bins)) axes.set_xlabel("Bin") axes.set_ylabel("Weight") axes.legend() if title: axes.set_title(title) return fig qaoa = MinimumEigenOptimizer(QAOA(reps=3, quantum_instance=backend)) result_qaoa = qaoa.solve(qubo_simp) print("Solving QUBO using QAOA") print(result_qaoa) print("Solving QUBO using CPLEX") result_ideal = CplexOptimizer().solve(qubo_simp) print(result_ideal) fig = get_figure(interpret(result_ideal.x, weights, num_items, num_bins, simplify=True), weights, max_weight, title="CPLEX") fig = get_figure(interpret(result_qaoa.x, weights, num_items, num_bins, simplify=True), weights, max_weight, title="QAOA") max_weight = 15 num_qubits = {} for i in range(2, 10): num_items = i num_bins = num_items weights = [np.random.randint(1, max_weight) for _ in range(i)] num_qubits[i] = BinPacking(num_items, num_bins, weights, max_weight, simplification=True).get_num_vars() plt.figure() plt.plot(num_qubits.keys(), num_qubits.values()) plt.xlabel("num items") plt.ylabel("num qubits") plt.grid() print(f"The number of qubits is: {num_qubits}") x = np.linspace(-2, 2, 100) plt.figure() plt.plot(x, np.exp(-x), label="Exponential") plt.plot(x, 1 - (x) + (x) ** 2 / 2, label="Approximation") plt.xlabel(r"$t = B - \sum_{i=1}^n s(i)*x_i$", fontsize=14) plt.ylabel("penalization", fontsize=14) plt.grid() plt.legend() def BinPackingNewApproach(num_items, num_bins, weights, max_weight, alpha=0.01, simplification=False): # Construct model using docplex mdl = Model("BinPackingNewApproach") y = mdl.binary_var_list(num_bins, name="y") # list of variables that represent the bins x = mdl.binary_var_matrix(num_items, num_bins, "x") # variables that represent the items on the specific bin objective = mdl.sum(y) # PENALIZATION penalization = 0 for j in range(num_bins): t = max_weight * y[j] - mdl.sum(weights[i] * x[i, j] for i in range(num_items)) penalization += -t + t**2 / 2 mdl.minimize(objective + alpha * penalization) for i in range(num_items): # First set of constraints: the items must be in any bin mdl.add_constraint(mdl.sum(x[i, j] for j in range(num_bins)) == 1) # Load quadratic program from docplex model qp = QuadraticProgram() qp.from_docplex(mdl) if simplification: l = int(np.ceil(np.sum(weights)/max_weight)) qp = qp.substitute_variables({f"y_{_}":1 for _ in range(l)}) # First simplification qp = qp.substitute_variables({"x_0_0":1}) # Assign the first item into the first bin qp = qp.substitute_variables({f"x_0_{_}":0 for _ in range(1, num_bins)}) # as the first item is in the first #bin it couldn't be in the other bins qubo = QuadraticProgramToQubo().convert(qp)# Create a converter from quadratic program to qubo representation return qubo max_weight = 15 num_qubits = {} num_qubits_new = {} for i in range(2, 10): num_items = i num_bins = num_items weights = [np.random.randint(1, max_weight) for _ in range(i)] num_qubits[i] = BinPacking(num_items, num_bins, weights, max_weight, simplification=True).get_num_vars() num_qubits_new[i] = BinPackingNewApproach(num_items, num_bins, weights, max_weight, simplification=True).get_num_vars() plt.figure() plt.plot(num_qubits.keys(), num_qubits.values(), label="Current Approach") plt.plot(num_qubits_new.keys(), num_qubits_new.values(), label="New Approach") plt.xlabel("num items") plt.ylabel("num qubits") plt.grid() plt.legend() print(f"The number of qubits for the Classical approach is: {num_qubits}") print(f"The number of qubits is for the new approach is: {num_qubits_new}") np.random.seed(15) num_items = 3 # number of items num_bins = num_items # maximum number of bins max_weight = 15 # max weight of a bin weights = np.random.randint(1, max_weight, num_items) # Randomly picking the item weight qubo_classical = BinPacking(num_items, num_bins, weights, max_weight, simplification=True) qubo_new = BinPackingNewApproach(num_items, num_bins, weights, max_weight, alpha=0.05, simplification=True) qaoa = MinimumEigenOptimizer(QAOA(optimizer=COBYLA(maxiter=10), reps=3, quantum_instance=backend)) result_qaoa_classical = qaoa.solve(qubo_classical) result_qaoa_new = qaoa.solve(qubo_new) result_cplex_classical = CplexOptimizer().solve(qubo_classical) print("------------------------------------------") print("Solving QUBO using QAOA Classical Approach") print(result_qaoa_classical) print("------------------------------------------") print("Solving QUBO using QAOA New Approach") print(result_qaoa_new) print("------------------------------------------") print("Solving QUBO using CPLEX") print(result_cplex_classical) print("------------------------------------------") fig = get_figure(interpret(result_ideal_old.x, weights, num_items, num_bins, simplify=True), weights, max_weight, title="CPLEX") fig = get_figure(interpret(result_qaoa_old.x, weights, num_items, num_bins, simplify=True), weights, max_weight, title="QAOA classical approach") fig = get_figure(interpret(result_qaoa_new.x, weights, num_items, num_bins, simplify=True), weights, max_weight, title="QAOA New Approach") solutions_new = [] solutions_classical = [] for _ in range(10): result_qaoa_new = qaoa.solve(qubo_new) result_qaoa_classical = qaoa.solve(qubo_classical) solutions_new.append(result_qaoa_new.fval) solutions_classical.append(result_qaoa_classical.fval) num_vars = qubo_new.get_num_vars() vars_new = qubo_new.variables result_cplex = CplexOptimizer().solve(qubo_classical) result_new_ideal = qubo_new.objective.evaluate(result_cplex.x[:num_vars])# Replacing the ideal solution into #our new approach to see the optimal solution on the new objective #function ratio_new = (np.abs(1 - np.array(solutions_new) / result_new_ideal) < 0.05).sum() ratio_classical = (np.abs(1 - np.array(solutions_classical) / result_cplex.fval) < 0.05).sum() fig, ax = plt.subplots(1,2, figsize=(15,5)) ax[0].plot(range(1,11), solutions_new, color="tab:green",label="new QUBO QAOA") ax[0].plot(range(1,11), solutions_classical, color="tab:red",label="classical QUBO QAOA") ax[0].plot([1, 10], 2*[result_new_ideal], ":", color="tab:green", label="new QUBO optimal") ax[0].plot([1, 10], 2*[result_cplex.fval], ":", color="tab:red", label="classical QUBO optimal") ax[0].set_xlabel("n", fontsize=14) ax[0].set_ylabel("Cost Obj. function", fontsize=14) ax[0].grid() ax[0].legend() ax[1].bar(0, 100 * ratio_new / 10, label="new") ax[1].bar(1, 100 * ratio_classical/ 10 + 0.5, label="Classical") ax[1].legend() ax[1].set_xticks([0,1]) ax[1].set_xticklabels(["", ""]) ax[1].set_ylabel("Ratio", fontsize=14) def new_eq_optimal(qubo_new, qubo_classical): """ From the classical solution and considering that cplex solution is the optimal, we can traslate the optimal solution to the QUBO representation based on our approach. """ num_vars = qubo_new.get_num_vars() vars_new = qubo_new.variables result_cplex = CplexOptimizer().solve(qubo_classical) result_new_ideal = qubo_new.objective.evaluate(result_cplex.x[:num_vars])# Replacing the ideal solution into #our new approach to see the optimal solution on the new objective #function return result_new_ideal np.random.seed(1) num_items = 3 # number of items num_bins = num_items # maximum number of bins max_weight = 15 # max weight of a bin repetitions = 10 cases = 5 solutions_new = {} optimal_new = [] ratio_new = [] for i in range(cases): # Testing 5 different randomly selected configurations of the problem print(f"----------- Case {i+1} -------------") weights = np.random.randint(1, max_weight, num_items) # Randomly picking the item weight qubo_new = BinPackingNewApproach(num_items, num_bins, weights, max_weight, alpha=0.05, simplification=True) qubo_classical = BinPacking(num_items, num_bins, weights, max_weight, simplification=True) optimal_new.append(new_eq_optimal(qubo_new, qubo_classical)) solutions_new[i] = [] for _ in range(repetitions): #Testing the ratio result_qaoa_new = qaoa.solve(qubo_new) solutions_new[i].append(result_qaoa_new.fval) ratio_new.append(100 * ((np.array(solutions_new[i]) / optimal_new[-1] - 1) < 5e-2).sum() / repetitions) plt.figure() plt.bar([i for i in range(1, cases + 1)], ratio_new) plt.xlabel("Case") plt.ylabel("Ratio") np.random.seed(1) num_items = 4 # number of items num_bins = num_items # maximum number of bins max_weight = 15 # max weight of a bin repetitions = 10 cases = 5 solutions_new = {} optimal_new = [] ratio_new = [] for i in range(cases): # Testing 5 different randomly selected configurations of the problem print(f"----------- Case {i+1} -------------") weights = np.random.randint(1, max_weight, num_items) # Randomly picking the item weight qubo_new = BinPackingNewApproach(num_items, num_bins, weights, max_weight, alpha=0.05, simplification=True) qubo_classical = BinPacking(num_items, num_bins, weights, max_weight, simplification=True) optimal_new.append(new_eq_optimal(qubo_new, qubo_classical)) solutions_new[i] = [] for _ in range(repetitions): #Testing the ratio result_qaoa_new = qaoa.solve(qubo_new) solutions_new[i].append(result_qaoa_new.fval) ratio_new.append(100 * ((np.array(solutions_new[i]) / optimal_new[-1] - 1) < 5e-2).sum() / repetitions) plt.figure() plt.bar([i for i in range(1, cases + 1)], ratio_new) plt.xlabel("Case") plt.ylabel("Ratio") np.random.seed(1) num_items = 5 # number of items num_bins = num_items # maximum number of bins max_weight = 15 # max weight of a bin repetitions = 10 cases = 5 solutions_new = {} optimal_new = [] ratio_new = [] qaoa = MinimumEigenOptimizer(QAOA(optimizer=COBYLA(maxiter=100), reps=4, quantum_instance=backend)) for i in range(cases): # Testing 5 different randomly selected configurations of the problem print(f"----------- Case {i+1} -------------") weights = np.random.randint(1, max_weight, num_items) # Randomly picking the item weight qubo_new = BinPackingNewApproach(num_items, num_bins, weights, max_weight, alpha=0.05, simplification=True) qubo_classical = BinPacking(num_items, num_bins, weights, max_weight, simplification=True) optimal_new.append(new_eq_optimal(qubo_new, qubo_classical)) solutions_new[i] = [] for _ in range(repetitions): #Testing the ratio result_qaoa_new = qaoa.solve(qubo_new) solutions_new[i].append(result_qaoa_new.fval) ratio_new.append(100 * ((np.array(solutions_new[i]) / optimal_new[-1] - 1) < 5e-2).sum() / repetitions) plt.figure() plt.bar([i for i in range(1, cases + 1)], ratio_new) plt.xlabel("Case") plt.ylabel("Ratio")
https://github.com/Pitt-JonesLab/slam_decomposition
Pitt-JonesLab
import logging logger = logging.getLogger() logger.setLevel(logging.ERROR) import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library import CXGate, XGate from qiskit.converters import circuit_to_dag from qiskit.dagcircuit import DAGCircuit, DAGOpNode from qiskit.quantum_info import Operator from qiskit.transpiler import PassManager from qiskit.transpiler.basepasses import AnalysisPass, TransformationPass from qiskit.transpiler.passes import ( Collect2qBlocks, ConsolidateBlocks, CountOps, Optimize1qGates, Unroll3qOrMore, ) from tqdm import tqdm from weylchamber import c1c2c3 from slam.basis import MixedOrderBasisCircuitTemplate from slam.utils.gates.bare_candidates import get_group_name from slam.utils.gates.custom_gates import ConversionGainGate, CustomCostGate, RiSwapGate from slam.utils.gates.duraton_scaling import atomic_cost_scaling from slam.utils.gates.family_extend import recursive_sibling_check from slam.utils.gates.winner_selection import pick_winner from slam.utils.polytopes.polytope_wrap import monodromy_range_from_target from slam.utils.transpiler_pass.weyl_decompose import ( RootiSwapWeylDecomposition as decomposer, ) class fooAnalysis(AnalysisPass): """print duration of the circuit (iswap = 1 unit)""" def __init__(self, duration_1q): super().__init__() self.duration_1q = duration_1q def run(self, dag): # XXX this probably didn't cause any issues, but problem in logic. The DAG longest path is not necessarily the duration longest path. """Start with overall longest path.""" freq = {} # tracking frequency of gates d = 0 # tracking critical path duration for gate in dag.longest_path(): if isinstance(gate, DAGOpNode): if gate.op.duration is not None: d += gate.op.duration elif gate.op.name in ["u", "u1", "u2", "u3"]: d += self.duration_1q elif gate.op.name in ["cx"]: d += 1 # longest path frequency tracking freq[gate.op.name] = freq.get(gate.op.name, 0) + 1 self.property_set["duration"] = d self.property_set["gate_counts"] = dag.count_ops() self.property_set["longest_path_counts"] = freq # XXX for now, just assume all measurements take place together at the end of the circuit # """Next, look at longest path on each wire""" # # to calculate duration over each wire, start by putting measurements at the end of each wire # # then, use remove_nonancestors_of followed by longest_path, to find the critical path for each wire # tempc = dag_to_circuit(dag) # tempc.measure_all() # msmtdag = circuit_to_dag(tempc) # # now, we have a dag with measurements at the end of each wire # msmtnodes = msmtdag.named_nodes('measure') # for i in range(len(msmtnodes)): # wire_d = [] # d = 0 # # make a working copy of the dag # msmtdag = circuit_to_dag(tempc) # node = msmtdag.named_nodes('measure')[i] # have to remake such that the node is in the copy of the dag, bad code :( # msmtdag.remove_nonancestors_of(node) # # now all paths lead to the measurement # # find the longest path # path = msmtdag.longest_path() # for gate in path: # if isinstance(gate, DAGOpNode): # if gate.op.duration is not None: # d += gate.op.duration # elif gate.op.name in ['u', 'u1', 'u2', 'u3']: # d += self.duration_1q # elif gate.op.name in ['cx']: # d += 1 # wire_d.append(d) # self.property_set['wire_duration'] = wire_d logging.info("\nTranspilation Results:") logging.info(f"Gate Counts: {dag.count_ops()}") logging.info(f"Longest Path Gate Counts: {freq}") logging.info(f"Duration: {d}") # logging.info(f"Wire Duration: {wire_d}") return 1 # success class SpeedGateSubstitute(TransformationPass): def __init__( self, speed_method, duration_1q, strategy, basic_metric, coupling_map, lambda_weight=0.47, family_extension=False, ): super().__init__() self.speed_method = speed_method self.duration_1q = duration_1q self.strategy = strategy self.basic_metric = basic_metric self.coupling_map = coupling_map self.lambda_weight = lambda_weight self.family_extension = family_extension # makes sure the data exists first # cost scaling is deprecated # cost_scaling(speed_method=speed_method, duration_1q=duration_1q) self.group_name = get_group_name(speed_method, duration_1q) # NOTE force requires so that only 2Q ops exist in dag # collect 2Q blocks self.requires.extend( [ Unroll3qOrMore(), Collect2qBlocks(), ConsolidateBlocks(force_consolidate=True), ] ) def run(self, dag: DAGCircuit): """Run the pass on `dag`.""" if ( self.strategy == "basic_overall" or self.strategy == "lambda_weight" or self.strategy == "basic_smush" or self.strategy == "lambda_smush" ): """Here, we define a single metric to pick a winner gate to be used for all decompositions. Metrics pick most efficient for either SWAP, CNOT, or Haar OR using lambda * d[cnot] + (1-lambda) * d[swap] as winner metric """ metric = ( self.basic_metric if ("basic" in self.strategy) else (-1, self.lambda_weight) ) smush_bool = True if ("smush" in self.strategy) else False winner_gate, scaled_winner_gate = pick_winner( self.group_name, metric=metric, plot=False, smush_bool=smush_bool, family_extension=self.family_extension, ) # that way we only have to compute a single coverage set # NOTE winner_gate goes to constructor so hits the saved polytope coverage set template = MixedOrderBasisCircuitTemplate( base_gates=[winner_gate], smush_bool=smush_bool ) logging.info("Found winner, begin substitution") # second, make substitutions for node in dag.two_qubit_ops(): target = Operator(node.op).data if self.family_extension: ret = recursive_sibling_check( template, target, cost_1q=self.duration_1q, basis_factor=scaled_winner_gate.duration, use_smush=smush_bool, ) ret[0] # should already be built # XXX template isn't using scaled gates will break the fooAnalysis # print("here") # idea is to substitute a dummy gate that contains the duration attribute # note the actual unitary doesn't matter since we're just using the duration # problem is that the 1Q gates are not used so don't get simplified away # need to check if subtemplate has 1Q gates then subtract duration_1q from the dummy cost # this is very hacky, don't like # XXX lets just assume it always has 1Q gates CustomCostGate( str="dummy1q", unitary=XGate(), duration=self.duration_1q, num_qubits=1, ) dummy_gate = CustomCostGate( unitary=target, duration=ret[1] - (2 * self.duration_1q), str="dummy", ) sub_qc = QuantumCircuit(2) # sub_qc.append(dummy_single, [0]) # sub_qc.append(dummy_single, [1]) sub_qc.append(dummy_gate, [0, 1]) # sub_qc.append(dummy_single, [0]) # sub_qc.append(dummy_single, [1]) sub_dag = circuit_to_dag(sub_qc) dag.substitute_node_with_dag(node, sub_dag) else: reps = monodromy_range_from_target(template, target_u=target)[0] # NOTE, when we build, actually use the scaled_winner_gate which has the proper duration attiriubte template.build(reps, scaled_winner_gate) # we should set all the U3 gates to be real valued - doesn't matter for sake of counting duration sub_qc = template.assign_Xk(template.parameter_guess()) sub_dag = circuit_to_dag(sub_qc) dag.substitute_node_with_dag(node, sub_dag) elif self.strategy == "weighted_overall": """Here, we are counting gates that appear in the circuit in order to define a winner metric.""" # first, need frqeuncy of each gate # NOTE this feels unoptimized, because we are consolidating 1Q gates, so more misses (?) target_ops = [g.op for g in dag.two_qubit_ops()] winner_gate, scaled_winner_gate = pick_winner( self.group_name, metric=-1, target_ops=target_ops, plot=False, family_extension=self.family_extension, ) # XXX unoptimized ! logging.info("Found winner, begin substitution") template = MixedOrderBasisCircuitTemplate(base_gates=[winner_gate]) # second, make substitutions for node in dag.two_qubit_ops(): target = Operator(node.op).data reps = monodromy_range_from_target(template, target_u=target)[0] template.build(reps, scaled_winner_gate) # we should set all the U3 gates to be real valued - doesn't matter for sake of counting duration sub_qc = template.assign_Xk(template.parameter_guess()) sub_dag = circuit_to_dag(sub_qc) dag.substitute_node_with_dag(node, sub_dag) elif self.strategy == "weighted_pairwise": """Here, we count gates that appear between each pair of qubits in the circuit, define a winner for each pair.""" # get edges from coupling map # turn off logging, too verbose with many winners logging.info("Iterating over edges, finding winners") logger.setLevel(logging.ERROR) edges = self.coupling_map.get_edges() # in order to remove duplicates, we need to sort the edges # only keep edges if the first qubit is smaller than the second edges = [e for e in edges if e[0] < e[1]] for edge in tqdm(edges): # target_ops = [g.op for g in dag.two_qubit_ops() if (g.qargs[0].index, g.qargs[1].index) == edge] # target ops are the 2Q gates that are between the two qubits but the order of the qubits is not important target_ops = [ g.op for g in dag.two_qubit_ops() if set(edge) == set((g.qargs[0].index, g.qargs[1].index)) ] if len(target_ops) == 0: continue winner_gate, scaled_winner_gate = pick_winner( self.group_name, metric=-1, target_ops=target_ops, tqdm_bool=False, plot=False, family_extension=self.family_extension, ) logging.info(f"Found winner for {edge} edge, begin substitution") template = MixedOrderBasisCircuitTemplate(base_gates=[winner_gate]) # second, make substitutions for the 2Q gates between the two qubits for node in dag.two_qubit_ops(): if set(edge) == set((node.qargs[0].index, node.qargs[1].index)): target = Operator(node.op).data reps = monodromy_range_from_target(template, target_u=target)[0] template.build(reps, scaled_winner_gate) # we should set all the U3 gates to be real valued - doesn't matter for sake of counting duration sub_qc = template.assign_Xk(template.parameter_guess()) sub_dag = circuit_to_dag(sub_qc) dag.substitute_node_with_dag(node, sub_dag) # turn logging back on logger.setLevel(logging.INFO) else: raise ValueError("Strategy not recognized") logging.warning( "1Q gates are not being set to accurate values, just placeholders for fast counting" ) return dag class OptimizedSqiswapSub(TransformationPass): """ Unoptimized code :( Replace CX-family gates with iSwap-fam identity, and SWAP gates with iSwap-fam identity This TransformationPass takes advantage of 2 main optimized: 1. The CX-family gates reduce from a. 2 Sqiswaps build all CX gates to b. iswap^n builds cx^n gates For a linear SLF, this changes CX from .1+.5+.1+.5+.1 = 1.3 to .1+1+.1 = 1.2 For a linear SLF, this changes sqCX from .1+.5+.1+.5+.1 = 1.3 to .1+.5+.1 = 0.7 ... 2. The SWAP gates reduce from a. 3 sqiswaps to b. 1 iswap + 1 sqiswap For a linear SLF, this changes SWAP from .1+.5+.1+.5+.1+.5+.1 = 1.9 to .1 + 1 + .1 + .5 + .1 = 1.8 We also believe it is possible to remove the last internal 1Q gate, which would give .1 + 1 +.5 + .1 = 1.7 3. It could be possible to remove the external gates if unitary equivalence >> local equivalence, but this is not implemented This could have very large savings for SWAP gate, but for CX we expect in some cases the external gates to be simplified away """ def __init__(self, duration_1q=0, speed_method="linear"): super().__init__() self.duration_1q = duration_1q self.speed_method = speed_method def run(self, dag): """Run the OptimizedSqiswapSub pass on `dag`.""" # first, we need to get a duration scaled iswap gate iswap = ConversionGainGate(0, 0, np.pi / 2, 0, t_el=1) sqiswap = ConversionGainGate(0, 0, np.pi / 2, 0, t_el=0.5) scaled_iswap, _ = atomic_cost_scaling( params=iswap.params, scores=np.array([0]), speed_method=self.speed_method, duration_1q=self.duration_1q, ) scaled_sqiswap, _ = atomic_cost_scaling( params=sqiswap.params, scores=np.array([0]), speed_method=self.speed_method, duration_1q=self.duration_1q, ) # second load pd coverage of sqiswap # we will use this for QV, and any other edge cases (non CX/SWAP gates) edge_iswap_template = MixedOrderBasisCircuitTemplate( base_gates=[iswap], use_smush_polytope=True ) template = MixedOrderBasisCircuitTemplate( base_gates=[sqiswap], use_smush_polytope=True ) # third, we iterate over the 2Q gates and replace them with the scaled iswap gate for node in dag.two_qubit_ops(): # convert node to weyl coordinate try: target = Operator(node.op).data target_coord = c1c2c3(target) except: # XXX I'm not confident this is always the right thing to do logging.warning( "ValueError in c1c2c3, setting target to real part, issue likely due to imaginary numerical error on SWAP gate" ) target = target.real sub_qc = QuantumCircuit(2) # add random 1Q unitaries to the sub circuit with np.random.random() sub_qc.u(np.random.random(), np.random.random(), np.random.random(), 0) sub_qc.u(np.random.random(), np.random.random(), np.random.random(), 1) # if target coord is a controlled unitary, use derivived 1-1 equivalency to iswap family (up to local equiv) if target_coord[1] == 0 and target_coord[2] == 0: # with parallel drive, CX==iSwap, sqCX==sqiswap, etc scale_factor = ( target_coord[0] / 0.5 ) # divide by .5 to get x-coord of CX sub_iswap = ConversionGainGate( *scaled_iswap.params[:-1], t_el=scaled_iswap.params[-1] * scale_factor, ) sub_iswap.normalize_duration(1) sub_iswap.duration = scaled_iswap.duration * scale_factor sub_qc.append(sub_iswap, [0, 1]) # if target coord is a swap, use derived equivalency to iswap family iswap_pd + 1Q + sqiswap (up to local equiv) # NOTE the best we have found is elif target_coord == (0.5, 0.5, 0.5): # with parallel drive, SWAP is 1 parallel-driven iSwap followed by a sqiswap sub_qc.append(scaled_iswap, [0, 1]) # XXX we think these can go away if have a perfect decomposition, but hard to find with our approx methods PERFECTED_DECOMP_SWAP = 0 # add random 1Q gates if not PERFECTED_DECOMP_SWAP: sub_qc.u( np.random.random(), np.random.random(), np.random.random(), 0 ) sub_qc.u( np.random.random(), np.random.random(), np.random.random(), 1 ) # add sqiswap scale_factor = 1 / 2 sub_iswap = ConversionGainGate( *scaled_iswap.params[:-1], t_el=scaled_iswap.params[-1] * scale_factor, ) sub_iswap.normalize_duration(1) sub_iswap.duration = scaled_iswap.duration * scale_factor sub_qc.append(sub_iswap, [0, 1]) elif target_coord == (0.5, 0.5, 0): # iSwap may show up from CX+SWAP # iswap is just iswap :) sub_qc.append(scaled_iswap, [0, 1]) else: # this is edge case # for example, in QFT there are some [SWAP+CX] => pSwap # pass this to standard monodromy template # the idea is that we can still may get an improvement from the \ # parallel-drive extended coverage polytope # XXX missing iSwap parallel driven, family-extension. This code is messy which is why it's not here yet # hardcode the cases # if its in extended iSwap in 1, do 2 sqiswaps no middle 1Q gate reps = monodromy_range_from_target( edge_iswap_template, target_u=target )[0] if reps == 1: sub_qc.append(scaled_iswap, [0, 1]) else: # if its in extended iSwap in 2 more just use the regular extended sqiswap reps = monodromy_range_from_target(template, target_u=target)[0] template.build(reps, scaled_sqiswap) sub_qc = template.assign_Xk( template.parameter_guess() ) # radom real values # this template is going to have an extra set of external 1Q gates, # because cases nested in this for loop have pre-, post- fixed gates # its not a problem to have doubles, as long as Optimized1QGates removes them # we need to make sure that when we simplify that they get cancelled out # add random 1Q unitaries to the sub circuit with np.random.random() sub_qc.u(np.random.random(), np.random.random(), np.random.random(), 0) sub_qc.u(np.random.random(), np.random.random(), np.random.random(), 1) # make the substitution sub_dag = circuit_to_dag(sub_qc) dag.substitute_node_with_dag(node, sub_dag) return dag # optimized sqiswap pass manager (with dummy substitution) class pass_manager_optimized_sqiswap(PassManager): """Note, the sqiswap basis gate is a bit of a misnomer, because the basis gate we would calibrate is actually a smaller fraction of an iswap (whatever smallest fraction preserves fidelity) For example, if we calibrate 1/16 of an iswap, we would build sqiswap and iswap gates by repeating the gate with no interleaving 1Q gates 8,16 times.""" def __init__(self, duration_1q=0, speed_method="linear"): passes = [] passes.extend([CountOps()]) # collapse 2Q gates passes.extend( [ Unroll3qOrMore(), Collect2qBlocks(), ConsolidateBlocks(force_consolidate=True), ] ) # every CX-family gate is replaced using iSwap-fam identity # every SWAP gate is repalced using iSwap-fam identity passes.extend( [OptimizedSqiswapSub(duration_1q=duration_1q, speed_method=speed_method)] ) # collapse 1Q gates passes.extend([Optimize1qGates()]) passes.extend([CountOps(), fooAnalysis(duration_1q)]) super().__init__(passes) logging.warning( "1Q gates are not being set to accurate values, just placeholders for fast counting" ) # speed-limit aware manager class pass_manager_slam(PassManager): def __init__( self, strategy="basic_overall", speed_method="linear", duration_1q=0, basic_metric=0, family_extension=0, coupling_map=None, ): passes = [] passes.extend([CountOps()]) passes.extend( [ SpeedGateSubstitute( strategy=strategy, speed_method=speed_method, duration_1q=duration_1q, basic_metric=basic_metric, coupling_map=coupling_map, family_extension=family_extension, ) ] ) # combine 1Q gates passes.extend([Optimize1qGates()]) passes.extend([CountOps(), fooAnalysis(duration_1q)]) super().__init__(passes) class pass_manager_basic(PassManager): def __init__(self, gate="sqiswap", duration_1q=0): passes = [] passes.extend([CountOps()]) # collect 2Q blocks # FIXME, it is probably faster to not consolidate, and have some smarter means of duplicate target substitution passes.extend( [ Unroll3qOrMore(), Collect2qBlocks(), ConsolidateBlocks(force_consolidate=True), ] ) if gate == "sqiswap": passes.extend([decomposer(basis_gate=RiSwapGate(1 / 2))]) elif gate == "cx": passes.extend([decomposer(basis_gate=CXGate())]) # combine 1Q gates passes.extend([Optimize1qGates()]) passes.extend([CountOps(), fooAnalysis(duration_1q)]) super().__init__(passes)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # 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. """ Example use of the initialize gate to prepare arbitrary pure states. """ import math from qiskit import QuantumCircuit, execute, BasicAer ############################################################### # Make a quantum circuit for state initialization. ############################################################### circuit = QuantumCircuit(4, 4, name="initializer_circ") desired_vector = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] circuit.initialize(desired_vector, [0, 1, 2, 3]) circuit.measure([0, 1, 2, 3], [0, 1, 2, 3]) print(circuit) ############################################################### # Execute on a simulator backend. ############################################################### shots = 10000 # Desired vector print("Desired probabilities: ") print([format(abs(x * x), ".3f") for x in desired_vector]) # Initialize on local simulator sim_backend = BasicAer.get_backend("qasm_simulator") job = execute(circuit, sim_backend, shots=shots) result = job.result() counts = result.get_counts(circuit) qubit_strings = [format(i, "04b") for i in range(2**4)] print("Probabilities from simulator: ") print([format(counts.get(s, 0) / shots, ".3f") for s in qubit_strings])
https://github.com/abbarreto/qiskit2
abbarreto
%run init.ipynb
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.providers.fake_provider import FakeHanoi backend = FakeHanoi() config = backend.configuration() # Basic Features print("This backend is called {0}, and is on version {1}. It has {2} qubit{3}. It " "{4} OpenPulse programs. The basis gates supported on this device are {5}." "".format(config.backend_name, config.backend_version, config.n_qubits, '' if config.n_qubits == 1 else 's', 'supports' if config.open_pulse else 'does not support', config.basis_gates)) config.dt # units of seconds config.meas_levels config.dtm config.meas_map config.drive(0) config.measure(0) config.acquire(0) props = backend.properties() def describe_qubit(qubit, properties): """Print a string describing some of reported properties of the given qubit.""" # Conversion factors from standard SI units us = 1e6 ns = 1e9 GHz = 1e-9 print("Qubit {0} has a \n" " - T1 time of {1} microseconds\n" " - T2 time of {2} microseconds\n" " - U2 gate error of {3}\n" " - U2 gate duration of {4} nanoseconds\n" " - resonant frequency of {5} GHz".format( qubit, properties.t1(qubit) * us, properties.t2(qubit) * us, properties.gate_error('sx', qubit), properties.gate_length('sx', qubit) * ns, properties.frequency(qubit) * GHz)) describe_qubit(0, props) defaults = backend.defaults() q0_freq = defaults.qubit_freq_est[0] # Hz q0_meas_freq = defaults.meas_freq_est[0] # Hz GHz = 1e-9 print("DriveChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_freq * GHz)) print("MeasureChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_meas_freq * GHz)) calibrations = defaults.instruction_schedule_map print(calibrations) measure_schedule = calibrations.get('measure', range(config.n_qubits)) measure_schedule.draw(backend=backend) # You can use `has` to see if an operation is defined. Ex: Does qubit 3 have an x gate defined? calibrations.has('x', 3) # Some circuit operations take parameters. U1 takes a rotation angle: calibrations.get('u1', 0, P0=3.1415) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/farhad-abdi/InSilicoQ
farhad-abdi
""" Quantum Data Encoding Functions: Basis Encoding, Amplitude Encoding, Angle Encoding """ from qiskit import QuantumCircuit from sklearn.preprocessing import normalize #import normalization function from qiskit.circuit.library import ZFeatureMap import numpy as np import math def angle_encoding(num_qubit, data): ''' Args: num_qubit : number of feature space dimesnion data : 1D array real data to be encoded Return: Quantum Data Circuit Object ''' data = normalize(data) feature_map = ZFeatureMap(feature_dimension= num_qubit, reps = 1 ) data_circ = feature_map.assign_parameters(data[0]/2) return data_circ def amplitude_encoding(data): ''' Args: data: 1D numpy array Return: Quantum Circ ''' cof = np.sum(np.power(data,2)) state = (1/np.sqrt(cof)) * data num_qubit = int(math.log2(len(data))) #how many time decopose trail and error!? decompose_time = len(data) circ = QuantumCircuit(num_qubit) circ.prepare_state(state, list(np.arange(num_qubit))) circ = circ.decompose(reps = decompose_time) return circ
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can show the phase of each state and use # degrees instead of radians from qiskit.quantum_info import DensityMatrix import numpy as np from qiskit import QuantumCircuit from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) qc.z(1) matrix = DensityMatrix(qc) plot_state_qsphere(matrix, show_state_phases = True, use_degrees = True)
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
''' Quantum Phase Estimation By Abdulah Amer T gate leaves |0> state alone and adds a phase of e^pi/4 to |1> state. Quantum Phase Estimation measures theta where T|1> = e^2ipitheta|1> First n-1 qubits are used for the protocol and get measured the nth qubit is put into the eigenstate of the operator whose phase we are measuring this is important ''' from qiskit import * import numpy as np from math import * from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt from fractions import Fraction S_simulator=Aer.backends(name='statevector_simulator')[0] M_simulator=Aer.backends(name='qasm_simulator')[0] # # a circuit with 4 qubits and 3 classical bits # # n=4 #number of qubits # m=3 #number of classical bits # # # a circuit with n qubits and m classical # qc=QuantumCircuit(n,m) # # qc.x(3) # # for qubit in range(3): # qc.h(qubit) # # #Now estimate phase for T gate with phase of pi/4 # # apply the T gate a bunch of times # # reps=1 # for counting_qubit in range(3): # for i in range(reps): # #applies T gate using the counting qubits as control # #qubits and the last qubit as the target qubit. # # # qc.cu1(pi/4, counting_qubit, 3) # # reps *=2 #doubles the number of T gates to each adjacent qubit # # # qc.draw(output='mpl') # # # #Do the inverse qft to find the state # def qft_inverse(qc,n): for qubit in range(n//2): #floor division for odd number of qubits qc.swap(qubit, n-qubit-1) #swaps the current qubit with n-qubit-1 for j in range(n): for m in range(j): qc.cu1(-pi/float(2**(j-m)),m,j) qc.h(j) # # # qc.barrier() # # qft_inverse(qc,3) # # qc.barrier() # # for n in range(3): # qc.measure(n,n) # # # #qc.draw(output='mpl') # #lol # # # results=execute(qc,backend=M_simulator, shots=4096).result() # histogram=results.get_counts() # # plot_histogram(histogram) # After measurement we divide the decimal equivalent by 2^n # 1/2^3 =1/8 , theta =1/8, therefore e^2ipitheta = e^ipi/4 #Which is the phase added by the T gate. #This was a pretty trivial result since we perfectly get #one highest probability #make functions to generalize even better # def prepQPE(qc, n,m): #prepares the circuit # for qubit in range(m): # qc.h(qubit) # # qc.x(m) # # # def CU(theta, qc, n,m): #performs controlled unitary operations # # prepQPE(qc,n,m) # # angle=theta # reps=1 # for counting_qubit in range(m): # for i in range(reps): # qc.cu1(angle, counting_qubit,5) # reps*=2 # #Let us also Automate more of the process so we can scale these things #To learn even more from them ''' Note we are making circuits to measure known thetas But we will try to build up to design a circuit to do Arbitrary Phase Estimation ''' #Makes an isntance of a quantum circuit that runs the QPE protocol def makeQPE(theta, n): #m=n-1 m=n-1 qc=QuantumCircuit(n,m) #Prep for qubit in range(m): qc.h(qubit) qc.x(m) #CU1 gates reps=1 for counting_qubit in range(m): for i in range(reps): qc.cu1(theta, counting_qubit, m) reps*=2 qc.barrier() qft_inverse(qc,m) qc.barrier() for n in range(m): qc.measure(n,n) return qc #gets out results and aquires the one with the most hits def get_results(q,n): m=n-1 results=execute(q, backend=M_simulator).result() histo=results.get_counts() higher=0 hits=histo.values() for i in hits: if i>higher: higher=i newhisto=dict([(value,key) for key, value in histo.items()]) answer=int(newhisto[higher],2) check=(answer/(2**m)) return check #simple finding error function def error(expected, actual): expected_minus_actual=abs(expected-actual) percent_error=expected_minus_actual/100 return percent_error #tie it all together def graph_qubits_error(piece_of_pi, qubits): #set up angle=pi*piece_of_pi expected=(piece_of_pi/2) qubits=[] results=[] errors=[] n=2 while n<=qubits: #make circuit and measure q=makeQPE(angle,n) actual=get_results(q,n) #our error err=error(expected, actual) #Dont forget how to graph qubits.append(n) results.append(actual) errors.append(err) n+=1 #Plotting########## # plt.figure(1) # plt.title('Value vs qubits used') # plt.plot(qubits,results, color='green', label='Experimental Result') # plt.hlines(expected,2,16, color='blue', linestyles='dashed', label=' Expected Value') # plt.xlabel('Number of Qubits') # plt.ylabel('Result of Measurement') # # # plt.figure(2) # plt.title('Error vs qubits used') # plt.plot(qubits, errors) # plt.xlabel('Number of Qubits') # plt.ylabel('Percent Error') # plt.show() piece_of_pi=1/2 qubits=8 #graph_qubits_error(piece_of_pi,qubits) def error_per_slice(piece_of_pi, qubits): angle=pi*piece_of_pi expected=(piece_of_pi/2) q=makeQPE(angle,qubits) actual=get_results(q,qubits) err=error(expected, actual) return err def yeet(): slices=[] list_of_errors=[] qubits=5 i=1 while i<=16: piece_of_pi=1/i slices.append(piece_of_pi) list_of_errors.append(error_per_slice(piece_of_pi, qubits)) i+=1 title= ('Error for different slices of pi using '+ str(qubits)+ ' qubits') plt.title(title) plt.plot(slices,list_of_errors, color='green') #plt.hlines(expected,2,16, color='blue', linestyles='dashed', label=' Expected Value') plt.xlabel('Slices') plt.ylabel('Error in measurement') #plt.show() return list_of_errors def get_slices(): slices=[] i=1 while i<=16: piece_of_pi=1/i slices.append(piece_of_pi) i+=1 return slices ''' some stuff to look at the fractions ''' def frac_stuff(slices): integers=[] for i in range(len(slices)): two_to_the_n=2**(qubits-1) it_theta=slices[i] integers.append(two_to_the_n*it_theta) fracslices=[] for i in range(len(slices)+1): piece='1/' + str(i) fracslices.append(piece) #gets rid of the 1/0 at the front of the list fracslices.pop(0) #inserts a 1 instead of 1/1 in our list fracslices.insert(0,1) #gets ride of 1/1 fracslices.pop(1) ''' Make a Table! ''' Dabois=yeet() header=['2^n*', 'Slice'] head1='2^n*'+ 'Theta' head2='Slice' head3='Error amounts' col1=integers col2=fracslices col3=Dabois from tabulate import tabulate table=tabulate({head2: col2, head1: col1, head3:col3}, headers='keys', tablefmt='github') for i in range(len(col1)): print(col2[i], '&' , round(col1[i],5), '&', round(col3[i],5)) return table #print(table) from qiskit.visualization import plot_bloch_vector ''' The following code is execute in Jupyter notebooks file called QPE final It gives us images Rx and Ry respectively #Rx q=QuantumRegister(1, 'l') blocher=QuantumCircuit(q) blocher.ry(pi/2,0) bloch_job=execute(blocher, S_simulator).result() plot_bloch_multivector(bloch_job.get_statevector(blocher), title='initial') #Ry blocher=QuantumCircuit(q) blocher.ry(pi/2,0) blocher.u1(pi/2,0) bloch_job=execute(blocher, S_simulator).result() plot_bloch_multivector(bloch_job.get_statevector(blocher), title='final') ''' piece_of_pi=1/4 qubits=3 q=makeQPE(piece_of_pi,qubits) #q.draw(output='mpl').savefig('The Circuit is Here.png') print(frac_stuff(get_slices()))
https://github.com/Chibikuri/qwopt
Chibikuri
import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.converters import circuit_to_dag, dag_to_circuit class Converter: ''' Converting quantum circuit to dag and extract information used for optimizations ''' def __init__(self): pass def converter(self, qc): dag = circuit_to_dag(qc) return dag def reverser(self, dag): circuit = dag_to_circuit(dag) return circuit if __name__ == '__main__': q = QuantumRegister(4) qc = QuantumCircuit(q) dag = Converter().converter(qc) dag.draw()
https://github.com/Advanced-Research-Centre/QPULBA
Advanced-Research-Centre
from qiskit import QuantumCircuit import numpy as np import random from qiskit import Aer, execute circ = QuantumCircuit(4) simulator = Aer.get_backend('statevector_simulator') def display(circ): sim_res = execute(circ, simulator).result() statevector = sim_res.get_statevector(circ) print("============ State Vector ============") for i in statevector: print(i) print("============..............============") # circ.initialize([1, 1, 0, 0] / np.sqrt(2), [0, 1]) display(circ) # initialize a1 = np.pi * random.random() circ.ry(a1,0) a2 = np.pi * random.random() circ.ry(a2,1) a3 = np.pi * random.random() circ.ry(a3,2) display(circ)
https://github.com/CodeJP97/QHT-2022-WoQ
CodeJP97
import networkx as nx from qiskit import QuantumCircuit, Aer from qiskit.circuit import Parameter import numpy as np import matplotlib.pyplot as plt from IPython.display import Image Image('./max_cut1.png') Image('./max_cut2.png') Image('./mac_cut3.png') G = nx.Graph() G.add_nodes_from([0, 1, 2, 3]) G.add_edges_from([(0, 1), (1, 2),(2, 3), (3, 0)]) pos=nx.spring_layout(G,seed = 1) nx.draw(G, with_labels=True, alpha=0.8, node_size=500, pos = pos) qaoa_circuit = QuantumCircuit(len(G.nodes())) qc = QuantumCircuit (2) gamma = Parameter ('gamma') qc.rzz(2*gamma, 0, 1) qc.decompose().draw() def initial_state(circuit): for i in range(circuit.num_qubits): circuit.h(i) return circuit qaoa_circuit = initial_state(qaoa_circuit) qaoa_circuit.draw() def problem_unitary(graph,circuit,gamma): for edge in list(G.edges()): circuit.rzz(2*gamma,edge[0],edge[1]) return circuit qaoa_circuit.barrier() qaoa_circuit = problem_unitary(G, qaoa_circuit, gamma) qaoa_circuit.decompose().draw() beta = Parameter('beta') def mix_unitary(circuit,beta): for i in range(circuit.num_qubits): circuit.rx(2*beta,i) return circuit qaoa_circuit.barrier() qaoa_circuit = mix_unitary(qaoa_circuit, beta) qaoa_circuit.draw() def create_qaoa_circuit(graph, theta): p = len(theta)//2 gamma = theta[p:] beta = theta[:p] qaoa_p = QuantumCircuit(len(graph.nodes())) qaoa_p = initial_state(qaoa_p) for i in range(p): qaoa_p = problem_unitary(graph, qaoa_p, gamma[i]) qaoa_p = mix_unitary(qaoa_p, beta[i]) qaoa_p.measure_all() return qaoa_p def get_cost(graph, state): cost = 0 for i,j in graph.edges(): if state[i] != state[j]: cost -= 1 return cost def expectation_value(graph, counts): avg = 0 sum_count = 0 for state, count in counts.items(): cost = get_cost(graph, state) avg += cost*count sum_count += count return avg/sum_count def run_qpu(graph, shots=512): backend = Aer.get_backend('aer_simulator') backend.shots = shots def run_circuit(theta): qc = create_qaoa_circuit(graph, theta) counts = backend.run(qc, seed_simulator = 5, nshots= shots).result().get_counts() return expectation_value(graph,counts) return run_circuit from scipy.optimize import minimize p=1 theta = [1.0 for i in range(2*p)] exp_value = run_qpu(G) res = minimize(exp_value, theta , method = 'COBYLA') res from qiskit.visualization import plot_histogram backend = Aer.get_backend('aer_simulator') backend.shots = 512 qc_res = create_qaoa_circuit(G, res.x) counts = backend.run(qc_res, seed_simulator = 5).result().get_counts() plot_histogram(counts)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # 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=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # 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. """Test the Solovay Kitaev transpilation pass.""" import unittest import math import numpy as np import scipy from ddt import ddt, data from qiskit.test import QiskitTestCase from qiskit import transpile from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import TGate, TdgGate, HGate, SGate, SdgGate, IGate, QFT from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info import Operator from qiskit.synthesis.discrete_basis.generate_basis_approximations import ( generate_basic_approximations, ) from qiskit.synthesis.discrete_basis.commutator_decompose import commutator_decompose from qiskit.synthesis.discrete_basis.gate_sequence import GateSequence from qiskit.transpiler import PassManager from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import UnitarySynthesis, Collect1qRuns, ConsolidateBlocks from qiskit.transpiler.passes.synthesis import SolovayKitaev, SolovayKitaevSynthesis def _trace_distance(circuit1, circuit2): """Return the trace distance of the two input circuits.""" op1, op2 = Operator(circuit1), Operator(circuit2) return 0.5 * np.trace(scipy.linalg.sqrtm(np.conj(op1 - op2).T.dot(op1 - op2))).real def _generate_x_rotation(angle: float) -> np.ndarray: return np.array( [[1, 0, 0], [0, math.cos(angle), -math.sin(angle)], [0, math.sin(angle), math.cos(angle)]] ) def _generate_y_rotation(angle: float) -> np.ndarray: return np.array( [[math.cos(angle), 0, math.sin(angle)], [0, 1, 0], [-math.sin(angle), 0, math.cos(angle)]] ) def _generate_z_rotation(angle: float) -> np.ndarray: return np.array( [[math.cos(angle), -math.sin(angle), 0], [math.sin(angle), math.cos(angle), 0], [0, 0, 1]] ) def is_so3_matrix(array: np.ndarray) -> bool: """Check if the input array is a SO(3) matrix.""" if array.shape != (3, 3): return False if abs(np.linalg.det(array) - 1.0) > 1e-10: return False if False in np.isreal(array): return False return True @ddt class TestSolovayKitaev(QiskitTestCase): """Test the Solovay Kitaev algorithm and transformation pass.""" def setUp(self): super().setUp() self.basic_approx = generate_basic_approximations([HGate(), TGate(), TdgGate()], 3) def test_unitary_synthesis(self): """Test the unitary synthesis transpiler pass with Solovay-Kitaev.""" circuit = QuantumCircuit(2) circuit.rx(0.8, 0) circuit.cx(0, 1) circuit.x(1) _1q = Collect1qRuns() _cons = ConsolidateBlocks() _synth = UnitarySynthesis(["h", "s"], method="sk") passes = PassManager([_1q, _cons, _synth]) compiled = passes.run(circuit) diff = np.linalg.norm(Operator(compiled) - Operator(circuit)) self.assertLess(diff, 1) self.assertEqual(set(compiled.count_ops().keys()), {"h", "s", "cx"}) def test_plugin(self): """Test calling the plugin directly.""" circuit = QuantumCircuit(1) circuit.rx(0.8, 0) unitary = Operator(circuit).data plugin = SolovayKitaevSynthesis() out = plugin.run(unitary, basis_gates=["h", "s"]) reference = QuantumCircuit(1, global_phase=3 * np.pi / 4) reference.h(0) reference.s(0) reference.h(0) self.assertEqual(dag_to_circuit(out), reference) def test_generating_default_approximation(self): """Test the approximation set is generated by default.""" skd = SolovayKitaev() circuit = QuantumCircuit(1) dummy = skd(circuit) self.assertIsNotNone(skd._sk.basic_approximations) def test_i_returns_empty_circuit(self): """Test that ``SolovayKitaev`` returns an empty circuit when it approximates the I-gate.""" circuit = QuantumCircuit(1) circuit.i(0) skd = SolovayKitaev(3, self.basic_approx) decomposed_circuit = skd(circuit) self.assertEqual(QuantumCircuit(1), decomposed_circuit) def test_exact_decomposition_acts_trivially(self): """Test that the a circuit that can be represented exactly is represented exactly.""" circuit = QuantumCircuit(1) circuit.t(0) circuit.h(0) circuit.tdg(0) synth = SolovayKitaev(3, self.basic_approx) dag = circuit_to_dag(circuit) decomposed_dag = synth.run(dag) decomposed_circuit = dag_to_circuit(decomposed_dag) self.assertEqual(circuit, decomposed_circuit) def test_fails_with_no_to_matrix(self): """Test failer if gate does not have to_matrix.""" circuit = QuantumCircuit(1) circuit.initialize("0") synth = SolovayKitaev(3, self.basic_approx) dag = circuit_to_dag(circuit) with self.assertRaises(TranspilerError) as cm: _ = synth.run(dag) self.assertEqual( "SolovayKitaev does not support gate without to_matrix method: initialize", cm.exception.message, ) def test_str_basis_gates(self): """Test specifying the basis gates by string works.""" circuit = QuantumCircuit(1) circuit.rx(0.8, 0) basic_approx = generate_basic_approximations(["h", "t", "s"], 3) synth = SolovayKitaev(2, basic_approx) dag = circuit_to_dag(circuit) discretized = dag_to_circuit(synth.run(dag)) reference = QuantumCircuit(1, global_phase=7 * np.pi / 8) reference.h(0) reference.t(0) reference.h(0) self.assertEqual(discretized, reference) def test_approximation_on_qft(self): """Test the Solovay-Kitaev decomposition on the QFT circuit.""" qft = QFT(3) transpiled = transpile(qft, basis_gates=["u", "cx"], optimization_level=1) skd = SolovayKitaev(1) with self.subTest("1 recursion"): discretized = skd(transpiled) self.assertLess(_trace_distance(transpiled, discretized), 15) skd.recursion_degree = 2 with self.subTest("2 recursions"): discretized = skd(transpiled) self.assertLess(_trace_distance(transpiled, discretized), 7) def test_u_gates_work(self): """Test SK works on Qiskit's UGate. Regression test of Qiskit/qiskit-terra#9437. """ circuit = QuantumCircuit(1) circuit.u(np.pi / 2, -np.pi, -np.pi, 0) circuit.u(np.pi / 2, np.pi / 2, -np.pi, 0) circuit.u(-np.pi / 4, 0, -np.pi / 2, 0) circuit.u(np.pi / 4, -np.pi / 16, 0, 0) circuit.u(0, 0, np.pi / 16, 0) circuit.u(0, np.pi / 4, np.pi / 4, 0) circuit.u(np.pi / 2, 0, -15 * np.pi / 16, 0) circuit.p(-np.pi / 4, 0) circuit.p(np.pi / 4, 0) circuit.u(np.pi / 2, 0, -3 * np.pi / 4, 0) circuit.u(0, 0, -np.pi / 16, 0) circuit.u(np.pi / 2, 0, 15 * np.pi / 16, 0) depth = 4 basis_gates = ["h", "t", "tdg", "s", "z"] gate_approx_library = generate_basic_approximations(basis_gates=basis_gates, depth=depth) skd = SolovayKitaev(recursion_degree=2, basic_approximations=gate_approx_library) discretized = skd(circuit) included_gates = set(discretized.count_ops().keys()) self.assertEqual(set(basis_gates), included_gates) @ddt class TestGateSequence(QiskitTestCase): """Test the ``GateSequence`` class.""" def test_append(self): """Test append.""" seq = GateSequence([IGate()]) seq.append(HGate()) ref = GateSequence([IGate(), HGate()]) self.assertEqual(seq, ref) def test_eq(self): """Test equality.""" base = GateSequence([HGate(), HGate()]) seq1 = GateSequence([HGate(), HGate()]) seq2 = GateSequence([IGate()]) seq3 = GateSequence([HGate(), HGate()]) seq3.global_phase = 0.12 seq4 = GateSequence([IGate(), HGate()]) with self.subTest("equal"): self.assertEqual(base, seq1) with self.subTest("same product, but different repr (-> false)"): self.assertNotEqual(base, seq2) with self.subTest("differing global phase (-> false)"): self.assertNotEqual(base, seq3) with self.subTest("same num gates, but different gates (-> false)"): self.assertNotEqual(base, seq4) def test_to_circuit(self): """Test converting a gate sequence to a circuit.""" seq = GateSequence([HGate(), HGate(), TGate(), SGate(), SdgGate()]) ref = QuantumCircuit(1) ref.h(0) ref.h(0) ref.t(0) ref.s(0) ref.sdg(0) # a GateSequence is SU(2), so add the right phase z = 1 / np.sqrt(np.linalg.det(Operator(ref))) ref.global_phase = np.arctan2(np.imag(z), np.real(z)) self.assertEqual(seq.to_circuit(), ref) def test_adjoint(self): """Test adjoint.""" seq = GateSequence([TGate(), SGate(), HGate(), IGate()]) inv = GateSequence([IGate(), HGate(), SdgGate(), TdgGate()]) self.assertEqual(seq.adjoint(), inv) def test_copy(self): """Test copy.""" seq = GateSequence([IGate()]) copied = seq.copy() seq.gates.append(HGate()) self.assertEqual(len(seq.gates), 2) self.assertEqual(len(copied.gates), 1) @data(0, 1, 10) def test_len(self, n): """Test __len__.""" seq = GateSequence([IGate()] * n) self.assertEqual(len(seq), n) def test_getitem(self): """Test __getitem__.""" seq = GateSequence([IGate(), HGate(), IGate()]) self.assertEqual(seq[0], IGate()) self.assertEqual(seq[1], HGate()) self.assertEqual(seq[2], IGate()) self.assertEqual(seq[-2], HGate()) def test_from_su2_matrix(self): """Test from_matrix with an SU2 matrix.""" matrix = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2) matrix /= np.sqrt(np.linalg.det(matrix)) seq = GateSequence.from_matrix(matrix) ref = GateSequence([HGate()]) self.assertEqual(seq.gates, []) self.assertTrue(np.allclose(seq.product, ref.product)) self.assertEqual(seq.global_phase, 0) def test_from_so3_matrix(self): """Test from_matrix with an SO3 matrix.""" matrix = np.array([[0, 0, -1], [0, -1, 0], [-1, 0, 0]]) seq = GateSequence.from_matrix(matrix) ref = GateSequence([HGate()]) self.assertEqual(seq.gates, []) self.assertTrue(np.allclose(seq.product, ref.product)) self.assertEqual(seq.global_phase, 0) def test_from_invalid_matrix(self): """Test from_matrix with invalid matrices.""" with self.subTest("2x2 but not SU2"): matrix = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2) with self.assertRaises(ValueError): _ = GateSequence.from_matrix(matrix) with self.subTest("not 2x2 or 3x3"): with self.assertRaises(ValueError): _ = GateSequence.from_matrix(np.array([[1]])) def test_dot(self): """Test dot.""" seq1 = GateSequence([HGate()]) seq2 = GateSequence([TGate(), SGate()]) composed = seq1.dot(seq2) ref = GateSequence([TGate(), SGate(), HGate()]) # check the product matches self.assertTrue(np.allclose(ref.product, composed.product)) # check the circuit & phases are equivalent self.assertTrue(Operator(ref.to_circuit()).equiv(composed.to_circuit())) @ddt class TestSolovayKitaevUtils(QiskitTestCase): """Test the public functions in the Solovay Kitaev utils.""" @data( _generate_x_rotation(0.1), _generate_y_rotation(0.2), _generate_z_rotation(0.3), np.dot(_generate_z_rotation(0.5), _generate_y_rotation(0.4)), np.dot(_generate_y_rotation(0.5), _generate_x_rotation(0.4)), ) def test_commutator_decompose_return_type(self, u_so3: np.ndarray): """Test that ``commutator_decompose`` returns two SO(3) gate sequences.""" v, w = commutator_decompose(u_so3) self.assertTrue(is_so3_matrix(v.product)) self.assertTrue(is_so3_matrix(w.product)) self.assertIsInstance(v, GateSequence) self.assertIsInstance(w, GateSequence) @data( _generate_x_rotation(0.1), _generate_y_rotation(0.2), _generate_z_rotation(0.3), np.dot(_generate_z_rotation(0.5), _generate_y_rotation(0.4)), np.dot(_generate_y_rotation(0.5), _generate_x_rotation(0.4)), ) def test_commutator_decompose_decomposes_correctly(self, u_so3): """Test that ``commutator_decompose`` exactly decomposes the input.""" v, w = commutator_decompose(u_so3) v_so3 = v.product w_so3 = w.product actual_commutator = np.dot(v_so3, np.dot(w_so3, np.dot(np.conj(v_so3).T, np.conj(w_so3).T))) self.assertTrue(np.allclose(actual_commutator, u_so3)) def test_generate_basis_approximation_gates(self): """Test the basis approximation generation works for all supported gates. Regression test of Qiskit/qiskit-terra#9585. """ basis = ["i", "x", "y", "z", "h", "t", "tdg", "s", "sdg"] approx = generate_basic_approximations(basis, depth=2) # This mainly checks that there are no errors in the generation (like # in computing the inverse as described in #9585), so a simple check is enough. self.assertGreater(len(approx), len(basis)) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_qsphere(state)
https://github.com/drnickallgood/simonqiskit
drnickallgood
from pprint import pprint import numpy as np import argparse from collections import defaultdict from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute from qiskit.visualization import plot_histogram from sympy import Matrix, mod_inverse from qiskit import IBMQ from qiskit.tools.monitor import job_monitor from qiskit.providers.ibmq import least_busy #IBMQ.save_account('<your acct number>') class Simons(object): def __init__(self, n, f): self._qr = QuantumRegister(2*n) self._cr = ClassicalRegister(n) self._oracle = self._create_oracle(f) def _create_oracle(self, f): n = len(list(f.keys())[0]) U = np.zeros(shape=(2 ** (2 * n), 2 ** (2 * n))) for a in range(2 ** n): ab = np.binary_repr(a, n) for k, v in f.items(): U[int(ab + k, 2), int(xor(ab, v) + k, 2)] = 1 return U def _create_circuit(self, oracle): circuit = QuantumCircuit(self._qr, self._cr) circuit.h(self._qr[:len(self._cr)]) circuit.barrier() circuit.unitary(oracle, self._qr, label='oracle') circuit.barrier() circuit.h(self._qr[:len(self._cr)]) circuit.measure(self._qr[:len(self._cr)], self._cr) return circuit def _solve(self, counts): # reverse inputs, remove all zero inputs, and sort counts = [(k[::-1], v) for k, v in counts.items() if not all([x == '0' for x in k])] counts.sort(key=lambda x: x[1], reverse=True) # construct sympy matrix matrix = Matrix([[int(i) for i in k] for k, _ in counts]) # gaussian elimination mod 2 matrix = matrix.rref(iszerofunc=lambda x: x % 2 == 0) matrix = matrix[0].applyfunc(lambda x: mod(x, 2)) # extract string n_rows, _ = matrix.shape s = [0] * len(self._cr) for r in range(n_rows): yi = [i for i, v in enumerate(list(matrix[r, :])) if v == 1] if len(yi) == 2: s[yi[0]] = '1' s[yi[1]] = '1' return s[::-1] def run(self, shots=1024, provider=None): circuit = self._create_circuit(self._oracle) if provider is None: # run the program on a QVM simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=shots) else: backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= len(self._qr) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) job = execute(circuit, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval=2) try: results = job.result() except: raise Exception(job.error_message()) counts = results.get_counts() print('Generated circuit: ') print(circuit.draw()) print('Circuit output:') print(counts) print("Time taken:", results.time_taken) return self._solve(counts) def mod(x, modulus): numer, denom = x.as_numer_denom() return numer * mod_inverse(denom, modulus) % modulus def xor(x, y): assert len(x) == len(y) n = len(x) return format(int(x, 2) ^ int(y, 2), f'0{n}b') def one_to_one_mapping(s): n = len(s) form_string = "{0:0" + str(n) + "b}" bit_map_dct = {} for idx in range(2 ** n): bit_string = np.binary_repr(idx, n) bit_map_dct[bit_string] = xor(bit_string, s) return bit_map_dct def two_to_one_mapping(s): mapping = one_to_one_mapping(s) n = len(mapping.keys()) // 2 new_range = np.random.choice(list(sorted(mapping.keys())), replace=False, size=n).tolist() mapping_pairs = sorted([(k, v) for k, v in mapping.items()], key=lambda x: x[0]) new_mapping = {} # f(x) = f(x xor s) for i in range(n): x = mapping_pairs[i] y = new_range[i] new_mapping[x[0]] = y new_mapping[x[1]] = y return new_mapping def main(): parser = argparse.ArgumentParser() parser.add_argument('string', help='Secret string s of length n') parser.add_argument('ftype', type=int, help='1 for one-to-one or 2 for two-to-one') parser.add_argument('--ibmq', action='store_true', help='Run on IBMQ') args = parser.parse_args() if args.ibmq: try: provider = IBMQ.load_account() except: raise Exception("Could not find saved IBMQ account.") assert all([x == '1' or x == '0' for x in args.string]), 'string argument must be a binary string.' n = len(args.string) if args.ftype == 1: mapping = one_to_one_mapping(args.string) elif args.ftype == 2: mapping = two_to_one_mapping(args.string) else: raise ValueError('Invalid function type.') print('Generated mapping:') pprint(mapping) simons = Simons(n, mapping) result = simons.run(provider=provider if args.ibmq else None) result = ''.join([str(x) for x in result]) # Check if result satisfies two-to-one function constraint success = np.array([mapping[x] == mapping[xor(x, result)] for x in mapping.keys()]).all() and not all([x == '0' for x in result]) if success: print(f'Oracle function is two-to-one with s = {result}.') else: print('Oracle is one-to-one.') if __name__ == '__main__': main()
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.problems import BaseProblem dummy_hamiltonian = None base_problem = BaseProblem(dummy_hamiltonian) print(base_problem.properties) from qiskit_nature.second_q.properties import AngularMomentum print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties) print("Adding AngularMomentum to problem.properties...") base_problem.properties.add(AngularMomentum(2)) print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties) print("Discarding AngularMomentum from problem.properties...") base_problem.properties.discard(AngularMomentum) print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties) from qiskit_nature.second_q.drivers import PySCFDriver es_problem = PySCFDriver().run() print(es_problem.properties.particle_number) print(es_problem.properties.angular_momentum) print(es_problem.properties.magnetization) print(es_problem.properties.electronic_dipole_moment) print(es_problem.properties.electronic_density) from qiskit_nature.second_q.properties import ElectronicDensity density = ElectronicDensity.from_orbital_occupation( es_problem.orbital_occupations, es_problem.orbital_occupations_b, ) es_problem.properties.electronic_density = density import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # 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. """Test the LayoutTransformation pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.transpiler import CouplingMap, Layout, Target from qiskit.circuit.library import CXGate from qiskit.transpiler.passes import LayoutTransformation class TestLayoutTransformation(QiskitTestCase): """ Tests the LayoutTransformation pass. """ def test_three_qubit(self): """Test if the permutation {0->2,1->0,2->1} is implemented correctly.""" v = QuantumRegister(3, "v") # virtual qubits coupling = CouplingMap([[0, 1], [1, 2]]) from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2}) to_layout = Layout({v[0]: 2, v[1]: 0, v[2]: 1}) ltpass = LayoutTransformation( coupling_map=coupling, from_layout=from_layout, to_layout=to_layout, seed=42 ) qc = QuantumCircuit(3) dag = circuit_to_dag(qc) output_dag = ltpass.run(dag) expected = QuantumCircuit(3) expected.swap(1, 0) expected.swap(1, 2) self.assertEqual(circuit_to_dag(expected), output_dag) def test_four_qubit(self): """Test if the permutation {0->3,1->0,2->1,3->2} is implemented correctly.""" v = QuantumRegister(4, "v") # virtual qubits coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2, v[3]: 3}) to_layout = Layout({v[0]: 3, v[1]: 0, v[2]: 1, v[3]: 2}) ltpass = LayoutTransformation( coupling_map=coupling, from_layout=from_layout, to_layout=to_layout, seed=42 ) qc = QuantumCircuit(4) # input (empty) physical circuit dag = circuit_to_dag(qc) output_dag = ltpass.run(dag) expected = QuantumCircuit(4) expected.swap(1, 0) expected.swap(1, 2) expected.swap(2, 3) self.assertEqual(circuit_to_dag(expected), output_dag) def test_four_qubit_with_target(self): """Test if the permutation {0->3,1->0,2->1,3->2} is implemented correctly.""" v = QuantumRegister(4, "v") # virtual qubits target = Target() target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None, (2, 3): None}) from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2, v[3]: 3}) to_layout = Layout({v[0]: 3, v[1]: 0, v[2]: 1, v[3]: 2}) ltpass = LayoutTransformation(target, from_layout=from_layout, to_layout=to_layout, seed=42) qc = QuantumCircuit(4) # input (empty) physical circuit dag = circuit_to_dag(qc) output_dag = ltpass.run(dag) expected = QuantumCircuit(4) expected.swap(1, 0) expected.swap(1, 2) expected.swap(2, 3) self.assertEqual(circuit_to_dag(expected), output_dag) @unittest.skip("rustworkx token_swapper produces correct, but sometimes random output") def test_full_connected_coupling_map(self): """Test if the permutation {0->3,1->0,2->1,3->2} in a fully connected map.""" # TODO: Remove skip when https://github.com/Qiskit/rustworkx/pull/897 is # merged and released. Should be rustworkx 0.13.1. v = QuantumRegister(4, "v") # virtual qubits from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2, v[3]: 3}) to_layout = Layout({v[0]: 3, v[1]: 0, v[2]: 1, v[3]: 2}) ltpass = LayoutTransformation( coupling_map=None, from_layout=from_layout, to_layout=to_layout, seed=42 ) qc = QuantumCircuit(4) # input (empty) physical circuit dag = circuit_to_dag(qc) output_dag = ltpass.run(dag) expected = QuantumCircuit(4) expected.swap(1, 0) expected.swap(2, 1) expected.swap(3, 2) self.assertEqual(circuit_to_dag(expected), output_dag) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization import QuadraticProgram problem = QuadraticProgram("sample") problem.binary_var("x") problem.binary_var("y") problem.maximize(linear={"x": 1, "y": -2}) print(problem.prettyprint()) from qiskit.algorithms import NumPyMinimumEigensolver from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = NumPyMinimumEigensolver() meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = NumPyMinimumEigensolver() meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) mes = QAOA(optimizer=COBYLA(), quantum_instance=qins) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer shots = 1000 mes = QAOA(sampler=Sampler(), optimizer=COBYLA()) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) mes = VQE(ansatz=RealAmplitudes(), optimizer=COBYLA(), quantum_instance=qins) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = SamplingVQE(sampler=Sampler(), ansatz=RealAmplitudes(), optimizer=COBYLA()) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Estimator from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = VQE(estimator=Estimator(), ansatz=RealAmplitudes(), optimizer=COBYLA()) try: meo = MinimumEigenOptimizer(min_eigen_solver=mes) except TypeError as ex: print(ex) from qiskit import BasicAer from qiskit.algorithms import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) qaoa = QAOA(optimizer=COBYLA(), quantum_instance=qins) optimizer = WarmStartQAOAOptimizer( pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25 ) result = optimizer.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer qaoa = QAOA(sampler=Sampler(), optimizer=COBYLA()) optimizer = WarmStartQAOAOptimizer( pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25 ) result = optimizer.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import GroverOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, quantum_instance=qins) result = optimizer.solve(problem) print(result) from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import GroverOptimizer optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, sampler=Sampler()) result = optimizer.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit.primitives import Sampler from qiskit_optimization.algorithms import GroverOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) try: optimizer = GroverOptimizer( num_value_qubits=3, num_iterations=3, quantum_instance=qins, sampler=Sampler() ) # raises an error because both quantum_instance and sampler are set. except ValueError as ex: print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
from math import pi, sin, cos theta1 = pi/4 theta2 = pi/6 print(round(cos(theta1),3),-round(sin(theta1),3),0,0) print(round(sin(theta1),3),-round(cos(theta1),3),0,0) print(0,0,round(cos(theta2),3),-round(sin(theta2),3)) print(0,0,round(sin(theta2),3),-round(cos(theta2),3)) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, sin, cos # the angle of rotation theta1 = pi/23 theta2 = 2*pi/23 theta3 = 4*pi/23 precision = 3 print("a1 = theta3 => sin(a1) = ",round(sin(theta3),precision)) print("a2 = theta2+theta3 => sin(a2) = ",round(sin(theta2+theta3),precision)) print("a3 = theta1 => sin(a3) = ",round(sin(theta1),precision)) print("a4 = theta1+theta2 => sin(a4) = ",round(sin(theta1+theta2),precision)) print() qreg = QuantumRegister(3) creg = ClassicalRegister(3) circuit = QuantumCircuit(qreg,creg) # controlled rotation when the third qubit is |1> circuit.cu3(2*theta1,0,0,qreg[2],qreg[0]) # controlled rotation when the second qubit is |1> circuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # controlled rotation when the third qubit is |0> circuit.x(qreg[2]) circuit.cu3(2*theta3,0,0,qreg[2],qreg[0]) circuit.x(qreg[2]) # read the corresponding unitary matrix job = execute(circuit,Aer.get_backend('unitary_simulator')) unitary_matrix=job.result().get_unitary(circuit,decimals=precision) for i in range(len(unitary_matrix)): s="" for j in range(len(unitary_matrix)): val = str(unitary_matrix[i][j].real) while(len(val)<precision+4): val = " "+val s = s + val print(s) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, sin, cos from random import randrange # the angle of rotation k1 = randrange(1,31) theta1 = k1*2*pi/31 k2 = randrange(1,31) theta2 = k2*2*pi/31 k3 = randrange(1,31) theta3 = k3*2*pi/31 max_percentange = 0 # for each stream of length from 1 to 31 for i in range(1,32): # initialize the circuit qreg = QuantumRegister(3) creg = ClassicalRegister(3) circuit = QuantumCircuit(qreg,creg) # Hadamard operators before reading the stream for m in range(3): circuit.h(qreg[m]) # read the stream of length i print("stream of length",i,"is being read") for j in range(i): # controlled rotation when the third qubit is |1> circuit.cu3(2*theta1,0,0,qreg[2],qreg[0]) # controlled rotation when the second qubit is |1> circuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # controlled rotation when the third qubit is |0> circuit.x(qreg[2]) circuit.cu3(2*theta3,0,0,qreg[2],qreg[0]) circuit.x(qreg[2]) # Hadamard operators after reading the stream for m in range(3): circuit.h(qreg[m]) # we measure after reading the whole stream circuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(circuit) print(counts) if '000' in counts.keys(): c = counts['000'] else: c = 0 print('000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange and i != 31: max_percentange = percentange print("the ration of 000 is ",percentange,"%") print() print("maximum percentage of observing unwanted '000' is",max_percentange) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi,sin # the angle of rotation k1 = randrange(1,61) theta1 = k1*2*pi/61 k2 = randrange(1,61) theta2 = k2*2*pi/61 k3 = randrange(1,61) theta3 = k3*2*pi/61 k4 = randrange(1,61) theta4 = k4*2*pi/61 max_percentange = 0 # for each stream of length of 1, 11, 21, 31, 41, 51, and 61 for i in [1,11,21,31,41,51,61]: #for i in range(1,62): # initialize the circuit qreg = QuantumRegister(4) creg = ClassicalRegister(4) circuit = QuantumCircuit(qreg,creg) # Hadamard operators before reading the stream for m in range(3): circuit.h(qreg[m]) # read the stream of length i print("stream of length",i,"is being read") for j in range(i): # the third qubit is in |0> # the second qubit is in |0> circuit.x(qreg[2]) circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta1,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) circuit.x(qreg[2]) # the third qubit is in |0> # the second qubit is in |1> circuit.x(qreg[2]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta2,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[2]) # the third qubit is in |1> # the second qubit is in |0> circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta3,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) # the third qubit is in |1> # the second qubit is in |1> circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta4,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) # Hadamard operators after reading the stream for m in range(3): circuit.h(qreg[m]) # we measure after reading the whole stream circuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(circuit) print(counts) if '0000' in counts.keys(): c = counts['0000'] else: c = 0 print('0000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange and i != 61: max_percentange = percentange print("the ration of 0000 is ",percentange,"%") print() print("maximum percentage of observing unwanted '0000' is",max_percentange)
https://github.com/Qiskit/feedback
Qiskit
%load_ext autoreload %autoreload 2 import numpy as np from qiskit import QuantumCircuit, BasicAer from qiskit.circuit.library import RealAmplitudes from qiskit.opflow import PauliSumOp observable = PauliSumOp.from_list( [ ("IIXZ", -1.052373245772859), ("IZXZ", 0.39793742484318045), ("ZIZZ", -0.39793742484318045), ("ZZXZ", -0.01128010425623538), ("XXZZ", 0.18093119978423156), ] ) U = RealAmplitudes(num_qubits=2, reps=2) bitsrings = [[0, 1], [1, 0]] schmidts = [1/np.sqrt(2**2), 1/np.sqrt(2**2)] print("Schmidts:", schmidts) print("Observable:") print(observable) print("U:") U.decompose().draw() from qiskit.evaluators import EntanglementForgingExpectationValue expval = EntanglementForgingExpectationValue(U, observable, bitstrings=bitsrings, schmidts=schmidts, backend=BasicAer.get_backend("qasm_simulator")) expectation = expval.evaluate([0, 1, 1, 2, 3, 5], shots=1000).value print("EF exp value: {}".format(expectation))
https://github.com/qBraid/qiskit-fall-fest-algiers
qBraid
! qbraid jobs enable qbraid_sdk !pip install qiskit from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector from numpy.random import randint import numpy as np import math qc=QuantumCircuit(2,1) qc.h(0) #Apply Hadamard Gate to the first qubit qc.cx(0,1) #Apply Control Unit Operation on the second qubit, in this case the control NOT gate (for the sake of simplicity qc.h(0) #Apply the Hadamard Gate again before output on the first qubit qc.measure(0,0) #Mesaure the output value of the first Qubit aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(qc, shots=1, memory=True) result = aer_sim.run(qobj).result() measured_bit = int(result.get_memory()[0]) measured_bit print(qc) #we draw the circuit print(measured_bit) def hadamard_test_real(): ##We copy the code above to create the circuit, the output is only the measured real value qc=QuantumCircuit(2,1) qc.h(0) qc.cx(0,1) qc.h(0) qc.measure(0,0) aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(qc, shots=1, memory=True) result = aer_sim.run(qobj).result() measured_bit = int(result.get_memory()[0]) return measured_bit print(hadamard_test_real()) def hadamard_test_imag(): ##We copy the code above to create the circuit, the output is only the measured Imaginary value qc=QuantumCircuit(2,1) qc.h(0) qc.p(-math.pi/2,0) qc.cx(0,1) qc.h(0) qc.measure(0,0) aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(qc, shots=1, memory=True) result = aer_sim.run(qobj).result() measured_bit = int(result.get_memory()[0]) return measured_bit print(hadamard_test_imag()) def roll_the_dice_twice(): k=0 a=0 b=0 while(k<6): k=k+1 a=hadamard_test_real()+a b=hadamard_test_imag()+b return a,b a,b=roll_the_dice_twice() print("Your Dice Rolled a: ",a," And Your Friend Rolled a: ",b) if (a<b): print("You WIN!") else: if(a==b): print("It's a TIE!") else: print("Your friend WINS!") from qbraid import get_devices get_devices() IBMQ.save_account('YOUR_IBMQ_KEY') from qbraid import device_wrapper, job_wrapper, get_jobs from qbraid.api import ibmq_least_busy_qpu, verify_config from qiskit import QuantumCircuit import numpy as np qiskit_circuit = QuantumCircuit(1, 1) qiskit_circuit.h(0) qiskit_circuit.ry(np.pi / 4, 0) qiskit_circuit.rz(np.pi / 2, 0) qiskit_circuit.measure(0, 0) qiskit_circuit.draw() shots=200 google_id = "google_cirq_dm_sim" qbraid_google_device = device_wrapper(google_id) aws_id = "aws_dm_sim" qbraid_aws_device = device_wrapper(aws_id) # Credential handled by qBraid Quantum Jobs qbraid_google_job = qbraid_google_device.run(qiskit_circuit, shots=shots) qbraid_aws_job = qbraid_aws_device.run(qiskit_circuit, shots=shots) get_jobs() jobs = [qbraid_google_job, qbraid_aws_job] google_result, aws_result = [job.result() for job in jobs] print(f"{qbraid_google_device.name} counts: {google_result.measurement_counts()}") print(f"{qbraid_aws_device.name} counts: {aws_result.measurement_counts()}") google_result.plot_counts() aws_result.plot_counts()
https://github.com/grossiM/Qiskit_workshop1019
grossiM
# initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.tools.visualization import plot_histogram # Creating registers # n qubits for querying the oracle and one qubit for storing the answer qr = QuantumRegister(2,name='qr') crsingle = ClassicalRegister(1) deutsch = QuantumCircuit(qr,crsingle) deutsch.x(qr[1]) deutsch.h(qr[1]) deutsch.draw(output='latex') deutsch.h(qr[0]) deutsch.draw(output='mpl') deutsch.cx(qr[0],qr[1]) deutsch.h(qr[0]) deutsch.measure(qr[0],crsingle[0]) deutsch.draw(output='mpl') # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(deutsch, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) # set the length of the $n$-bit string. n = 2 # set the oracle, b for balanced, c for constant oracle = "b" # if the oracle is balanced, set the hidden bitstring, b if oracle == "b": b = 3 # np.random.randint(1,2**n) uncomment for a random value # if the oracle is constant, set c = 0 or 1 randomly. if oracle == "c": c = np.random.randint(2) # Creating registers # n qubits for querying the oracle and one qubit for storing the answer qr = QuantumRegister(n+1) cr = ClassicalRegister(n) djCircuit = QuantumCircuit(qr, cr) barriers = True # Since all qubits are initialized to |0>, we need to flip the second register qubit to the the |1> state djCircuit.x(qr[n]) # Apply barrier if barriers: djCircuit.barrier() # Apply Hadamard gates to all qubits djCircuit.h(qr) # Apply barrier if barriers: djCircuit.barrier() # Query the oracle if oracle == "c": # if the oracle is constant, return c if c == 1: djCircuit.x(qr[n]) else: djCircuit.iden(qr[n]) else: # otherwise, the oracle is balanced and it returns the inner product of the input with b (non-zero bitstring) for i in range(n): if (b & (1 << i)): djCircuit.cx(qr[i], qr[n]) # Apply barrier if barriers: djCircuit.barrier() # Apply Hadamard gates to the first register after querying the oracle for i in range(n): djCircuit.h(qr[i]) # Measure the first register for i in range(n): djCircuit.measure(qr[i], cr[i]) djCircuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(djCircuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) # Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits #IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and not x.configuration().simulator and x.status().operational==True)) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor shots = 1024 job = execute(djCircuit, backend=backend, shots=shots) job_monitor(job, interval = 2) # Get the results of the computation results = job.result() answer = results.get_counts() plot_histogram(answer) N = 4 qrQFT = QuantumRegister(N,'qftr') QFT = QuantumCircuit(qrQFT) for i in range(N): QFT.h(qrQFT[i]) for k in range(i+1,N): l = k-i+1 QFT.cu1(2*math.pi/(2**l),qrQFT[k],qrQFT[i]) QFT.draw(output='mpl') import qiskit qiskit.__qiskit_version__
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import * from qiskit.compiler import * from qiskit.tools.jupyter import * from qiskit.visualization import * import numpy as np import qiskit.quantum_info as qi # Loading your IBM Q account(s) provider = IBMQ.load_account() #This cell is just for seeing what the U tilde matrix looks like a, b, c, d = np.cos(np.pi/8), np.sin(np.pi/8), -np.sin(np.pi/8), np.cos(np.pi/8) u_tilde = np.array([[a,c],[b,d]]).reshape(2,2) print(u_tilde) #This cell defines the controlled variant of the U tilde matrix qc_for_u = QuantumCircuit(1) qc_for_u.ry(np.pi/4, 0) qc_for_u.name = "U" controlled_u_tilde = qc_for_u.to_gate().control(2) qc1 = QuantumCircuit(3) qc1.x(0) qc1.x(1) qc1.toffoli(0,1,2)#Flipping the third bit if the first two are zero qc1.x(0) #Essentially 000 -> 001 qc1.x(1) qc1.x(0) qc1.toffoli(0,2,1)#Flipping the second bit if the first bit is zero and the third is one qc1.x(0) #Essentially 001 -> 011 qc1.append(controlled_u_tilde, [1, 2, 0]) qc1.x(0) qc1.toffoli(0,2,1)#Undoing the flip from before qc1.x(0) qc1.x(0) qc1.x(1) qc1.toffoli(0,1,2)#Undoing the flip from before qc1.x(0) qc1.x(1) qc1.draw('mpl') U_circ = qi.Operator(qc1).data print(U_circ) qc2 = QuantumCircuit(3) # Code for U qc2.x(0) qc2.x(1) qc2.toffoli(0,1,2)#Flipping the third bit if the first two are zero qc2.x(0) #Essentially 000 -> 001 qc2.x(1) qc2.x(0) qc2.toffoli(0,2,1)#Flipping the second bit if the first bit is zero and the third is one qc2.x(0) #Essentially 001 -> 011 qc2.append(controlled_u_tilde, [1, 2, 0]) qc2.x(0) qc2.toffoli(0,2,1)#Undoing the flip from before qc2.x(0) qc2.x(0) qc2.x(1) qc2.toffoli(0,1,2)#Undoing the flip from before qc2.x(0) qc2.x(1) # Code for V qc2.x(0) qc2.toffoli(0,1,2) # |010> -> |011> qc2.x(0) qc2.toffoli(1,2,0) # V-tilde is the same as Toffoli qc2.x(0) qc2.toffoli(0,1,2) # Reversing the flip qc2.x(0) qc2.draw('mpl') def without_global_phase(matrix: np.ndarray, atol: float = 1e-8) : phases1 = np.angle(matrix[abs(matrix) > atol].ravel(order='F')) if len(phases1) > 0: matrix = np.exp(-1j * phases1[0]) * matrix return matrix V_circ = without_global_phase(qi.Operator(qc2).data) print(V_circ) #Function just returns norm ignoring global phase between unitaries def norm(unitary_a: np.ndarray, unitary_b: np.ndarray) : return np.linalg.norm(without_global_phase(unitary_b)-without_global_phase(unitary_a), ord=2) #Make the Pauli Y gate qcy = QuantumCircuit(1) for i in range(6): qcy.t(0) qcy.h(0) for i in range(4): qcy.t(0) qcy.h(0) for i in range(2): qcy.t(0) Y_circ = qi.Operator(qcy).data Y = np.array([[0,-1j],[1j,0]]) print(norm(Y_circ,Y)) print("Final Circuit:") qcy.draw('mpl') uni_q = np.array([[-0.25+0.60355339j, 0.60355339+0.45710678j], [0.60355339-0.45710678j, 0.25+0.60355339j]]).reshape(2,2) while True: qc3 = QuantumCircuit(1) for i in range(5): for j in range(np.random.randint(8)): qc3.t(0) qc3.h(0) for j in range(np.random.randint(8)): qc3.t(0) uni_q_circ = qi.Operator(qc3).data if norm(uni_q_circ,uni_q) < 1e-8: break print("Final Error: ", norm(uni_q_circ,uni_q)) print("Final Circuit:") qc3.draw('mpl') #Defining the gate as controlled_irx from qiskit.extensions import * pi_alpha = np.arccos(0.6) qc_for_irx = QuantumCircuit(1) irx = np.array([[1j*np.cos(pi_alpha/2),np.sin(pi_alpha/2)],[np.sin(pi_alpha/2),1j*np.cos(pi_alpha/2)]]).reshape(2,2) g_irx = UnitaryGate(data=irx,label=None) controlled_irx = g_irx.control(2) def final_vector(qc): backend = Aer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() outputstate = result.get_statevector(qc, decimals=3) return outputstate n = 4 qcb = QuantumCircuit(n,n) qcb.x(0)#Ancilla qcb.x(1)#Ancilla You can use these two as control to use the controlled_irx gate count1 = 0 while abs(0.5 - (count1*pi_alpha/np.pi)%2) >= 1e-2 or count1 % 4 != 0: count1 += 1 count2 = 0 while abs(1.5 - (count2*pi_alpha/np.pi)%2) >= 1e-2 or count2 % 4 != 0: count2 += 1 count3 = 0 while abs(4.0 - (count3*pi_alpha/np.pi)%4) >= 1e-2 or count3 % 4 != 2: count3 += 1 for i in range(count1): # Rotation about x by pi/2 (count1 % 4 == 0) qcb.append(controlled_irx, [0, 1, 2]) qcb.cx(2, 3) for i in range(count2): # Rotation about x by -pi/2 (count2 % 4 == 0) qcb.append(controlled_irx, [0, 1, 2]) qcb.x(0) qcb.cx(3, 0) for i in range(count3): # Rotation about x by 0 (count3 % 4 == 2) qcb.append(controlled_irx, [0, 2, 3]) qcb.cx(3, 0) qcb.x(0) print("Executing circuit...") #Get state of qubit which should have the |+> state using the backend simulator i = 3 #Index for the qubit at |+> state qcb.h(i)#Puts the |+> state to |0> for i in range(4): qcb.measure(i, i) def run_circuit(qcb): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qcb, backend, shots = 2000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qcb) print(counts) plot_histogram(counts)
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 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. """Quickstart example on using the Sampler primitive. This example samples a 2-qubit Bell state. """ from qiskit import QuantumCircuit from qiskit_aqt_provider import AQTProvider from qiskit_aqt_provider.primitives import AQTSampler # Define a circuit circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) circuit.measure_all() # Select an execution backend provider = AQTProvider("ACCESS_TOKEN") backend = provider.get_backend("offline_simulator_no_noise") # Instantiate a sampler on the execution backend sampler = AQTSampler(backend) # Set the transpiler's optimization level sampler.set_transpile_options(optimization_level=3) # Sample the circuit on the execution backend result = sampler.run(circuit).result() quasi_dist = result.quasi_dists[0] print(quasi_dist)
https://github.com/kerenavnery/qmail
kerenavnery
from qiskit import * from channel_class import Channel n_master = 2 # two qubits, the one on alice side n_channel = 2 n_slave = 1 # two quantum channels and one qubit on bobs side slave_offset = n_master channel = Channel(slave_offset, 5000, remote_port = 5001) #create a Quantum circuit circ = QuantumCircuit(n_master + n_channel + n_slave) ## Master, Oracle circ.rx(0.234,0 + channel._offset) circ.rz(0.54,0 + channel._offset) circ.ry(0.94,0 + channel._offset) circ.rx(0.1,0 + channel._offset) ## Creating Entaglement now on Bobs side circ.h(1+channel._offset) circ.cx(1+channel._offset,4+channel._offset) ## Master, teleportation protocol circ.cx(0 + channel._offset, 1 + channel._offset) circ.h(0 + channel._offset) ## Write the result on the communication qubits, this should be done with classical communication at some point circ.cx(0 + channel._offset, 2 + channel._offset) circ.cx(1 + channel._offset, 3 + channel._offset) ## Alice sends here qubits to Bob channel.send(circ,[1]) ## TODO: remove ## The circuit how it looks on Alice side circ.draw()
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
#from qiskit_textbook.widgets import bv_widget #bv_widget(2, "11") # initialization # initialization ####################################################################################################################### qiskit_edit_1 from qiskit import QuantumCircuit, execute from qiskit import QuantumRegister, ClassicalRegister from qiskit.tools.monitor import job_monitor from qiskit import * import time import matplotlib.pyplot as plt import argparse import sys from concurrent.futures import ThreadPoolExecutor import resource from time import sleep ######################################################################################################################### import numpy as np # importing Qiskit #from qiskit import IBMQ, Aer #from qiskit.providers.ibmq import least_busy #from qiskit import QuantumCircuit, assemble, transpile # import basic plot tools from qiskit.visualization import plot_histogram n = 3 # number of qubits used to represent s s = '011' # the hidden binary string ## noise options options = { "plot": True, "thermal_factor": 0.99, "decoherence_factor": .99, "depolarization_factor": 0.99, "bell_depolarization_factor": 0.99, "decay_factor": 0.99, "rotation_error": {'rx':[.9, 0.], 'ry':[1., 0.], 'rz': [1., 0.]}, "tsp_model_error": [1., 0.], "plot": False } # We need a circuit with n qubits, plus one auxiliary qubit # Also need n classical bits to write the output to bv_circuit = QuantumCircuit(n+1, n) # put auxiliary in state |-> bv_circuit.h(n) bv_circuit.z(n) # Apply Hadamard gates before querying the oracle for i in range(n): bv_circuit.h(i) # Apply barrier bv_circuit.barrier() # Apply the inner-product oracle s = s[::-1] # reverse s to fit qiskit's qubit ordering for q in range(n): if s[q] == '0': bv_circuit.i(q) else: bv_circuit.cx(q, n) # Apply barrier bv_circuit.barrier() #Apply Hadamard gates after querying the oracle for i in range(n): bv_circuit.h(i) # Measurement for i in range(n): bv_circuit.measure(i, i, basis='Ensemble',add_param='Z') bv_circuit.draw() qc = QuantumCircuit(4,4) s = '101' string = '111' for i in range(3): if string[i] == '1': qc.x(i) qc.barrier() s = s[::-1] # reverse s to fit qiskit's qubit ordering for q in range(n): if s[q] == '0': qc.i(q) else: qc.cx(q, n) # Measurement for i in range(n): qc.measure(i, i, basis='Ensemble',add_param='Z') qc.draw() # use local simulator backend = qiskit.BasicAer.get_backend('dm_simulator') # without noise job = execute(qc, backend=backend, shots=1) job_result = job.result() #print(job_result['results'][0]['data']['densitymatrix']) job_result['results'][0]['data']['ensemble_probability'] # use local simulator backend = qiskit.BasicAer.get_backend('dm_simulator') # without noise job = execute(bv_circuit, backend=backend, shots=1) job_result = job.result() #print(job_result['results'][0]['data']['densitymatrix']) job_result['results'][0]['data']['ensemble_probability'] #with noise job1 = execute(bv_circuit, backend=backend, backend_options=options, shots=1) job_result1 = job1.result() #print(job_result1['results'][0]['data']['densitymatrix']) job_result1['results'][0]['data']['ensemble_probability'] no_noise=job_result['results'][0]['data']['ensemble_probability'] noisy=job_result1['results'][0]['data']['ensemble_probability'] labels = noisy.keys() without_noise = no_noise.values() with_noise = noisy.values() x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise') rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Probability') ax.set_title('Ensemble Probabilities with Noise') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show() # Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor shots = 1024 transpiled_bv_circuit = transpile(bv_circuit, backend) job = backend.run(transpiled_bv_circuit, shots=shots) job_monitor(job, interval=2) # Get the results from the computation results = job.result() answer = results.get_counts() plot_histogram(answer) from qiskit_textbook.widgets import bv_widget bv_widget(3, "011", hide_oracle=False) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/arnavdas88/QuGlassyIsing
arnavdas88
!pip install qiskit J = 4.0 B_x = 1.5 B_z = 1.5 import numpy as np from qiskit.providers.aer import AerSimulator, QasmSimulator from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.aqua.operators import * from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, NumPyEigensolver from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.visualization import plot_histogram Hamiltonian = J * (Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z) - B_z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ) ) - B_x * ( ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X )) ansatz = TwoLocal(num_qubits=36, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True) print(ansatz) backend = AerSimulator(method='matrix_product_state') quantum_instance = QuantumInstance(backend, shots = 8192, initial_layout = None, optimization_level = 3) optimizer = COBYLA(maxiter=10000, tol=0.000000001) vqe = VQE(Hamiltonian, ansatz, optimizer, include_custom = False) print('We are using:', quantum_instance.backend) vqe_result = vqe.run(quantum_instance) print(vqe['result']) plot_histogram(vqe_result['eigenstate']) import pickle filename = "2D_Ising_Model_CountsDIS3.pkl" a = {'vqe_result': vqe_result} #This saves the data with open(filename, 'wb') as handle: pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL) # This loads the data with open(filename, 'rb') as handle: b = pickle.load(handle)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/DylanLi272/QiskitFinalProject
DylanLi272
from qiskit import BasicAer, Aer, IBMQ from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.algorithms import VQE, ExactEigensolver, NumPyEigensolver from qiskit.aqua.components.initial_states import Zero from qiskit.aqua.components.optimizers import ADAM, AQGD, COBYLA, L_BFGS_B, SLSQP from qiskit.aqua.components.optimizers import SPSA, TNC, POWELL, P_BFGS from qiskit.aqua.components.optimizers import NFT, NELDER_MEAD, GSLS, CG from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ from qiskit.aqua.operators import WeightedPauliOperator, Z2Symmetries from qiskit.chemistry import FermionicOperator from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import QuantumError, ReadoutError from qiskit.providers.aer.noise.errors import pauli_error from qiskit.providers.aer.noise.errors import depolarizing_error from qiskit.providers.aer.noise.errors import thermal_relaxation_error from qiskit.providers.aer import noise from qiskit.tools.monitor import job_monitor from qiskit.providers.ibmq import least_busy import warnings IBMQ.load_account() provider = IBMQ.get_provider(group='open') backend = least_busy(provider.backends(simulator=False, operational=True)) import numpy as np import matplotlib.pyplot as plt from functools import partial inter_dist = 1.5108585 driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') # please be aware that the idx here with respective to original idx freeze_list = [0] remove_list = [-3, -2] # negative number denotes the reverse order #Classically solve for the lowest eigenvalue def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref backend = BasicAer.get_backend('statevector_simulator') #Define our noise model based on the ibmq_essex chip chip_name = 'ibmq_essex' device = provider.get_backend(chip_name) coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(device.properties()) basis_gates = noise_model.basis_gates # Classically solve for the lowest eigenvalue # This is used just to compare how well you VQE approximation is performing def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref counts = [] values = [] params = [] deviation = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) # Define your function for computing the qubit operations of LiH def compute_LiH_qubitOp(map_type, inter_dist, basis='sto3g'): # Specify details of our molecule driver = PySCFDriver(atom='Li 0 0 0; H 0 0 ' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis=basis) # Compute relevant 1 and 2 body integrals. molecule = driver.run() h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 nuclear_repulsion_energy = molecule.nuclear_repulsion_energy print("# of electrons: {}".format(num_particles)) print("# of spin orbitals: {}".format(num_spin_orbitals)) # Please be aware that the idx here with respective to original idx freeze_list = [0,1,6,7] remove_list = [0,1,4,5] # negative number denotes the reverse order # Prepare full idx of freeze_list and remove_list # Convert all negative idx to positive num_spin_orbitals -= len(remove_list) # Prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian # and if PARITY mapping is selected, reduction qubits energy_shift = 0.0 qubit_reduction = True if map_type == 'parity' else False ferOp = FermionicOperator(h1=h1, h2=h2) if len(freeze_list) > 0: ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list)//2 if len(remove_list) > 0: ferOp = ferOp.fermion_mode_elimination(remove_list) qubitOp = ferOp.mapping(map_type) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) return qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy = compute_LiH_qubitOp(map_type, inter_dist) # Classically solve for the exact solution and use that as your reference value ref = exact_solver(qubitOp) # Specify your initial state init_state = HartreeFock(num_spin_orbitals, num_particles, qubit_mapping=map_type) # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. RY_var_form = RY(qubitOp.num_qubits, depth=2) # Choose where to run/simulate our circuit quantum_instance = backend max_eval = 1000 # Choose the classical optimizer SPSA_optimizer = SPSA(max_eval) warnings.filterwarnings("ignore") SPSA_vqe = VQE(qubitOp, RY_var_form, SPSA_optimizer, callback=store_intermediate_result) SPSA_vqe_eigenvalue = np.real(SPSA_vqe.run(backend)['eigenvalue']) # Now compare the results of different compositions of your VQE algorithm! SPSA_vqe_result = np.real(energy_shift + SPSA_vqe_eigenvalue) print("==================================================") print('Reference value: {}'.format(ref)) print("SPSA VQE energy: ", SPSA_vqe_eigenvalue) print("HF energy: {}".format(molecule.hf_energy)) print("SPSA Reference Value Percent Error: " + str(abs((SPSA_vqe_eigenvalue-ref)/ref)*100) + "%") print("SPSA Energy Value Percent Error: " + str(np.real(abs((SPSA_vqe_result-molecule.hf_energy)/molecule.hf_energy))*100) + "%") print("==================================================")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.x(0).c_if(cr, 0) qc.measure(0, 0) qc.draw('mpl')
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # 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=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
MonitSharma
import pennylane as qml from pennylane import numpy as np from pennylane.optimize import AdamOptimizer, GradientDescentOptimizer import matplotlib.pyplot as plt # Set a random seed np.random.seed(42) # Make a dataset of points inside and outside of a circle def circle(samples, center=[0.0, 0.0], radius=np.sqrt(2 / np.pi)): """ Generates a dataset of points with 1/0 labels inside a given radius. Args: samples (int): number of samples to generate center (tuple): center of the circle radius (float: radius of the circle Returns: Xvals (array[tuple]): coordinates of points yvals (array[int]): classification labels """ Xvals, yvals = [], [] for i in range(samples): x = 2 * (np.random.rand(2)) - 1 y = 0 if np.linalg.norm(x - center) < radius: y = 1 Xvals.append(x) yvals.append(y) return np.array(Xvals, requires_grad=False), np.array(yvals, requires_grad=False) def plot_data(x, y, fig=None, ax=None): """ Plot data with red/blue values for a binary classification. Args: x (array[tuple]): array of data points as tuples y (array[int]): array of data points as tuples """ if fig == None: fig, ax = plt.subplots(1, 1, figsize=(5, 5)) reds = y == 0 blues = y == 1 ax.scatter(x[reds, 0], x[reds, 1], c="red", s=20, edgecolor="k") ax.scatter(x[blues, 0], x[blues, 1], c="blue", s=20, edgecolor="k") ax.set_xlabel("$x_1$") ax.set_ylabel("$x_2$") Xdata, ydata = circle(500) fig, ax = plt.subplots(1, 1, figsize=(4, 4)) plot_data(Xdata, ydata, fig=fig, ax=ax) plt.show() # Define output labels as quantum state vectors def density_matrix(state): """Calculates the density matrix representation of a state. Args: state (array[complex]): array representing a quantum state vector Returns: dm: (array[complex]): array representing the density matrix """ return state * np.conj(state).T label_0 = [[1], [0]] label_1 = [[0], [1]] state_labels = np.array([label_0, label_1], requires_grad=False) dev = qml.device("default.qubit", wires=1) # Install any pennylane-plugin to run on some particular backend @qml.qnode(dev) def qcircuit(params, x, y): """A variational quantum circuit representing the Universal classifier. Args: params (array[float]): array of parameters x (array[float]): single input vector y (array[float]): single output state density matrix Returns: float: fidelity between output state and input """ for p in params: qml.Rot(*x, wires=0) qml.Rot(*p, wires=0) return qml.expval(qml.Hermitian(y, wires=[0])) def cost(params, x, y, state_labels=None): """Cost function to be minimized. Args: params (array[float]): array of parameters x (array[float]): 2-d array of input vectors y (array[float]): 1-d array of targets state_labels (array[float]): array of state representations for labels Returns: float: loss value to be minimized """ # Compute prediction for each input in data batch loss = 0.0 dm_labels = [density_matrix(s) for s in state_labels] for i in range(len(x)): f = qcircuit(params, x[i], dm_labels[y[i]]) loss = loss + (1 - f) ** 2 return loss / len(x) def test(params, x, y, state_labels=None): """ Tests on a given set of data. Args: params (array[float]): array of parameters x (array[float]): 2-d array of input vectors y (array[float]): 1-d array of targets state_labels (array[float]): 1-d array of state representations for labels Returns: predicted (array([int]): predicted labels for test data output_states (array[float]): output quantum states from the circuit """ fidelity_values = [] dm_labels = [density_matrix(s) for s in state_labels] predicted = [] for i in range(len(x)): fidel_function = lambda y: qcircuit(params, x[i], y) fidelities = [fidel_function(dm) for dm in dm_labels] best_fidel = np.argmax(fidelities) predicted.append(best_fidel) fidelity_values.append(fidelities) return np.array(predicted), np.array(fidelity_values) def accuracy_score(y_true, y_pred): """Accuracy score. Args: y_true (array[float]): 1-d array of targets y_predicted (array[float]): 1-d array of predictions state_labels (array[float]): 1-d array of state representations for labels Returns: score (float): the fraction of correctly classified samples """ score = y_true == y_pred return score.sum() / len(y_true) def iterate_minibatches(inputs, targets, batch_size): """ A generator for batches of the input data Args: inputs (array[float]): input data targets (array[float]): targets Returns: inputs (array[float]): one batch of input data of length `batch_size` targets (array[float]): one batch of targets of length `batch_size` """ for start_idx in range(0, inputs.shape[0] - batch_size + 1, batch_size): idxs = slice(start_idx, start_idx + batch_size) yield inputs[idxs], targets[idxs] # Generate training and test data num_training = 200 num_test = 2000 Xdata, y_train = circle(num_training) X_train = np.hstack((Xdata, np.zeros((Xdata.shape[0], 1), requires_grad=False))) Xtest, y_test = circle(num_test) X_test = np.hstack((Xtest, np.zeros((Xtest.shape[0], 1), requires_grad=False))) # Train using Adam optimizer and evaluate the classifier num_layers = 3 learning_rate = 0.6 epochs = 10 batch_size = 32 opt = AdamOptimizer(learning_rate, beta1=0.9, beta2=0.999) # initialize random weights params = np.random.uniform(size=(num_layers, 3), requires_grad=True) predicted_train, fidel_train = test(params, X_train, y_train, state_labels) accuracy_train = accuracy_score(y_train, predicted_train) predicted_test, fidel_test = test(params, X_test, y_test, state_labels) accuracy_test = accuracy_score(y_test, predicted_test) # save predictions with random weights for comparison initial_predictions = predicted_test loss = cost(params, X_test, y_test, state_labels) print( "Epoch: {:2d} | Cost: {:3f} | Train accuracy: {:3f} | Test Accuracy: {:3f}".format( 0, loss, accuracy_train, accuracy_test ) ) for it in range(epochs): for Xbatch, ybatch in iterate_minibatches(X_train, y_train, batch_size=batch_size): params, _, _, _ = opt.step(cost, params, Xbatch, ybatch, state_labels) predicted_train, fidel_train = test(params, X_train, y_train, state_labels) accuracy_train = accuracy_score(y_train, predicted_train) loss = cost(params, X_train, y_train, state_labels) predicted_test, fidel_test = test(params, X_test, y_test, state_labels) accuracy_test = accuracy_score(y_test, predicted_test) res = [it + 1, loss, accuracy_train, accuracy_test] print( "Epoch: {:2d} | Loss: {:3f} | Train accuracy: {:3f} | Test accuracy: {:3f}".format( *res ) ) print( "Cost: {:3f} | Train accuracy {:3f} | Test Accuracy : {:3f}".format( loss, accuracy_train, accuracy_test ) ) print("Learned weights") for i in range(num_layers): print("Layer {}: {}".format(i, params[i])) fig, axes = plt.subplots(1, 3, figsize=(10, 3)) plot_data(X_test, initial_predictions, fig, axes[0]) plot_data(X_test, predicted_test, fig, axes[1]) plot_data(X_test, y_test, fig, axes[2]) axes[0].set_title("Predictions with random weights") axes[1].set_title("Predictions after training") axes[2].set_title("True test data") plt.tight_layout() plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) with pulse.build() as hahn_echo: with pulse.align_equispaced(duration=100): pulse.play(x90, d0) pulse.play(x180, d0) pulse.play(x90, d0) hahn_echo.draw()
https://github.com/BOBO1997/osp_solutions
BOBO1997
import re import itertools import numpy as np import random random.seed(42) import mitiq from qiskit import QuantumCircuit, QuantumRegister from qiskit.ignis.mitigation import expectation_value # Pauli Twirling def pauli_twirling(circ: QuantumCircuit) -> QuantumCircuit: """ [internal function] This function takes a quantum circuit and return a new quantum circuit with Pauli Twirling around the CNOT gates. Args: circ: QuantumCircuit Returns: QuantumCircuit """ def apply_pauli(num: int, qb: int) -> str: if (num == 0): return f'' elif (num == 1): return f'x q[{qb}];\n' elif (num == 2): return f'y q[{qb}];\n' else: return f'z q[{qb}];\n' paulis = [(i,j) for i in range(0,4) for j in range(0,4)] paulis.remove((0,0)) paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)] new_circ = '' ops = circ.qasm().splitlines(True) #! split the quantum circuit into qasm operators for op in ops: if (op[:2] == 'cx'): # add Pauli Twirling around the CNOT gate num = random.randrange(len(paulis)) qbs = re.findall('q\[(.)\]', op) new_circ += apply_pauli(paulis[num][0], qbs[0]) new_circ += apply_pauli(paulis[num][1], qbs[1]) new_circ += op new_circ += apply_pauli(paulis_map[num][0], qbs[0]) new_circ += apply_pauli(paulis_map[num][1], qbs[1]) else: new_circ += op return QuantumCircuit.from_qasm_str(new_circ) def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0], pt = False): """ This function outputs the circuit list for zero-noise extrapolation. Args: qcs: List[QuantumCircuit], the input quantum circuits. scale_factors: List[float], to what extent the noise scales are investigated. pt: bool, whether add Pauli Twirling or not. Returns: folded_qcs: List[QuantumCircuit] """ folded_qcs = [] #! ZNE用の回路 for qc in qcs: folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用 folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化 if pt: folded_qcs = [pauli_twirling(circ) for circ in folded_qcs] return folded_qcs def make_stf_basis(n, basis_elements = ["X","Y","Z"]): """ [internal function] This function outputs all the combinations of length n string for given basis_elements. When basis_elements is X, Y, and Z (default), the output becomes the n-qubit Pauli basis. Args: n: int basis_elements: List[str] Returns: basis: List[str] """ if n == 1: return basis_elements basis = [] for i in basis_elements: sub_basis = make_stf_basis(n - 1, basis_elements) basis += [i + j for j in sub_basis] return basis def reduce_hist(hist, poses): """ [internal function] This function returns the reduced histogram to the designated positions. Args: hist: Dict[str, float] poses: List[int] Returns: ret_hist: Dict[str, float] """ n = len(poses) ret_hist = {format(i, "0" + str(n) + "b"): 0 for i in range(1 << n)} for k, v in hist.items(): pos = "" for i in range(n): pos += k[poses[i]] ret_hist[pos] += v return ret_hist def make_stf_expvals(n, stf_hists): """ [internal function] This function create the expectations under expanded basis, which are used to reconstruct the density matrix. Args: n: int, the size of classical register in the measurement results. stf_hists: List[Dict[str, float]], the input State Tomography Fitter histograms. Returns: st_expvals: List[float], the output State Tomography expectation values. """ assert len(stf_hists) == 3 ** n stf_basis = make_stf_basis(n, basis_elements=["X","Y","Z"]) st_basis = make_stf_basis(n, basis_elements=["I","X","Y","Z"]) stf_hists_dict = {basis: hist for basis, hist in zip(stf_basis, stf_hists)} st_hists_dict = {basis: stf_hists_dict.get(basis, None) for basis in st_basis} # remaining for basis in sorted(set(st_basis) - set(stf_basis)): if basis == "I" * n: continue reduction_poses = [] reduction_basis = "" for i, b in enumerate(basis): if b != "I": reduction_poses.append(n - 1 - i) # big endian reduction_basis += b # こっちはそのまま(なぜならラベルはlittle endianだから) else: reduction_basis += "Z" st_hists_dict[basis] = reduce_hist(stf_hists_dict[reduction_basis], reduction_poses) st_expvals = dict() for basis, hist in st_hists_dict.items(): if basis == "I" * n: st_expvals[basis] = 1.0 continue st_expvals[basis], _ = expectation_value(hist) return st_expvals def zne_decoder(n, result, scale_factors=[1.0, 2.0, 3.0], fac_type="lin"): """ This function applies the zero-noise extrapolation to the measured results and output the mitigated zero-noise expectation values. Args: n: int, the size of classical register in the measurement results. result: Result, the returned results from job. scale_factors: List[float], this should be the same as the zne_wrapper. fac_type: str, "lin" or "exp", whether to use LinFactory option or ExpFactory option in mitiq, to extrapolate the expectation values. Returns: zne_expvals: List[float], the mitigated zero-noise expectation values. """ hists = result.get_counts() num_scale_factors = len(scale_factors) assert len(hists) % num_scale_factors == 0 scale_wise_expvals = [] # num_scale_factors * 64 for i in range(num_scale_factors): scale_wise_hists = [hists[3 * j + i] for j in range(len(hists) // num_scale_factors)] st_expvals = make_stf_expvals(n, scale_wise_hists) scale_wise_expvals.append( list(st_expvals.values()) ) scale_wise_expvals = np.array(scale_wise_expvals) linfac = mitiq.zne.inference.LinearFactory(scale_factors) expfac = mitiq.zne.ExpFactory(scale_factors) zne_expvals = [] for i in range(4 ** n): if fac_type == "lin": zne_expvals.append( linfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) else: zne_expvals.append( expfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) return zne_expvals
https://github.com/rmlarose/qcbq
rmlarose
#!pip install qiskit # Include the necessary imports for this program import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Create a Quantum Register with 1 qubit (wire). qr = QuantumRegister(1) # Create a Classical Register with 1 bit (double wire). cr = ClassicalRegister(1) # Create a Quantum Circuit from the quantum and classical registers circ = QuantumCircuit(qr, cr) # Place an X gate on the qubit wire. The registers are zero-indexed. circ.x(qr[0]) # Measure the qubit into the classical register circ.measure(qr, cr) # Draw the circuit circ.draw(output='mpl') # Import BasicAer from qiskit import BasicAer # Use BasicAer's qasm_simulator backend_sim = BasicAer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator, running it 100 times. job_sim = execute(circ, backend_sim, shots=100) # Grab the results from the job. result_sim = job_sim.result() # Print the counts, which are contained in a Python dictionary counts = result_sim.get_counts(circ) print(counts) from qiskit.tools.visualization import plot_histogram # Plot the results on a bar chart plot_histogram(counts) # Include the necessary imports for this program # Create a Quantum Register with 1 qubit (wire). # Create a Classical Register with 1 bit (double wire). # Create a Quantum Circuit from the quantum and classical registers # Place two X gates on the qubit wire. The registers are zero-indexed. # Measure the qubit into the classical register # Draw the circuit # Import BasicAer # Use BasicAer's qasm_simulator # Execute the circuit on the qasm simulator, running it 100 times. # Grab the results from the job. # Print the counts, which are contained in a Python dictionary # Plot the results on a bar chart
https://github.com/carstenblank/dc-qiskit-algorithms
carstenblank
# Copyright 2018 Carsten Blank # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math from typing import List, Union from bitstring import BitArray from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit import Qubit from .UniformRotation import cnry class FFQramEntry(object): """ An DB entry of the FF QRAM scheme """ def __init__(self): """ Creates an entry with binary data & label as well as an (optional) amplitude """ self.probability_amplitude = 0.0 # type: float self.data = bytes() # type: bytes self.label = bytes() # type: bytes def get_bits(self, bin_length=None): # type: (FFQramEntry) -> str """ Get the binary bit representation of data and label for state basis identification :return: a bit array """ b = self.data + self.label ba = BitArray(b) ba = ba.bin.lstrip('0') ba = ba.zfill(bin_length) if bin_length is not None else ba return ba def bus_size(self): # type: (FFQramEntry) -> int """ Returns needed bus size for this entry :return: the length """ return len(self.get_bits(1)) def add_to_circuit(self, qc, bus, register): # type: (FFQramEntry, QuantumCircuit, Union[QuantumRegister, list], Qubit) -> QuantumCircuit """ This method adds the gates to encode this entry into the circuit :param qc: quantum circuit to apply the entry to :param bus: the registers for the bus :param register: the target register for the amplitude :return: the applied circuit """ theta = math.asin(self.probability_amplitude) if theta == 0: return qc bus_register = [] # type: List[Qubit] if isinstance(bus, QuantumRegister): bus_register = list(bus) else: bus_register = bus ba = self.get_bits(len(bus_register)) for i, b in enumerate(reversed(ba)): if b == "0": qc.x(bus_register[i]) cnry(qc, theta, bus_register, register) for i, b in enumerate(reversed(ba)): if b == "0": qc.x(bus_register[i]) return qc def __str__(self): return "FFQramEntry(%.8f, %s)" % (self.probability_amplitude, self.get_bits().bin) @staticmethod def _count_set_bits(b): # type: (bytes) -> int """ Returns the number of ones in the byte array :param b: the data :return: the count """ raise DeprecationWarning("This method is as it stands not functional... there is no way to reconcile this.") class FFQramDb(List[FFQramEntry]): """ The DB object with methods to create circuits """ def bus_size(self): # type: (FFQramDb) -> int """ From all entries get the maximum needed bus size :return: the bus size for the DB """ return max([e.bus_size() for e in self]) def add_to_circuit(self, qc, bus, register): # type: (FFQramDb, QuantumCircuit, Union[QuantumRegister, List[Qubit]], Qubit) -> None """ Add the DB to the circuit. :param qc: the quantum circuit :param bus: the bus register :param register: the target register for the amplitudes :return: the circuit after DB being applied """ for entry in self: entry.add_to_circuit(qc, bus, register) def add_entry(self, pa, data, label): # type: (FFQramDb, float, bytes, bytes) -> None """ Add an entry to the (classical representation of) the DB. :param pa: probability amplitude :param data: binary representation of data :param label: binary representation of the label """ entry = FFQramEntry() entry.probability_amplitude = pa entry.data = data entry.label = label self.append(entry) def add_entry_int(self, pa, data, label): # type: (FFQramDb, float, int, int) -> None """ Add an entry to the (classical representation of) the DB. :param pa: probability amplitude :param data: the integer value of the data :param label: the integer value of the label """ raise DeprecationWarning("This method is as it stands not functional... there is no way to reconcile this.") def add_vector(db, vec): # type: (FFQramDb, List[complex]) -> None """ Add a vector to the DB. It makes sense to give an empty DB. :param db: The FFQRAM DB :param vec: the vector to be added """ import numpy as np vector = np.asarray(vec) l2_norm = np.linalg.norm(vector) unit_vector = vector / l2_norm number_of_bytes = int(np.ceil(np.log2(len(vector))) // 8 + 1) for i, v in enumerate(unit_vector): if abs(v) > 1e-6: label_as_bytes = (i).to_bytes(number_of_bytes, byteorder='big') db.add_entry(v, b'', label_as_bytes)
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # 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=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/abbarreto/qiskit3
abbarreto
%run init.ipynb # tem algum problema com a funcao produto tensorial do sympy (implementar eu mesmo ...) k000 = Matrix([1,0,0,0,0,0,0,0]); k001 = Matrix([0,1,0,0,0,0,0,0]) k010 = Matrix([0,0,1,0,0,0,0,0]); k011 = Matrix([0,0,0,1,0,0,0,0]) k100 = Matrix([0,0,0,0,1,0,0,0]); k101 = Matrix([0,0,0,0,0,1,0,0]) k110 = Matrix([0,0,0,0,0,0,1,0]); k111 = Matrix([0,0,0,0,0,0,0,1]) #k000,k001,k010,k011,k100,k101,k110,k111, k001*k001.T p = symbols('p') #p = 0 Psi0 = sqrt((4-3*p)/4)*k000 + sqrt(p/4)*(k101+k010+k111) Psi1 = sqrt((4-3*p)/4)*k100 + sqrt(p/4)*(k001-k110-k011) #Psi0.T, Psi1.T r00,r01,r10,r11 = symbols('r_{00} r_{01} r_{10} r_{11}') rhoA = Matrix([[r00,r01],[r10,r11]]); rhoA, rhoA[0,0] #rhoA = Matrix([[2/3,1/3],[1/3,1/3]]); #rhoA, rhoA[0,0] def rhoABt_s(rhoA,p): Psi0 = sqrt((4-3*p)/4)*k000 + sqrt(p/4)*(k101+k010+k111) Psi1 = sqrt((4-3*p)/4)*k100 + sqrt(p/4)*(k001-k110-k011) return rhoA[0,0]*Psi0*Psi0.T + rhoA[0,1]*Psi0*Psi1.T + rhoA[1,0]*Psi1*Psi0.T + rhoA[1,1]*Psi1*Psi1.T rhoABt_ = rhoABt_s(rhoA,p); rhoABt_ # não foi possivel diagonalizar com sympy def ptraceB(da, db, rho): rhoA = zeros(da,da) for j in range(0, da): for k in range(0, da): for l in range(0, db): rhoA[j,k] += rho[j*db+l,k*db+l] return rhoA rhoAt = ptraceB(2, 4, rhoABt_); simplify(rhoAt) # ok! rhoA = Matrix([[2/3,1/3],[1/3,1/3]]) p = np.arange(0,1.1,0.1); N = len(p) Cl1 = np.zeros(N); Pjb = np.zeros(N) for j in range(0,N): rhoABt_ = rhoABt_s(rhoA,p[j]) rhoA_ = ptraceB(2, 4, rhoABt_) Cl1[j] = coh_l1_s(rhoA_) Pjb[j] = predict_jb_s(rhoA_) # calculo feito a partir de rhoAB_til import matplotlib matplotlib.rcParams.update({'font.size':12}) plt.figure(figsize = (6,4), dpi = 100) plt.plot(p,Cl1,label=r'$C_{l_1}$') plt.plot(p,Pjb,label=r'$P_{jb}$') plt.xlabel(r'$p$') plt.legend() plt.show() evv = rhoABt.eigenvects(); evv def tp_vv_s(psi, csi): # tensor product, of vectors, symbolic M = psi.shape[0]; N = csi.shape[0] eta = zeros(M*N,1) for j in range(0,M): for k in range(0,N): eta[j*N+k] = psi[j]*csi[k] return eta def cb(d,j): # estados da base computacional v = zeros(d,1) v[j] = 1 return v cb(2,0) def PhiABCt_s(rhoA,p): rhoABt = rhoABt_s(rhoA,p) eig = rhoABt.eigenvects() d = rhoABt.shape[0]; Phi = zeros(d*d,1) ne = 0; j = 0; l = -1 while ne < d: mult = eig[j][1]; ne += mult for k in range(0,mult): l += 1 Phi += sqrt(abs(eig[j][0]))*tp_vv_s(eig[j][2][k],cb(d,l)) j += 1 for j in range(0,d*d): if im(Phi[j]) < 10**-5: Phi[j] = re(Phi[j]) return Phi def coh_l1_s(rho): d = rho.shape[0]; C = 0 for j in range(0,d-1): for k in range(j+1,d): C += abs(rho[j,k]) return 2*C def predict_jb_s(rho): return abs(rho[0,0]-rho[1,1]) def proj_s(psi): # simbolic projector d = psi.shape[0] proj = zeros(d,d) for j in range(0,d): for k in range(0,d): proj[j,k] = psi[j]*conjugate(psi[k]) return proj rhoA = Matrix([[2/3,1/3],[1/3,1/3]]) p = np.arange(0,1.1,0.1); N = len(p) Cl1 = np.zeros(N); Pjb = np.zeros(N) for j in range(0,N): Phi = PhiABCt_s(rhoA,p[j]); PPhi = proj_s(Phi)#; print(PPhi) rhoA_ = ptraceB(2, 2**5, PPhi)#; print(rhoA_[0,1]) Cl1[j] = coh_l1_s(rhoA_) Pjb[j] = predict_jb_s(rhoA_) # calculo feito a partir de PhiABC import matplotlib matplotlib.rcParams.update({'font.size':12}) plt.figure(figsize = (6,4), dpi = 100) plt.plot(p,Cl1,label=r'$C_{l_1}$') plt.plot(p,Pjb,label=r'$P_{jb}$') plt.xlabel(r'$p$') plt.legend() plt.show() def rho_AB_til(rhoA,p): rhoAbc = np.zeros((2**3,2**3), dtype=complex)#; print(rhoAbc) ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]])#; print(ket0,ket1) ket00 = np.kron(ket0,ket0); ket01 = np.kron(ket0,ket1); ket10 = np.kron(ket1,ket0) ket11 = np.kron(ket1,ket1); #print(ket00,'',ket01,'',ket10,'',ket11) ket000 = np.kron(ket0,ket00); ket100 = np.kron(ket1,ket00) ket001 = np.kron(ket0,ket01); ket101 = np.kron(ket1,ket01) ket010 = np.kron(ket0,ket10); ket110 = np.kron(ket1,ket10) ket011 = np.kron(ket0,ket11); ket111 = np.kron(ket1,ket11) Psi0 = math.sqrt((4-3*p)/4)*ket000 + math.sqrt(p/4)*(ket101+ket010+ket111) Psi1 = math.sqrt((4-3*p)/4)*ket100 + math.sqrt(p/4)*(ket001-ket110-ket011) rhoAbc = rhoA[0,0]*Psi0@Psi0.T + rhoA[0,1]*Psi0@Psi1.T\ + rhoA[1,0]*Psi1@Psi0.T + rhoA[1,1]*Psi1@Psi1.T return rhoAbc def pTraceR_num(dl, dr, rhoLR): rhoL = np.zeros((dl, dl), dtype=complex) for j in range(0, dl): for k in range(j, dl): for l in range(0, dr): rhoL[j,k] += rhoLR[j*dr+l,k*dr+l] if j != k: rhoL[k,j] = np.conj(rhoL[j,k]) return rhoL rhoA = np.array([[2/3,1/3],[1/3,1/3]]); print(rhoA) # estado inicial p = 0. rhoAbc = rho_AB_til(rhoA,p)#; print(rhoAbc) rhoA_ = pTraceR_num(2, 4, rhoAbc); print(rhoA_) def coh_l1(rho): d = rho.shape[0]; #d = rho.dims()[0] C = 0 for j in range(0,d-1): for k in range(j+1,d): C += np.abs(rho[j,k]) return 2*C def predict_jb(rho): return abs(rho[0,0]-rho[1,1]) p = np.arange(0,1.1,0.1); #print(p) N = len(p)#; print(N) Cl1 = np.zeros(N); Pjb = np.zeros(N) for j in range(0,N): rhoAbc = rho_AB_til(rhoA,p[j]) rhoA_ = pTraceR_num(2, 4, rhoAbc) Cl1[j] = coh_l1(rhoA_) Pjb[j] = predict_jb(rhoA_) # calculo feito a partir de rhoAB_til import matplotlib matplotlib.rcParams.update({'font.size':12}) plt.figure(figsize = (6,4), dpi = 100) plt.plot(p,Cl1,label=r'$C_{l_1}$') plt.plot(p,Pjb,label=r'$P_{jb}$') plt.xlabel(r'$p$') plt.legend() plt.show() from numpy import linalg w, v = linalg.eig(rhoAbc) print(v[0][:]) print(np.shape(v[:][0])) ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]) ket00 = np.kron(ket0,ket0); ket01 = np.kron(ket0,ket1) ket10 = np.kron(ket1,ket0); ket11 = np.kron(ket1,ket1) ket000 = np.kron(ket0,ket00); ket100 = np.kron(ket1,ket00) ket001 = np.kron(ket0,ket01); ket101 = np.kron(ket1,ket01) ket010 = np.kron(ket0,ket10); ket110 = np.kron(ket1,ket10) ket011 = np.kron(ket0,ket11); ket111 = np.kron(ket1,ket11) p = np.arange(0,1.1,0.1) N = len(p) Cl1 = np.zeros(N); Pjb = np.zeros(N) for j in range(0,N): rhoAbc = rho_AB_til(rhoA,p[j]) w, v = linalg.eig(rhoAbc); w = np.abs(w) PhiAbcdef = math.sqrt(w[0])*np.kron(v.T[0],ket000) + math.sqrt(w[1])*np.kron(v.T[1],ket001)\ + math.sqrt(w[2])*np.kron(v.T[2],ket010) + math.sqrt(w[3])*np.kron(v.T[3],ket011)\ + math.sqrt(w[4])*np.kron(v.T[4],ket100) + math.sqrt(w[5])*np.kron(v.T[5],ket101)\ + math.sqrt(w[6])*np.kron(v.T[6],ket110) + math.sqrt(w[7])*np.kron(v.T[7],ket111) rhoAbcdef = np.outer(PhiAbcdef,np.conj(PhiAbcdef))#; print(np.shape(rhoAbcdef)) rhoA_ = pTraceR_num(2, 2**5, rhoAbcdef); print(rhoA_)#; print(np.shape(rhoA_)) Cl1[j] = coh_l1(rhoA_) Pjb[j] = predict_jb(rhoA_) # calculo feito a partir da purificacao rhoAB_til import matplotlib matplotlib.rcParams.update({'font.size':12}) plt.figure(figsize = (6,4), dpi = 100) plt.plot(p,Cl1,label=r'$C_{l_1}$') plt.plot(p,Pjb,label=r'$P_{jb}$') plt.xlabel(r'$p$') plt.legend() plt.show() rho_A = Matrix([[2/3,1/3],[1/3,1/3]]) rho_A.eigenvects() rho_A*Matrix([[0.85],[0.52]])/0.87, rho_A*Matrix([[-0.5257],[0.85]])/0.127 w, v = linalg.eig(rhoA) # os autovetores são as colunas de v print(w, v, v.T[0], v.T[1], np.shape(v.T[1])) # nao pode usar import qiskit from qiskit import * nshots = 8192 IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_quito') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor from qiskit_experiments.library import StateTomography r00 = 2/3; r01 = 1.33/3; r10 = 1.33/3; r11 = 1/3 # initial state r = math.sqrt((r00-r11)**2 + abs(2*r01)**2) # raio de Bloch th = math.acos((r00-r11)/r) ph = math.acos(re(2*r01)/(r*sin(th))) # angulos de Bloch r0 = (1+r)/2.; r1 = (1-r)/2. # autovetores print(r, th, ph, r0, r1) pt = np.arange(0,1.01,0.01) # for the theoretical results Ct = (1-pt)*(2*1.33/3) Pt = (1-pt)*(1/3) p = np.arange(0,1.1,0.1) d = len(p) Csim = np.zeros(d); Psim = np.zeros(d) for j in range(0,d): pI = (4-3*p[j])/4; pX = p[j]/4; pZ = p[j]/4; pY = p[j]/4 # depolarizing # sequencia: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 # = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Phi_ABCD = [math.sqrt(r0*pI)*math.cos(th/2), math.sqrt(r0*pX)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pZ)*math.cos(th/2), -1j*math.sqrt(r0*pY)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r1*pI)*math.sin(th/2), -math.sqrt(r1*pX)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pZ)*math.sin(th/2), 1j*math.sqrt(r1*pY)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r0*pI)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pX)*math.cos(th/2), -math.sqrt(r0*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), 1j*math.sqrt(r0*pY)*math.cos(th/2), -math.sqrt(r1*pI)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pX)*math.sin(th/2), math.sqrt(r1*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), 1j*math.sqrt(r1*pY)*math.sin(th/2)] qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.initialize(Phi_ABCD, [qr[3],qr[2],qr[1],qr[0]]) job_sim = StateTomography(qc, measurement_qubits = [0]) data = job_sim.run(simulator, shots=nshots).block_for_results() rho_sim = data.analysis_results(0).value rho = rho_sim.to_operator().data Csim[j] = coh_l1(rho) Psim[j] = predict_jb(rho) p = np.arange(0,1.1,0.1); d = len(p) Cexp = np.zeros(d); Pexp = np.zeros(d) for j in range(0,d): pI = (4-3*p[j])/4; pX = p[j]/4; pZ = p[j]/4; pY = p[j]/4 Phi_ABCD = [math.sqrt(r0*pI)*math.cos(th/2), math.sqrt(r0*pX)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pZ)*math.cos(th/2), -1j*math.sqrt(r0*pY)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r1*pI)*math.sin(th/2), -math.sqrt(r1*pX)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pZ)*math.sin(th/2), 1j*math.sqrt(r1*pY)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r0*pI)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pX)*math.cos(th/2), -math.sqrt(r0*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), 1j*math.sqrt(r0*pY)*math.cos(th/2), -math.sqrt(r1*pI)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pX)*math.sin(th/2), math.sqrt(r1*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), 1j*math.sqrt(r1*pY)*math.sin(th/2)] qr = QuantumRegister(4); qc = QuantumCircuit(qr) qc.initialize(Phi_ABCD, [qr[3],qr[2],qr[1],qr[0]]) qcst = StateTomography(qc, measurement_qubits = [0]) data = qcst.run(device) print(data.experiment_id) rho = data.block_for_results().analysis_results(0).value rhoM = rho.to_operator().data Cexp[j] = coh_l1(rhoM) Pexp[j] = predict_jb(rhoM) print(Cexp,Pexp) import matplotlib matplotlib.rcParams.update({'font.size':12}) plt.figure(figsize = (6,4), dpi = 100) plt.plot(pt,Ct,label=r'$C_{l_1}^{the}$') plt.plot(pt,Pt,label=r'$P_{jb}^{the}$') plt.plot(p,Csim,'*',label=r'$C_{l_1}^{sim}$') plt.plot(p,Psim,'o',label=r'$P_{jb}^{sim}$') plt.plot(p,Cexp,'^',label=r'$C_{l_1}^{exp}$') plt.plot(p,Pexp,'+',label=r'$P_{jb}^{exp}$') plt.xlabel(r'$p$') plt.legend() plt.show() # para o chip quito, sem mitigacao de erro # para o chip manila sem mitigacao de erro
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """FilterOpNodes pass testing""" from qiskit import QuantumCircuit from qiskit.transpiler.passes import FilterOpNodes from test import QiskitTestCase # pylint: disable=wrong-import-order class TestFilterOpNodes(QiskitTestCase): """Tests for FilterOpNodes transformation pass.""" def test_empty_circuit(self): """Empty DAG has does nothing.""" circuit = QuantumCircuit() self.assertEqual(FilterOpNodes(lambda x: False)(circuit), circuit) def test_remove_x_gate(self): """Test filter removes matching gates.""" circuit = QuantumCircuit(2) circuit.x(0) circuit.x(1) circuit.cx(0, 1) circuit.cx(1, 0) circuit.cx(0, 1) circuit.measure_all() filter_pass = FilterOpNodes(lambda node: node.op.name != "x") expected = QuantumCircuit(2) expected.cx(0, 1) expected.cx(1, 0) expected.cx(0, 1) expected.measure_all() self.assertEqual(filter_pass(circuit), expected) def test_filter_exception(self): """Test a filter function exception passes through.""" circuit = QuantumCircuit(2) circuit.x(0) circuit.x(1) circuit.cx(0, 1) circuit.cx(1, 0) circuit.cx(0, 1) circuit.measure_all() def filter_fn(node): raise TypeError("Failure") filter_pass = FilterOpNodes(filter_fn) with self.assertRaises(TypeError): filter_pass(circuit) def test_no_matches(self): """Test the pass does nothing if there are no filter matches.""" circuit = QuantumCircuit(2) circuit.x(0) circuit.x(1) circuit.cx(0, 1) circuit.cx(1, 0) circuit.cx(0, 1) circuit.measure_all() filter_pass = FilterOpNodes(lambda node: node.op.name != "cz") self.assertEqual(filter_pass(circuit), circuit)
https://github.com/W-Bernau/QiskitAlgorithms
W-Bernau
#Importing Libraries from qiskit import * from qiskit_aer import Aer from math import pi, gcd import numpy as np from qiskit.visualization import plot_bloch_multivector,plot_state_qsphere import matplotlib.pyplot as plt #Drawing a Basic Circuit qc = QuantumCircuit(2) qc.barrier() qc1 = qc.copy() qc.h(0) qc.barrier() qc2 =qc.copy() qc.draw('mpl') #Showing two different states backend = Aer.get_backend('statevector_simulator') q1 = transpile(qc1,backend) job1 = (backend.run(q1)).result().get_statevector() backend = Aer.get_backend('statevector_simulator') q2 = transpile(qc2,backend) job2 = (backend.run(q2)).result().get_statevector() print(job1,job2) #Showing the Pauli & Hardaman Gate (controlled NOT) q = QuantumRegister(2) qc = QuantumCircuit(2) qc.cx(0,1) qc.ch(0,1) qc.y(0) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = transpile(qc, backend) result = (backend.run(job)).result() print(result.get_unitary(qc, decimals=3)) #Showing an elementary three qubit gates q = QuantumRegister(3) qc = QuantumCircuit(3) qc.cx(0,2) qc.ccx(0,1,2) qc.draw(output='mpl') #Showing U Operator and Phase Gates q = QuantumRegister(3) qc = QuantumCircuit(q) qc.u(pi/2,pi/2,pi/2,q[0]) qc.cu(pi/2, 0, 0, 0, 0, 1) qc.u(pi/2,pi/2,pi/2,q[1]) qc.cu(pi/2, 0, 0, 0, 1, 2) qc.u(pi/2,pi/2,pi/2,q[2]) qc.draw(output='mpl') from qiskit.circuit.library import QFT from fractions import Fraction def modular_exponentiation(given_circuit, n, m, a): for x in range(n): exponent = 2**x given_circuit.append(a_x_mod15(a, exponent), [x] + list(range(n, n+m))) def shor_circuit(a,n,m): # Input : a - guess for factor of 15 # n - number of measurements # m - number of target qubits # Setting up circuit shor = QuantumCircuit(n+m, n) # Initializing firsts n qubits with Hadamard shor.h(range(n)) # Applying sigma_x gate to last qubit shor.x(n+m-1) shor.barrier() #Apply modular exponentiation gates modular_exponentiation(shor, n, m, a) shor.barrier() #Apply inverse QFT shor.append(QFT(n, do_swaps=False).inverse(), range(n)) # measure the first n qubits shor.measure(range(n), range(n)) return shor n = 4; m = 4; a = 2 shor_example = shor_circuit(a,n,m) shor_example.draw(output = 'mpl') #Shor's Algorithm for 15 backend = Aer.get_backend('qasm_simulator') def factor(N=15,backend=backend): found_factors = False n = len(bin(N))-2 m = n valid_a = [2,7,8,11,13] while found_factors == False: # STEP 1: Choose a randomly in valid a's if len(valid_a)==0: break a = np.random.choice(valid_a) print(f"Trying a = {a}") r = 1 #defining a wrong r # STEP 2: Find period r while a**r%N != 1: #Adding loop because QPE + continued fractions can find wrong r ## Substep 2.1: Find phase s/r #Defining Shor's Circuits (QPE): qc = shor_circuit(a,n,m) #Doing the measurement (binary): measure = (transpile(qc, backend=backend)) job = (backend.run(measure, shots=1,memory=True)).result().get_memory()[0] #Converting to decimal base: job = int(job,2) phase = job/(2**(n-1)) ## Substep 2.2: Find denominator r (Continued fraction algorithm) r = Fraction(phase).limit_denominator(N).denominator # STEPS 3 and 4: check if r is even and a^(r/2) != -1 (mod N) if r%2==0 and (a**(r/2)+1)%N!=0: #STEP 5: Compute factors factors = [gcd(a**(r//2)-1,N),gcd(a**(r//2)+1,N)] print(f" --- order r = {r}") if factors[0] not in [1,N]: # Check to see if factor is a non trivial one found_factors = True print(f" --- Sucessfully found factors {factors}") else: print(f" --- Trivial factors found: [1,15]") if found_factors == False: print(f" --- a={a} failed!") valid_a.remove(a) factor()
https://github.com/rubenandrebarreiro/ibm-qiskit-global-summer-school-2023
rubenandrebarreiro
# upgrade/update pip library !pip install --upgrade pip # install the last official version of the grader from IBM's Qiskit Community !pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git@main # import the quantum circuit, Aer, # and execute instruction # from the IBM' Qiskit library from qiskit import QuantumCircuit, Aer, execute # import the numpy library import numpy as np # import the plot histogram function # from the IBM's Qiskit Visualization module from qiskit.visualization import plot_histogram # import the plotting from # the Matplotlib's Pyplot module import matplotlib.pyplot as plt # import the GCD (Greatest Common Divisor) # from the built-in mathematics module from math import gcd # define the function to genera the quantum circuit # for the Quantum Fourier Transform (QFT) on n qubits def qft(n): # creates a quantum circuit with n qubits, # implementing the Quantum Fourier Transform (QFT) circuit = QuantumCircuit(n) # define the function to perform the Swap gates # on the quantum registers of the quantum circuit # for the Quantum Fourier Transform (QFT) on n qubits def swap_registers( circuit, n ): # for a number of iterations equal to half of # the number of qubits used on the quantum circuit # for the Quantum Fourier Transform (QFT) for qubit in range( n // 2 ): # apply the Swap gate between the kth qubit and # the (n - k)th qubit on the quantum register defined before circuit.swap( qubit, ( n - qubit - 1 ) ) # return the quantum circuit with the Swap gates # applied on the n qubits of the quantum register, # to implement the Quantum Fourier Transform (QFT) return circuit # define the function to perform the Controlled-Phase gates # on the quantum registers of the quantum circuit # for the Quantum Fourier Transform (QFT) on n qubits # (it is applied to the first n qubits, # and without the Swap gates performed) def qft_rotations( circuit, n ): # if it is the last opposite iteration if n == 0: # return with the Controlled-Phase gates # on the quantum registers of the quantum circuit # for the Quantum Fourier Transform (QFT) on n qubits # (it is applied to the first n qubits, # and without the Swap gates performed) return circuit # iterates on the opposite direction, # setting a new nth iteration n -= 1 # apply the Hadamard gate to the kth qubit, # on the quantum register defined before, # and iterating on the opposite direction circuit.h(n) # for the remaining qubits to consider # i the kth opposite iteration for qubit in range(n): # apply the Controlled-Phase gate for # the theta angle equal to (pi / 2)^(n - k), # with control on the nth qubit and target on the kth qubit circuit.cp( ( np.pi / 2 )**( n - qubit ), qubit, n ) # call this fuction recursively for # the next opposite iteration qft_rotations( circuit, n ) # perform the Controlled-Phase gates # on the quantum registers of the quantum circuit # for the Quantum Fourier Transform (QFT) on n qubits # (it is applied to the first n qubits, # and without the Swap gates performed) qft_rotations( circuit, n ) # perform the Swap gates on the quantum registers of # the quantum circuit for the Quantum Fourier Transform (QFT) on n qubits swap_registers( circuit, n ) # return the quantum circuit with n qubits, # implementing the Quantum Fourier Transform (QFT) return circuit # define the function to genera the quantum circuit # for the Inverse Quantum Fourier Transform (IQFT) on n qubits def qft_dagger( circuit, n ): # note: do not forget to apply again the Swap gates # to peform its inverse operation # for a number of iterations equal to half of # the number of qubits used on the quantum circuit # for the Inverse Quantum Fourier Transform (IQFT) for qubit in range( n // 2 ): # apply the Swap gate between the kth qubit and # the (n - k)th qubit on the quantum register defined before circuit.swap( qubit, ( n - qubit - 1 ) ) # for each number of qubits of the quantum register defined before, # to consider in the current jth iteration for j in range(n): # for each mth qubit of the quantum register defined before, # to consider in the current iteration for m in range(j): # apply the Controlled-Phase gate for # the theta angle equal to -pi / ( 2^( j - m ) ), # with control on the mth qubit and target on the jth qubit qc.cp( -np.pi / float( 2**( j - m ) ), m, j ) # apply the Hadamard gate to the jth qubit # on the quantum register defined before qc.h(j) # define the size n of the quantum register to # store the phase information phase_register_size = 4 # create a quantum circuit with a quantum register # with n qubits and a classical register with n bits, # to implement the Quantum Phase Estimation (QPE) for n = 4 qubits qpe4 = QuantumCircuit( ( phase_register_size + 1 ), phase_register_size ) #################################################### #### insert your code here #### # define the function to perform the Quantum Hadamard Transform on # the n qubits of the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE) def apply_quantum_hadamard_transform( circuit, n ): # for each qubit of the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE) for n qubits for qubit_idx in range(n): # apply the Hadamard gate to the current ith qubit circuit.h(qubit_idx) # define the function to perform the Controlled-Phase gates on # the n qubits of the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE), # as part of the Quantum Fourier Transform (QFT) def apply_controlled_phases( theta, circuit, n ): # for each ith step according to # the number of n qubits used for step in range(n): # compute the iteration parameter t # as a power of 2, according to the current step t = 2**step # for each iteration according to # the iteration parameter t for _ in range(t): # apply the Controlled-Phase gate for the theta angle, # with control on the ith qubit and target on the last qubit circuit.cp( theta, step, n ) # define the function to perform the Swap gates on # the n qubits of the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE), # as part of the Quantum Fourier Transform (QFT) def apply_swaps( circuit, n ): # for a number of iterations equal to half of # the number of phase counting qubits used # on the resepective quantum circuit # for the Quantum Fourier Transform (QFT) for qubit_idx in range( phase_register_size // 2 ): # apply the Swap gate between the kth qubit and # the (n - k)th qubit on the quantum register defined before circuit.swap( qubit_idx, ( n - qubit_idx - 1 ) ) # define the function to perform # the Inverse Quantum Fourier Transform (IQFT) on # the n qubits of the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE) def apply_quantum_fourier_transform_inverse( circuit, n ): # for each qubit on the quantum register for j in range(n): # for each additional mth qubit ranging to # the current jth qubit being iterated before for m in range(j): # apply the Controlled-Phase gate for # the theta angle equal to -pi / ( 2^( j - m ) ), # with control on the mth qubit and target on the jth qubit circuit.cp( -np.pi / float( 2**( j - m ) ), m, j ) # apply the Hadamard gate to the jth qubit (system's qubit) circuit.h(j) # define the function to perform a measurement of # all the n qubits on the quantum register of a quantum circuit, # and storing the classical outcomes on the n bits of # the classical register of that same quantum circuit def measure_all_qubits(circuit, n): # for each pair of qubits and bits for j in range(n): # measure the current qubit on the quantum register, # and stores the classical outcome obtained # in the current bit on the classical register circuit.measure(j, j) # define the function to perform the Quantum Phase Estimation (QPE) # according to a theta angle given, on a quantum circuit of n qubits def quantum_phase_estimation( theta, circuit, n ): # perform the Quantum Hadamard Transform on # the n qubits of the quantum register of # the quantum circuit implementing # the Quantum Phase Estimation (QPE) apply_quantum_hadamard_transform( circuit, n ) # apply the Pauli-X gate to the last qubit on # the quantum register of the quantum circuit of # the Quantum Phase Estimation (QPE) circuit.x(n) # apply a barrier to the quantum circuit of # the Quantum Phase Estimation (QPE) circuit.barrier() # perform the Controlled-Phase gates on # the n qubits of the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE), # as part of the Quantum Fourier Transform (QFT) apply_controlled_phases( theta, circuit, n ) # apply a barrier to the quantum circuit of # the Quantum Phase Estimation (QPE) circuit.barrier() # perform the Swap gates on the n qubits of # the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE), # as part of the Quantum Fourier Transform (QFT) apply_swaps( circuit, n ) # apply a barrier to the quantum circuit of # the Quantum Phase Estimation (QPE) circuit.barrier() # perform the Inverse Quantum Fourier Transform (IQFT) on # the n qubits of the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE) apply_quantum_fourier_transform_inverse( circuit, n ) # apply a barrier to the quantum circuit of # the Quantum Phase Estimation (QPE) circuit.barrier() # perform a measurement of all the n qubits on # the quantum register of the quantum circuit of # the Quantum Phase Estimation (QPE) and storing # the classical outcomes on the n bits of # the classical register of that same quantum circuit measure_all_qubits( circuit, n ) #################################################### # define the theta angle to be equal to (2 * pi) / 3 theta = ( 2 * np.pi ) / 3 # perform the Quantum Phase Estimation (QPE) # according to the theta angle defined, # on the quantum circuit of n qubits defined before quantum_phase_estimation( theta, qpe4, phase_register_size ) # draw the quantum circuit implementing # the Quantum Phase Estimation (QPE) defined before qpe4.draw("mpl") # run this cell to simulate 'qpe4' and # to plot the histogram of the result # create the Aer Simulator object sim = Aer.get_backend("aer_simulator") # define the number of shots shots = 20000 # execute the simulation for the Quantum Phase Estimation (QPE), # with n = 4 counting qubits, and retrieve # the result counts of this quantum simulation count_qpe4 = execute( qpe4, sim, shots=shots ).result().get_counts() # plot the histogram of the result counts of the quantum simulation # for the Quantum Phase Estimation (QPE), with n = 4 counting qubits plot_histogram( count_qpe4, figsize=(9,5) ) # submit your answer # import the grader for the exercise 1 of the lab 3 from qc_grader.challenges.qgss_2023 import grade_lab3_ex1 # grade the exercise 1 of the lab 3 grade_lab3_ex1( count_qpe4 ) # process the result count data to determine accuracy of # the estimated phase and grab the highest probability measurement # define the maximum number of counts which will be obtained max_binary_counts = 0 # define the maximum binary value which will be obtained max_binary_val = "" # for each count obtained from the quantum simulation of # the Quantum Phase Estimation (QPE) for key, item in count_qpe4.items(): # if the current number of counts is greater than # the current maximum number of counts obtained if item > max_binary_counts: # update the maximum number of counts obtained max_binary_counts = item # update the maximum binary value obtained max_binary_val = key ######################################### #### your function to convert a binary #### #### string to a decimal number goes here #### # define the function to convert # a binary string to a decimal number def bin_to_decimal( binary_string ): # return a binary string # converted to a decimal number return int( binary_string, 2 ) # calculate the estimated phase obtained # from the quantum simulation of # the Quantum Phase Estimation (QPE) estimated_phase = ( bin_to_decimal(max_binary_val) / 2**phase_register_size ) # calculate the phase accuracy # which can be obtained from # the quantum simulation of # the Quantum Phase Estimation (QPE) # with the quantum circuit defined before, # inverse of the highest power of 2 # (i.e. smallest decimal) this quantum circuit can estimate phase_accuracy_window = 2**( -phase_register_size ) # submit your answer # import the grader for the exercise 2 of the lab 3 from qc_grader.challenges.qgss_2023 import grade_lab3_ex2 # grade the exercise 2 of the lab 3 grade_lab3_ex2( [ estimated_phase, phase_accuracy_window ] ) # import the IBM's Provider from # the Qiskit's IBM Provider module from qiskit_ibm_provider import IBMProvider # import the transpile function from # the IBM's Qikist Compiler module from qiskit.compiler import transpile # create an IBM's Provider object provider = IBMProvider() # define the hub for the IBM's Provider hub = "summer-school-6" # define the group for the IBM's Provider group = "group-3" # define the project for the IBM's Provider project = "7048813929" # define the backend's name for the IBM's Provider backend_name = "ibmq_manila" # retrieve the backend from the IBM's Provider backend = provider.get_backend( backend_name, instance=f"{hub}/{group}/{project}" ) ########################################## #### your code goes here #### # define the initial maximum quantum circuit depth obtained max_depth = 1e-20 # define the initial minimum quantum circuit depth obtained min_depth = 1e20 # define the number of trials to transpile/optimize # the quantum circuit for the Quantum Phase Estimation (QPE) num_trials = 10 # for each trial to transpile/optimize the quantum circuit # for the Quantum Phase Estimation (QPE) for _ in range(num_trials): # transpile/optimize the quantum circuit # for the Quantum Phase Estimation (QPE), # for the current considering trial transpiled_qpe4 = transpile( qpe4, backend, optimization_level=3 ) # retrieve the quantum circuit depth of # the transpiled/optimized quantum circuit # for the Quantum Phase Estimation (QPE) transpiled_qpe4_depth = transpiled_qpe4.depth() # if the quantum circuit depth of # the transpiled/optimized quantum circuit # for the Quantum Phase Estimation (QPE) # is greater than the current maximum # quantum circuit depth obtained if transpiled_qpe4_depth > max_depth: # update the maximum quantum circuit depth # obtained with the current quantum circuit depth max_depth = transpiled_qpe4_depth # update the quantum circuit with the maximum depth # with the current quantum circuit transpiled/optimized max_depth_qpe = transpiled_qpe4 # if the quantum circuit depth of # the transpiled/optimized quantum circuit # for the Quantum Phase Estimation (QPE) # is lower than the current minimum # quantum circuit depth obtained if transpiled_qpe4_depth < min_depth: # update the minimum quantum circuit depth # obtained with the current quantum circuit depth min_depth = transpiled_qpe4_depth # update the quantum circuit with the minimum depth # with the current quantum circuit transpiled/optimized min_depth_qpe = transpiled_qpe4 ########################################## # submit your answer # import the grader for the exercise 3 of the lab 3 from qc_grader.challenges.qgss_2023 import grade_lab3_ex3 # grade the exercise 3 of the lab 3 grade_lab3_ex3( [ max_depth_qpe, min_depth_qpe ] ) # define the number of shots #shots = 2000 # OPTIONAL: run the minimum depth quantum circuit for # the Quantum Phase Estimation (QPE) # execute and retrieve the job for the simulation # for the Quantum Phase Estimation (QPE), # with n = 4 counting qubits, and retrieve # the result counts of this quantum simulation, # using the minimum quantum circuit depth #job_min_qpe4 = backend.run( min_depth_qpe, sim, shots=shots ) # print the id of the job of the simulation # for the Quantum Phase Estimation (QPE), # with n = 4 counting qubits, and retrieve # the result counts of this quantum simulation, # using the minimum quantum circuit depth #print( job_min_qpe4.job_id() ) # gather the result counts data # execute the simulation for the Quantum Phase Estimation (QPE), # with n = 4 counting qubits, and retrieve # the result counts of this quantum simulation, # using the minimum quantum circuit depth #count_min_qpe4 = job_min_qpe4.result().get_counts() # plot the histogram of the result counts of the quantum simulation # for the Quantum Phase Estimation (QPE), with n = 4 counting qubits, # and using the minimum quantum circuit depth #plot_histogram( count_min_qpe4, figsize=(9,5) ) # OPTIONAL: run the maximum depth quantum circuit for # the Quantum Phase Estimation (QPE) # execute and retrieve the job for the simulation # for the Quantum Phase Estimation (QPE), # with n = 4 counting qubits, and retrieve # the result counts of this quantum simulation, # using the maximum quantum circuit depth #job_max_qpe4 = backend.run( max_depth_qpe, sim, shots=shots ) # print the id of the job of the simulation # for the Quantum Phase Estimation (QPE), # with n = 4 counting qubits, and retrieve # the result counts of this quantum simulation, # using the maximum quantum circuit depth #print( job_max_qpe4.job_id() ) # gather the result counts data # execute the simulation for the Quantum Phase Estimation (QPE), # with n = 4 counting qubits, and retrieve # the result counts of this quantum simulation, # using the maximum quantum circuit depth #count_max_qpe4 = job_max_qpe4.result().get_counts() # plot the histogram of the result counts of the quantum simulation # for the Quantum Phase Estimation (QPE), with n = 4 counting qubits, # and using the maximum quantum circuit depth #plot_histogram( count_max_qpe4, figsize=(9,5) ) # define the function to perform the Quantum Hadamard Transform on # the n qubits of the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE) def apply_quantum_hadamard_transform( circuit, n ): # for each qubit of the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE) for n qubits for qubit_idx in range(n): # apply the Hadamard gate to the current ith qubit circuit.h(qubit_idx) # define the function to perform the Controlled-Phase gates on # the n qubits of the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE), # as part of the Quantum Fourier Transform (QFT) def apply_controlled_phases( theta, circuit, n ): # for each ith step according to # the number of n qubits used for step in range(n): # compute the iteration parameter t # as a power of 2, according to the current step t = 2**step # for each iteration according to # the iteration parameter t for _ in range(t): # apply the Controlled-Phase gate for the theta angle, # with control on the ith qubit and target on the last qubit circuit.cp( theta, step, n ) # define the function to perform the Swap gates on # the n qubits of the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE), # as part of the Quantum Fourier Transform (QFT) def apply_swaps( circuit, n ): # for a number of iterations equal to half of # the number of phase counting qubits used # on the resepective quantum circuit # for the Quantum Fourier Transform (QFT) for qubit_idx in range( phase_register_size // 2 ): # apply the Swap gate between the kth qubit and # the (n - k)th qubit on the quantum register defined before circuit.swap( qubit_idx, ( n - qubit_idx - 1 ) ) # define the function to perform # the Inverse Quantum Fourier Transform (IQFT) on # the n qubits of the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE) def apply_quantum_fourier_transform_inverse( circuit, n ): # for each jth qubit on the quantum register for j in range(n): # for each additional mth qubit ranging to # the current jth qubit being iterated before for m in range(j): # apply the Controlled-Phase gate for # the theta angle equal to -pi / ( 2^( j - m ) ), # with control on the mth qubit and target on the jth qubit circuit.cp( -np.pi / float( 2**( j - m ) ), m, j ) # apply the Hadamard gate to the jth qubit circuit.h(j) # define the function to perform a measurement of # all the n qubits on the quantum register of a quantum circuit, # and storing the classical outcomes on the n bits of # the classical register of that same quantum circuit def measure_all_qubits( circuit, n ): # for each pair of qubits and bits for j in range(n): # measure the current qubit on the quantum register, # and stores the classical outcome obtained # in the current bit on the classical register circuit.measure(j, j) # define the function to create a quantum circuit, # implementing the Quantum Phase Estimation (QPE) on (n + 1) qubits def qpe_circuit(register_size): ######################################### #### your code goes here #### # define the theta phase angle to estimate theta = 1/7 # create the quantum circuit with a quantum register with (n + 1) qubits # and a classical register with n bits, intended to implement # the Quantum Phase Estimation (QPE) on n qubits qpe = QuantumCircuit( ( register_size + 1 ), register_size ) # perform the Quantum Hadamard Transform on # the n qubits of the quantum register of # the quantum circuit implementing # the Quantum Phase Estimation (QPE) apply_quantum_hadamard_transform( qpe, register_size ) # apply the Pauli-X gate to the last qubit on # the quantum register of the quantum circuit of # the Quantum Phase Estimation (QPE) qpe.x(register_size) # apply a barrier to the quantum circuit of # the Quantum Phase Estimation (QPE) qpe.barrier() # perform the Controlled-Phase gates on # the n qubits of the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE), # as part of the Quantum Fourier Transform (QFT) apply_controlled_phases( theta, qpe, register_size ) # apply a barrier to the quantum circuit of # the Quantum Phase Estimation (QPE) qpe.barrier() # perform the Swap gates on the n qubits of # the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE), # as part of the Quantum Fourier Transform (QFT) apply_swaps( qpe, register_size ) # apply a barrier to the quantum circuit of # the Quantum Phase Estimation (QPE) qpe.barrier() # perform the Inverse Quantum Fourier Transform (IQFT) on # the n qubits of the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE) apply_quantum_fourier_transform_inverse( qpe, register_size ) # apply a barrier to the quantum circuit of # the Quantum Phase Estimation (QPE) qpe.barrier() # perform a measurement of all the n qubits on # the quantum register of the quantum circuit of # the Quantum Phase Estimation (QPE) and storing # the classical outcomes on the n bits of # the classical register of that same quantum circuit measure_all_qubits( qpe, register_size ) # return the quantum circuit, implementing # the Quantum Phase Estimation (QPE) on n qubits return qpe ######################################### # run this cell to simulate 'qpe' and # to plot the histogram of the result # define several quantum register sizes # equal to n, allowing to vary them #reg_size = 4 reg_size = 5 #reg_size = 6 #reg_size = 7 #reg_size = 8 # create a quantum circuit for # the Quantum Phase Estimation (QPE), # given the quantum register defined before, # with n counting qubits qpe_check = qpe_circuit( reg_size ) # create the Aer Simulator object sim = Aer.get_backend("aer_simulator") # define the number of shots shots = 10000 # execute the simulation for the Quantum Phase Estimation (QPE), # with n counting qubits, and retrieve its result counts count_qpe = execute( qpe_check, sim, shots=shots ).result().get_counts() # plot the histogram of the result counts of the quantum simulation # for the Quantum Phase Estimation (QPE), with n counting qubits plot_histogram( count_qpe, figsize=(9,5) ) # process the result count data to determine accuracy of # the estimated phase and grab the highest probability measurement # define the maximum number of counts which will be obtained max_binary_counts = 0 # define the maximum binary value which will be obtained max_binary_val = "" # for each count obtained from the quantum simulation of # the Quantum Phase Estimation (QPE) for key, item in count_qpe.items(): # if the current number of counts is greater than # the current maximum number of counts obtained if item > max_binary_counts: # update the maximum number of counts obtained max_binary_counts = item # update the maximum binary value obtained max_binary_val = key ######################################### #### your function to convert a binary #### #### string to a decimal number goes here #### # define the function to convert # a binary string to a decimal number def bin_to_decimal( binary_string ): # return a binary string # converted to a decimal number return int( binary_string, 2 ) # calculate the estimated phase obtained # from the quantum simulation of # the Quantum Phase Estimation (QPE) estimated_phase = ( bin_to_decimal(max_binary_val) / 2**reg_size ) # print the estimated phase obtained # from the quantum simulation of # the Quantum Phase Estimation (QPE) print("Estimated Phase:", estimated_phase) # calculate the phase accuracy # which can be obtained from # the quantum simulation of # the Quantum Phase Estimation (QPE) # with the quantum circuit defined before, # inverse of the highest power of 2 # (i.e. smallest decimal) this quantum circuit can estimate phase_accuracy_window = 2**( -reg_size ) # print the phase accuracy # which can be obtained from # the quantum simulation of # the Quantum Phase Estimation (QPE) # with the quantum circuit defined before, # inverse of the highest power of 2 # (i.e. smallest decimal) this quantum circuit can estimate print("Phase Accuracy Window:", phase_accuracy_window) # define the theta phase angle, # which was pretended to be estimated theta = 1 / 7 # compute the accuracy of the estimated phase, # as the distance between the estimated phase # and the theta phase angle, which was pretended to be estimated accuracy_estimated_phase = abs( theta - estimated_phase ) # print the accuracy of the estimated phase, # as the distance between the estimated phase # and the theta phase angle, which was pretended to be estimated print("Accuracy of the Estimated Phase:", accuracy_estimated_phase) ### put your answer here ### # to estimate accurately the phase information to be within 2^(-6) # we need n + 1 = 6 (=) n = 5 qubits to store the phase information required_register_size = 5 ### submit your answer ### # import the grader for the exercise 4 of the lab 3 from qc_grader.challenges.qgss_2023 import grade_lab3_ex4 # grade the exercise 4 of the lab 3 grade_lab3_ex4( required_register_size ) # create 7 mod 15 unitary operator # for a quantum circuit N = 15 # define the number of m qubits required # for the 7 mod 15 operator to be executed m = int( np.ceil( np.log2( N ) ) ) # create the quantum circuit with # a quantum register of m qubits # to implement the 7 mod 15 unitary operator U_qc = QuantumCircuit( m ) # apply the Pauli-X gate to all the m qubits of # the quantum register of the quantum circuit # implementing the 7 mod 15 unitary operator U_qc.x( range(m) ) # apply the Swap gate between the 2nd qubit and # the 3rd qubit on the quantum register of # the quantum circuit implementing # the 7 mod 15 unitary operator U_qc.swap(1, 2) # apply the Swap gate between the 3rd qubit and # the 4th qubit on the quantum register of # the quantum circuit implementing # the 7 mod 15 unitary operator U_qc.swap(2, 3) # apply the Swap gate between the 1st qubit and # the 4th qubit on the quantum register of # the quantum circuit implementing # the 7 mod 15 unitary operator U_qc.swap(0, 3) # convert the quantum circuit implementing # the 7 mod 15 unitary operator to # a quantum unitary gate U = U_qc.to_gate() # define the name of the 7 mod 15 # unitary operator created before U.name ="{}Mod{}".format(7, N) # your code goes here # print the number of qubits print("Num. qubits: m =", m); # define the quantum circuits for the inputs # |1> = |0001>, |2> = |0010>, and |5> = |0101> ######################################### # create the a quantum circuit with m qubits, # for the input state |1> = |0001> qcirc_input_1 = QuantumCircuit(m) # apply the Pauli-X gate to # the 1st qubit of the quantum register of # the quantum circuit defined before qcirc_input_1.x(0) # apply the U gate to all # the m qubits of the quantum register of # the quantum circuit defined before qcirc_input_1.append( U, range(m) ) # measure all the m qubits of # the quantum register of # the quantum circuit defined before qcirc_input_1.measure_all() ######################################### # create the a quantum circuit with m qubits, # for input state |2> = |0010> qcirc_input_2 = QuantumCircuit(m) # apply the Pauli-X gate to # the 2nd qubit of the quantum register of # the quantum circuit defined before qcirc_input_2.x(1) # apply the U gate to all # the m qubits of the quantum register of # the quantum circuit defined before qcirc_input_2.append( U, range(m) ) # measure all the m qubits of # the quantum register of # the quantum circuit defined before qcirc_input_2.measure_all() ######################################### # create the a quantum circuit with m qubits, # for input state |5> = |0101> qcirc_input_5 = QuantumCircuit(m) # apply the Pauli-X gate to # the 1st qubit of the quantum register of # the quantum circuit defined before qcirc_input_5.x(0) # apply the Pauli-X gate to # the 3rd qubit of the quantum register of # the quantum circuit defined before qcirc_input_5.x(2) # apply the U gate to all # the m qubits of the quantum register of # the quantum circuit defined before qcirc_input_5.append( U, range(m) ) # measure all the m qubits of # the quantum register of # the quantum circuit defined before qcirc_input_5.measure_all() ######################################### # run this cell to simulate 'qcirc' and to plot the histogram of the result # create the Aer Simulator object sim = Aer.get_backend("aer_simulator") # define the number of shots shots = 20000 # save the count data for the input state |1> = |0001> input_1 = execute(qcirc_input_1, sim, shots=shots).result().get_counts() # save the count data for the input state |2> = |0010> input_2 = execute(qcirc_input_2, sim, shots=shots).result().get_counts() # save the count data for the input state |5> = |0101> input_5 = execute(qcirc_input_5, sim, shots=shots).result().get_counts() # submit your answer # import the grader for the exercise 5 of the lab 3 from qc_grader.challenges.qgss_2023 import grade_lab3_ex5 # grade the exercise 5 of the lab 3 grade_lab3_ex5( [ input_1, input_2, input_5 ] ) # create an unitary quantum circuit # with a quantum register of m qubits unitary_circ = QuantumCircuit(m) #### your code goes here #### # for each iteration in a range of 2^2 = 4 for _ in range( 2**2 ): # apply the U gate on all # the m qubits on the quantum register unitary_circ.append( U, range(m) ) # create a Unitary Simulator object sim = Aer.get_backend("unitary_simulator") # execute the quantum simulation of # an unitary quantum circuit with # a quantum register of m qubits, # defined before, retrieving its unitary operator unitary = execute( unitary_circ, sim ).result().get_unitary() # submit your answer # import the grader for the exercise 6 of the lab 3 from qc_grader.challenges.qgss_2023 import grade_lab3_ex6 # grade the exercise 6 of the lab 3 grade_lab3_ex6( unitary, unitary_circ ) # define the function to built a 2^k-Controlled-U gate object, # which repeats the action of the operator U, 2^k times def cU_multi(k): # define the size n of the system's quantum register sys_register_size = 4 # create the quantum circuit with n qubits on # the system's quantum register, to build # a 2^k-Controlled-U gate object circ = QuantumCircuit( sys_register_size ) # for each iteration ranging until 2^k for _ in range(2**k): # apply the U gate to all the n qubits on # the system's quantum register of # the quantum circuit to represent # the 2^k-Controlled-U gate circ.append(U, range(sys_register_size)) # convert the operator resulting from the construction of # the quantum circuit defined before, to a quantum gate U_multi = circ.to_gate() # define the name of the 2^k-Controlled-U gate, # as being a "7 Mod 15 gate" U_multi.name = "7Mod15_[2^{}]".format(k) # set this 2^k-Controlled-U gate as multi-qubit gate, # depending on a given control qubit cU_multi = U_multi.control() # return the 2^k-Controlled-U gate object, # which repeats the action of the operator U, 2^k times return cU_multi # define the size m of the quantum register # for the phase counting of the qubits phase_register_size = 8 # define the size n of the quantum register # for the successive applications of # the 2^k-Controlled-U gate defined before cu_register_size = 4 # create the Quantum Circuit needed to run # with m = 8 qubits for the phase counting # and with n = 4 qubits for the successive # applications of the 2^k-Controlled-U gate # defined before, to implement the Shor's Algorithm # for Factoring, based on Quantum Phase Estimation (QPE) shor_qpe = QuantumCircuit( ( phase_register_size + cu_register_size ), phase_register_size ) # perform the Quantum Hadamard Transform on # the m qubits for the phase counting of # the quantum register of the quantum circuit # implementing the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) apply_quantum_hadamard_transform( shor_qpe, phase_register_size ) # apply the Pauli-X gate to the last qubit on # the quantum register of the quantum circuit to # implement the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) shor_qpe.x( phase_register_size ) # apply a barrier to the quantum circuit to # implement the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) shor_qpe.barrier() # for each kth qubit on the quantum register # for the phase counting of the qubits for k in range( phase_register_size ): # retrieve the 2^k-Controlled-U gate object, # which repeats the action of the operator U, # 2^k times, defined before cU = cU_multi(k) # apply the 2^k-Controlled-U gate object, # which repeats the action of the operator U, # 2^k times, defined before, for the kth iteration, # to the quantum circuit to implement # the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) shor_qpe.append( cU, [k] + list( range( phase_register_size, ( phase_register_size + cu_register_size ) ) ) ) # apply a barrier to the quantum circuit to # implement the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) shor_qpe.barrier() # perform the Swap gates on the n qubits of # the quantum register of the quantum circuit # implementing the Quantum Phase Estimation (QPE), # as part of the Quantum Fourier Transform (QFT), # required to build the quantum circuit to implement # the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) apply_swaps(shor_qpe, phase_register_size) # apply a barrier to the quantum circuit to # implement the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) shor_qpe.barrier() # perform the Inverse Quantum Fourier Transform (IQFT) on # the m qubits for the phase counting of # the quantum register of the quantum circuit # implementing the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) apply_quantum_fourier_transform_inverse( shor_qpe, phase_register_size ) # apply a barrier to the quantum circuit to # implement the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) shor_qpe.barrier() # perform a measurement of all # the m qubits for the phase counting of # the quantum register of the quantum circuit # implementing the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) shor_qpe.measure( range( phase_register_size ), range( phase_register_size ) ) # draw the quantum circuit implementing # the quantum circuit to # implement the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) shor_qpe.draw("mpl") # run this cell to simulate 'shor_qpe' and # to plot the histogram of the results # create an Aer Simulator object sim = Aer.get_backend("aer_simulator") # define the number of shots shots = 20000 # execute the quantum simulation for # the quantum circuit for the Shor's Algorithm, # based on Quantum Phase Estimation (QPE), # with n phase counting qubits, and retrieve # the result counts of this quantum simulation shor_qpe_counts = execute(shor_qpe, sim, shots=shots).result().get_counts() # plot the histogram of the result counts of the quantum simulation # for the quantum circuit for the Shor's Algorithm, based on # Quantum Phase Estimation (QPE), with n phase counting qubits plot_histogram( shor_qpe_counts, figsize=(9,5) ) # submit your answer # import the grader for the exercise 7 of the lab 3 from qc_grader.challenges.qgss_2023 import grade_lab3_ex7 # grade the exercise 7 of the lab 3 grade_lab3_ex7( shor_qpe_counts ) # import the Fraction object # from the built-in fractions module from fractions import Fraction # print the number '0.666', # as an unlimited Fraction object print( "Unlimited Fraction(0.666):", Fraction(0.666), '\n') # print the number '0.666', # as a limited Fraction object # with the denominator of 15 print( "Limited Fraction(0.666), with a max. denominator of 15:", Fraction(0.666).limit_denominator(15) ) # create a list with the estimated phases of the result counts # obtained from the execution of the quantum simulation # for the Quantum Phase Estimation (QPE), with n counting qubits estimated_phases = [ bin_to_decimal(binary_val) / 2**phase_register_size for binary_val in shor_qpe_counts ] # print the list with the estimated phases of the result counts # obtained from the execution of the quantum simulation # for the Quantum Phase Estimation (QPE), with n counting qubits print( "Estimated Phases:", estimated_phases ) # create a list of with the estimated phases of the result counts # obtained from the execution of the quantum simulation # for the Quantum Phase Estimation (QPE), with n counting qubits, # represented as Fraction objects with the format s/r shor_qpe_fractions = [ Fraction(estimated_phase).limit_denominator(15) for estimated_phase in estimated_phases ] # print the list of with the estimated phases of the result counts # obtained from the execution of the quantum simulation # for the Quantum Phase Estimation (QPE), with n counting qubits, # represented as Fraction objects with the format s/r print( "Estimated Fractions:", shor_qpe_fractions ) # submit your answer # import the grader for the exercise 8 of the lab 3 from qc_grader.challenges.qgss_2023 import grade_lab3_ex8 # grade the exercise 8 of the lab 3 grade_lab3_ex8( shor_qpe_fractions ) # define the function to create and execute # the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE), # with k phase counting qubits def shor_qpe(k): # define the co-prime a a = 7 # define the number N to factor N = 15 # compute the number m of # additional qubits required m = int( np.ceil( np.log2(N) ) ) ################################################# # step 1. Begin a while loop until a nontrivial guess is found #### your code goes here #### # define the boolean flag to determine # if a non trivial guess was found, initially as False non_trivial_guess_found = False # while no trivial factor guess was found, # execute the while loop while( not non_trivial_guess_found ): ################################################# # step 2a. construct a QPE quantum circuit # with m phase counting qubits to guess # the phase phi = s/r, using the function # cU_multi() defined before #### your code goes here #### # create a quantum circuit for # the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE), # with k phase counting qubits, # and additional m qubits for # the successive applications of # the 2^k-Controlled-U gate defined before qc = QuantumCircuit( ( k + m ), k) # perform the Quantum Hadamard Transform on # the k phase counting qubits of the respective # quantum register of the quantum circuit # for the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) apply_quantum_hadamard_transform( qc, k ) # apply a Pauli-X gate to the last # phase counting qubit of the respective # quantum register of the quantum circuit # for the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) qc.x(k) # apply a barrier to the quantum circuit for # the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE), # with k phase counting qubits, # and additional m qubits for # the successive applications of # the 2^k-Controlled-U gate defined before qc.barrier() # for each kth qubit on the quantum register # for the phase counting of the qubits for k_i in range(k): # retrieve the 2^k-Controlled-U gate object, # which repeats the action of the operator U, # 2^k times, defined before cU = cU_multi(k_i) # apply the 2^k-Controlled-U gate object, # which repeats the action of the operator U, # 2^k times, defined before, for the kth iteration, # to the quantum circuit for the Shor's Algorithm # for Factoring, based on Quantum Phase Estimation (QPE), # with k phase counting qubits, and additional m qubits # for the successive applications of # the 2^k-Controlled-U gate defined before qc.append( cU, [k_i] + list( range( k, ( k + m ) ) ) ) # apply a barrier to the quantum circuit for # the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE), # with k phase counting qubits, # and additional m qubits for # the successive applications of # the 2^k-Controlled-U gate defined before qc.barrier() # perform the Swap gates on the k # phase counting qubits of the respective # quantum register of the quantum circuit # for the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE), # as part of the Quantum Fourier Transform (QFT) apply_swaps( qc, k ) # apply a barrier to the quantum circuit for # the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE), # with k phase counting qubits, # and additional m qubits for # the successive applications of # the 2^k-Controlled-U gate defined before qc.barrier() # perform the Inverse Quantum Fourier Transform (IQFT) on # the k phase counting qubits of the respective # quantum register of the quantum circuit # for the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) apply_quantum_fourier_transform_inverse( qc, k ) # apply a barrier to the quantum circuit for # the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE), # with k phase counting qubits, # and additional m qubits for # the successive applications of # the 2^k-Controlled-U gate defined before qc.barrier() # perform a measurement of all # the k phase counting qubits of the respective # quantum register of the quantum circuit # for the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) qc.measure( range(k), range(k) ) ################################################# # step 2b. run the QPE quantum circuit with a single shot, # record the results and convert the estimated phase # bitstring to a decimal format #### your code goes here #### # create an Aer Simulator object sim = Aer.get_backend("aer_simulator") # define the number of shots shots = 1 # execute the simulation for the Quantum Phase Estimation (QPE), # with n counting qubits, and retrieve the result counts # obtained from this quantum simulation shor_qpe_counts = execute( qc, sim, shots=shots ).result().get_counts() # plot the histogram of the result counts of the quantum simulation # for the Quantum Phase Estimation (QPE), with n counting qubits plot_histogram( shor_qpe_counts, figsize=(9,5) ) # compute the estimated phases from the result counts # obtained from the quantum simulation of the quantum circuit # implementing the Shor's Algorithm for Factoring, # based on Quantum Phase Estimation (QPE) estimated_phases = [ bin_to_decimal( binary_val ) / 2**k for binary_val in shor_qpe_counts ] ################################################# # step 3. use the Fraction object to find the guess for r #### your code goes here #### # convert the estimated phase to a fraction s/r format fraction_s_r = [ Fraction(estimated_phase).limit_denominator(N) for estimated_phase in estimated_phases ][0] # retrieve the numerator s and the denominator r # from the estimated phase represented as a fraction s, r = fraction_s_r.numerator, fraction_s_r.denominator ################################################# # step 4. now that r has been found, use the built-in # greatest common divisor function to determine # the guesses for a factor of N # build the list of guesses for possible non-trivial factors of N guesses = [ gcd( a**( r // 2 ) - 1, N ), gcd( a**( r // 2 ) + 1, N ) ] ################################################# # step 5. for each guess in guesses, check if # at least one is a non-trivial factor, # i.e., ( ( guess != 1 ) or ( guess != N ) ) # and ( N % guess == 0 ) #### your code goes here #### # for each of the guesses computed before for guess in guesses: # if the current guess is not a trivial factor if ( ( ( guess != 1 ) or ( guess != N ) ) and ( N % guess == 0 ) ): # update the boolean flag to determine # if a non trivial guess was found, as True non_trivial_guess_found = True # break the current for loop break ################################################# # step 6. if a non-trivial factor is found return # the list 'guesses', otherwise # continue the while loop # return the list of the guesses, # containing a non-trivial factor of N return guesses ################################################# # submit your circuit # import the grader for the exercise 9 of the lab 3 from qc_grader.challenges.qgss_2023 import grade_lab3_ex9 # grade the exercise 9 of the lab 3 grade_lab3_ex9( shor_qpe ) # import the IBM's Qiskit Jupyter Tools import qiskit.tools.jupyter # show the table of the IBM's Qiskit version %qiskit_version_table
https://github.com/sebasmos/QuantumVE
sebasmos
# This code is part of qiskit-runtime. # # (C) Copyright IBM 2021. # # 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. """The FeatureMap class.""" import json import numpy as np from qiskit import QuantumCircuit, QuantumRegister class FeatureMap: """Mapping data with the feature map.""" def __init__(self, feature_dimension, entangler_map=None): """ Args: feature_dimension (int): number of features (twice the number of qubits for this encoding) entangler_map (list[list]): connectivity of qubits with a list of [source, target], or None for full entanglement. Note that the order in the list is the order of applying the two-qubit gate. Raises: ValueError: If the value of ``feature_dimension`` is odd. """ if isinstance(feature_dimension, int): if feature_dimension % 2 == 0: self._feature_dimension = feature_dimension else: raise ValueError("Feature dimension must be an even integer.") else: raise ValueError("Feature dimension must be an even integer.") self._num_qubits = int(feature_dimension / 2) if entangler_map is None: self._entangler_map = [ [i, j] for i in range(self._num_qubits) for j in range(i + 1, self._num_qubits) ] else: self._entangler_map = entangler_map self._num_parameters = self._num_qubits def construct_circuit(self, x=None, parameters=None, q=None, inverse=False, name=None): """Construct the feature map circuit. Args: x (numpy.ndarray): data vector of size feature_dimension parameters (numpy.ndarray): optional parameters in feature map q (QauntumRegister): the QuantumRegister object for the circuit inverse (bool): whether or not to invert the circuit name (str): The name to use for the constructed ``QuantumCircuit`` object Returns: QuantumCircuit: a quantum circuit transforming data x Raises: ValueError: If the input parameters or vector are invalid """ if parameters is not None: if isinstance(parameters, (int, float)): raise ValueError("Parameters must be a list.") if len(parameters) == 1: parameters = parameters * np.ones(self._num_qubits) else: if len(parameters) != self._num_parameters: raise ValueError( "The number of feature map parameters must be {}.".format( self._num_parameters ) ) if len(x) != self._feature_dimension: raise ValueError( "The input vector must be of length {}.".format(self._feature_dimension) ) if q is None: q = QuantumRegister(self._num_qubits, name="q") circuit = QuantumCircuit(q, name=name) for i in range(self._num_qubits): circuit.ry(-parameters[i], q[i]) for source, target in self._entangler_map: circuit.cz(q[source], q[target]) for i in range(self._num_qubits): circuit.rz(-2 * x[2 * i + 1], q[i]) circuit.rx(-2 * x[2 * i], q[i]) if inverse: return circuit.inverse() else: return circuit def to_json(self): """Return JSON representation of this object. Returns: str: JSON string representing this object. """ return json.dumps( {"feature_dimension": self._feature_dimension, "entangler_map": self._entangler_map} ) @classmethod def from_json(cls, data): """Return an instance of this class from the JSON representation. Args: data (str): JSON string representing an object. Returns: FeatureMap: An instance of this class. """ return cls(**json.loads(data))