repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
from qiskit.optimization import QuadraticProgram
from qiskit.optimization.algorithms import MinimumEigenOptimizer
from dwave.plugins.qiskit import DWaveMinimumEigensolver
import numpy as np
A = np.array([[0,1,2,3,4,1],
[2,1,4,1,0,2],
[1,1,1,1,0,3],
[1,5,2,3,4,1]])
m, n = A.shape
c = np.array([1,2,1,3,1,4])
b = np.array([1, 3, 2, 6])
model = QuadraticProgram("Binary Test")
# add variables
x = [model.binary_var('x'+str(j)) for j in range(n)]
# add linear constraints
for i in range(m):
model.linear_constraint(linear=A[i], sense='==', rhs=b[i], name='A'+str(i)+'eq'+'b'+str(i))
# add linear objective function
model.minimize(linear = c)
print(model.export_as_lp_string())
# Use D-Wave QPU as a minimum eigen solver
# See https://github.com/dwavesystems/dwave-qiskit-plugin
dwave_solver = DWaveMinimumEigensolver()
optimizer = MinimumEigenOptimizer(dwave_solver)
result = optimizer.solve(model)
print(result)
result.min_eigen_solver_result.sampleset.to_pandas_dataframe()
|
https://github.com/abbarreto/qiskit3
|
abbarreto
| |
https://github.com/tuf65651/quantum-research
|
tuf65651
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
backend = Aer.get_backend("qasm_simulator")
def ripple_carry_bits(circuit, control_bit, acc_reg, scratch_reg, start_shifting_at):
"""Continue a carry operation
This assumes that whatever simple op triggered the ripple has already occurred.
For example, if the ripple started with addition of 1 to the least significant bit,
manually flip and then call function.
@param circuit: QuantumCircuit containing operands
@param control_bit: single bit controling whether op begins.
@param acc_reg: QuantumRegister containing integer to shift
@param scratch_reg: Quantum registered in initial |0..0> state used to store carry result of each simple addition.
@param start_shifting_at: index in acc_reg of bit to shift
TESTING - Passed minimal test cases July 18 at 8:24am Pacific Time
"""
circuit.ccx(control_bit, acc_reg[start_shifting_at], scratch_reg[start_shifting_at])
circuit.cx(control_bit, acc_reg[start_shifting_at])
# After flipping target, state |0> means we should have carried... =>
# before flipping target, state |1> means we should carry.
# Flip each bit, if it's 1, carry to the next bit, and flip it back.
for bit in range(start_shifting_at + 1, len(acc_reg) - 1):
circuit.ccx(acc_reg[bit], scratch_reg[bit - 1], scratch_reg[bit])
circuit.cx(scratch_reg[bit - 1], acc_reg[bit])
def c_ripple_subtract(circuit, control_bit, min_reg, scratch_reg, start_shifting_at):
"""Continue a subtract operation
@param circuit: QuantumCircuit containing operands
@param control_bit: single bit controling whether op begins.
@param min_reg: QuantumRegister containing integer to shift
@param scratch_reg: Quantum registered in initial |0..0> state used to store carry result of each simple addition.
@param start_shifting_at: index in acc_reg of bit to shift
TESTING - Passed minimal test cases July 18 at 8:24am Pacific Time
"""
circuit.ccx(control_bit, acc_reg[start_shifting_at], scratch_reg[start_shifting_at])
circuit.cx(control_bit, acc_reg[start_shifting_at])
# After flipping target, state |0> means we should have carried... =>
# before flipping target, state |1> means we should carry.
# Flip each bit, if it's 1, carry to the next bit, and flip it back.
for bit in range(start_shifting_at + 1, len(acc_reg) - 1):
circuit.ccx(acc_reg[bit], scratch_reg[bit - 1], scratch_reg[bit])
circuit.cx(scratch_reg[bit - 1], acc_reg[bit])
def add_to_b_in_place(circuit, a_reg, b_reg, scratch_reg):
"""|a > | b > => |a > |a+b >
TESTING - Passed minimal test cases July 18 at 8:24am Pacific Time
"""
for bit in range(len(a_reg)):
circuit.reset(scratch_reg)
ripple_carry_bits(
circuit=circuit,
control_bit=a_reg[bit],
acc_reg=b_reg,
scratch_reg=scratch_reg,
start_shifting_at=bit)
def sub_b_from_a_in_place(circuit, minnd_reg, subtrhnd_reg, scratch_reg):
"""Subtract subtrahend integer b from minuend integer a in register a
@param circuit: QuantumCircuit containing other parameters
@param minnd_reg: QuantumRegister transformed from minuend to difference
@param subtrhnd_reg: QuantumRegister containing subtrahend
@param scratch_reg: QuantumRegister in initial |0...0> state used as borrow flags
for each primitive op (final bit indicates negative difference)
"""
def bit_shift_left(circuit, register, places=1):
"""
TESTING - Passed minimal test cases July 21 at 2:30 Pacific Time
"""
# zero out all trailing bits
num_bits = len(register)
for rollover in range(num_bits - places, num_bits):
circuit.reset(register[rollover])
# swap every bit 'places' forward, with last bits wrapping around to beginning
for bit in range(num_bits - 1,places-1,-1):
circuit.swap(register[bit], register[bit - places])
def c_copy_register(circuit, control_bit, origin, dest):
"""sets contents of dest with contents of origin if control_bit
WARNING - perform a reset before use
"""
circuit.reset(dest)
for bit in range(len(dest)):
circuit.ccx(control_bit, origin[bit], dest[bit])
def multiply(circuit, multiplicand, multiplier, scratch_zero_check, scratch_carrier, prod_accumulator):
c_copy_register(circuit=circuit, control_bit=multiplier[0], origin=multiplicand, dest=prod_accumulator)
for bit in range(1, len(multiplier)):
# free up scratch space
circuit.reset(scratch_carrier)
circuit.reset(scratch_zero_check)
# shift multiplicand one space left, to match magnitude of current multiplier bit
bit_shift_left(circuit=circuit, register=multiplicand, places=1)
# copy multiplicand into scratch register only if multiplicand bit, else keep scratch register |0>
c_copy_register(circuit=circuit, control_bit=multiplier[bit], origin=multiplicand, dest=scratch_zero_check)
# add that scratch term (shifted multiplicand or zero) to accumulated product
add_to_b_in_place(circuit=circuit, a_reg=scratch_zero_check, b_reg=prod_accumulator, scratch_reg=scratch_carrier)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
%matplotlib inline
import qiskit.pulse as pulse
import qiskit.pulse.pulse_lib as pulse_lib
from qiskit.compiler import assemble
import qiskit
qiskit.__qiskit_version__
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='your-hub-name') # change to your hub name
backend = provider.get_backend('ibmq_poughkeepsie')
backend_config = backend.configuration()
from qiskit.tools.jupyter import backend_overview, backend_monitor
%qiskit_backend_monitor backend
backend_defaults = backend.defaults()
backend_devicespec = pulse.DeviceSpecification.create_from(backend)
dt = backend_config.dt
# choose device to work on
from qiskit import IBMQ
IBMQ.load_account()
qubit = 1
center_frequency_GHz = backend_defaults.qubit_freq_est[qubit]
# define frequencies to do VNA sweep
import numpy as np
frequency_span_kHz = 20000
frequency_step_kHz = 1000
frequency_min = center_frequency_GHz - frequency_span_kHz/2.e6
frequency_max = center_frequency_GHz + frequency_span_kHz/2.e6
frequencies_GHz = np.arange(frequency_min, frequency_max, frequency_step_kHz/1e6)
print(frequencies_GHz)
# drive pulse parameters
drive_power = 0.01
drive_samples = 128
drive_sigma = 16
# creating drive pulse
drive_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_power,
sigma=drive_sigma, name='mydrivepulse')
drive_pulse_qubit = drive_pulse(backend_devicespec.q[qubit].drive)
# measurement pulse parameters
meas_amp = 0.05
meas_samples = 1200
meas_sigma = 4
meas_risefall = 25
# creating measurement pulse
meas_pulse = pulse_lib.gaussian_square(duration=meas_samples, amp=meas_amp,
sigma=meas_sigma, risefall=meas_risefall,
name='mymeasurepulse')
meas_pulse_qubit = meas_pulse(backend_devicespec.q[qubit].measure)
# create acquire pulse
acq_cmd=pulse.Acquire(duration=meas_samples)
acq_cmd_qubit = acq_cmd(backend_devicespec.q, backend_devicespec.mem)
# combined measure and acquire pulse
measure_and_acquire_qubit = meas_pulse_qubit | acq_cmd_qubit
# scalefactor for received data
scale_factor = 1e-10
# schedules
schedules = []
schedule_LOs = []
num_shots_per_frequency = 256
for jj, drive_frequency in enumerate(frequencies_GHz):
# start an empty schedule with a label
this_schedule = pulse.Schedule(name="Frequency = {}".format(drive_frequency))
this_schedule += drive_pulse_qubit
this_schedule += measure_and_acquire_qubit << this_schedule.duration
schedules.append(this_schedule)
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: drive_frequency})
schedule_LOs.append(thisLO)
VNASweep_experiment_qobj = assemble(schedules, backend = backend,
meas_level=1, meas_return='single',
shots=num_shots_per_frequency,
schedule_los = schedule_LOs
)
schedules[-1].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
job = backend.run(VNASweep_experiment_qobj)
from qiskit.tools.monitor import job_monitor
print(job.job_id())
job_monitor(job, monitor_async='True')
job = backend.retrieve_job('5d2e228e15ce0100196d8c22')
VNASweep_results = job.result(timeout=3600)
plot_X = frequencies_GHz
plot_Y = []
for kk, drive_frequency in enumerate(frequencies_GHz):
thisfrequency_results = VNASweep_results.get_memory(kk)*scale_factor
plot_Y.append( np.mean(thisfrequency_results[:, qubit]) )
import matplotlib.pyplot as plotter
plotter.plot(plot_X, plot_Y)
rough_frequency_qubit = frequencies_GHz [
np.where( plot_Y == np.max(plot_Y))[0]
].tolist()[0]
rough_frequency_qubit = round(rough_frequency_qubit, 5)
print(rough_frequency_qubit)
# Rabi experiment parameters
num_Rabi_points = 64
num_shots_per_point = 256
# drive parameters
drive_power_min = 0
drive_power_max = 0.1
drive_powers = np.linspace(drive_power_min, drive_power_max, num_Rabi_points)
drive_samples = 128
drive_sigma = 16
# create schedules for Rabi experiment
Rabi_schedules = []
Rabi_schedule_LOs = []
for ii, drive_power in enumerate(drive_powers):
rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_power,
sigma=drive_sigma, name='rabi_pulse_{}'.format(ii))
rabi_pulse_qubit = rabi_pulse(backend_devicespec.q[qubit].drive)
# start an empty schedule with a label
this_schedule = pulse.Schedule(name="Rabi drive = {}".format(drive_power))
this_schedule += rabi_pulse_qubit
this_schedule += measure_and_acquire_qubit << this_schedule.duration
Rabi_schedules.append(this_schedule)
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: rough_frequency_qubit})
Rabi_schedule_LOs.append(thisLO)
Rabi_schedules[-1].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
rabi_experiment_qobj = assemble (Rabi_schedules, backend = backend,
meas_level=1, meas_return='avg',
shots=num_shots_per_point,
schedule_los = Rabi_schedule_LOs
)
job = backend.run(rabi_experiment_qobj)
print(job.job_id())
job_monitor(job, monitor_async=True)
job = backend.retrieve_job('5d2e2a0099a509001888ab02')
Rabi_results = job.result(timeout=3600)
plot_X = drive_powers
plot_Y = []
for jj, drive_power in enumerate(drive_powers):
thispower_results = Rabi_results.get_memory(jj)*scale_factor
plot_Y.append( thispower_results[qubit] )
import matplotlib.pyplot as plotter
plot_Y = plot_Y - np.mean(plot_Y)
plotter.plot(plot_X, plot_Y)
from scipy.optimize import curve_fit
fit_func = lambda x,A,B,T,phi: (A*np.cos(2*np.pi*x/T+phi)+B)
#Fit the data
fitparams, conv = curve_fit(fit_func, plot_X, plot_Y, [3.0 ,0.0 ,0.04 ,0])
#get the pi amplitude
first_peak = abs(np.pi-fitparams[3])*fitparams[2]/(2*np.pi)
pi_amp = abs(fitparams[2]/2)
plotter.scatter(plot_X, plot_Y)
plotter.plot(plot_X, fit_func(plot_X, *fitparams), color='red')
plotter.axvline(first_peak, color='black', linestyle='dashed')
plotter.axvline(first_peak + pi_amp, color='black', linestyle='dashed')
plotter.xlabel('Pulse amplitude, a.u.', fontsize=20)
plotter.ylabel('Signal, a.u.', fontsize=20)
plotter.title('Rough Pi Amplitude Calibration', fontsize=20)
print('Pi Amplitude %f'%(pi_amp))
# Rabi experiment parameters
num_shots_gndexc = 512
# drive parameters
drive_power = pi_amp
print(drive_power)
# create schedules for Rabi experiment
gndexc_schedules = []
gndexc_schedule_LOs = []
pi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=pi_amp,
sigma=drive_sigma, name='pi_pulse'.format(ii))
pi_pulse_qubit = pi_pulse(backend_devicespec.q[qubit].drive)
# ground state schedule
gnd_schedule = pulse.Schedule(name="ground state")
gnd_schedule += measure_and_acquire_qubit << gnd_schedule.duration
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: rough_frequency_qubit})
# excited state schedule
exc_schedule = pulse.Schedule(name="excited state")
exc_schedule += pi_pulse_qubit
exc_schedule += measure_and_acquire_qubit << exc_schedule.duration
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: rough_frequency_qubit})
gndexc_schedules.append(gnd_schedule)
gndexc_schedules.append(exc_schedule)
gndexc_schedule_LOs.append(thisLO)
gndexc_schedule_LOs.append(thisLO)
gndexc_schedules[0].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
gndexc_schedules[1].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
gndexc_experiment_qobj = assemble (gndexc_schedules, backend = backend,
meas_level=1, meas_return='single',
shots=num_shots_gndexc,
schedule_los = gndexc_schedule_LOs
)
job = backend.run(gndexc_experiment_qobj)
print(job.job_id())
job_monitor(job, monitor_async=True)
job = backend.retrieve_job('5d2e2c3a61157a0018e22440')
gndexc_results = job.result(timeout=3600)
gnd_results = gndexc_results.get_memory(0)[:, qubit]*scale_factor
exc_results = gndexc_results.get_memory(1)[:, qubit]*scale_factor
plotter.scatter(np.real(gnd_results), np.imag(gnd_results),
s=5, cmap='viridis',c='blue',alpha=0.5, label='state_0')
plotter.scatter(np.real(exc_results), np.imag(exc_results),
s=5, cmap='viridis',c='red',alpha=0.5, label='state_1')
mean_gnd = np.mean(gnd_results) # takes mean of both real and imaginary parts
mean_exc = np.mean(exc_results)
plotter.scatter(np.real(mean_gnd), np.imag(mean_gnd),
s=200, cmap='viridis',c='blue',alpha=1.0, label='state_0_mean')
plotter.scatter(np.real(mean_exc), np.imag(mean_exc),
s=200, cmap='viridis',c='red',alpha=1.0, label='state_1_mean')
plotter.xlabel('I (a.u.)')
plotter.xlabel('Q (a.u.)')
def get_01(IQ_data):
dist_0 = np.linalg.norm(np.array([
np.real(IQ_data) - np.real(mean_gnd),
np.imag(IQ_data) - np.imag(mean_gnd)
]))
dist_1 = np.linalg.norm(np.array([
np.real(IQ_data) - np.real(mean_exc),
np.imag(IQ_data) - np.imag(mean_exc)
]))
if dist_1 <= dist_0:
return 1
else:
return 0
print(get_01(mean_gnd), get_01(mean_exc))
# T1 experiment parameters
time_max_us = 500
time_step_us = 2
times_us = np.arange(1, time_max_us, time_step_us)
num_shots_per_point = 512
# drive parameters
drive_power = pi_amp
print(drive_power)
# create schedules for Ramsey experiment
T1_schedules = []
T1_schedule_LOs = []
T1_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_power,
sigma=drive_sigma, name='T1_pulse')
T1_pulse_qubit = T1_pulse(backend_devicespec.q[qubit].drive)
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: rough_frequency_qubit})
for ii, delay_time_us in enumerate(times_us):
# start an empty schedule with a label
this_schedule = pulse.Schedule(name="T1 delay = {} us".format(delay_time_us))
this_schedule += T1_pulse_qubit
this_schedule |= (measure_and_acquire_qubit << int(delay_time_us*1000/dt))
T1_schedules.append(this_schedule)
T1_schedule_LOs.append(thisLO)
T1_schedules[0].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
T1_experiment_qobj = assemble (T1_schedules, backend = backend,
meas_level=1, meas_return='avg',
shots=num_shots_per_point,
schedule_los = T1_schedule_LOs
)
job = backend.run(T1_experiment_qobj)
print(job.job_id())
job_monitor(job, monitor_async=True)
job = backend.retrieve_job('5d2e79ad99a509001888ab09')
T1_results = job.result(timeout=3600)
plot_X = times_us
plot_Y = []
for jj, delay_time_us in enumerate(times_us):
thisdelay_results = T1_results.get_memory(jj)*scale_factor
plot_Y.append( thisdelay_results[qubit] )
plotter.plot(plot_X, plot_Y)
from scipy.optimize import curve_fit
fit_func2 = lambda x,A,B: (A*np.exp(-x/59.8)+B)
#Fit the data
fitparams2, conv2 = curve_fit(fit_func2, plot_X,
plot_Y,
[-1.0,-11])
print(f"T1 from backend = {backend.properties().qubits[qubit][0].value} us")
plotter.scatter(plot_X, plot_Y)
plotter.plot(plot_X, fit_func2(plot_X, *fitparams2), color='black')
plotter.xlim(0, np.max(plot_X))
plotter.xlabel('Delay before measurement, ($\mu$s)', fontsize=20)
plotter.ylabel('Measured signal, a.u.', fontsize=20)
# Ramsey experiment parameters
time_max_us = 100
time_step_us = 0.25
times_us = np.arange(1, time_max_us, time_step_us)
num_shots_per_point = 256
# drive parameters
drive_power = pi_amp/2
print(drive_power)
# create schedules for Ramsey experiment
Ramsey_schedules = []
Ramsey_schedule_LOs = []
ramsey_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_power,
sigma=drive_sigma, name='ramsey_pulse')
ramsey_pulse_qubit = ramsey_pulse(backend_devicespec.q[qubit].drive)
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: rough_frequency_qubit})
for ii, delay_time_us in enumerate(times_us):
# start an empty schedule with a label
this_schedule = pulse.Schedule(name="Ramsey delay = {} us".format(delay_time_us))
this_schedule += ramsey_pulse_qubit
this_schedule |= (ramsey_pulse_qubit << int(this_schedule.duration+delay_time_us*1000/dt))
this_schedule |= (measure_and_acquire_qubit << this_schedule.duration)
Ramsey_schedules.append(this_schedule)
Ramsey_schedule_LOs.append(thisLO)
Ramsey_schedules[-1].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
ramsey_experiment_qobj = assemble (Ramsey_schedules, backend = backend,
meas_level=1, meas_return='avg',
shots=num_shots_per_point,
schedule_los = Ramsey_schedule_LOs
)
job = backend.run(ramsey_experiment_qobj)
print(job.job_id())
job_monitor(job, monitor_async=True)
job = backend.retrieve_job('5d2e75dc137af400181be14a')
Ramsey_results = job.result(timeout=3600)
plot_X = times_us
plot_Y = []
for jj, delay_time_us in enumerate(times_us):
thisdelay_results = Ramsey_results.get_memory(jj)[qubit]*scale_factor
plot_Y.append(np.mean(thisdelay_results))
plotter.plot(plot_X, (plot_Y))
from scipy.optimize import curve_fit
fit_func = lambda x,A,T,phi,T2p,B: (A*np.exp(-x/T2p)*(np.sin(2*np.pi*x/T+phi))+B)
#Fit the data
fitparams, conv = curve_fit(fit_func, plot_X,
plot_Y,
[1.0,10,0,4,34])
#off-resonance component
delT = fitparams[1]
delf_MHz = 1./(delT)
print(f"df = {delf_MHz} MHz")
first_peak = (np.pi-fitparams[2])*delT/(2*np.pi) + delT/4
second_peak = first_peak + delT
print(f"T2p = {fitparams[3]} us")
print(f"T2 from backend = {backend.properties().qubits[qubit][1].value} us")
#get the pi amplitude
plotter.scatter(plot_X, plot_Y)
plotter.plot(plot_X, fit_func(plot_X, *fitparams), color='red')
plotter.axvline(first_peak, color='black', linestyle='dashed')
plotter.axvline(second_peak, color='red', linestyle='dashed')
plotter.xlim(0, np.max(plot_X))
plotter.xlabel('Ramsey delay, ($\mu$s)', fontsize=20)
plotter.ylabel('Ramsey signal, a.u.', fontsize=20)
plotter.title('Rough $\Delta$f Calibration', fontsize=20)
precise_frequency_qubit_plus = round(rough_frequency_qubit + delf_MHz/1e3, 5)
precise_frequency_qubit_minus = round(rough_frequency_qubit - delf_MHz/1e3, 5)
print(f"{rough_frequency_qubit}->{precise_frequency_qubit_plus} or {precise_frequency_qubit_minus}")
# T2 experiment parameters
time_max_us = 125
time_step_us = 0.5
times_us = np.arange(1, time_max_us, time_step_us)
num_shots_per_point = 512
# drive parameters
drive_power_1 = pi_amp/2
drive_power_2 = pi_amp
print(drive_power_1)
print(drive_power_2)
# create schedules for Ramsey experiment
T2_schedules = []
T2_schedule_LOs = []
T2_pulse_pio2 = pulse_lib.gaussian(duration=drive_samples, amp=drive_power_1,
sigma=drive_sigma, name='T2_pio2_pulse')
T2_pulse_pio2_qubit = T2_pulse_pio2(backend_devicespec.q[qubit].drive)
T2_pulse_pi = pulse_lib.gaussian(duration=drive_samples, amp=drive_power_2,
sigma=drive_sigma, name='T2_pi_pulse')
T2_pulse_pi_qubit = T2_pulse_pi(backend_devicespec.q[qubit].drive)
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: precise_frequency_qubit_minus})
for ii, delay_time_us in enumerate(times_us):
# start an empty schedule with a label
this_schedule = pulse.Schedule(name="T2 delay = {} us".format(delay_time_us))
this_schedule |= T2_pulse_pio2_qubit
this_schedule |= (T2_pulse_pi_qubit << int(this_schedule.duration +
delay_time_us*1000/dt))
this_schedule |= (T2_pulse_pio2_qubit << int(this_schedule.duration +
delay_time_us*1000/dt))
this_schedule |= (measure_and_acquire_qubit << int(this_schedule.duration))
T2_schedules.append(this_schedule)
T2_schedule_LOs.append(thisLO)
T2_schedules[0].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
T2_experiment_qobj = assemble (T2_schedules, backend = backend,
meas_level=1, meas_return='avg',
shots=num_shots_per_point,
schedule_los = T2_schedule_LOs
)
job = backend.run(T2_experiment_qobj)
print(job.job_id())
job_monitor(job, monitor_async=True)
T2job = backend.retrieve_job('5d2f6c0ae741150012334c44')
T2_results = T2job.result(timeout=3600)
plot_X = 2.*times_us
plot_Y = []
for jj, delay_time_us in enumerate(times_us):
thisdelay_results = T2_results.get_memory(jj)*scale_factor
plot_Y.append( thisdelay_results[qubit] )
plotter.plot(plot_X, plot_Y)
T2y_echo = plot_Y
T2x_echo = plot_X
from scipy.optimize import curve_fit
T2guess = backend.properties().qubits[qubit][1].value
fit_func2 = lambda x,A,B: (A*np.exp(-x/T2guess)+B)
#Fit the data
fitparams2, conv2 = curve_fit(fit_func2, plot_X,
plot_Y,
[-2.0,1.0])
print(f"T2 from backend = {backend.properties().qubits[qubit][1].value} us")
plotter.scatter(plot_X, plot_Y)
plotter.plot(plot_X, fit_func2(plot_X, *fitparams2), color='black')
plotter.xlim(0, np.max(plot_X))
plotter.xlabel('Total time, ($\mu$s)', fontsize=20)
plotter.ylabel('Measured signal, a.u.', fontsize=20)
# measurement pulse parameters
meas_amp = 0.1
meas_samples = 1200
meas_sigma = 4
meas_risefall = 25
# creating measurement pulse
meas_pulse = pulse_lib.gaussian_square(duration=meas_samples, amp=meas_amp,
sigma=meas_sigma, risefall=meas_risefall,
name='mymeasurepulse')
meas_pulse_qubit = meas_pulse(backend_devicespec.q[qubit].measure)
# create acquire pulse
acq_cmd=pulse.Acquire(duration=meas_samples)
acq_cmd_qubit = acq_cmd(backend_devicespec.q, backend_devicespec.mem)
# combined measure and acquire pulse
measure_and_acquire_qubit = meas_pulse_qubit | acq_cmd_qubit
# scalefactor for received data
scale_factor = 1e-10
# T2 experiment parameters
tau_us_min = 1
tau_us_max = 30
tau_step_us = 0.1
taus_us = np.arange(tau_us_min, tau_us_max, tau_step_us)
num_shots_per_point = 512
ncpmg = 10
# drive parameters
drive_power_1 = pi_amp/2
drive_power_2 = pi_amp
print(f"Total time ranges from {2.*ncpmg*taus_us[0]} to {2.*ncpmg*taus_us[-1]} us")
# create schedules for Ramsey experiment
T2cpmg_schedules = []
T2cpmg_schedule_LOs = []
T2cpmg_pulse_pio2 = pulse_lib.gaussian(duration=drive_samples, amp=drive_power_1,
sigma=drive_sigma, name='T2cpmg_pio2_pulse')
T2cpmg_pulse_pio2_qubit = T2cpmg_pulse_pio2(backend_devicespec.q[qubit].drive)
T2cpmg_pulse_pi = pulse_lib.gaussian(duration=drive_samples, amp=drive_power_2,
sigma=drive_sigma, name='T2cpmg_pi_pulse')
T2cpmg_pulse_pi_qubit = T2cpmg_pulse_pi(backend_devicespec.q[qubit].drive)
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: precise_frequency_qubit_minus})
for ii, delay_time_us in enumerate(taus_us):
# start an empty schedule with a label
this_schedule = pulse.Schedule(name="T2cpmg delay = {} us".format(delay_time_us))
this_schedule |= T2cpmg_pulse_pio2_qubit
this_schedule |= (T2cpmg_pulse_pi_qubit << int(this_schedule.duration +
delay_time_us*1000/dt))
for _ in range(ncpmg-1):
this_schedule |= (T2cpmg_pulse_pi_qubit << int(this_schedule.duration +
2*delay_time_us*1000/dt))
this_schedule |= (T2cpmg_pulse_pio2_qubit << int(this_schedule.duration +
delay_time_us*1000/dt))
this_schedule |= (measure_and_acquire_qubit << int(this_schedule.duration))
T2cpmg_schedules.append(this_schedule)
T2cpmg_schedule_LOs.append(thisLO)
T2cpmg_schedules[0].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
T2cpmg_experiment_qobj = assemble (T2cpmg_schedules, backend = backend,
meas_level=1, meas_return='avg',
shots=num_shots_per_point,
schedule_los = T2cpmg_schedule_LOs
)
job = backend.run(T2cpmg_experiment_qobj)
print(job.job_id())
job_monitor(job, monitor_async=True)
T2cpmgjob = backend.retrieve_job('5d2f6e1aca4ad70012795340')
T2cpmg_results = T2cpmgjob.result(timeout=3600)
plot_X = 2.*ncpmg*taus_us
plot_Y = []
for jj, delay_time_us in enumerate(taus_us):
thisdelay_results = T2cpmg_results.get_memory(jj)*scale_factor
plot_Y.append( thisdelay_results[qubit] )
plotter.plot(plot_X, plot_Y)
T2y_cpmg = plot_Y
T2x_cpmg = plot_X
from scipy.optimize import curve_fit
T2guess = backend.properties().qubits[qubit][1].value
fit_func2 = lambda x,A,B: (A*np.exp(-x/T2guess)+B)
#Fit the data
fitparams2, conv2 = curve_fit(fit_func2, plot_X,
plot_Y,
[-2.0,1.0])
print(f"T2 from backend = {T2guess} us")
plotter.scatter(plot_X, plot_Y)
plotter.plot(plot_X, fit_func2(plot_X, *fitparams2), color='black')
plotter.xlim(0, np.max(plot_X))
plotter.xlabel('Total time, ($\mu$s)', fontsize=20)
plotter.ylabel('Measured signal, a.u.', fontsize=20)
|
https://github.com/Dpbm/scientific-research-1-quantum-oracles
|
Dpbm
|
%matplotlib inline
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_histogram, array_to_latex
from qiskit_aer import AerSimulator
from utils import get_image_path
def simulate(qc, backend=AerSimulator(), shots=1000):
transpiled_qc = transpile(qc, backend)
return backend.run(transpiled_qc, shots=shots).result()
oracle_swap = QuantumCircuit(4)
oracle_swap.swap(0, -1)
oracle_swap.swap(1, -2)
oracle_swap.draw('mpl', filename=get_image_path("minimal-oracle.png"))
oracle_copy = oracle_swap.copy()
oracle_copy.save_unitary()
unitary = simulate(oracle_copy).get_unitary()
array_to_latex(unitary, max_size=10000)
oracle = oracle_swap.to_gate(label="$oracle_{Swap}$")
qc = QuantumCircuit(4)
qc.h(range(1, 4))
qc.draw('mpl')
qc_copy = qc.copy()
qc_copy.measure_all()
plot_histogram(simulate(qc_copy, shots=100).get_counts())
qc.append(oracle, range(4))
qc.measure_all()
qc.draw('mpl')
plot_histogram(simulate(qc, shots=100).get_counts())
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
print(qiskit.__version__)
from qiskit.aqua.algorithms import Shor
from qiskit.aqua import QuantumInstance
import numpy as np
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend=backend, shots=1024)
my_shor = Shor(N=2189,a=4,quantum_instance=quantum_instance)
Shor.run(my_shor)
|
https://github.com/tuf65651/quantum-research
|
tuf65651
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import math
# Loading your IBM Q account(s)
IBMQ.load_accounts()
q = QuantumRegister(3)
c = ClassicalRegister(3)
qft3 = QuantumCircuit(q,c)
qft3.h(q[0])
qft3.cu1(math.pi/2, q[1], q[0])
qft3.cu1(math.pi/4, q[2], q[0])
qft3.h(q[1])
qft3.cu1(math.pi/2, q[2], q[1])
qft3.h(q[2])
qft3.draw()
def input_state(circ, q, n):
"""n-bit input state for QFT that produces output 1."""
for j in range(n):
circ.h(q[j])
circ.u1(math.pi/float(2**j) * (-1), q[j])#.inverse()
def qft(circ, q, n):
"""n-bit QFT on q in circ"""
for j in range(n):
circ.h(q[j])
for k in range(j+1, n):
circ.cu1(math.pi/float(2**(k-j)), q[k], q[j])
circ.barrier()
q = QuantumRegister(3, 'x')
c = ClassicalRegister(3, 'c')
qft3 = QuantumCircuit(q, c)
qft(qft3, q, 3)
# qft(qft3, q, 3)
for i in range(3):
qft3.measure(q[i], c[i])
#print(qft3.qasm())
qft3.draw()
backend = Aer.get_backend("qasm_simulator")
simulate = execute(qft3, backend=backend, shots=4069).result()
simulate.get_counts()
plot_histogram(simulate.get_counts())
q = QuantumRegister(8, 'x')
c = ClassicalRegister(8, 'c')
qft8a = QuantumCircuit(q, c)
# for i in range(4):
# qft8a.x(q[2*i])
qft(qft8a, q, 8)
qft(qft8a, q, 8)
for i in range(8):
qft8a.measure(q[i], c[i])
qft8a.draw()
backend = Aer.get_backend("qasm_simulator")
simulate = execute(qft8a, backend=backend, shots=1024).result()
plot_histogram(simulate.get_counts())
simulate.get_counts()
qft(qft3)
qft.measure(q,c)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 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.
"""Tests evaluator of auxiliary operators for algorithms."""
import unittest
from typing import Tuple, Union
from test.python.algorithms import QiskitAlgorithmsTestCase
import numpy as np
from ddt import ddt, data
from qiskit_algorithms.list_or_dict import ListOrDict
from qiskit.providers import Backend
from qiskit.quantum_info import Statevector
from qiskit_algorithms import eval_observables
from qiskit import BasicAer, QuantumCircuit
from qiskit.circuit.library import EfficientSU2
from qiskit.opflow import (
PauliSumOp,
X,
Z,
I,
ExpectationFactory,
OperatorBase,
ExpectationBase,
StateFn,
)
from qiskit.utils import QuantumInstance, algorithm_globals
@ddt
class TestAuxOpsEvaluator(QiskitAlgorithmsTestCase):
"""Tests evaluator of auxiliary operators for algorithms."""
def setUp(self):
super().setUp()
self.seed = 50
algorithm_globals.random_seed = self.seed
with self.assertWarns(DeprecationWarning):
self.h2_op = (
-1.052373245772859 * (I ^ I)
+ 0.39793742484318045 * (I ^ Z)
- 0.39793742484318045 * (Z ^ I)
- 0.01128010425623538 * (Z ^ Z)
+ 0.18093119978423156 * (X ^ X)
)
self.threshold = 1e-8
self.backend_names = ["statevector_simulator", "qasm_simulator"]
def get_exact_expectation(self, ansatz: QuantumCircuit, observables: ListOrDict[OperatorBase]):
"""
Calculates the exact expectation to be used as an expected result for unit tests.
"""
if isinstance(observables, dict):
observables_list = list(observables.values())
else:
observables_list = observables
# the exact value is a list of (mean, variance) where we expect 0 variance
exact = [
(Statevector(ansatz).expectation_value(observable), 0)
for observable in observables_list
]
if isinstance(observables, dict):
return dict(zip(observables.keys(), exact))
return exact
def _run_test(
self,
expected_result: ListOrDict[Tuple[complex, complex]],
quantum_state: Union[QuantumCircuit, Statevector],
decimal: int,
expectation: ExpectationBase,
observables: ListOrDict[OperatorBase],
quantum_instance: Union[QuantumInstance, Backend],
):
with self.assertWarns(DeprecationWarning):
result = eval_observables(
quantum_instance, quantum_state, observables, expectation, self.threshold
)
if isinstance(observables, dict):
np.testing.assert_equal(list(result.keys()), list(expected_result.keys()))
np.testing.assert_array_almost_equal(
list(result.values()), list(expected_result.values()), decimal=decimal
)
else:
np.testing.assert_array_almost_equal(result, expected_result, decimal=decimal)
@data(
[
PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]),
PauliSumOp.from_list([("II", 2.0)]),
],
[
PauliSumOp.from_list([("ZZ", 2.0)]),
],
{
"op1": PauliSumOp.from_list([("II", 2.0)]),
"op2": PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]),
},
{
"op1": PauliSumOp.from_list([("ZZ", 2.0)]),
},
)
def test_eval_observables(self, observables: ListOrDict[OperatorBase]):
"""Tests evaluator of auxiliary operators for algorithms."""
ansatz = EfficientSU2(2)
parameters = np.array(
[1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0],
dtype=float,
)
bound_ansatz = ansatz.bind_parameters(parameters)
expected_result = self.get_exact_expectation(bound_ansatz, observables)
for backend_name in self.backend_names:
shots = 4096 if backend_name == "qasm_simulator" else 1
decimal = (
1 if backend_name == "qasm_simulator" else 6
) # to accommodate for qasm being imperfect
with self.subTest(msg=f"Test {backend_name} backend."):
backend = BasicAer.get_backend(backend_name)
with self.assertWarns(DeprecationWarning):
quantum_instance = QuantumInstance(
backend=backend,
shots=shots,
seed_simulator=self.seed,
seed_transpiler=self.seed,
)
expectation = ExpectationFactory.build(
operator=self.h2_op,
backend=quantum_instance,
)
with self.subTest(msg="Test QuantumCircuit."):
self._run_test(
expected_result,
bound_ansatz,
decimal,
expectation,
observables,
quantum_instance,
)
with self.subTest(msg="Test QuantumCircuit with Backend."):
self._run_test(
expected_result,
bound_ansatz,
decimal,
expectation,
observables,
backend,
)
with self.subTest(msg="Test Statevector."):
statevector = Statevector(bound_ansatz)
self._run_test(
expected_result,
statevector,
decimal,
expectation,
observables,
quantum_instance,
)
with self.assertWarns(DeprecationWarning):
with self.subTest(msg="Test StateFn."):
statefn = StateFn(bound_ansatz)
self._run_test(
expected_result,
statefn,
decimal,
expectation,
observables,
quantum_instance,
)
if __name__ == "__main__":
unittest.main()
|
https://github.com/Chibikuri/qwopt
|
Chibikuri
|
from .ruleset import ruleset
from .converter import Converter
from qiskit import transpile
import sys
# FIXME out of pep write __init__.py
sys.path.append('../')
from compiler import parser
class Optimizer:
def __init__(self, graph, prob_dist):
pass
def optimize(self, qc, n_rules, config, **kwargs):
'''
qc: QuantumCircuit
n_rules: the number of rules
config: toml file
kwargs: optimization config
'''
# nqc = transpile(qc, basis_gates=['cx', 'u3'])
dag = Converter().converter(qc)
rule = ruleset.Rules(config)
errors = []
# FIXME detect the number of rules
for i in range(n_rules):
dag, success = eval('rule._rule%s(dag)' % str(i))
if not success:
errors.append(i)
if len(errors) == 0:
print('All optimization rules are applied successfully!')
else:
ms = str(errors)[1:-1]
print('Rules, %s are not applied for some reasons!' % ms)
|
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_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure(0, 0)
circ.measure(1, 1)
circ.draw('mpl')
from qiskit import pulse
from qiskit.pulse.library import Gaussian
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration('h', [0], h_q0)
from qiskit import transpile
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
circ = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ.draw('mpl', idle_wires=False)
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
circ = QuantumCircuit(1, 1)
custom_gate = Gate('my_custom_gate', 1, [3.14, 1])
# 3.14 is an arbitrary parameter for demonstration
circ.append(custom_gate, [0])
circ.measure(0, 0)
circ.draw('mpl')
with pulse.build(backend, name='custom') as my_schedule:
pulse.play(Gaussian(duration=64, amp=0.2, sigma=8), pulse.drive_channel(0))
circ.add_calibration('my_custom_gate', [0], my_schedule, [3.14, 1])
# Alternatively: circ.add_calibration(custom_gate, [0], my_schedule)
circ = transpile(circ, backend)
circ.draw('mpl', idle_wires=False)
circ = QuantumCircuit(2, 2)
circ.append(custom_gate, [1])
from qiskit import QiskitError
try:
circ = transpile(circ, backend)
except QiskitError as e:
print(e)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# 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=invalid-name
"""Tests for Operator matrix linear operator class."""
import unittest
import logging
import copy
from test import combine
import numpy as np
from ddt import ddt
from numpy.testing import assert_allclose
import scipy.linalg as la
from qiskit import QiskitError
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.library import HGate, CHGate, CXGate, QFT
from qiskit.test import QiskitTestCase
from qiskit.transpiler.layout import Layout, TranspileLayout
from qiskit.quantum_info.operators import Operator, ScalarOp
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.compiler.transpiler import transpile
from qiskit.circuit import Qubit
from qiskit.circuit.library import Permutation, PermutationGate
logger = logging.getLogger(__name__)
class OperatorTestCase(QiskitTestCase):
"""Test utils for Operator"""
# Pauli-matrix unitaries
UI = np.eye(2)
UX = np.array([[0, 1], [1, 0]])
UY = np.array([[0, -1j], [1j, 0]])
UZ = np.diag([1, -1])
UH = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
@classmethod
def rand_rho(cls, n):
"""Return random density matrix"""
seed = np.random.randint(0, np.iinfo(np.int32).max)
logger.debug("rand_rho default_rng seeded with seed=%s", seed)
rng = np.random.default_rng(seed)
psi = rng.random(n) + 1j * rng.random(n)
rho = np.outer(psi, psi.conj())
rho /= np.trace(rho)
return rho
@classmethod
def rand_matrix(cls, rows, cols=None, real=False):
"""Return a random matrix."""
seed = np.random.randint(0, np.iinfo(np.int32).max)
logger.debug("rand_matrix default_rng seeded with seed=%s", seed)
rng = np.random.default_rng(seed)
if cols is None:
cols = rows
if real:
return rng.random(size=(rows, cols))
return rng.random(size=(rows, cols)) + 1j * rng.random(size=(rows, cols))
def simple_circuit_no_measure(self):
"""Return a unitary circuit and the corresponding unitary array."""
qr = QuantumRegister(3)
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.x(qr[1])
circ.ry(np.pi / 2, qr[2])
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = Operator(np.kron(y90, np.kron(self.UX, self.UH)))
return circ, target
def simple_circuit_with_measure(self):
"""Return a unitary circuit with measurement."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circ = QuantumCircuit(qr, cr)
circ.h(qr[0])
circ.x(qr[1])
circ.measure(qr, cr)
return circ
@ddt
class TestOperator(OperatorTestCase):
"""Tests for Operator linear operator class."""
def test_init_array_qubit(self):
"""Test subsystem initialization from N-qubit array."""
# Test automatic inference of qubit subsystems
mat = self.rand_matrix(8, 8)
op = Operator(mat)
assert_allclose(op.data, mat)
self.assertEqual(op.dim, (8, 8))
self.assertEqual(op.input_dims(), (2, 2, 2))
self.assertEqual(op.output_dims(), (2, 2, 2))
self.assertEqual(op.num_qubits, 3)
op = Operator(mat, input_dims=8, output_dims=8)
assert_allclose(op.data, mat)
self.assertEqual(op.dim, (8, 8))
self.assertEqual(op.input_dims(), (2, 2, 2))
self.assertEqual(op.output_dims(), (2, 2, 2))
self.assertEqual(op.num_qubits, 3)
def test_init_array(self):
"""Test initialization from array."""
mat = np.eye(3)
op = Operator(mat)
assert_allclose(op.data, mat)
self.assertEqual(op.dim, (3, 3))
self.assertEqual(op.input_dims(), (3,))
self.assertEqual(op.output_dims(), (3,))
self.assertIsNone(op.num_qubits)
mat = self.rand_matrix(2 * 3 * 4, 4 * 5)
op = Operator(mat, input_dims=[4, 5], output_dims=[2, 3, 4])
assert_allclose(op.data, mat)
self.assertEqual(op.dim, (4 * 5, 2 * 3 * 4))
self.assertEqual(op.input_dims(), (4, 5))
self.assertEqual(op.output_dims(), (2, 3, 4))
self.assertIsNone(op.num_qubits)
def test_init_array_except(self):
"""Test initialization exception from array."""
mat = self.rand_matrix(4, 4)
self.assertRaises(QiskitError, Operator, mat, input_dims=[4, 2])
self.assertRaises(QiskitError, Operator, mat, input_dims=[2, 4])
self.assertRaises(QiskitError, Operator, mat, input_dims=5)
def test_init_operator(self):
"""Test initialization from Operator."""
op1 = Operator(self.rand_matrix(4, 4))
op2 = Operator(op1)
self.assertEqual(op1, op2)
def test_circuit_init(self):
"""Test initialization from a circuit."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
op = Operator(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 0, 1)
op = Operator(circuit)
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(0, 1)
op = Operator(circuit)
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_instruction_init(self):
"""Test initialization from a circuit."""
gate = CXGate()
op = Operator(gate).data
target = gate.to_matrix()
global_phase_equivalent = matrix_equal(op, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
gate = CHGate()
op = Operator(gate).data
had = HGate().to_matrix()
target = np.kron(had, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0]))
global_phase_equivalent = matrix_equal(op, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Operator, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(2, 2, real=True)
self.assertEqual(Operator(np.array(mat, dtype=complex)), Operator(mat))
mat = self.rand_matrix(4, 4)
self.assertEqual(Operator(mat.tolist()), Operator(mat))
def test_data(self):
"""Test Operator representation string property."""
mat = self.rand_matrix(2, 2)
op = Operator(mat)
assert_allclose(mat, op.data)
def test_to_matrix(self):
"""Test Operator to_matrix method."""
mat = self.rand_matrix(2, 2)
op = Operator(mat)
assert_allclose(mat, op.to_matrix())
def test_dim(self):
"""Test Operator dim property."""
mat = self.rand_matrix(4, 4)
self.assertEqual(Operator(mat).dim, (4, 4))
self.assertEqual(Operator(mat, input_dims=[4], output_dims=[4]).dim, (4, 4))
self.assertEqual(Operator(mat, input_dims=[2, 2], output_dims=[2, 2]).dim, (4, 4))
def test_input_dims(self):
"""Test Operator input_dims method."""
op = Operator(self.rand_matrix(2 * 3 * 4, 4 * 5), input_dims=[4, 5], output_dims=[2, 3, 4])
self.assertEqual(op.input_dims(), (4, 5))
self.assertEqual(op.input_dims(qargs=[0, 1]), (4, 5))
self.assertEqual(op.input_dims(qargs=[1, 0]), (5, 4))
self.assertEqual(op.input_dims(qargs=[0]), (4,))
self.assertEqual(op.input_dims(qargs=[1]), (5,))
def test_output_dims(self):
"""Test Operator output_dims method."""
op = Operator(self.rand_matrix(2 * 3 * 4, 4 * 5), input_dims=[4, 5], output_dims=[2, 3, 4])
self.assertEqual(op.output_dims(), (2, 3, 4))
self.assertEqual(op.output_dims(qargs=[0, 1, 2]), (2, 3, 4))
self.assertEqual(op.output_dims(qargs=[2, 1, 0]), (4, 3, 2))
self.assertEqual(op.output_dims(qargs=[2, 0, 1]), (4, 2, 3))
self.assertEqual(op.output_dims(qargs=[0]), (2,))
self.assertEqual(op.output_dims(qargs=[1]), (3,))
self.assertEqual(op.output_dims(qargs=[2]), (4,))
self.assertEqual(op.output_dims(qargs=[0, 2]), (2, 4))
self.assertEqual(op.output_dims(qargs=[2, 0]), (4, 2))
def test_reshape(self):
"""Test Operator reshape method."""
op = Operator(self.rand_matrix(8, 8))
reshaped1 = op.reshape(input_dims=[8], output_dims=[8])
reshaped2 = op.reshape(input_dims=[4, 2], output_dims=[2, 4])
self.assertEqual(op.output_dims(), (2, 2, 2))
self.assertEqual(op.input_dims(), (2, 2, 2))
self.assertEqual(reshaped1.output_dims(), (8,))
self.assertEqual(reshaped1.input_dims(), (8,))
self.assertEqual(reshaped2.output_dims(), (2, 4))
self.assertEqual(reshaped2.input_dims(), (4, 2))
def test_reshape_num_qubits(self):
"""Test Operator reshape method with num_qubits."""
op = Operator(self.rand_matrix(8, 8), input_dims=(4, 2), output_dims=(2, 4))
reshaped = op.reshape(num_qubits=3)
self.assertEqual(reshaped.num_qubits, 3)
self.assertEqual(reshaped.output_dims(), (2, 2, 2))
self.assertEqual(reshaped.input_dims(), (2, 2, 2))
def test_reshape_raise(self):
"""Test Operator reshape method with invalid args."""
op = Operator(self.rand_matrix(3, 3))
self.assertRaises(QiskitError, op.reshape, num_qubits=2)
def test_copy(self):
"""Test Operator copy method"""
mat = np.eye(2)
with self.subTest("Deep copy"):
orig = Operator(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Operator(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_unitary(self):
"""Test is_unitary method."""
# X-90 rotation
X90 = la.expm(-1j * 0.5 * np.pi * np.array([[0, 1], [1, 0]]) / 2)
self.assertTrue(Operator(X90).is_unitary())
# Non-unitary should return false
self.assertFalse(Operator([[1, 0], [0, 0]]).is_unitary())
def test_to_operator(self):
"""Test to_operator method."""
op1 = Operator(self.rand_matrix(4, 4))
op2 = op1.to_operator()
self.assertEqual(op1, op2)
def test_conjugate(self):
"""Test conjugate method."""
matr = self.rand_matrix(2, 4, real=True)
mati = self.rand_matrix(2, 4, real=True)
op = Operator(matr + 1j * mati)
uni_conj = op.conjugate()
self.assertEqual(uni_conj, Operator(matr - 1j * mati))
def test_transpose(self):
"""Test transpose method."""
matr = self.rand_matrix(2, 4, real=True)
mati = self.rand_matrix(2, 4, real=True)
op = Operator(matr + 1j * mati)
uni_t = op.transpose()
self.assertEqual(uni_t, Operator(matr.T + 1j * mati.T))
def test_adjoint(self):
"""Test adjoint method."""
matr = self.rand_matrix(2, 4, real=True)
mati = self.rand_matrix(2, 4, real=True)
op = Operator(matr + 1j * mati)
uni_adj = op.adjoint()
self.assertEqual(uni_adj, Operator(matr.T - 1j * mati.T))
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Operator(np.eye(2)).compose, Operator(np.eye(3)))
self.assertRaises(QiskitError, Operator(np.eye(2)).compose, 2)
def test_compose(self):
"""Test compose method."""
op1 = Operator(self.UX)
op2 = Operator(self.UY)
targ = Operator(np.dot(self.UY, self.UX))
self.assertEqual(op1.compose(op2), targ)
self.assertEqual(op1 & op2, targ)
targ = Operator(np.dot(self.UX, self.UY))
self.assertEqual(op2.compose(op1), targ)
self.assertEqual(op2 & op1, targ)
def test_dot(self):
"""Test dot method."""
op1 = Operator(self.UY)
op2 = Operator(self.UX)
targ = Operator(np.dot(self.UY, self.UX))
self.assertEqual(op1.dot(op2), targ)
self.assertEqual(op1 @ op2, targ)
targ = Operator(np.dot(self.UX, self.UY))
self.assertEqual(op2.dot(op1), targ)
self.assertEqual(op2 @ op1, targ)
def test_compose_front(self):
"""Test front compose method."""
opYX = Operator(self.UY).compose(Operator(self.UX), front=True)
matYX = np.dot(self.UY, self.UX)
self.assertEqual(opYX, Operator(matYX))
opXY = Operator(self.UX).compose(Operator(self.UY), front=True)
matXY = np.dot(self.UX, self.UY)
self.assertEqual(opXY, Operator(matXY))
def test_compose_subsystem(self):
"""Test subsystem compose method."""
# 3-qubit operator
mat = self.rand_matrix(8, 8)
mat_a = self.rand_matrix(2, 2)
mat_b = self.rand_matrix(2, 2)
mat_c = self.rand_matrix(2, 2)
op = Operator(mat)
op1 = Operator(mat_a)
op2 = Operator(np.kron(mat_b, mat_a))
op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a)))
# op3 qargs=[0, 1, 2]
targ = np.dot(np.kron(mat_c, np.kron(mat_b, mat_a)), mat)
self.assertEqual(op.compose(op3, qargs=[0, 1, 2]), Operator(targ))
self.assertEqual(op.compose(op3([0, 1, 2])), Operator(targ))
self.assertEqual(op & op3([0, 1, 2]), Operator(targ))
# op3 qargs=[2, 1, 0]
targ = np.dot(np.kron(mat_a, np.kron(mat_b, mat_c)), mat)
self.assertEqual(op.compose(op3, qargs=[2, 1, 0]), Operator(targ))
self.assertEqual(op & op3([2, 1, 0]), Operator(targ))
# op2 qargs=[0, 1]
targ = np.dot(np.kron(np.eye(2), np.kron(mat_b, mat_a)), mat)
self.assertEqual(op.compose(op2, qargs=[0, 1]), Operator(targ))
self.assertEqual(op & op2([0, 1]), Operator(targ))
# op2 qargs=[2, 0]
targ = np.dot(np.kron(mat_a, np.kron(np.eye(2), mat_b)), mat)
self.assertEqual(op.compose(op2, qargs=[2, 0]), Operator(targ))
self.assertEqual(op & op2([2, 0]), Operator(targ))
# op1 qargs=[0]
targ = np.dot(np.kron(np.eye(4), mat_a), mat)
self.assertEqual(op.compose(op1, qargs=[0]), Operator(targ))
self.assertEqual(op & op1([0]), Operator(targ))
# op1 qargs=[1]
targ = np.dot(np.kron(np.eye(2), np.kron(mat_a, np.eye(2))), mat)
self.assertEqual(op.compose(op1, qargs=[1]), Operator(targ))
self.assertEqual(op & op1([1]), Operator(targ))
# op1 qargs=[2]
targ = np.dot(np.kron(mat_a, np.eye(4)), mat)
self.assertEqual(op.compose(op1, qargs=[2]), Operator(targ))
self.assertEqual(op & op1([2]), Operator(targ))
def test_dot_subsystem(self):
"""Test subsystem dot method."""
# 3-qubit operator
mat = self.rand_matrix(8, 8)
mat_a = self.rand_matrix(2, 2)
mat_b = self.rand_matrix(2, 2)
mat_c = self.rand_matrix(2, 2)
op = Operator(mat)
op1 = Operator(mat_a)
op2 = Operator(np.kron(mat_b, mat_a))
op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a)))
# op3 qargs=[0, 1, 2]
targ = np.dot(mat, np.kron(mat_c, np.kron(mat_b, mat_a)))
self.assertEqual(op.dot(op3, qargs=[0, 1, 2]), Operator(targ))
self.assertEqual(op.dot(op3([0, 1, 2])), Operator(targ))
# op3 qargs=[2, 1, 0]
targ = np.dot(mat, np.kron(mat_a, np.kron(mat_b, mat_c)))
self.assertEqual(op.dot(op3, qargs=[2, 1, 0]), Operator(targ))
self.assertEqual(op.dot(op3([2, 1, 0])), Operator(targ))
# op2 qargs=[0, 1]
targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_b, mat_a)))
self.assertEqual(op.dot(op2, qargs=[0, 1]), Operator(targ))
self.assertEqual(op.dot(op2([0, 1])), Operator(targ))
# op2 qargs=[2, 0]
targ = np.dot(mat, np.kron(mat_a, np.kron(np.eye(2), mat_b)))
self.assertEqual(op.dot(op2, qargs=[2, 0]), Operator(targ))
self.assertEqual(op.dot(op2([2, 0])), Operator(targ))
# op1 qargs=[0]
targ = np.dot(mat, np.kron(np.eye(4), mat_a))
self.assertEqual(op.dot(op1, qargs=[0]), Operator(targ))
self.assertEqual(op.dot(op1([0])), Operator(targ))
# op1 qargs=[1]
targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_a, np.eye(2))))
self.assertEqual(op.dot(op1, qargs=[1]), Operator(targ))
self.assertEqual(op.dot(op1([1])), Operator(targ))
# op1 qargs=[2]
targ = np.dot(mat, np.kron(mat_a, np.eye(4)))
self.assertEqual(op.dot(op1, qargs=[2]), Operator(targ))
self.assertEqual(op.dot(op1([2])), Operator(targ))
def test_compose_front_subsystem(self):
"""Test subsystem front compose method."""
# 3-qubit operator
mat = self.rand_matrix(8, 8)
mat_a = self.rand_matrix(2, 2)
mat_b = self.rand_matrix(2, 2)
mat_c = self.rand_matrix(2, 2)
op = Operator(mat)
op1 = Operator(mat_a)
op2 = Operator(np.kron(mat_b, mat_a))
op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a)))
# op3 qargs=[0, 1, 2]
targ = np.dot(mat, np.kron(mat_c, np.kron(mat_b, mat_a)))
self.assertEqual(op.compose(op3, qargs=[0, 1, 2], front=True), Operator(targ))
# op3 qargs=[2, 1, 0]
targ = np.dot(mat, np.kron(mat_a, np.kron(mat_b, mat_c)))
self.assertEqual(op.compose(op3, qargs=[2, 1, 0], front=True), Operator(targ))
# op2 qargs=[0, 1]
targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_b, mat_a)))
self.assertEqual(op.compose(op2, qargs=[0, 1], front=True), Operator(targ))
# op2 qargs=[2, 0]
targ = np.dot(mat, np.kron(mat_a, np.kron(np.eye(2), mat_b)))
self.assertEqual(op.compose(op2, qargs=[2, 0], front=True), Operator(targ))
# op1 qargs=[0]
targ = np.dot(mat, np.kron(np.eye(4), mat_a))
self.assertEqual(op.compose(op1, qargs=[0], front=True), Operator(targ))
# op1 qargs=[1]
targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_a, np.eye(2))))
self.assertEqual(op.compose(op1, qargs=[1], front=True), Operator(targ))
# op1 qargs=[2]
targ = np.dot(mat, np.kron(mat_a, np.eye(4)))
self.assertEqual(op.compose(op1, qargs=[2], front=True), Operator(targ))
def test_power(self):
"""Test power method."""
X90 = la.expm(-1j * 0.5 * np.pi * np.array([[0, 1], [1, 0]]) / 2)
op = Operator(X90)
self.assertEqual(op.power(2), Operator([[0, -1j], [-1j, 0]]))
self.assertEqual(op.power(4), Operator(-1 * np.eye(2)))
self.assertEqual(op.power(8), Operator(np.eye(2)))
def test_expand(self):
"""Test expand method."""
mat1 = self.UX
mat2 = np.eye(3, dtype=complex)
mat21 = np.kron(mat2, mat1)
op21 = Operator(mat1).expand(Operator(mat2))
self.assertEqual(op21.dim, (6, 6))
assert_allclose(op21.data, Operator(mat21).data)
mat12 = np.kron(mat1, mat2)
op12 = Operator(mat2).expand(Operator(mat1))
self.assertEqual(op12.dim, (6, 6))
assert_allclose(op12.data, Operator(mat12).data)
def test_tensor(self):
"""Test tensor method."""
mat1 = self.UX
mat2 = np.eye(3, dtype=complex)
mat21 = np.kron(mat2, mat1)
op21 = Operator(mat2).tensor(Operator(mat1))
self.assertEqual(op21.dim, (6, 6))
assert_allclose(op21.data, Operator(mat21).data)
mat12 = np.kron(mat1, mat2)
op12 = Operator(mat1).tensor(Operator(mat2))
self.assertEqual(op12.dim, (6, 6))
assert_allclose(op12.data, Operator(mat12).data)
def test_power_except(self):
"""Test power method raises exceptions if not square."""
op = Operator(self.rand_matrix(2, 3))
# Non-integer power raises error
self.assertRaises(QiskitError, op.power, 0.5)
def test_add(self):
"""Test add method."""
mat1 = self.rand_matrix(4, 4)
mat2 = self.rand_matrix(4, 4)
op1 = Operator(mat1)
op2 = Operator(mat2)
self.assertEqual(op1._add(op2), Operator(mat1 + mat2))
self.assertEqual(op1 + op2, Operator(mat1 + mat2))
self.assertEqual(op1 - op2, Operator(mat1 - mat2))
def test_add_except(self):
"""Test add method raises exceptions."""
op1 = Operator(self.rand_matrix(2, 2))
op2 = Operator(self.rand_matrix(3, 3))
self.assertRaises(QiskitError, op1._add, op2)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8, 8)
mat0 = self.rand_matrix(2, 2)
mat1 = self.rand_matrix(2, 2)
op = Operator(mat)
op0 = Operator(mat0)
op01 = Operator(np.kron(mat1, mat0))
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + Operator(np.kron(np.eye(4), mat0))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + Operator(np.kron(np.kron(np.eye(2), mat0), np.eye(2)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + Operator(np.kron(mat0, np.eye(4)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + Operator(np.kron(np.eye(2), np.kron(mat1, mat0)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + Operator(np.kron(np.eye(2), np.kron(mat0, mat1)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + Operator(np.kron(mat1, np.kron(np.eye(2), mat0)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + Operator(np.kron(mat0, np.kron(np.eye(2), mat1)))
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8, 8)
mat0 = self.rand_matrix(2, 2)
mat1 = self.rand_matrix(2, 2)
op = Operator(mat)
op0 = Operator(mat0)
op01 = Operator(np.kron(mat1, mat0))
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - Operator(np.kron(np.eye(4), mat0))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - Operator(np.kron(np.kron(np.eye(2), mat0), np.eye(2)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - Operator(np.kron(mat0, np.eye(4)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - Operator(np.kron(np.eye(2), np.kron(mat1, mat0)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - Operator(np.kron(np.eye(2), np.kron(mat0, mat1)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - Operator(np.kron(mat1, np.kron(np.eye(2), mat0)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - Operator(np.kron(mat0, np.kron(np.eye(2), mat1)))
self.assertEqual(value, target)
def test_multiply(self):
"""Test multiply method."""
mat = self.rand_matrix(4, 4)
val = np.exp(5j)
op = Operator(mat)
self.assertEqual(op._multiply(val), Operator(val * mat))
self.assertEqual(val * op, Operator(val * mat))
self.assertEqual(op * val, Operator(mat * val))
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
op = Operator(self.rand_matrix(2, 2))
self.assertRaises(QiskitError, op._multiply, "s")
self.assertRaises(QiskitError, op.__rmul__, "s")
self.assertRaises(QiskitError, op._multiply, op)
self.assertRaises(QiskitError, op.__rmul__, op)
def test_negate(self):
"""Test negate method"""
mat = self.rand_matrix(4, 4)
op = Operator(mat)
self.assertEqual(-op, Operator(-1 * mat))
def test_equiv(self):
"""Test negate method"""
mat = np.diag([1, np.exp(1j * np.pi / 2)])
phase = np.exp(-1j * np.pi / 4)
op = Operator(mat)
self.assertTrue(op.equiv(phase * mat))
self.assertTrue(op.equiv(Operator(phase * mat)))
self.assertFalse(op.equiv(2 * mat))
def test_reverse_qargs(self):
"""Test reverse_qargs method"""
circ1 = QFT(5)
circ2 = circ1.reverse_bits()
state1 = Operator(circ1)
state2 = Operator(circ2)
self.assertEqual(state1.reverse_qargs(), state2)
def test_drawings(self):
"""Test draw method"""
qc1 = QFT(5)
op = Operator.from_circuit(qc1)
with self.subTest(msg="str(operator)"):
str(op)
for drawtype in ["repr", "text", "latex_source"]:
with self.subTest(msg=f"draw('{drawtype}')"):
op.draw(drawtype)
with self.subTest(msg=" draw('latex')"):
op.draw("latex")
def test_from_circuit_constructor_no_layout(self):
"""Test initialization from a circuit using the from_circuit constructor."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
op = Operator.from_circuit(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 0, 1)
op = Operator.from_circuit(circuit)
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(0, 1)
op = Operator.from_circuit(circuit)
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout(self):
"""Test initialization from a circuit with an embedded reverse layout."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 1, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit)
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(1, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit)
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_from_transpile(self):
"""Test initialization from a circuit with an embedded final layout."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
output = transpile(circuit, initial_layout=[2, 1, 0])
op = Operator.from_circuit(output)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_from_transpile_with_registers(self):
"""Test initialization from a circuit with an embedded final layout."""
# Test tensor product of 1-qubit gates
qr = QuantumRegister(3, name="test_reg")
circuit = QuantumCircuit(qr)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
output = transpile(circuit, initial_layout=[2, 1, 0])
op = Operator.from_circuit(output)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_and_final_layout(self):
"""Test initialization from a circuit with an embedded final layout."""
# Test tensor product of 1-qubit gates
qr = QuantumRegister(3, name="test_reg")
circuit = QuantumCircuit(qr)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
Layout({circuit.qubits[0]: 1, circuit.qubits[1]: 2, circuit.qubits[2]: 0}),
)
circuit.swap(0, 1)
circuit.swap(1, 2)
op = Operator.from_circuit(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_and_manual_final_layout(self):
"""Test initialization from a circuit with an embedded final layout."""
# Test tensor product of 1-qubit gates
qr = QuantumRegister(3, name="test_reg")
circuit = QuantumCircuit(qr)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
final_layout = Layout({circuit.qubits[0]: 1, circuit.qubits[1]: 2, circuit.qubits[2]: 0})
circuit.swap(0, 1)
circuit.swap(1, 2)
op = Operator.from_circuit(circuit, final_layout=final_layout)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_ignore_set_layout(self):
"""Test initialization from a circuit with an ignored embedded reverse layout."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs()
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 1, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs()
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(1, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs()
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_user_specified_layout(self):
"""Test initialization from a circuit with a user specified reverse layout."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
layout = Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2})
op = Operator.from_circuit(circuit, layout=layout)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 1, 0)
layout = Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1})
op = Operator.from_circuit(circuit, layout=layout)
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(1, 0)
layout = Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1})
op = Operator.from_circuit(circuit, layout=layout)
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_ghz_out_of_order_layout(self):
"""Test an out of order ghz state with a layout set."""
circuit = QuantumCircuit(5)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
circuit._layout = TranspileLayout(
Layout(
{
circuit.qubits[3]: 0,
circuit.qubits[4]: 1,
circuit.qubits[2]: 2,
circuit.qubits[0]: 3,
circuit.qubits[1]: 4,
}
),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
result = Operator.from_circuit(circuit)
expected = QuantumCircuit(5)
expected.h(0)
expected.cx(0, 1)
expected.cx(0, 2)
expected.cx(0, 3)
expected.cx(0, 4)
expected_op = Operator(expected)
self.assertTrue(expected_op.equiv(result))
def test_from_circuit_empty_circuit_empty_layout(self):
"""Test an out of order ghz state with a layout set."""
circuit = QuantumCircuit()
circuit._layout = TranspileLayout(Layout(), {})
op = Operator.from_circuit(circuit)
self.assertEqual(Operator([1]), op)
def test_from_circuit_constructor_empty_layout(self):
"""Test an out of order ghz state with a layout set."""
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
layout = Layout()
with self.assertRaises(IndexError):
Operator.from_circuit(circuit, layout=layout)
def test_compose_scalar(self):
"""Test that composition works with a scalar-valued operator over no qubits."""
base = Operator(np.eye(2, dtype=np.complex128))
scalar = Operator(np.array([[-1.0 + 0.0j]]))
composed = base.compose(scalar, qargs=[])
self.assertEqual(composed, Operator(-np.eye(2, dtype=np.complex128)))
def test_compose_scalar_op(self):
"""Test that composition works with an explicit scalar operator over no qubits."""
base = Operator(np.eye(2, dtype=np.complex128))
scalar = ScalarOp(coeff=-1.0 + 0.0j)
composed = base.compose(scalar, qargs=[])
self.assertEqual(composed, Operator(-np.eye(2, dtype=np.complex128)))
def test_from_circuit_single_flat_default_register_transpiled(self):
"""Test a transpiled circuit with layout set from default register."""
circuit = QuantumCircuit(5)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
init_layout = Layout(
{
circuit.qubits[0]: 3,
circuit.qubits[1]: 4,
circuit.qubits[2]: 1,
circuit.qubits[3]: 2,
circuit.qubits[4]: 0,
}
)
tqc = transpile(circuit, initial_layout=init_layout)
result = Operator.from_circuit(tqc)
self.assertTrue(Operator.from_circuit(circuit).equiv(result))
def test_from_circuit_loose_bits_transpiled(self):
"""Test a transpiled circuit with layout set from loose bits."""
bits = [Qubit() for _ in range(5)]
circuit = QuantumCircuit()
circuit.add_bits(bits)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
init_layout = Layout(
{
circuit.qubits[0]: 3,
circuit.qubits[1]: 4,
circuit.qubits[2]: 1,
circuit.qubits[3]: 2,
circuit.qubits[4]: 0,
}
)
tqc = transpile(circuit, initial_layout=init_layout)
result = Operator.from_circuit(tqc)
self.assertTrue(Operator(circuit).equiv(result))
def test_from_circuit_multiple_registers_bits_transpiled(self):
"""Test a transpiled circuit with layout set from loose bits."""
regs = [QuantumRegister(1, name=f"custom_reg-{i}") for i in range(5)]
circuit = QuantumCircuit()
for reg in regs:
circuit.add_register(reg)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
tqc = transpile(circuit, initial_layout=[3, 4, 1, 2, 0])
result = Operator.from_circuit(tqc)
self.assertTrue(Operator(circuit).equiv(result))
def test_from_circuit_single_flat_custom_register_transpiled(self):
"""Test a transpiled circuit with layout set from loose bits."""
circuit = QuantumCircuit(QuantumRegister(5, name="custom_reg"))
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
tqc = transpile(circuit, initial_layout=[3, 4, 1, 2, 0])
result = Operator.from_circuit(tqc)
self.assertTrue(Operator(circuit).equiv(result))
def test_from_circuit_mixed_reg_loose_bits_transpiled(self):
"""Test a transpiled circuit with layout set from loose bits."""
bits = [Qubit(), Qubit()]
circuit = QuantumCircuit()
circuit.add_bits(bits)
circuit.add_register(QuantumRegister(3, name="a_reg"))
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
init_layout = Layout(
{
circuit.qubits[0]: 3,
circuit.qubits[1]: 4,
circuit.qubits[2]: 1,
circuit.qubits[3]: 2,
circuit.qubits[4]: 0,
}
)
tqc = transpile(circuit, initial_layout=init_layout)
result = Operator.from_circuit(tqc)
self.assertTrue(Operator(circuit).equiv(result))
def test_apply_permutation_back(self):
"""Test applying permutation to the operator,
where the operator is applied first and the permutation second."""
op = Operator(self.rand_matrix(64, 64))
pattern = [1, 2, 0, 3, 5, 4]
# Consider several methods of computing this operator and show
# they all lead to the same result.
# Compose the operator with the operator constructed from the
# permutation circuit.
op2 = op.copy()
perm_op = Operator(Permutation(6, pattern))
op2 &= perm_op
# Compose the operator with the operator constructed from the
# permutation gate.
op3 = op.copy()
perm_op = Operator(PermutationGate(pattern))
op3 &= perm_op
# Modify the operator using apply_permutation method.
op4 = op.copy()
op4 = op4.apply_permutation(pattern, front=False)
self.assertEqual(op2, op3)
self.assertEqual(op2, op4)
def test_apply_permutation_front(self):
"""Test applying permutation to the operator,
where the permutation is applied first and the operator second"""
op = Operator(self.rand_matrix(64, 64))
pattern = [1, 2, 0, 3, 5, 4]
# Consider several methods of computing this operator and show
# they all lead to the same result.
# Compose the operator with the operator constructed from the
# permutation circuit.
op2 = op.copy()
perm_op = Operator(Permutation(6, pattern))
op2 = perm_op & op2
# Compose the operator with the operator constructed from the
# permutation gate.
op3 = op.copy()
perm_op = Operator(PermutationGate(pattern))
op3 = perm_op & op3
# Modify the operator using apply_permutation method.
op4 = op.copy()
op4 = op4.apply_permutation(pattern, front=True)
self.assertEqual(op2, op3)
self.assertEqual(op2, op4)
def test_apply_permutation_qudits_back(self):
"""Test applying permutation to the operator with heterogeneous qudit spaces,
where the operator O is applied first and the permutation P second.
The matrix of the resulting operator is the product [P][O] and
corresponds to suitably permuting the rows of O's matrix.
"""
mat = np.array(range(6 * 6)).reshape((6, 6))
op = Operator(mat, input_dims=(2, 3), output_dims=(2, 3))
perm = [1, 0]
actual = op.apply_permutation(perm, front=False)
# Rows of mat are ordered to 00, 01, 02, 10, 11, 12;
# perm maps these to 00, 10, 20, 01, 11, 21,
# while the default ordering is 00, 01, 10, 11, 20, 21.
permuted_mat = mat.copy()[[0, 2, 4, 1, 3, 5]]
expected = Operator(permuted_mat, input_dims=(2, 3), output_dims=(3, 2))
self.assertEqual(actual, expected)
def test_apply_permutation_qudits_front(self):
"""Test applying permutation to the operator with heterogeneous qudit spaces,
where the permutation P is applied first and the operator O is applied second.
The matrix of the resulting operator is the product [O][P] and
corresponds to suitably permuting the columns of O's matrix.
"""
mat = np.array(range(6 * 6)).reshape((6, 6))
op = Operator(mat, input_dims=(2, 3), output_dims=(2, 3))
perm = [1, 0]
actual = op.apply_permutation(perm, front=True)
# Columns of mat are ordered to 00, 01, 02, 10, 11, 12;
# perm maps these to 00, 10, 20, 01, 11, 21,
# while the default ordering is 00, 01, 10, 11, 20, 21.
permuted_mat = mat.copy()[:, [0, 2, 4, 1, 3, 5]]
expected = Operator(permuted_mat, input_dims=(3, 2), output_dims=(2, 3))
self.assertEqual(actual, expected)
@combine(
dims=((2, 3, 4, 5), (5, 2, 4, 3), (3, 5, 2, 4), (5, 3, 4, 2), (4, 5, 2, 3), (4, 3, 2, 5))
)
def test_reverse_qargs_as_apply_permutation(self, dims):
"""Test reversing qargs by pre- and post-composing with reversal
permutation.
"""
perm = [3, 2, 1, 0]
op = Operator(
np.array(range(120 * 120)).reshape((120, 120)), input_dims=dims, output_dims=dims
)
op2 = op.reverse_qargs()
op3 = op.apply_permutation(perm, front=True).apply_permutation(perm, front=False)
self.assertEqual(op2, op3)
def test_apply_permutation_exceptions(self):
"""Checks that applying permutation raises an error when dimensions do not match."""
op = Operator(
np.array(range(24 * 30)).reshape((24, 30)), input_dims=(6, 5), output_dims=(2, 3, 4)
)
with self.assertRaises(QiskitError):
op.apply_permutation([1, 0], front=False)
with self.assertRaises(QiskitError):
op.apply_permutation([2, 1, 0], front=True)
def test_apply_permutation_dimensions(self):
"""Checks the dimensions of the operator after applying permutation."""
op = Operator(
np.array(range(24 * 30)).reshape((24, 30)), input_dims=(6, 5), output_dims=(2, 3, 4)
)
op2 = op.apply_permutation([1, 2, 0], front=False)
self.assertEqual(op2.output_dims(), (4, 2, 3))
op = Operator(
np.array(range(24 * 30)).reshape((30, 24)), input_dims=(2, 3, 4), output_dims=(6, 5)
)
op2 = op.apply_permutation([2, 0, 1], front=True)
self.assertEqual(op2.input_dims(), (4, 2, 3))
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeManilaV2
from qiskit import transpile
from qiskit.tools.visualization import plot_histogram
# Get a fake backend from the fake provider
backend = FakeManilaV2()
# Create a simple circuit
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(0,2)
circuit.measure_all()
circuit.draw('mpl')
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(circuit, backend)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated fake backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
"""
StatePreparation test.
"""
import unittest
import math
import numpy as np
from ddt import ddt, data
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import Statevector, Operator
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
from qiskit.circuit.library import StatePreparation
@ddt
class TestStatePreparation(QiskitTestCase):
"""Test initialization with StatePreparation class"""
def test_prepare_from_label(self):
"""Prepare state from label."""
desired_sv = Statevector.from_label("01+-lr")
qc = QuantumCircuit(6)
qc.prepare_state("01+-lr", range(6))
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_prepare_from_int(self):
"""Prepare state from int."""
desired_sv = Statevector.from_label("110101")
qc = QuantumCircuit(6)
qc.prepare_state(53, range(6))
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_prepare_from_list(self):
"""Prepare state from list."""
desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc = QuantumCircuit(2)
qc.prepare_state([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_prepare_single_qubit(self):
"""Prepare state in single qubit."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
circuit.prepare_state([1 / math.sqrt(2), 1 / math.sqrt(2)], qreg[1])
expected = QuantumCircuit(qreg)
expected.prepare_state([1 / math.sqrt(2), 1 / math.sqrt(2)], [qreg[1]])
self.assertEqual(circuit, expected)
def test_nonzero_state_incorrect(self):
"""Test final state incorrect if initial state not zero"""
desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc = QuantumCircuit(2)
qc.x(0)
qc.prepare_state([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
actual_sv = Statevector(qc)
self.assertFalse(desired_sv == actual_sv)
@data(2, "11", [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
def test_inverse(self, state):
"""Test inverse of StatePreparation"""
qc = QuantumCircuit(2)
stateprep = StatePreparation(state)
qc.append(stateprep, [0, 1])
qc.append(stateprep.inverse(), [0, 1])
self.assertTrue(np.allclose(Operator(qc).data, np.identity(2**qc.num_qubits)))
def test_double_inverse(self):
"""Test twice inverse of StatePreparation"""
desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc = QuantumCircuit(2)
stateprep = StatePreparation([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc.append(stateprep.inverse().inverse(), [0, 1])
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_incompatible_state_and_qubit_args(self):
"""Test error raised if number of qubits not compatible with state arg"""
qc = QuantumCircuit(3)
with self.assertRaises(QiskitError):
qc.prepare_state("11")
def test_incompatible_int_state_and_qubit_args(self):
"""Test error raised if number of qubits not compatible with integer state arg"""
# pylint: disable=pointless-statement
with self.assertRaises(QiskitError):
stateprep = StatePreparation(5, num_qubits=2)
stateprep.definition
def test_int_state_and_no_qubit_args(self):
"""Test automatic determination of qubit number"""
stateprep = StatePreparation(5)
self.assertEqual(stateprep.num_qubits, 3)
def test_repeats(self):
"""Test repeat function repeats correctly"""
qc = QuantumCircuit(2)
qc.append(StatePreparation("01").repeat(2), [0, 1])
self.assertEqual(qc.decompose().count_ops()["state_preparation"], 2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/C2QA/bosonic-qiskit
|
C2QA
|
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa.
import os
import sys
module_path = os.path.abspath(os.path.join("../.."))
if module_path not in sys.path:
sys.path.append(module_path)
import c2qa
import numpy as np
import qiskit
# Define Hamiltonian parameters
omega_R = 2
omega_Q = 5
chi = 0.1
from qiskit.circuit import Parameter
# Set number of qubits per qumode
num_qubits_per_qumode = 3
# Define parameter dt
dt = Parameter('dt')
# Create new circuit
qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode)
qbr = qiskit.QuantumRegister(1)
U_JC = c2qa.CVCircuit(qmr,qbr)
# Append U_R
U_JC.cv_r(-omega_R*dt,qmr[0])
# Append U_Q
U_JC.rz(omega_Q*dt,qbr[0])
# Append U_\chi -- KS: this needs to be updated to reflect naming conventions in manuscript
U_JC.cv_c_r(-chi*dt/2,qmr[0],qbr[0])
# Compile this circuit into a single parameterized gate
U_JC = U_JC.to_gate(label='U_JC')
qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode)
qbr = qiskit.QuantumRegister(1)
# Instantiate the circuit and initialize the qubit to the '+' state.
circuit = c2qa.CVCircuit(qmr,qbr)
circuit.initialize([1/np.sqrt(2), 1/np.sqrt(2)], qbr)
# Append the time evolution unitary
circuit.append(U_JC,qmr[0] + [qbr[0]]);
# Draw the circuit
circuit.decompose().draw(output='mpl')
I_qumode = circuit.ops.get_eye(qmr.cutoff).toarray()
sigmax = np.kron(np.array([[0, 1], [1, 0]]), I_qumode)
sigmaz = np.kron(np.array([[1, 0], [0, -1]]), I_qumode)
# First construct operator sigma^x. First, we need to retrieve the identity operator over the qumode. As its dimensionality is
# dependent upon the cutoff, the easiest way to do this is to use
tarray = np.linspace(0,3*2*np.pi/omega_Q,100)
sigma_x_expectation = []
sigma_z_expectation = []
for tau in tarray:
state, result, _ = c2qa.util.simulate(circuit.assign_parameters({dt : tau}))
sigma_x_expectation.append(state.expectation_value(sigmax).real)
sigma_z_expectation.append(state.expectation_value(sigmaz).real)
import matplotlib.pyplot as plt
fontsize = 20
plt.figure(figsize=(15,4))
plt.subplot(1,2,1)
plt.plot(tarray/(2*np.pi/omega_Q),sigma_x_expectation,linewidth=2)
plt.ylabel(r'$\langle\sigma^x\rangle$',fontsize=fontsize,usetex=True);
plt.xlabel(r'$t$ $(2\pi/\omega_Q)$',fontsize=fontsize,usetex=True);
plt.xlim([0,3]);
plt.ylim([-1.05,1.05]);
plt.subplot(1,2,2)
plt.plot(tarray/(2*np.pi/omega_Q),sigma_z_expectation,linewidth=2,color='tab:red')
plt.ylabel(r'$\langle\sigma^z\rangle$',fontsize=fontsize,usetex=True);
plt.xlabel(r'$t$ $(2\pi/\omega_Q)$',fontsize=fontsize,usetex=True);
plt.xlim([0,3]);
plt.ylim([-1.05,1.05]);
fockNumberList = [0,1,2,3,4]
tarray = np.linspace(0,3*2*np.pi/omega_Q,100)
plt.figure(figsize=(15,4))
plt.ylabel(r'$\langle\sigma^x\rangle$',fontsize=fontsize,usetex=True);
plt.xlabel(r'$t$ $(2\pi/\omega_Q)$',fontsize=fontsize,usetex=True);
plt.xlim([0,3]);
plt.ylim([-1.05,1.05]);
for fockNumber in fockNumberList:
print("Time evolving for Fock state |" + str(fockNumber) + '>...')
qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode)
qbr = qiskit.QuantumRegister(1)
# Instantiate the circuit and initialize the qubit to the '+' state.
circuit = c2qa.CVCircuit(qmr,qbr)
circuit.initialize([1/np.sqrt(2), 1/np.sqrt(2)], qbr)
# Initialize the qumode
circuit.cv_initialize(fockNumber,qmr[0])
circuit.append(U_JC,qmr[0] + [qbr[0]]);
sigma_x_expectation = []
for tau in tarray:
state, result, _ = c2qa.util.simulate(circuit.assign_parameters({dt : tau}))
sigma_x_expectation.append(state.expectation_value(sigmax).real)
plt.plot(tarray/(2*np.pi/omega_Q),sigma_x_expectation,linewidth=2, label = r'$|' + str(fockNumber) + r'\rangle $')
plt.legend()
# Choose alpha for coherent state
alpha = 1
# Choose total animation time
total_time = 1*2*np.pi/omega_R
# First construct circuit_qubit0
qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode)
qbr = qiskit.QuantumRegister(1)
# Create new circuit
qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode)
qbr = qiskit.QuantumRegister(1)
U_JC = c2qa.CVCircuit(qmr,qbr)
# Append U_R
U_JC.cv_r(-omega_R*total_time,qmr[0])
# Append U_Q
U_JC.rz(omega_Q*total_time,qbr[0])
# Append U_\chi -- KS: this needs to be updated to reflect naming conventions in manuscript
U_JC.cv_c_r(-chi*total_time/2,qmr[0],qbr[0])
# Compile this circuit into a single parameterized gate
U_JC = U_JC.to_gate(label='U_JC')
# Instantiate the circuit and initialize the qubit to the '0' state.
circuit_0 = c2qa.CVCircuit(qmr,qbr)
circuit_0.initialize([1,0], qbr)
# Now initialize the qumode in a coherent state
cutoff = 2**num_qubits_per_qumode
coeffs = [np.exp(-np.abs(alpha)**2/2)*alpha**n/(np.sqrt(np.math.factorial(n))) for n in range(0,cutoff)]
circuit_0.cv_initialize(coeffs,qmr[0])
# Append time evolution unitary
circuit_0.append(U_JC,qmr[0] + [qbr[0]]);
# circuit_0.assign_parameters({dt : total_time})
# dt = total_time
# # Append U_R
# circuit_0.cv_r(-omega_R*dt,qmr[0])
# # Append U_Q
# circuit_0.rz(omega_Q*dt,qbr[0])
# # Append U_\chi -- KS: this needs to be updated to reflect naming conventions in manuscript
# circuit_0.cv_c_r(-chi*dt/2,qmr[0],qbr[0])
# Compile this circuit into a single parameterized gate
# U_JC = U_JC.to_gate(label='U_JC')
# # Now repeat the above steps for a qubit initialized to the '1' state:
# circuit_1 = c2qa.CVCircuit(qmr,qbr)
# circuit_1.initialize([0,1], qbr)
# circuit_1.cv_d(alpha,qmr[0])
# circuit_1.append(U_JC,qmr[0] + [qbr[0]]);
# circuit_1 = circuit_1.assign_parameters({dt : total_time})
# Animate wigner function of each circuit
c2qa.animate.animate_wigner(circuit_0, animation_segments = 1000)
|
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
|
bayesian-randomized-benchmarking
|
import numpy as np
import copy
import qiskit_experiments as qe
import qiskit.circuit.library as circuits
rb = qe.randomized_benchmarking
# for retrieving gate calibration
from datetime import datetime
import qiskit.providers.aer.noise.device as dv
# import the bayesian packages
import pymc3 as pm
import arviz as az
import bayesian_fitter as bf
simulation = True # make your choice here
if simulation:
from qiskit.providers.aer import AerSimulator
from qiskit.test.mock import FakeParis
backend = AerSimulator.from_backend(FakeParis())
else:
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_lima') # type here hardware backend
lengths = np.arange(1, 1000, 100)
num_samples = 10
seed = 1010
qubits = [0]
physical_qubits = [0]
nQ = len(qubits)
scale = (2 ** nQ - 1) / 2 ** nQ
interleaved_gate =''
# Run an RB experiment on a single qubit
exp1 = rb.StandardRB(qubits, lengths, num_samples=num_samples, seed=seed)
expdata1 = exp1.run(backend)
# retrieve from the frequentist model (fm) analysis
# some values,including priors, for the bayesian analysis
perr_fm, popt_fm, epc_est_fm, epc_est_fm_err, experiment_type = bf.retrieve_from_lsf(expdata1)
EPG_dic = expdata1._analysis_results[0]['EPG'][qubits[0]]
# get count data
Y = bf.get_GSP_counts(expdata1._data, len(lengths),range(num_samples))
shots = bf.guess_shots(Y)
#build model
original_model = bf.get_bayesian_model(model_type="pooled",Y=Y,shots=shots,m_gates=lengths,
mu_AB=[popt_fm[0],popt_fm[2]],cov_AB=[perr_fm[0],perr_fm[2]],
alpha_ref=popt_fm[1],
alpha_lower=popt_fm[1]-6*perr_fm[1],
alpha_upper=min(1.-1.E-6,popt_fm[1]+6*perr_fm[1]))
pm.model_to_graphviz(original_model)
trace_o = bf.get_trace(original_model)
# backend's recorded EPG
print(rb.RBUtils.get_error_dict_from_backend(backend, qubits))
bf.RB_bayesian_results(original_model, trace_o, lengths,
epc_est_fm, epc_est_fm_err, experiment_type, scale,
num_samples, Y, shots, physical_qubits, interleaved_gate, backend,
EPG_dic = EPG_dic)
# describe RB experiment
interleaved_gate =''
physical_qubits = qubits = (1,4)
nQ = len(qubits)
scale = (2 ** nQ - 1) / 2 ** nQ # defined for the 2-qubit run
lengths = np.arange(1, 200, 30)
lengths_1_qubit = np.arange(1, 1000, 100)
num_samples = 10
seed = 1010
# Run a 1-qubit RB expriment on each qubit to determine the error-per-gate of 1-qubit gates
epg_data = {}
expdata_dic = {}
lengths_1_qubit = np.arange(1, 1000, 100)
for qubit in qubits:
exp = rb.StandardRB([qubit], lengths_1_qubit, num_samples=num_samples, seed=seed)
expdata_dic[qubit] = exp.run(backend)
epg_data[qubit] = expdata_dic[qubit].analysis_result(0)['EPG'][qubit]
# Run a 1-qubit RB bayesian analysis on each qubit to determine the bayesian error-per-gate of 1-qubit gates
epg_data_bayes = {}
for qubit in qubits:
# retrieve from the frequentist model (fm) analysis
# some values,including priors, for the bayesian analysis
perr_fm, popt_fm, epc_est_fm, epc_est_fm_err, experiment_type = bf.retrieve_from_lsf(expdata_dic[qubit])
Y = bf.get_GSP_counts(expdata_dic[qubit]._data, len(lengths_1_qubit),range(num_samples))
shots = bf.guess_shots(Y)
#build and run model
oneQ_model = bf.get_bayesian_model(model_type="pooled",Y=Y,shots=shots,m_gates=lengths_1_qubit,
mu_AB=[popt_fm[0],popt_fm[2]],cov_AB=[perr_fm[0],perr_fm[2]],
alpha_ref=popt_fm[1],
alpha_lower=popt_fm[1]-6*perr_fm[1],
alpha_upper=min(1.-1.E-6,popt_fm[1]+6*perr_fm[1]))
trace_oneQ = bf.get_trace(oneQ_model)
azoneQ_summary = bf.get_summary(oneQ_model, trace_oneQ, kind = 'stats')
print(azoneQ_summary,'\n')
epc_est_a = 0.5*(1 - azoneQ_summary['mean']['alpha']) # there is only one qubit, thus scale = 0.5
epg_data_bayes[qubit] = {}
for i, (gate,EPG) in enumerate(epg_data[qubit].items()):
epg_data_bayes[qubit][gate] = EPG*epc_est_a/epc_est_fm
# Run a frequentist RB experiment on 2 qubits
exp2 = rb.StandardRB(qubits, lengths, num_samples=num_samples, seed=seed)
# Use the EPG data of the 1-qubit runs to ensure correct 2-qubit EPG computation
exp2.set_analysis_options(epg_1_qubit=epg_data)
# Run the 2-qubit experiment
expdata2 = exp2.run(backend)
# Compare the computed EPG with the backend's recorded EPG:
expected_epg = rb.RBUtils.get_error_dict_from_backend(backend, qubits)[(qubits, 'cx')]
exp2_epg = expdata2.analysis_result(0)['EPG'][qubits]['cx']
print("Backend's reported EPG:", expected_epg)
print("Experiment computed EPG:", exp2_epg)
# Bayesian version
# Use the EPG data of the 1-qubit runs to ensure correct 2-qubit EPG computation
exp2.set_analysis_options(epg_1_qubit=epg_data_bayes)
# Run the 2-qubit experiment
expdata2b = exp2.run(backend)
# Compare the computed EPG with the backend's recorded EPG:
exp2_epg_b = expdata2b.analysis_result(0)['EPG'][qubits]['cx']
print("Backend's reported EPG:", expected_epg)
print("Experiment computed EPG:", exp2_epg_b)
# retrieve from the frequentist model (fm) analysis
# some values,including priors, for the bayesian analysis
perr_fm, popt_fm, epc_est_fm, epc_est_fm_err, experiment_type = bf.retrieve_from_lsf(expdata2b)
EPG_dic = expdata2b._analysis_results[0]['EPG'][qubits]
# get count data
Y = bf.get_GSP_counts(expdata2b._data, len(lengths),range(num_samples))
shots = bf.guess_shots(Y)
#build model
S2QB_model = bf.get_bayesian_model(model_type="pooled",Y=Y,shots=shots,m_gates=lengths,
mu_AB=[popt_fm[0],popt_fm[2]],cov_AB=[perr_fm[0],perr_fm[2]],
alpha_ref=popt_fm[1],
alpha_lower=popt_fm[1]-6*perr_fm[1],
alpha_upper=min(1.-1.E-6,popt_fm[1]+6*perr_fm[1]))
pm.model_to_graphviz(S2QB_model)
trace_s2 = bf.get_trace(S2QB_model)
bf.RB_bayesian_results(S2QB_model, trace_s2, lengths,
epc_est_fm, epc_est_fm_err, experiment_type, scale,
num_samples, Y, shots, physical_qubits, interleaved_gate, backend,
EPG_dic = EPG_dic)
# describe RB experiment
interleaved_gate = "x"
physical_qubits = [0]
qubits = [0]
interleaved_circuit = circuits.XGate()
lengths = np.arange(1, 1000, 100)
num_samples = 10
seed = 1010
# Run an interleaved RB experiment
int_exp1 = rb.InterleavedRB(interleaved_circuit, qubits,
lengths, num_samples=num_samples, seed=seed)
int_expdata1 = int_exp1.run(backend)
# retrieve from the frequentist model (fm) analysis
# some values,including priors, for the bayesian analysis
perr_fm, popt_fm, epc_est_fm, epc_est_fm_err, experiment_type = bf.retrieve_from_lsf(int_expdata1)
nQ = len(physical_qubits)
scale = (2 ** nQ - 1) / 2 ** nQ
Y1 = bf.get_GSP_counts(int_expdata1._data, len(lengths),
range(0,2*num_samples-1,2))
Y2 = bf.get_GSP_counts(int_expdata1._data, len(lengths),
range(1,2*num_samples,2))
Y = np.vstack((Y1,Y2))
RvsI = np.vstack((np.ones_like(Y1),np.zeros_like(Y2)))
IvsR = np.vstack((np.zeros_like(Y1),np.ones_like(Y2)))
shots = bf.guess_shots(Y)
tilde1 = bf.get_bayesian_model("tilde",Y=Y,shots=shots, m_gates=lengths,
alpha_ref=popt_fm[1], p_testval= popt_fm[2],
alpha_lower=popt_fm[1]-6*perr_fm[1],
alpha_upper=min(1.-1.E-6,popt_fm[1]+6*perr_fm[1]),
p_lower=popt_fm[2]-6*perr_fm[2],
p_upper=min(1.-1.E-6,popt_fm[2]+6*perr_fm[2]),
mu_AB=[popt_fm[0],popt_fm[3]],cov_AB=[perr_fm[0],perr_fm[3]],
RvsI=RvsI,IvsR=IvsR)
pm.model_to_graphviz(tilde1)
trace_t = bf.get_trace(tilde1)
t = None # enter t in datetime format if necessary
e_list = dv.gate_error_values(backend.properties()) # use properties(datetime=t) if t is defined
epc_calib = [item for item in e_list if item[0] == interleaved_gate and item[1] == physical_qubits][0][2]
print('EPC calibration: {0:.6f}'.format(epc_calib))
# example of interpolated EPC_cal for hardware experiments
# EPC0 + (t_exp - tO) * (EPC1 - EPC0) / (t1 - t0)
# code here:
# epc_calib = 2.307E-4 + (23.6-7)*(2.193E-4 - 2.307E-4)/24
bf.RB_bayesian_results(tilde1, trace_t, lengths,
epc_est_fm, epc_est_fm_err, experiment_type, scale,
num_samples, Y, shots, physical_qubits, interleaved_gate, backend,
epc_calib = epc_calib, Y1 = Y1, Y2 = Y2)
# describe RB experiment
interleaved_gate = "cx"
physical_qubits = [1,4]
qubits = [1,4]
interleaved_circuit = circuits.CXGate()
lengths = np.arange(1, 200, 30)
num_samples = 10
seed = 1010
# Run an Interleaved RB experiment
interleaved_circuit = circuits.CXGate()
int_exp2 = rb.InterleavedRB(interleaved_circuit, physical_qubits,
lengths, num_samples=num_samples, seed=seed)
int_expdata2 = int_exp2.run(backend)
# retrieve from the frequentist model (fm) analysis
# some values,including priors, for the bayesian analysis
perr_fm, popt_fm, epc_est_fm, epc_est_fm_err, experiment_type = bf.retrieve_from_lsf(int_expdata2)
nQ = len(physical_qubits)
scale = (2 ** nQ - 1) / 2 ** nQ
Y1 = bf.get_GSP_counts(int_expdata2._data, len(lengths),
range(0,2*num_samples-1,2))
Y2 = bf.get_GSP_counts(int_expdata2._data, len(lengths),
range(1,2*num_samples,2))
Y = np.vstack((Y1,Y2))
RvsI = np.vstack((np.ones_like(Y1),np.zeros_like(Y2)))
IvsR = np.vstack((np.zeros_like(Y1),np.ones_like(Y2)))
shots = bf.guess_shots(Y1)
tilde2 = bf.get_bayesian_model("tilde",Y=Y,shots=shots, m_gates=lengths,
alpha_ref=popt_fm[1], p_testval= popt_fm[2],
alpha_lower=popt_fm[1]-6*perr_fm[1],
alpha_upper=min(1.-1.E-6,popt_fm[1]+6*perr_fm[1]),
p_lower=popt_fm[2]-6*perr_fm[2],
p_upper=min(1.-1.E-6,popt_fm[2]+6*perr_fm[2]),
mu_AB=[popt_fm[0],popt_fm[3]],cov_AB=[perr_fm[0],perr_fm[3]],
RvsI=RvsI,IvsR=IvsR)
pm.model_to_graphviz(tilde2)
trace_t2 = bf.get_trace(tilde2)
t = None # enter t in datetime format if necessary
e_list = dv.gate_error_values(backend.properties()) # use properties(datetime=t) if t is defined
epc_calib = [item for item in e_list if item[0] == interleaved_gate and item[1] == physical_qubits][0][2]
print('EPC calibration: {0:.6f}'.format(epc_calib))
bf.RB_bayesian_results(tilde2, trace_t2, lengths,
epc_est_fm, epc_est_fm_err, experiment_type, scale,
num_samples, Y, shots, physical_qubits, interleaved_gate, backend,
epc_calib = epc_calib, Y1 = Y1, Y2 = Y2)
|
https://github.com/lancecarter03/QiskitLearning
|
lancecarter03
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
circuit = QuantumCircuit(3,3)
circuit.draw(output="mpl")
circuit.x(0)
circuit.barrier()
circuit.draw(output="mpl")
circuit.h(1)
circuit.cx(1,2)
circuit.draw(output="mpl")
circuit.cx(0,1)
circuit.h(0)
circuit.draw(output="mpl")
circuit.barrier()
circuit.measure([0,1],[0,1])
circuit.draw(output="mpl")
circuit.barrier()
circuit.cx(1,2)
circuit.cz(0,2)
circuit.draw(output="mpl")
circuit.measure(2,2)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend = simulator, shots =1024).result()
counts = result.get_counts()
plot_histogram(counts)
|
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
|
bayesian-randomized-benchmarking
|
#Import general libraries (needed for functions)
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
#Import Qiskit classes
import qiskit
import qiskit_experiments as qe
rb = qe.randomized_benchmarking
from scipy.optimize import curve_fit
# import the bayesian packages
import pymc3 as pm
import arviz as az
import bayesian_fitter as bf
# initialize the Bayesian extension
%config InlineBackend.figure_format = 'retina'
# Initialize random number generator
RANDOM_SEED = 8927
np.random.seed(RANDOM_SEED)
az.style.use("arviz-darkgrid")
# choice of "simulation, "real", "retrieve"
option = "simulation"
# Determine the backend
if option == "simulation":
from qiskit.test.mock import FakeAthens
backend = FakeAthens()
hardware = 'ibmq_athens' # hardware reference
else:
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
device = provider.get_backend('ibmq_athens')
backend = device
hardware = device.name() # hardware used
# RB design
q_list = [0,1]
lengths = [1, 20, 40, 60, 80, 100, 150, 200, 250, 300, 350, 400, 450, 500]
num_samples = 5
seed = 1010
num_qubits = len(q_list)
scale = (2 ** num_qubits - 1) / (2 ** num_qubits)
shots = 1024
if option != "retrieve":
exp = rb.RBExperiment(q_list, lengths, num_samples=num_samples, seed=seed)
eda= exp.run(backend)
# obtain EPC from alpha (used by plot_posterior)
def alpha_to_EPC(alpha):
return scale*(1-alpha)
# one or two qubits for retrieve and for the plots
list_bitstring = ['0', '00']
# obtain the current count values
Y_list = []
if option == "simulation":
for i_sample in range(num_samples*len(lengths)):
Y_list.append(eda.data[i_sample]['counts']\
[eda.data[i_sample]['metadata']['ylabel']])
else: # specify job (fresh job or run some time ago)
job = backend.retrieve_job('6097aed0a4885edfb19508fa') # athens 01'
for rbseed, result in enumerate(job.result().get_counts()):
total_counts = 0
for key,val in result.items():
if key in list_bitstring:
total_counts += val
Y_list.append(total_counts)
Y = np.array(Y_list).reshape(num_samples, len(lengths))
#get LSF EPC and priors
if option != "retrieve":
popt = eda._analysis_results[0]['popt']
pcov = eda._analysis_results[0]['pcov']
else: # manual entry (here for job ''6097aed0a4885edfb19508fa')
popt = [0.7207075, 0.95899375, 0.2545933 ]
pcov = [[ 2.53455272e-04, -9.10001034e-06, -1.29839515e-05],
[-9.10001034e-06, 9.55193998e-06, -7.07822420e-06],
[-1.29839515e-05, -7.07822420e-06, 2.07452483e-05]]
alpha_ref=popt[1]
mu_AB= [popt[0],popt[2]]
alpha_ref_err = np.sqrt(pcov[1][1])
EPC = scale*(1-alpha_ref)
EPC_err = scale*alpha_ref_err
cov_AB= [0.0001, 0.0001]
alpha_lower=0.8
alpha_upper=0.999
sigma_theta = .004
pooled_model = bf.get_bayesian_model(model_type="pooled",
Y=Y,shots=1024,m_gates=lengths,
alpha_ref = alpha_ref,
mu_AB=mu_AB,cov_AB=cov_AB)
pm.model_to_graphviz(pooled_model)
with pooled_model:
trace_p= pm.sample(draws = 2000, tune= 10000, target_accept=0.97,
return_inferencedata=True)
az.plot_trace(trace_p)
with pooled_model:
azp_summary = az.summary(trace_p, hdi_prob=.94, round_to=6, kind="all")
azp_summary
epc_p =scale*(1 - azp_summary['mean']['alpha'])
epc_p_err = scale* (azp_summary['sd']['alpha'])
with pooled_model:
ax = az.plot_posterior(trace_p, var_names=['alpha'], round_to=4, point_estimate=None,
transform = alpha_to_EPC, textsize = 10.0, color='b')
ax.set_title("RB_process: standard "+str(q_list)+", backend: "+backend.name(),
fontsize=12)
Bayes_legend ="Bayesian Pooled Model:\n EPC {0:1.3e} ± {1:1.3e}".format(epc_p, epc_p_err)
ax.axvline(x=EPC,color='r',ls=":")
Fitter_legend ="Frequentist model:\n EPC {0:1.3e} ± {1:1.3e}".format(EPC, EPC_err)
ax.legend((Bayes_legend, "$Highest\; density\; interval$ HDI",
Fitter_legend),fontsize=10 )
hierarchical_model = bf.get_bayesian_model(model_type="hierarchical",
Y=Y,shots=1024,m_gates=lengths,
alpha_ref = alpha_ref,
mu_AB=mu_AB,cov_AB=cov_AB)
pm.model_to_graphviz(hierarchical_model)
with hierarchical_model:
trace_h= pm.sample(draws = 2000, tune= 10000, target_accept=0.97,
return_inferencedata=True)
az.plot_trace(trace_h)
with hierarchical_model:
azh_summary = az.summary(trace_h, hdi_prob=.94, round_to=6,
kind="all", var_names=["~GSP"])
azh_summary
epc_h =scale*(1 - azh_summary['mean']['alpha'])
epc_h_err = scale* (azh_summary['sd']['alpha'])
with hierarchical_model:
ax = az.plot_posterior(trace_h, var_names=['alpha'], round_to=4, point_estimate=None,
transform = alpha_to_EPC, textsize = 10.0, color='b')
ax.set_title("RB_process: standard "+str(q_list)+", backend: "+backend.name(),
fontsize=12)
Bayes_legend ="Bayesian Hierarchical Model:\n EPC {0:1.3e} ± {1:1.3e}".format(epc_h, epc_h_err)
ax.axvline(x=EPC,color='r',ls=":")
Fitter_legend ="Frequentist model:\n EPC {0:1.3e} ± {1:1.3e}".format(EPC, EPC_err)
ax.legend((Bayes_legend, "$Highest\; density\; interval$ HDI",
Fitter_legend),fontsize=10 )
# compare LSF and SMC
print("Model: Frequentist Bayesian")
print(" LSF pooled hierarchical")
print("EPC {0:.5f} {1:.5f} {2:.5f}"
.format(EPC, epc_p, epc_h))
print("ERROR ± {0:.5f} ± {1:.5f} ± {2:.5f}"
.format(EPC_err, epc_p_err, epc_h_err))
import matplotlib.pyplot as plt # seems we need to reimport for replot WIP
#fig, plt = plt.subplots(1, 1, sharex=True, figsize=(10, 6))
fig, plt = plt.subplots(1, 1, sharex=True, figsize=(10, 6))
plt.set_ylabel("Ground State Population")
plt.set_xlabel("Number of Cliffords")
for i_seed in range(num_samples):
plt.scatter(lengths, Y[i_seed,:]/1024, label = "data",
marker="+",color="purple")
plt.plot(np.array(lengths)-0.5,azp_summary['mean']['AB[0]']\
*azp_summary['mean']['alpha']**lengths+\
azp_summary['mean']['AB[1]']-0.002,'o-',color="c")
plt.plot(np.array(lengths)+0.5,azh_summary['mean']['AB[0]']\
*azh_summary['mean']['alpha']**\
lengths+azh_summary['mean']['AB[1]']+0.002,'o-',color="orange")
plt.legend(("Pooled Model",
"Hierarchical Model"))
plt.set_title("RB_process: standard "+str(q_list)+\
", device: "+hardware+', backend: '+backend.name(),
fontsize=14);
# Leave-one-out Cross-validation (LOO) comparison
df_comp_loo = az.compare({"hierarchical": trace_h, "pooled": trace_p})
df_comp_loo
az.plot_compare(df_comp_loo, insample_dev=False);
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# 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.
"""Class for a Real McLachlan's Variational Principle."""
from __future__ import annotations
import warnings
from collections.abc import Sequence
import numpy as np
from numpy import real
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.primitives import Estimator
from qiskit.quantum_info import SparsePauliOp
from qiskit.quantum_info.operators.base_operator import BaseOperator
from .real_variational_principle import RealVariationalPrinciple
from ....exceptions import AlgorithmError
from ....gradients import (
BaseEstimatorGradient,
BaseQGT,
DerivativeType,
LinCombQGT,
LinCombEstimatorGradient,
)
class RealMcLachlanPrinciple(RealVariationalPrinciple):
"""Class for a Real McLachlan's Variational Principle. It aims to minimize the distance
between both sides of the Schrödinger equation with a quantum state given as a parametrized
trial state. The principle leads to a system of linear equations handled by a linear solver.
The real variant means that we consider real time dynamics.
"""
def __init__(
self,
qgt: BaseQGT | None = None,
gradient: BaseEstimatorGradient | None = None,
) -> None:
"""
Args:
qgt: Instance of a the GQT class used to compute the QFI.
If ``None`` provided, ``LinCombQGT`` is used.
gradient: Instance of a class used to compute the state gradient.
If ``None`` provided, ``LinCombEstimatorGradient`` is used.
Raises:
AlgorithmError: If the gradient instance does not contain an estimator.
"""
self._validate_grad_settings(gradient)
if gradient is not None:
try:
estimator = gradient._estimator
except Exception as exc:
raise AlgorithmError(
"The provided gradient instance does not contain an estimator primitive."
) from exc
else:
estimator = Estimator()
gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG)
if qgt is None:
qgt = LinCombQGT(estimator)
super().__init__(qgt, gradient)
def evolution_gradient(
self,
hamiltonian: BaseOperator,
ansatz: QuantumCircuit,
param_values: Sequence[float],
gradient_params: Sequence[Parameter] | None = None,
) -> np.ndarray:
"""
Calculates an evolution gradient according to the rules of this variational principle.
Args:
hamiltonian: Operator used for Variational Quantum Time Evolution.
ansatz: Quantum state in the form of a parametrized quantum circuit.
param_values: Values of parameters to be bound.
gradient_params: List of parameters with respect to which gradients should be computed.
If ``None`` given, gradients w.r.t. all parameters will be computed.
Returns:
An evolution gradient.
Raises:
AlgorithmError: If a gradient job fails.
"""
try:
estimator_job = self.gradient._estimator.run([ansatz], [hamiltonian], [param_values])
energy = estimator_job.result().values[0]
except Exception as exc:
raise AlgorithmError("The primitive job failed!") from exc
modified_hamiltonian = self._construct_modified_hamiltonian(hamiltonian, real(energy))
try:
evolution_grad = (
0.5
* self.gradient.run(
[ansatz],
[modified_hamiltonian],
parameters=[gradient_params],
parameter_values=[param_values],
)
.result()
.gradients[0]
)
except Exception as exc:
raise AlgorithmError("The gradient primitive job failed!") from exc
# The BaseEstimatorGradient class returns the gradient of the opposite sign than we expect
# here (i.e. with a minus sign), hence the correction that cancels it to recover the
# real McLachlan's principle equations that do not have a minus sign.
evolution_grad = (-1) * evolution_grad
return evolution_grad
@staticmethod
def _construct_modified_hamiltonian(hamiltonian: BaseOperator, energy: float) -> BaseOperator:
"""
Modifies a Hamiltonian according to the rules of this variational principle.
Args:
hamiltonian: Operator used for Variational Quantum Time Evolution.
energy: The energy correction value.
Returns:
A modified Hamiltonian.
"""
energy_term = SparsePauliOp.from_list(
hamiltonian.to_list() + [("I" * hamiltonian.num_qubits, -energy)]
)
return energy_term
@staticmethod
def _validate_grad_settings(gradient):
if gradient is not None:
if not hasattr(gradient, "_derivative_type"):
raise ValueError(
"The gradient instance provided does not support calculating imaginary part. "
"Please choose a different gradient class."
)
if gradient._derivative_type != DerivativeType.IMAG:
warnings.warn(
"A gradient instance with a setting for calculating real part of the"
"gradient was provided. This variational principle requires the"
"imaginary part. The setting to imaginary was changed automatically."
)
gradient._derivative_type = DerivativeType.IMAG
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
# import matplotlib.pyplot as plt
%matplotlib inline
print(qiskit.__version__)
circuit = QuantumCircuit(2,2)
circuit.h(0)
circuit.cx(0,1)
circuit.measure([0,1],[0,1])
# circuit.measure_all()
circuit.barrier()
# circuit.draw(output='mpl')
circuit.draw(output='mpl')
simulator = Aer.get_backend('aer_simulator')
result = execute(circuit, backend=simulator, shots=1024).result()
count = result.get_counts()
print(count)
from qiskit.tools.visualization import plot_histogram
plot_histogram(count)
from qiskit import IBMQ
IBMQ.save_account("b32678329f7f6dd426b8cf18f20bea23c2cd056b0bee2b4bcf49744b612e598f20f7170a8da4bfd99b009b6fa59d596edea7a6926fd388be158843d8ef******", overwrite=True)
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider.backends()
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
job = execute(circuit, backend=backend, shots=1024)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
count = result.get_counts()
print(count)
from qiskit.tools.visualization import plot_histogram
plot_histogram(count)
|
https://github.com/kaelynj/Qiskit-HubbardModel
|
kaelynj
|
%matplotlib inline
import sys
sys.path.append('./src')
# Importing standard Qiskit libraries and configuring account
#from qiskit import QuantumCircuit, execute, Aer, IBMQ
#from qiskit.compiler import transpile, assemble
#from qiskit.tools.jupyter import *
#from qiskit.visualization import *
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
import ClassicalHubbardEvolutionChain as chc
import random as rand
import scipy.linalg as la
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters: x (int), n (int, number of digits)"""
binry = format(x, 'b').zfill(n)
sup = list( reversed( binry[0:int(len(binry)/2)] ) )
sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) )
return format(x, 'b').zfill(n)
#============ Run Classical Evolution ==============
#Define our basis states
#States for 3 electrons with net spin up
'''
states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]],
[[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]],
[[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ]
'''
#States for 2 electrons in singlet state
states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]],
[[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]],
[[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ]
#'''
#States for a single electron
#states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ]
#Possible initial wavefunctions
#wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state
wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state
#wfk = [0., 1., 0.] #1 electron initial state
#System parameters
t = 1.0
U = 2.
classical_time_step = 0.01
classical_total_time = 500*0.01
times = np.arange(0., classical_total_time, classical_time_step)
evolution, engs = chc.sys_evolve(states, wfk, t, U, classical_total_time, classical_time_step)
#print(evolution)
probs = [np.sum(x) for x in evolution]
#print(probs)
#print(np.sum(evolution[0]))
print(engs)
states_list = []
nsite = 3
for state in range(0, 2**(2*nsite)):
state_bin = get_bin(state, 2*nsite)
state_list = [[],[]]
for mode in range(0,nsite):
state_list[0].append(int(state_bin[mode]))
state_list[1].append(int(state_bin[mode+nsite]))
#print(state_list)
states_list.append(state_list)
#print(states_list[18])
#evolution2, engs2 = chc.sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step)
#System parameters
t = 1.0
U = 2.
classical_time_step = 0.01
classical_total_time = 500*0.01
times = np.arange(0., classical_total_time, classical_time_step)
#Create full Hamiltonian
wfk_full = np.zeros(len(states_list))
#wfk_full[18] = 1. #010010
wfk_full[21] = 1. #010101
#wfk_full[2] = 1. #000010
#evolution2, engs2 = chc.sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step)
def repel(l,state):
if state[0][l]==1 and state[1][l]==1:
return state
else:
return []
#Check if two states are different by a single hop
def hop(psii, psij, hopping):
#Check spin down
hopp = 0
if psii[0]==psij[0]:
#Create array of indices with nonzero values
'''
indi = np.nonzero(psii[1])[0]
indj = np.nonzero(psij[1])[0]
if len(indi) != len(indj):
return hopp
print('ind_i: ',indi,' ind_j: ',indj)
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -hopping
print('Hopping Found: ',psii,' with: ',psij)
return hopp
'''
hops = []
for site in range(len(psii[0])):
if psii[1][site] != psij[1][site]:
hops.append(site)
if len(hops)==2 and np.sum(psii[1]) == np.sum(psij[1]):
if hops[1]-hops[0]==1:
hopp = -hopping
return hopp
#Check spin up
if psii[1]==psij[1]:
'''
indi = np.nonzero(psii[0])[0]
indj = np.nonzero(psij[0])[0]
if len(indi) != len(indj):
return hopp
print('ind_i: ',indi,' ind_j: ',indj)
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -hopping
print('Hopping Found: ',psii,' with: ',psij)
return hopp
'''
hops = []
for site in range(len(psii[1])):
if psii[0][site] != psij[0][site]:
hops.append(site)
if len(hops)==2 and np.sum(psii[0])==np.sum(psij[0]):
if hops[1]-hops[0]==1:
hopp = -hopping
return hopp
return hopp
def get_hamiltonian(states, t, U):
H = np.zeros((len(states),len(states)) )
#Construct Hamiltonian matrix
for i in range(len(states)):
psi_i = states[i]
for j in range(i, len(states)):
psi_j = states[j]
if j==i:
for l in range(0,len(states[0][0])):
if psi_i == repel(l,psi_j):
H[i,j] = U
break
else:
#print('psi_i: ',psi_i,' psi_j: ',psi_j)
H[i,j] = hop(psi_i, psi_j, t)
H[j,i] = H[i,j]
return H
hamil = get_hamiltonian(states_list, t, U)
print(hamil)
print(states_list)
print()
print("Target state: ", states_list[21])
mapping = get_mapping(states_list)
print('Second mapping set')
print(mapping[1])
print(wfk_full)
mapped_wfk = np.zeros(6)
for i in range(len(mapping)):
if 21 in mapping[i]:
print("True for mapping set: ",i)
def get_mapping(states):
num_sites = len(states[0][0])
mode_list = []
for i in range(0,2*num_sites):
index_list = []
for state_index in range(0,len(states)):
state = states[state_index]
#Check spin-up modes
if i < num_sites:
if state[0][i]==1:
index_list.append(state_index)
#Check spin-down modes
else:
if state[1][i-num_sites]==1:
index_list.append(state_index)
if index_list:
mode_list.append(index_list)
return mode_list
def wfk_energy(wfk, hamil):
eng = np.dot(np.conj(wfk), np.dot(hamil, wfk))
return eng
def get_variance(wfk, h):
h_squared = np.matmul(h, h)
eng_squared = np.vdot(wfk, np.dot(h_squared, wfk))
squared_eng = np.vdot(wfk, np.dot(h, wfk))
var = np.sqrt(eng_squared - squared_eng)
return var
def sys_evolve(states, init_wfk, hopping, repulsion, total_time, dt):
hamiltonian = get_hamiltonian(states, hopping, repulsion)
t_operator = la.expm(-1j*hamiltonian*dt)
mapping = get_mapping(states)
print(mapping)
#Initalize system
tsteps = int(total_time/dt)
evolve = np.zeros([tsteps, len(init_wfk)])
mode_evolve = np.zeros([tsteps, len(mapping)])
wfk = init_wfk
energies = np.zeros(tsteps)
#Store first time step in mode_evolve
evolve[0] = np.multiply(np.conj(wfk), wfk)
for i in range(0, len(mapping)):
wfk_sum = 0.
norm = 0.
print("Mapping: ", mapping[i])
for j in mapping[i]:
print(evolve[0][j])
wfk_sum += evolve[0][j]
mode_evolve[0][i] = wfk_sum
energies[0] = wfk_energy(wfk, hamiltonian)
norm = np.sum(mode_evolve[0])
mode_evolve[0][:] = mode_evolve[0][:] / norm
#print('wfk_sum: ',wfk_sum,' norm: ',norm)
#print('Variance: ',get_variance(wfk, hamiltonian) )
#Now do time evolution
print(mode_evolve[0])
times = np.arange(0., total_time, dt)
for t in range(1, tsteps):
wfk = np.dot(t_operator, wfk)
evolve[t] = np.multiply(np.conj(wfk), wfk)
#print(evolve[t])
energies[t] = wfk_energy(wfk, hamiltonian)
for i in range(0, len(mapping)):
norm = 0.
wfk_sum = 0.
for j in mapping[i]:
wfk_sum += evolve[t][j]
mode_evolve[t][i] = wfk_sum
norm = np.sum(mode_evolve[t])
mode_evolve[t][:] = mode_evolve[t][:] / norm
#Return time evolution
return mode_evolve, energies
evolution2, engs2 = sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step)
print(evolution2)
#print(engs2)
colors = list(mcolors.TABLEAU_COLORS.keys())
fig2, ax2 = plt.subplots(figsize=(20,10))
for i in range(3):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(times, evolution2[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
ax2.plot(times, evolution2[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
plt.legend()
#print(evolution[10])
#H = np.array([[0., -t, 0.],[-t, 0., -t],[0., -t, 0.]])
#print(np.dot(np.conj(evolution[10]), np.dot(H, evolution[10])))
print(engs[0])
plt.plot(times, engs)
plt.xlabel('Time')
plt.ylabel('Energy')
#Save data
import json
fname = './data/classical_010101.json'
data = {'times': list(times)}
for i in range(3):
key1 = 'site_up'+str(i)
key2 = 'site_dwn'+str(i)
data[key1] = list(evolution2[:,i])
data[key2] = list(evolution2[:,i+3])
with open(fname, 'w') as fp:
json.dump(data, fp, indent=4)
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
cos = np.cos(np.sqrt(2)*times)**2
sit1 = "Site "+str(1)+r'$\uparrow$'
sit2 = "Site "+str(2)+r'$\uparrow$'
sit3 = "Site "+str(3)+r'$\uparrow$'
#ax2.plot(times, evolution[:,0], marker='.', color='k', linewidth=2, label=sit1)
#ax2.plot(times, evolution[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2)
#ax2.plot(times, evolution[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3)
#ax2.plot(times, cos, label='cosdat')
#ax2.plot(times, np.zeros(len(times)))
for i in range(3):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(times, evolution[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
ax2.plot(times, evolution[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
#ax2.set_ylim(0, 1.)
ax2.set_xlim(0, classical_total_time)
#ax2.set_xlim(0, 1.)
ax2.set_xticks(np.arange(0,classical_total_time, 0.2))
#ax2.set_yticks(np.arange(0,1.1, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax2.legend(fontsize=20)
#Try by constructing the matrix and finding the eigenvalues
N = 3
Nup = 2
Ndwn = N - Nup
t = 1.
U = 2.
#Check if two states are different by a single hop
def hop(psii, psij):
#Check spin down
hopp = 0
if psii[0]==psij[0]:
#Create array of indices with nonzero values
indi = np.nonzero(psii[1])[0]
indj = np.nonzero(psij[1])[0]
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -t
return hopp
#Check spin up
if psii[1]==psij[1]:
indi = np.nonzero(psii[0])[0]
indj = np.nonzero(psij[0])[0]
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -t
return hopp
return hopp
#On-site terms
def repel(l,state):
if state[0][l]==1 and state[1][l]==1:
return state
else:
return []
#States for 3 electrons with net spin up
states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]],
[[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]],
[[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ]
#States for 2 electrons in singlet state
#states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]],
# [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]],
# [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ]
#States for a single electron
states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ]
H = np.zeros((len(states),len(states)) )
#Construct Hamiltonian matrix
for i in range(len(states)):
psi_i = states[i]
for j in range(len(states)):
psi_j = states[j]
if j==i:
for l in range(0,N):
if psi_i == repel(l,psi_j):
H[i,j] = U
break
else:
H[i,j] = hop(psi_i, psi_j)
print(H)
results = la.eig(H)
print()
for i in range(len(results[0])):
print('Eigenvalue: ',results[0][i])
print('Eigenvector: \n',results[1][i])
print('Norm: ', np.linalg.norm(results[1][i]))
print('Density Matrix: ')
print(np.outer(results[1][i],results[1][i]))
print()
dens_ops = []
eigs = []
for vec in results[1]:
dens_ops.append(np.outer(results[1][i],results[1][i]))
eigs.append(results[0][i])
print(dens_ops)
dt = 0.01
tsteps = 450
times = np.arange(0., tsteps*dt, dt)
t_op = la.expm(-1j*H*dt)
#print(np.subtract(np.identity(len(H)), dt*H*1j))
#print(t_op)
wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.]
wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state
evolve = np.zeros([tsteps, len(wfk)])
mode_evolve = np.zeros([tsteps, 6])
evolve[0] = wfk
#Figure out how to generalize this later
#'''[[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8]]
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2.
mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2.
mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2.
'''
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3.
mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3.
'''
print(mode_evolve[0])
#Define density matrices
for t in range(1, tsteps):
#t_op = la.expm(-1j*H*t)
wfk = np.dot(t_op, wfk)
evolve[t] = np.multiply(np.conj(wfk), wfk)
norm = np.sum(evolve[t])
#print(evolve[t])
#Store data in modes rather than basis defined in 'states' variable
#''' #Procedure for two electrons
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2)
mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2)
mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2)
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2)
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2)
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2)
'''
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3.
mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3.
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3.
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3.
print(mode_evolve[t])
'''
#print(np.linalg.norm(evolve[t]))
#print(len(evolve[:,0]) )
#print(len(times))
#print(evolve[:,0])
#print(min(evolve[:,0]))
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
cos = np.cos(np.sqrt(2)*times)**2
sit1 = "Site "+str(1)+r'$\uparrow$'
sit2 = "Site "+str(2)+r'$\uparrow$'
sit3 = "Site "+str(3)+r'$\uparrow$'
#ax2.plot(times, evolve[:,0], marker='.', color='k', linewidth=2, label=sit1)
#ax2.plot(times, evolve[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2)
#ax2.plot(times, evolve[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3)
#ax2.plot(times, cos, label='cosdat')
#ax2.plot(times, np.zeros(len(times)))
for i in range(3):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
#ax2.set_ylim(0, 1.)
ax2.set_xlim(0, tsteps*dt+dt/2.)
#ax2.set_xlim(0, 1.)
ax2.set_xticks(np.arange(0,tsteps*dt+dt, 0.2))
#ax2.set_yticks(np.arange(0,1.1, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax2.legend(fontsize=20)
dt = 0.1
tsteps = 50
times = np.arange(0., tsteps*dt, dt)
t_op = la.expm(-1j*H*dt)
#print(np.subtract(np.identity(len(H)), dt*H*1j))
#print(t_op)
#wfk = [0., 1., 0., 0., .0, 0., 0., 0., 0.] #Half-filling initial state
wfk0 = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state
#wfk0 = [0., 1., 0.] #1 electron initial state
evolve = np.zeros([tsteps, len(wfk0)])
mode_evolve = np.zeros([tsteps, 6])
evolve[0] = wfk0
#Figure out how to generalize this later
#'''
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2.
mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2.
mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2.
'''
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3.
mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3.
#'''
#Define density matrices
for t in range(1, tsteps):
t_op = la.expm(-1j*H*t*dt)
wfk = np.dot(t_op, wfk0)
evolve[t] = np.multiply(np.conj(wfk), wfk)
norm = np.sum(evolve[t])
print(evolve[t])
#Store data in modes rather than basis defined in 'states' variable
#'''
#Procedure for two electrons
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2)
mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2)
mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2)
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2)
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2)
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2)
#Procedure for half-filling
'''
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3.
mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3.
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3.
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3.
#'''
#print(mode_evolve[t])
#print(np.linalg.norm(evolve[t]))
#print(len(evolve[:,0]) )
#print(len(times))
#print(evolve[:,0])
#print(min(evolve[:,0]))
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
cos = np.cos(np.sqrt(2)*times)**2
sit1 = "Site "+str(1)+r'$\uparrow$'
sit2 = "Site "+str(2)+r'$\uparrow$'
sit3 = "Site "+str(3)+r'$\uparrow$'
#ax2.plot(times, evolve[:,0], marker='.', color='k', linewidth=2, label=sit1)
#ax2.plot(times, evolve[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2)
#ax2.plot(times, evolve[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3)
#ax2.plot(times, cos, label='cosdat')
#ax2.plot(times, np.zeros(len(times)))
for i in range(3):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
#ax2.set_ylim(0, 1.)
ax2.set_xlim(0, tsteps*dt+dt/2.)
#ax2.set_xlim(0, 1.)
ax2.set_xticks(np.arange(0,tsteps*dt+dt, 0.2))
#ax2.set_yticks(np.arange(0,1.1, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax2.legend(fontsize=20)
#Calculate total energy for 1D Hubbard model of N sites
#Number of sites in chain
N = 10
Ne = 10
#Filling factor
nu = Ne/N
#Hamiltonian parameters
t = 2.0 #Hopping
U = 4.0 #On-site repulsion
state = np.zeros(2*N)
#Add in space to populate array randomly, but do it by hand for now
#Populate Psi
n = 0
while n < Ne:
site = rand.randint(0,N-1)
spin = rand.randint(0,1)
if state[site+spin*N]==0:
state[site+spin*N] = 1
n+=1
print(state)
#Loop over state and gather energy
E = 0
############# ADD UP ENERGY FROM STATE #############
#Add hoppings at edges
if state[0]==1:
if state[1]==0:
E+=t/2.
if state[N-1]==0: #Periodic boundary
E+=t/2.
if state[N]==1:
if state[N+1]==0:
E+=t/2.
if state[-1]==0:
E+=t/2.
print('Ends of energy are: ',E)
for i in range(1,N-1):
print('i is: ',i)
#Check spin up sites if site is occupied and if electron can hop
if state[i]==1:
if state[i+1]==0:
E+=t/2.
if state[i-1]==0:
E+=t/2.
#Check spin down sites if site is occupied and if electron can hop
j = i+N
if state[j]==1:
if state[j+1]==0:
E+=t/2.
if state[j-1]==0:
E+=t/2.
#Check Hubbard repulsion terms
for i in range(0,N):
if state[i]==1 and state[i+N]==1:
E+=U/4.
print('Energy is: ',E)
print('State is: ',state)
#Try by constructing the matrix and finding the eigenvalues
N = 3
Nup = 2
Ndwn = N - Nup
t = 1.0
U = 2.5
#To generalize, try using permutations function but for now hard code this
#Store a list of 2d list of all the states where the 2d list stores the spin-up occupation
#and the spin down occupation
states = [ [1,1,0,1,0,0], [1,1,0,0,1,0], [1,1,0,0,0,1],
[1,0,1,1,0,0], [1,0,1,0,1,0], [1,0,1,0,0,1],
[0,1,1,1,0,0], [0,1,1,0,1,0], [0,1,1,0,0,1] ]
print(len(states))
H = np.zeros((len(states),len(states)) )
print(H[0,4])
print(states[0])
for i in range(len(states)):
psi_i = states[i]
for j in range(len(states)):
psi_j = states[j]
#Check over sites
#Check rest of state for hopping or double occupation
for l in range(1,N-1):
#Check edges
if psi_i[l]==1 and (psi_j[l+1]==1 and psi_i[l+1]==0) or (psi_j[l-1]==1 and psi_i[l-1]==0):
H[i,j] = -t/2.
break
if psi_i[l+N]==1 and (psi_j[l+1+N]==1 and psi_i[l+1+N]==0) or (psi_j[l-1+N]==1 and psi_i[l-1+N]==0):
H[i,j] = -t/2.
break
if psi_i==psi_j:
for l in range(N):
if psi_i[l]==1 and psi_j[l+N]==1:
H[i,j] = U/4.
break
print(H)
tst = [[0,1],[2,3]]
print(tst[1][1])
psi_i = [[1,1,0],[1,0,0]]
psi_j = [[1,1,0],[0,1,0]]
print(psi_j[0])
print(psi_j[1], ' 1st: ',psi_j[1][0], ' 2nd: ',psi_j[1][1], ' 3rd: ',psi_j[1][2])
for l in range(N):
print('l: ',l)
if psi_j[1][l]==0 and psi_j[1][l-1]==1:
psi_j[1][l]=1
psi_j[1][l-1]=0
print('1st')
print(psi_j)
break
if psi_j[1][l-1]==0 and psi_j[1][l]==1:
psi_j[1][l-1]=1
psi_j[1][l]=0
print('2nd')
print(psi_j)
break
if psi_j[1][l]==0 and psi_j[1][l+1]==1:
psi_j[1][l]=1
psi_j[1][l+1]=0
print('3rd: l=',l,' l+1=',l+1)
print(psi_j)
break
if psi_j[1][l+1]==0 and psi_j[1][l]==1:
psi_j[1][l+1]=1
psi_j[1][l]=0
print('4th')
print(psi_j)
break
def hoptst(l,m,spin,state):
#Spin is either 0 or 1 which corresponds to which array w/n state we're examining
if (state[spin][l]==0 and state[spin][m]==1):
state[spin][l]=1
state[spin][m]=0
return state
elif (state[spin][m]==0 and state[spin][l]==1):
state[spin][m]=1
state[spin][l]=0
return state
else:
return []
#Try using hoptst:
print(hoptst(0,1,1,psi_j))
### Function to permutate a given list
# Python function to print permutations of a given list
def permutation(lst):
# If lst is empty then there are no permutations
if len(lst) == 0:
return []
# If there is only one element in lst then, only
# one permuatation is possible
if len(lst) == 1:
return [lst]
# Find the permutations for lst if there are
# more than 1 characters
l = [] # empty list that will store current permutation
# Iterate the input(lst) and calculate the permutation
for i in range(len(lst)):
m = lst[i]
# Extract lst[i] or m from the list. remLst is
# remaining list
remLst = lst[:i] + lst[i+1:]
# Generating all permutations where m is first
# element
for p in permutation(remLst):
l.append([m] + p)
return l
# Driver program to test above function
data = list('1000')
for p in permutation(data):
print(p)
import itertools
items = [1,0,0]
perms = itertools.permutations
tst = 15.2
tst = np.full(3, tst)
print(tst)
H = np.array([[1, 1], [1, -1]])
H_2 = np.tensordot(H,H, 0)
print(H_2)
print('==============================')
M = np.array([[0,1,1,0],[1,1,0,0],[1,0,1,0],[0,0,0,1]])
print(M)
print(np.dot(np.conj(M.T),M))
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
# pylint: disable=redefined-outer-name
"""
Unit tests for QiskitProvider class
"""
import random
import warnings
from types import SimpleNamespace
from unittest.mock import MagicMock, Mock, patch
import numpy as np
import pytest
from qiskit import QuantumCircuit
from qiskit.providers import Job
from qiskit.providers.fake_provider import GenericBackendV2
from qiskit.providers.models import QasmBackendConfiguration
from qiskit_ibm_runtime import QiskitRuntimeService, RuntimeJob
from qiskit_ibm_runtime.exceptions import IBMNotAuthorizedError, RuntimeInvalidStateError
from qiskit_ibm_runtime.qiskit_runtime_service import QiskitBackendNotFoundError
from qbraid.programs import NATIVE_REGISTRY, ProgramSpec
from qbraid.runtime import DeviceActionType, DeviceStatus, DeviceType, JobStateError, TargetProfile
from qbraid.runtime.exceptions import QbraidRuntimeError
from qbraid.runtime.qiskit import QiskitBackend, QiskitJob, QiskitResult, QiskitRuntimeProvider
FIXTURE_COUNT = sum(key in NATIVE_REGISTRY for key in ["qiskit", "braket", "cirq"])
class FakeDevice(GenericBackendV2):
"""A test Qiskit device."""
# pylint: disable-next=too-many-arguments
def __init__(
self,
num_qubits,
local=True,
simulator=True,
operational=True,
status_msg="active",
**kwargs,
):
super().__init__(num_qubits)
self._num_qubits = num_qubits
self._operational = operational
self._status_msg = status_msg
self._local = local
self._simulator = simulator
self._instance = kwargs.get("instance", None)
def status(self):
"""Return the status of the backend."""
status_obj = SimpleNamespace()
status_obj.operational = self._operational
status_obj.status_msg = self._status_msg
# dummy value proportional to num_qubits
status_obj.pending_jobs = 0 if self._local else random.randint(1, 100)
return status_obj
def configuration(self):
"""Return the configuration of the backend."""
return QasmBackendConfiguration(
backend_name="fake_backend",
backend_version="1.0",
n_qubits=self._num_qubits,
basis_gates=["u1", "u2", "u3", "cx"],
gates=[],
local=self._local,
simulator=self._simulator,
conditional=False,
open_pulse=False,
memory=True,
max_shots=8192,
coupling_map=None,
)
class FakeService:
"""Fake Qiskit runtime service for testing."""
def backend(self, backend_name, instance=None):
"""Return fake backend."""
for backend in self.backends(instance=instance):
if backend_name == backend.name:
return backend
raise QiskitBackendNotFoundError("No backend matches the criteria.")
def backends(self, **kwargs): # pylint: disable=unused-argument
"""Return fake Qiskit backend."""
return [FakeDevice(num_qubits=n, **kwargs) for n in [5, 20]]
def backend_names(self, **kwargs):
"""Return fake backend names."""
return [backend.name for backend in self.backends(**kwargs)]
def least_busy(self, **kwargs):
"""Return the least busy backend based on the number of pending jobs."""
backends = self.backends(**kwargs)
return min(backends, key=lambda backend: backend.status().pending_jobs)
def job(self, job_id): # pylint: disable=unused-argument
"""Return fake job."""
return MagicMock(spec=RuntimeJob)
def _create_backend_fixture(service: FakeService, local: bool, simulator: bool) -> QiskitBackend:
"""Create a Qiskit backend fixture."""
backend = service.backends(local=local, simulator=simulator)[0]
program_spec = ProgramSpec(QuantumCircuit)
if local:
device_type = DeviceType.LOCAL_SIMULATOR
elif simulator:
device_type = DeviceType.SIMULATOR
else:
device_type = DeviceType.QPU
profile = TargetProfile(
device_id=backend.name,
device_type=device_type,
action_type=DeviceActionType.OPENQASM,
num_qubits=backend.num_qubits,
program_spec=program_spec,
provider_name="IBM",
)
return QiskitBackend(profile, service)
@pytest.fixture
def fake_service():
"""Return a fake Qiskit runtime service."""
return FakeService()
@pytest.fixture
def fake_device(fake_service):
"""Return a fake local simulator backend."""
return _create_backend_fixture(fake_service, local=True, simulator=True)
def test_provider_initialize_service():
"""Test getting IBMQ provider using qiskit_ibm_provider package."""
with patch("qbraid.runtime.qiskit.provider.QiskitRuntimeService") as mock_runtime_service:
mock_runtime_service.return_value = Mock(spec=QiskitRuntimeService)
provider = QiskitRuntimeProvider(token="test_token", channel="test_channel")
assert isinstance(provider.runtime_service, QiskitRuntimeService)
assert provider.token == "test_token"
assert provider.channel == "test_channel"
assert provider.runtime_service == mock_runtime_service.return_value
def test_provider_save_config(fake_service):
"""Test saving the IBM account configuration to disk."""
with patch("qbraid.runtime.qiskit.provider.QiskitRuntimeService") as mock_runtime_service:
mock_runtime_service.return_value = fake_service
provider = QiskitRuntimeProvider(token="fake_token", channel="fake_channel")
provider.save_config(token="fake_token", channel="fake_channel", overwrite=False)
mock_runtime_service.save_account.assert_called_once_with(
token="fake_token", channel="fake_channel", overwrite=False
)
provider.save_config()
mock_runtime_service.save_account.assert_called_with(
token="fake_token", channel="fake_channel", overwrite=True
)
@pytest.mark.parametrize(
"local,simulator,num_qubits,device_type",
[
(True, True, 20, DeviceType.LOCAL_SIMULATOR),
(False, True, 5, DeviceType.SIMULATOR),
(False, False, 5, DeviceType.QPU),
],
)
def test_provider_build_runtime_profile(local, simulator, num_qubits, device_type):
"""Test building runtime profile for Qiskit backend."""
with patch("qbraid.runtime.qiskit.provider.QiskitRuntimeService") as mock_runtime_service:
mock_runtime_service.return_value = FakeService()
backend = FakeDevice(num_qubits, local=local, simulator=simulator)
provider = QiskitRuntimeProvider(token="test_token", channel="test_channel")
profile = provider._build_runtime_profile(backend)
assert profile["device_id"] == f"generic_backend_{num_qubits}q"
assert profile["device_type"] == device_type.name
assert profile["num_qubits"] == num_qubits
assert profile["max_shots"] == 8192
qiskit_backend = QiskitBackend(profile, mock_runtime_service())
assert isinstance(qiskit_backend, QiskitBackend)
assert qiskit_backend.profile == profile
def test_provider_get_devices(fake_service):
"""Test getting a backend from the runtime service."""
with patch("qbraid.runtime.qiskit.provider.QiskitRuntimeService") as mock_runtime_service:
mock_runtime_service.return_value = fake_service
provider = QiskitRuntimeProvider(token="test_token", channel="test_channel")
devices = provider.get_devices()
assert len(devices) == 2
assert all(isinstance(device, QiskitBackend) for device in devices)
device = devices[0]
device_copy = provider.get_device(device.id)
assert device.id == device_copy.id
assert str(device) == f"QiskitBackend('{device.id}')"
@pytest.mark.parametrize("local", [True, False])
def test_provider_least_busy(fake_service, local):
"""Test getting a backend from the runtime service, both local and non-local."""
with patch("qbraid.runtime.qiskit.provider.QiskitRuntimeService") as mock_provider_service:
mock_provider_service.return_value = fake_service
provider = QiskitRuntimeProvider(token="test_token", channel="test_channel")
least_busy = provider.least_busy(local=local)
least_busy._backend = FakeDevice(5, local=local)
assert least_busy.queue_depth() == 0 if local else least_busy.queue_depth() > 0
@pytest.mark.parametrize(
"operational,local,status_msg,expected_status",
[
(True, True, "active", DeviceStatus.ONLINE),
(True, False, "active", DeviceStatus.ONLINE),
(True, False, "not active", DeviceStatus.UNAVAILABLE),
(False, False, None, DeviceStatus.OFFLINE),
],
)
def test_device_status(fake_service, operational, local, status_msg, expected_status):
"""Test getting a backend from the runtime service, both local and non-local."""
with patch("qbraid.runtime.qiskit.provider.QiskitRuntimeService") as mock_provider_service:
mock_provider_service.return_value = fake_service
provider = QiskitRuntimeProvider(token="test_token", channel="test_channel")
params = {"operational": operational, "local": local, "status_msg": status_msg}
device = provider.get_devices(**params)[0]
device._backend = FakeDevice(device.num_qubits, **params)
assert device.status() == expected_status
@pytest.mark.parametrize("circuit", range(FIXTURE_COUNT), indirect=True)
def test_device_run(fake_device, circuit):
"""Test run method from wrapped fake Qiskit backends"""
with warnings.catch_warnings():
warnings.simplefilter(action="ignore", category=RuntimeWarning)
qbraid_job = fake_device.run(circuit, shots=10)
vendor_job = qbraid_job._job
assert isinstance(qbraid_job, QiskitJob)
assert isinstance(vendor_job, Job)
def test_device_run_batch(fake_device, run_inputs):
"""Test run method from wrapped fake Qiskit backends"""
with warnings.catch_warnings():
warnings.simplefilter(action="ignore", category=RuntimeWarning)
qbraid_job = fake_device.run(run_inputs, shots=10)
vendor_job = qbraid_job._job
assert isinstance(qbraid_job, QiskitJob)
assert isinstance(vendor_job, Job)
@pytest.fixture
def mock_service():
"""Fixture to create a mock QiskitRuntimeService."""
service = MagicMock(spec=QiskitRuntimeService)
service.job.return_value = MagicMock(spec=RuntimeJob)
return service
def test_job_initialize_from_service(mock_service):
"""Test successful job retrieval with a provided service.
Args:
mock_service (MagicMock): A mocked service passed as a fixture.
Tests that QiskitJob retrieves a job using a provided mock service and verifies
that the job method is called exactly once with the correct job ID.
"""
job_id = "test_job_id"
job = QiskitJob(job_id, service=mock_service)
assert job._job is not None
mock_service.job.assert_called_once_with(job_id)
def test_job_initialize_service_from_device(mock_service):
"""Test job retrieval when service is provided via the device attribute."""
mock_device = MagicMock()
mock_device._service = mock_service
job_id = "test_job_id"
job = QiskitJob(job_id, device=mock_device)
assert job._job is not None
mock_service.job.assert_called_once_with(job_id)
def test_job_service_initialization():
"""Test job retrieval when initializing a new service."""
with patch("qbraid.runtime.qiskit.job.QiskitRuntimeService") as mock_service_class:
mock_service = MagicMock(spec=QiskitRuntimeService)
mock_service.job.return_value = MagicMock(spec=RuntimeJob)
mock_service_class.return_value = mock_service
job_id = "test_job_id"
job = QiskitJob(job_id)
assert job._job is not None
mock_service.job.assert_called_once_with(job_id)
def test_job_service_initialization_failure():
"""Test handling of service initialization failure."""
with patch("qbraid.runtime.qiskit.job.QiskitRuntimeService", side_effect=IBMNotAuthorizedError):
job_id = "test_job_id"
with pytest.raises(QbraidRuntimeError) as exc_info:
QiskitJob(job_id)
assert "Failed to initialize the quantum service." in str(exc_info.value)
def test_job_retrieval_failure(mock_service):
"""Test handling of job retrieval failure."""
mock_service.job.side_effect = ConnectionError
job_id = "test_job_id"
with pytest.raises(QbraidRuntimeError) as exc_info:
QiskitJob(job_id, service=mock_service)
assert "Error retrieving job test_job_id" in str(exc_info.value)
@pytest.fixture
def mock_runtime_job():
"""Fixture to create a mock QiskitRuntimeJob object."""
return MagicMock()
def test_job_queue_position(mock_runtime_job):
"""Test that the queue position of the job is correctly returned."""
queue_position = 5
mock_runtime_job.queue_position.return_value = queue_position
job = QiskitJob(job_id="123", job=mock_runtime_job)
assert job.queue_position() == queue_position
def test_cancel_job_in_terminal_state(mock_runtime_job):
"""Test attempting to cancel a job in a terminal state raises JobStateError."""
job = QiskitJob(job_id="123", job=mock_runtime_job)
job.is_terminal_state = MagicMock(return_value=True) # Simulate terminal state
with pytest.raises(JobStateError, match="Cannot cancel quantum job in non-terminal state."):
job.cancel()
def test_cancel_job_success(mock_runtime_job):
"""Test successful cancellation of a non-terminal job."""
job = QiskitJob(job_id="123", job=mock_runtime_job)
job.is_terminal_state = MagicMock(return_value=False)
mock_runtime_job.cancel.return_value = None
assert job.cancel() is None
def test_cancel_job_fails_due_to_runtime_error(mock_runtime_job):
"""Test that cancellation fails with a RuntimeInvalidStateError and raises JobStateError."""
mock_job = mock_runtime_job
mock_job.cancel.side_effect = RuntimeInvalidStateError
job = QiskitJob(job_id="123", job=mock_job)
job.is_terminal_state = MagicMock(return_value=False)
with pytest.raises(JobStateError):
job.cancel()
@pytest.fixture
def mock_runtime_result():
"""Return a mock Qiskit result."""
mock_result = Mock()
mock_result.results = [Mock(), Mock()]
meas1 = ["01"] * 9 + ["10"] + ["11"] * 4 + ["00"] * 6
meas2 = ["0"] * 8 + ["1"] * 12
mock_result.get_memory.side_effect = [meas1, meas2]
mock_result.get_counts.side_effect = [{"01": 9, "10": 1, "11": 4, "00": 6}, {"0": 8, "1": 12}]
return mock_result
def test_result_from_job(mock_runtime_job, mock_runtime_result):
"""Test that result returns QiskitResult when the job is in a terminal state."""
mock_job = QiskitJob(job_id="123", job=mock_runtime_job)
mock_runtime_job.result.return_value = mock_runtime_result
result = mock_job.result()
assert isinstance(result, QiskitResult)
assert isinstance(result.raw_counts(), dict)
assert isinstance(result.measurements(), np.ndarray)
def test_result_raw_counts(mock_runtime_result):
"""Test getting raw counts from a Qiskit result."""
qr = QiskitResult()
qr._result = mock_runtime_result
expected = {"01": 9, "10": 1, "11": 4, "00": 6}
assert qr.raw_counts() == expected
def test_result_format_measurements():
"""Test formatting measurements into integers."""
qr = QiskitResult()
memory_list = ["010", "111"]
expected = [[0, 1, 0], [1, 1, 1]]
assert qr._format_measurements(memory_list) == expected
def test_result_measurements_single_circuit(mock_runtime_result):
"""Test getting measurements from a single circuit."""
qr = QiskitResult()
qr._result = mock_runtime_result
mock_runtime_result.results = [Mock()]
expected = np.array([[0, 1]] * 9 + [[1, 0]] + [[1, 1]] * 4 + [[0, 0]] * 6)
assert np.array_equal(qr.measurements(), expected)
def test_result_measurements_multiple_circuits(mock_runtime_result):
"""Test getting measurements from multiple circuits."""
qr = QiskitResult()
qr._result = mock_runtime_result
expected_meas1 = np.array([[0, 1]] * 9 + [[1, 0]] + [[1, 1]] * 4 + [[0, 0]] * 6)
expected_meas2 = np.array([[0, 0]] * 8 + [[0, 1]] * 12)
expected = np.array([expected_meas1, expected_meas2])
assert np.array_equal(qr.measurements(), expected)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford, random_clifford
qc = QuantumCircuit(3)
cliff = random_clifford(2)
qc.append(cliff, [0, 1])
qc.ccx(0, 1, 2)
qc.draw('mpl')
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
import math
import random
import numpy as np
from scipy.optimize import minimize
def apply_fixed_ansatz(qubits, parameters):
for iz in range (0, len(qubits)):
circ.ry(parameters[0][iz], qubits[iz])
circ.cz(qubits[0], qubits[1])
circ.cz(qubits[2], qubits[0])
for iz in range (0, len(qubits)):
circ.ry(parameters[1][iz], qubits[iz])
circ.cz(qubits[1], qubits[2])
circ.cz(qubits[2], qubits[0])
for iz in range (0, len(qubits)):
circ.ry(parameters[2][iz], qubits[iz])
circ = QuantumCircuit(3)
apply_fixed_ansatz([0, 1, 2], [[1, 1, 1], [1, 1, 1], [1, 1, 1]])
print(circ)
#Creates the Hadamard test
def had_test(gate_type, qubits, ancilla_index, parameters):
circ.h(ancilla_index)
apply_fixed_ansatz(qubits, parameters)
for ie in range (0, len(gate_type[0])):
if (gate_type[0][ie] == 1):
circ.cz(ancilla_index, qubits[ie])
for ie in range (0, len(gate_type[1])):
if (gate_type[1][ie] == 1):
circ.cz(ancilla_index, qubits[ie])
circ.h(ancilla_index)
circ = QuantumCircuit(4)
had_test([[0, 0, 0], [0, 0, 1]], [1, 2, 3], 0, [[1, 1, 1], [1, 1, 1], [1, 1, 1]])
print(circ)
#Creates controlled anstaz for calculating |<b|psi>|^2 with a Hadamard test
def control_fixed_ansatz(qubits, parameters, ancilla, reg):
for i in range (0, len(qubits)):
circ.cry(parameters[0][i], qiskit.circuit.Qubit(reg, ancilla), qiskit.circuit.Qubit(reg, qubits[i]))
circ.ccx(ancilla, qubits[1], 4)
circ.cz(qubits[0], 4)
circ.ccx(ancilla, qubits[1], 4)
circ.ccx(ancilla, qubits[0], 4)
circ.cz(qubits[2], 4)
circ.ccx(ancilla, qubits[0], 4)
for i in range (0, len(qubits)):
circ.cry(parameters[1][i], qiskit.circuit.Qubit(reg, ancilla), qiskit.circuit.Qubit(reg, qubits[i]))
circ.ccx(ancilla, qubits[2], 4)
circ.cz(qubits[1], 4)
circ.ccx(ancilla, qubits[2], 4)
circ.ccx(ancilla, qubits[0], 4)
circ.cz(qubits[2], 4)
circ.ccx(ancilla, qubits[0], 4)
for i in range (0, len(qubits)):
circ.cry(parameters[2][i], qiskit.circuit.Qubit(reg, ancilla), qiskit.circuit.Qubit(reg, qubits[i]))
q_reg = QuantumRegister(5)
circ = QuantumCircuit(q_reg)
control_fixed_ansatz([1, 2, 3], [[1, 1, 1], [1, 1, 1], [1, 1, 1]], 0, q_reg)
print(circ)
def control_b(ancilla, qubits):
for ia in qubits:
circ.ch(ancilla, ia)
circ = QuantumCircuit(4)
control_b(0, [1, 2, 3])
print(circ)
#Create the controlled Hadamard test, for calculating <psi|psi>
def special_had_test(gate_type, qubits, ancilla_index, parameters, reg):
circ.h(ancilla_index)
control_fixed_ansatz(qubits, parameters, ancilla_index, reg)
for ty in range (0, len(gate_type)):
if (gate_type[ty] == 1):
circ.cz(ancilla_index, qubits[ty])
control_b(ancilla_index, qubits)
circ.h(ancilla_index)
q_reg = QuantumRegister(5)
circ = QuantumCircuit(q_reg)
special_had_test([[0, 0, 0], [0, 0, 1]], [1, 2, 3], 0, [[1, 1, 1], [1, 1, 1], [1, 1, 1]], q_reg)
print(circ)
#Implements the entire cost function on the quantum circuit
def calculate_cost_function(parameters):
global opt
overall_sum_1 = 0
parameters = [parameters[0:3], parameters[3:6], parameters[6:9]]
for i in range(0, len(gate_set)):
for j in range(0, len(gate_set)):
global circ
qctl = QuantumRegister(5)
qc = ClassicalRegister(5)
circ = QuantumCircuit(qctl, qc)
backend = Aer.get_backend('statevector_simulator')
multiply = coefficient_set[i]*coefficient_set[j]
had_test([gate_set[i], gate_set[j]], [1, 2, 3], 0, parameters)
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=100)
o = outputstate
m_sum = 0
for l in range (0, len(o)):
if (l%2 == 1):
n = float(o[l])**2
m_sum+=n
overall_sum_1+=multiply*(1-(2*m_sum))
overall_sum_2 = 0
for i in range(0, len(gate_set)):
for j in range(0, len(gate_set)):
multiply = coefficient_set[i]*coefficient_set[j]
mult = 1
for extra in range(0, 2):
qctl = QuantumRegister(5)
qc = ClassicalRegister(5)
circ = QuantumCircuit(qctl, qc)
backend = Aer.get_backend('statevector_simulator')
if (extra == 0):
special_had_test(gate_set[i], [1, 2, 3], 0, parameters, qctl)
if (extra == 1):
special_had_test(gate_set[j], [1, 2, 3], 0, parameters, qctl)
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=100)
o = outputstate
m_sum = 0
for l in range (0, len(o)):
if (l%2 == 1):
n = float(o[l])**2
m_sum+=n
mult = mult*(1-(2*m_sum))
overall_sum_2+=multiply*mult
print(1-float(overall_sum_2/overall_sum_1))
return 1-float(overall_sum_2/overall_sum_1)
coefficient_set = [0.55, 0.45]
gate_set = [[0, 0, 0], [0, 0, 1]]
out = minimize(calculate_cost_function, x0=[float(random.randint(0,3000))/1000 for i in range(0, 9)], method="COBYLA", options={'maxiter':200})
print(out)
out_f = [out['x'][0:3], out['x'][3:6], out['x'][6:9]]
circ = QuantumCircuit(3, 3)
apply_fixed_ansatz([0, 1, 2], out_f)
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
o = result.get_statevector(circ, decimals=10)
a1 = coefficient_set[1]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,-1,0,0,0], [0,0,0,0,0,-1,0,0], [0,0,0,0,0,0,-1,0], [0,0,0,0,0,0,0,-1]])
a2 = coefficient_set[0]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,1]])
a3 = np.add(a1, a2)
b = np.array([float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8))])
print((b.dot(a3.dot(o)/(np.linalg.norm(a3.dot(o)))))**2)
coefficient_set = [0.55, 0.225, 0.225]
gate_set = [[0, 0, 0], [0, 1, 0], [0, 0, 1]]
out = minimize(calculate_cost_function, x0=[float(random.randint(0,3000))/1000 for i in range(0, 9)], method="COBYLA", options={'maxiter':200})
print(out)
out_f = [out['x'][0:3], out['x'][3:6], out['x'][6:9]]
circ = QuantumCircuit(3, 3)
apply_fixed_ansatz([0, 1, 2], out_f)
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
o = result.get_statevector(circ, decimals=10)
a1 = coefficient_set[2]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,-1,0,0,0], [0,0,0,0,0,-1,0,0], [0,0,0,0,0,0,-1,0], [0,0,0,0,0,0,0,-1]])
a0 = coefficient_set[1]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,-1,0,0,0,0,0], [0,0,0,-1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,-1,0], [0,0,0,0,0,0,0,-1]])
a2 = coefficient_set[0]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,1]])
a3 = np.add(np.add(a2, a0), a1)
b = np.array([float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8))])
print((b.dot(a3.dot(o)/(np.linalg.norm(a3.dot(o)))))**2)
#Implements the entire cost function on the quantum circuit (sampling, 100000 shots)
def calculate_cost_function(parameters):
global opt
overall_sum_1 = 0
parameters = [parameters[0:3], parameters[3:6], parameters[6:9]]
for i in range(0, len(gate_set)):
for j in range(0, len(gate_set)):
global circ
qctl = QuantumRegister(5)
qc = ClassicalRegister(1)
circ = QuantumCircuit(qctl, qc)
backend = Aer.get_backend('qasm_simulator')
multiply = coefficient_set[i]*coefficient_set[j]
had_test([gate_set[i], gate_set[j]], [1, 2, 3], 0, parameters)
circ.measure(0, 0)
job = execute(circ, backend, shots=100000)
result = job.result()
outputstate = result.get_counts(circ)
if ('1' in outputstate.keys()):
m_sum = float(outputstate["1"])/100000
else:
m_sum = 0
overall_sum_1+=multiply*(1-2*m_sum)
overall_sum_2 = 0
for i in range(0, len(gate_set)):
for j in range(0, len(gate_set)):
multiply = coefficient_set[i]*coefficient_set[j]
mult = 1
for extra in range(0, 2):
qctl = QuantumRegister(5)
qc = ClassicalRegister(1)
circ = QuantumCircuit(qctl, qc)
backend = Aer.get_backend('qasm_simulator')
if (extra == 0):
special_had_test(gate_set[i], [1, 2, 3], 0, parameters, qctl)
if (extra == 1):
special_had_test(gate_set[j], [1, 2, 3], 0, parameters, qctl)
circ.measure(0, 0)
job = execute(circ, backend, shots=100000)
result = job.result()
outputstate = result.get_counts(circ)
if ('1' in outputstate.keys()):
m_sum = float(outputstate["1"])/100000
else:
m_sum = 0
mult = mult*(1-2*m_sum)
overall_sum_2+=multiply*mult
print(1-float(overall_sum_2/overall_sum_1))
return 1-float(overall_sum_2/overall_sum_1)
coefficient_set = [0.55, 0.225, 0.225]
gate_set = [[0, 0, 0], [0, 1, 0], [0, 0, 1]]
out = minimize(calculate_cost_function, x0=[float(random.randint(0,3000))/1000 for i in range(0, 9)], method="COBYLA", options={'maxiter':200})
print(out)
out_f = [out['x'][0:3], out['x'][3:6], out['x'][6:9]]
circ = QuantumCircuit(3, 3)
apply_fixed_ansatz([0, 1, 2], out_f)
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
o = result.get_statevector(circ, decimals=10)
a1 = coefficient_set[2]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,-1,0,0,0], [0,0,0,0,0,-1,0,0], [0,0,0,0,0,0,-1,0], [0,0,0,0,0,0,0,-1]])
a0 = coefficient_set[1]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,-1,0,0,0,0,0], [0,0,0,-1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,-1,0], [0,0,0,0,0,0,0,-1]])
a2 = coefficient_set[0]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,1]])
a3 = np.add(np.add(a2, a0), a1)
b = np.array([float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8))])
print((b.dot(a3.dot(o)/(np.linalg.norm(a3.dot(o)))))**2)
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
from transpile_benchy.metrics.gate_counts import (
DepthMetric,
TotalMetric,
TotalSwaps,
)
from qiskit.circuit.library import iSwapGate
from qiskit.transpiler import CouplingMap
from mirror_gates.pass_managers import Mirage, QiskitLevel3
from mirror_gates.utilities import SubsMetric
from mirror_gates.logging import transpile_benchy_logger
# N = 4
# coupling_map = CouplingMap.from_line(N)
# coupling_map = CouplingMap.from_heavy_hex(5)
coupling_map = CouplingMap.from_grid(6, 6)
from transpile_benchy.library import CircuitLibrary
library = CircuitLibrary.from_txt("../../../circuits/medium_circuits.txt")
# library = CircuitLibrary.from_txt("../../circuits/debug.txt")
# XXX set consolidate to False
# this is allowed only because my pass manager will preserve consolidation
# see post_stage, I call fastconsolidate manually
# NOTE: use TotalSwaps to verify baselines have > 0 swaps
# otherwise, there is no room for improvement.
# we can include these if we want to show our methods will still work
# but somewhat trivial since we just append VF2Layout
metrics = [
DepthMetric(consolidate=False),
TotalMetric(consolidate=False),
TotalSwaps(consolidate=False),
SubsMetric(),
]
transpilers = [
# QiskitLevel3(coupling_map, cx_basis=True),
# Mirage(coupling_map, cx_basis=True, parallel=0),
QiskitLevel3(coupling_map),
Mirage(coupling_map, logger=transpile_benchy_logger),
]
from transpile_benchy.benchmark import Benchmark
benchmark = Benchmark(
transpilers=transpilers,
circuit_library=library,
metrics=metrics,
logger=transpile_benchy_logger,
num_runs=5,
)
benchmark.run()
# print(benchmark)
print(benchmark)
benchmark.summary_statistics(transpilers[0], transpilers[1])
from transpile_benchy.render import plot_benchmark
plot_benchmark(benchmark, save=1, legend_show=0, filename="grid", color_override=[0, 3])
|
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
|
PavanCyborg
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
class DeutschJozsa:
'''
Class to generate a DeutschJozsa object containing:
- init functions
- oracle function
- dj function
'''
def __init__(self, case, input_str):
'''
Initialization of the object:
@case: (str) type of oracle balanced or constant
@input_str: (str) string input state values
'''
self.case = case
self.number_qubit = len(input_str)
self.str_input = input_str
def oracle(self):
'''
Will create the oracle needed for the Deutsch-Jozsa algorithm
No input, the function will be used in the dj function
@return the oracle in form of a gate
'''
# Create the QuantumCircuit with n+1 qubits
self.oracle_circuit = QuantumCircuit(self.number_qubit+1)
# Balanced case
if self.case == "balanced":
# apply an X-gate to a qubit when its value is 1
for qubit in range(len(self.str_input)):
if self.str_input[qubit] == '1':
self.oracle_circuit.x(qubit)
# Apply CNOT gates on each qubit
for qubit in range(self.number_qubit):
self.oracle_circuit.cx(qubit, self.number_qubit)
# apply another set of X gates when the input qubit == 1
for qubit in range(len(self.str_input)):
if self.str_input[qubit] == '1':
self.oracle_circuit.x(qubit)
# Constant case
if self.case == "constant":
# Output 0 for a constant oracle
self.output = np.random.randint(2)
if self.output == 1:
self.oracle_circuit.x(self.number_qubit)
# convert the quantum circuit into a gate
self.oracle_gate = self.oracle_circuit.to_gate()
# name of the oracle
self.oracle_gate.name = "Oracle"
return self.oracle_gate
def dj(self):
'''
Create the Deutsch-Jozsa algorithm in the general case with n qubit
No input
@return the quantum circuit of the DJ
'''
self.dj_circuit = QuantumCircuit(self.number_qubit+1, self.number_qubit)
# Set up the output qubit:
self.dj_circuit.x(self.number_qubit)
self.dj_circuit.h(self.number_qubit)
# Psi_0
for qubit in range(self.number_qubit):
self.dj_circuit.h(qubit)
# Psi_1 + oracle
self.dj_circuit.append(self.oracle(), range(self.number_qubit+1))
# Psi_2
for qubit in range(self.number_qubit):
self.dj_circuit.h(qubit)
# Psi_3
# Let's put some measurement
for i in range(self.number_qubit):
self.dj_circuit.measure(i, i)
return self.dj_circuit
test = DeutschJozsa('constant', '0110')
#circuit = test.oracle()
dj_circuit = test.dj()
dj_circuit.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
from qiskit import IBMQ
#TOKEN = 'paste your token here'
#IBMQ.save_account(TOKEN)
IBMQ.load_account() # Load account from disk
IBMQ.providers()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
provider.backends(filters=lambda x: x.configuration().n_qubits >= 5
and not x.configuration().simulator
and x.status().operational==True)
backend = provider.get_backend('ibmq_manila')
backend
mapped_circuit = transpile(dj_circuit, backend=backend)
qobj = assemble(mapped_circuit, backend=backend, shots=1024)
job = backend.run(qobj)
job.status() # 9:17 pm
result = job.result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
plot_histogram(counts,figsize=(10,8), filename='DJ.jpeg')
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
# with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
# with open(filename, "wb") as f:
# pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
# with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump(backend.properties(), f)
retrieved_jobs = jobs
retrieved_cal_job = cal_job
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/joemoorhouse/quantum-mc
|
joemoorhouse
|
from qiskit import QuantumRegister, QuantumCircuit, Aer, execute
from qiskit.circuit.library import LinearAmplitudeFunction
from qiskit.aqua.algorithms import IterativeAmplitudeEstimation
import numpy as np
# define linear objective function
num_sum_qubits = 5
breakpoints = [0]
slopes = [1]
offsets = [0]
f_min = 0
f_max = 10
c_approx = 0.25
objective = LinearAmplitudeFunction(
num_sum_qubits,
slope=slopes,
offset=offsets,
# max value that can be reached by the qubit register (will not always be reached)
domain=(0, 2**num_sum_qubits-1),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints
)
qr_sum = QuantumRegister(5, "sum")
state_preparation = QuantumCircuit(qr_sum) # to complete
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
# construct amplitude estimation
ae_cdf = IterativeAmplitudeEstimation(state_preparation=state_preparation,
epsilon=epsilon, alpha=alpha,
objective_qubits=[len(qr_sum)])
result_cdf = ae_cdf.run(quantum_instance=Aer.get_backend('qasm_simulator'), shots=100)
# print results
exact_value = 1 # to calculate
conf_int = np.array(result_cdf['confidence_interval'])
print('Exact value: \t%.4f' % exact_value)
print('Estimated value:\t%.4f' % result_cdf['estimation'])
print('Confidence interval: \t[%.4f, %.4f]' % tuple(conf_int))
def transform_from_
|
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/C2QA/bosonic-qiskit
|
C2QA
|
import json
import logging
import numpy as np
import warnings
from functools import wraps
from typing import Any, Callable, Optional, Tuple, Union
from qiskit import IBMQ, QuantumCircuit, assemble
from qiskit.circuit import Barrier, Gate, Instruction, Measure
from qiskit.circuit.library import UGate, U3Gate, CXGate
from qiskit.providers.ibmq import AccountProvider, IBMQProviderError
from qiskit.providers.ibmq.job import IBMQJob
def get_provider() -> AccountProvider:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
ibmq_logger = logging.getLogger('qiskit.providers.ibmq')
current_level = ibmq_logger.level
ibmq_logger.setLevel(logging.ERROR)
# get provider
try:
provider = IBMQ.get_provider()
except IBMQProviderError:
provider = IBMQ.load_account()
ibmq_logger.setLevel(current_level)
return provider
def get_job(job_id: str) -> Optional[IBMQJob]:
try:
job = get_provider().backends.retrieve_job(job_id)
return job
except Exception:
pass
return None
def circuit_to_json(qc: QuantumCircuit) -> str:
class _QobjEncoder(json.encoder.JSONEncoder):
def default(self, obj: Any) -> Any:
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, complex):
return (obj.real, obj.imag)
return json.JSONEncoder.default(self, obj)
return json.dumps(circuit_to_dict(qc), cls=_QobjEncoder)
def circuit_to_dict(qc: QuantumCircuit) -> dict:
qobj = assemble(qc)
return qobj.to_dict()
def get_job_urls(job: Union[str, IBMQJob]) -> Tuple[bool, Optional[str], Optional[str]]:
try:
job_id = job.job_id() if isinstance(job, IBMQJob) else job
download_url = get_provider()._api_client.account_api.job(job_id).download_url()['url']
result_url = get_provider()._api_client.account_api.job(job_id).result_url()['url']
return download_url, result_url
except Exception:
return None, None
def cached(key_function: Callable) -> Callable:
def _decorator(f: Any) -> Callable:
f.__cache = {}
@wraps(f)
def _decorated(*args: Any, **kwargs: Any) -> int:
key = key_function(*args, **kwargs)
if key not in f.__cache:
f.__cache[key] = f(*args, **kwargs)
return f.__cache[key]
return _decorated
return _decorator
def gate_key(gate: Gate) -> Tuple[str, int]:
return gate.name, gate.num_qubits
@cached(gate_key)
def gate_cost(gate: Gate) -> int:
if isinstance(gate, (UGate, U3Gate)):
return 1
elif isinstance(gate, CXGate):
return 10
elif isinstance(gate, (Measure, Barrier)):
return 0
return sum(map(gate_cost, (g for g, _, _ in gate.definition.data)))
def compute_cost(circuit: Union[Instruction, QuantumCircuit]) -> int:
print('Computing cost...')
circuit_data = None
if isinstance(circuit, QuantumCircuit):
circuit_data = circuit.data
elif isinstance(circuit, Instruction):
circuit_data = circuit.definition.data
else:
raise Exception(f'Unable to obtain circuit data from {type(circuit)}')
return sum(map(gate_cost, (g for g, _, _ in circuit_data)))
def uses_multiqubit_gate(circuit: QuantumCircuit) -> bool:
circuit_data = None
if isinstance(circuit, QuantumCircuit):
circuit_data = circuit.data
elif isinstance(circuit, Instruction) and circuit.definition is not None:
circuit_data = circuit.definition.data
else:
raise Exception(f'Unable to obtain circuit data from {type(circuit)}')
for g, _, _ in circuit_data:
if isinstance(g, (Barrier, Measure)):
continue
elif isinstance(g, Gate):
if g.num_qubits > 1:
return True
elif isinstance(g, (QuantumCircuit, Instruction)) and uses_multiqubit_gate(g):
return True
return False
|
https://github.com/nahumsa/volta
|
nahumsa
|
def dswap_test_circuit(qc1: QuantumCircuit, qc2: QuantumCircuit) -> QuantumCircuit:
""" Construct the destructive SWAP test circuit given two circuits.
Args:
qc1(qiskit.QuantumCircuit): Quantum circuit for the
first state.
qc2(qiskit.QuantumCircuit): Quantum circuit for the
second state.
Output:
(qiskit.QuantumCircuit): swap test circuit.
"""
# Helper variables
n_total = qc1.num_qubits + qc2.num_qubits
range_qc1 = [i for i in range(qc1.num_qubits)]
range_qc2 = [i + qc1.num_qubits for i in range(qc2.num_qubits)]
# Constructing the SWAP test circuit
qc_swap = QuantumCircuit(n_total , n_total)
qc_swap.append(qc1, range_qc1)
qc_swap.append(qc2, range_qc2)
for index, qubit in enumerate(range_qc1):
qc_swap.cx(qubit, range_qc2[index])
qc_swap.h(qubit)
for index, qubit in enumerate(range_qc1):
qc_swap.measure(qubit, 2*index)
for index, qubit in enumerate(range_qc2):
qc_swap.measure(range_qc2[index] , 2*index + 1)
return qc_swap
import textwrap
import qiskit
from qiskit import QuantumCircuit, execute
from typing import Union
from qiskit.aqua import QuantumInstance
from qiskit.providers import BaseBackend
def measure_dswap_test(qc1: QuantumCircuit, qc2: QuantumCircuit,
backend: Union[BaseBackend,QuantumInstance],
num_shots: int=10000) -> float:
"""Returns the fidelity from a destructive SWAP test.
Args:
qc1 (QuantumCircuit): Quantum Circuit for the first state.
qc2 (QuantumCircuit): Quantum Circuit for the second state.
backend (Union[BaseBackend,QuantumInstance]): Backend.
num_shots (int, optional): Number of shots. Defaults to 10000.
Returns:
float: result of the overlap betweeen the first and second state.
"""
n = qc1.num_qubits
swap_circuit = dswap_test_circuit(qc1, qc2)
# Check if the backend is a quantum instance.
if qiskit.aqua.quantum_instance.QuantumInstance == type(backend):
count = backend.execute(swap_circuit).get_counts()
else:
count = execute(swap_circuit, backend=backend, shots=num_shots).result().get_counts()
result = 0
for meas, counts in count.items():
split_meas = textwrap.wrap(meas, 2)
for m in split_meas:
if m == '11':
result -= counts
else:
result += counts
total = sum(count.values())
return result/(n*total)
from qiskit import QuantumCircuit, execute
qc1 = QuantumCircuit(n)
qc2 = QuantumCircuit(n)
backend = BasicAer.get_backend('qasm_simulator')
measure_dswap_test(qc1, qc2, backend)
from qiskit import BasicAer
backend = BasicAer.get_backend('qasm_simulator')
num_shots = 10000
count = execute(swap_circuit, backend=backend, shots=num_shots).result().get_counts()
import textwrap
result = 0
for meas, counts in count.items():
split_meas = textwrap.wrap(meas, 2)
for m in split_meas:
if m == '11':
result -= counts
else:
result += counts
total = sum(count.values())
result/(n*total)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# External imports
from pylab import cm
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
# Qiskit imports
from qiskit import QuantumCircuit
from qiskit.circuit import ParameterVector
from qiskit.visualization import circuit_drawer
from qiskit.algorithms.optimizers import SPSA
from qiskit.circuit.library import ZZFeatureMap
from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel
from qiskit_machine_learning.kernels.algorithms import QuantumKernelTrainer
from qiskit_machine_learning.algorithms import QSVC
from qiskit_machine_learning.datasets import ad_hoc_data
class QKTCallback:
"""Callback wrapper class."""
def __init__(self) -> None:
self._data = [[] for i in range(5)]
def callback(self, x0, x1=None, x2=None, x3=None, x4=None):
"""
Args:
x0: number of function evaluations
x1: the parameters
x2: the function value
x3: the stepsize
x4: whether the step was accepted
"""
self._data[0].append(x0)
self._data[1].append(x1)
self._data[2].append(x2)
self._data[3].append(x3)
self._data[4].append(x4)
def get_callback_data(self):
return self._data
def clear_callback_data(self):
self._data = [[] for i in range(5)]
adhoc_dimension = 2
X_train, y_train, X_test, y_test, adhoc_total = ad_hoc_data(
training_size=20,
test_size=5,
n=adhoc_dimension,
gap=0.3,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
plt.scatter(
X_train[np.where(y_train[:] == 0), 0],
X_train[np.where(y_train[:] == 0), 1],
marker="s",
facecolors="w",
edgecolors="b",
label="A train",
)
plt.scatter(
X_train[np.where(y_train[:] == 1), 0],
X_train[np.where(y_train[:] == 1), 1],
marker="o",
facecolors="w",
edgecolors="r",
label="B train",
)
plt.scatter(
X_test[np.where(y_test[:] == 0), 0],
X_test[np.where(y_test[:] == 0), 1],
marker="s",
facecolors="b",
edgecolors="w",
label="A test",
)
plt.scatter(
X_test[np.where(y_test[:] == 1), 0],
X_test[np.where(y_test[:] == 1), 1],
marker="o",
facecolors="r",
edgecolors="w",
label="B test",
)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for classification")
plt.show()
# Create a rotational layer to train. We will rotate each qubit the same amount.
training_params = ParameterVector("θ", 1)
fm0 = QuantumCircuit(2)
fm0.ry(training_params[0], 0)
fm0.ry(training_params[0], 1)
# Use ZZFeatureMap to represent input data
fm1 = ZZFeatureMap(2)
# Create the feature map, composed of our two circuits
fm = fm0.compose(fm1)
print(circuit_drawer(fm))
print(f"Trainable parameters: {training_params}")
# Instantiate quantum kernel
quant_kernel = TrainableFidelityQuantumKernel(feature_map=fm, training_parameters=training_params)
# Set up the optimizer
cb_qkt = QKTCallback()
spsa_opt = SPSA(maxiter=10, callback=cb_qkt.callback, learning_rate=0.05, perturbation=0.05)
# Instantiate a quantum kernel trainer.
qkt = QuantumKernelTrainer(
quantum_kernel=quant_kernel, loss="svc_loss", optimizer=spsa_opt, initial_point=[np.pi / 2]
)
# Train the kernel using QKT directly
qka_results = qkt.fit(X_train, y_train)
optimized_kernel = qka_results.quantum_kernel
print(qka_results)
# Use QSVC for classification
qsvc = QSVC(quantum_kernel=optimized_kernel)
# Fit the QSVC
qsvc.fit(X_train, y_train)
# Predict the labels
labels_test = qsvc.predict(X_test)
# Evalaute the test accuracy
accuracy_test = metrics.balanced_accuracy_score(y_true=y_test, y_pred=labels_test)
print(f"accuracy test: {accuracy_test}")
plot_data = cb_qkt.get_callback_data() # callback data
K = optimized_kernel.evaluate(X_train) # kernel matrix evaluated on the training samples
plt.rcParams["font.size"] = 20
fig, ax = plt.subplots(1, 2, figsize=(14, 5))
ax[0].plot([i + 1 for i in range(len(plot_data[0]))], np.array(plot_data[2]), c="k", marker="o")
ax[0].set_xlabel("Iterations")
ax[0].set_ylabel("Loss")
ax[1].imshow(K, cmap=cm.get_cmap("bwr", 20))
fig.tight_layout()
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/TaiteHopkins/OracleCircuit
|
TaiteHopkins
|
#Dependency import
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
import math
from qiskit.visualization import array_to_latex
#Problem Statement:
#Creating an Oracle Circuit and Diffuser which inverts the phase for the state 110101
#Defining Unitary Display function for confirmation, implementing Aer Sim
def display_unitary(qc, prefix=""):
sim = Aer.get_backend('aer_simulator')
qc = qc.copy()
qc.save_unitary()
unitary = sim.run(qc).result().get_unitary()
display(array_to_latex(unitary, prefix=prefix))
#Using V-Oracle Model - Vemula et Al. 2022 arXiv:2205.00117v1 [quant-ph] 30 Apr 2022
def v_oracle(circuit):
circuit.toffoli(0,1,6)
circuit.toffoli(2,3,7)
circuit.toffoli(6,7,8)
circuit.toffoli(4,8,9)
circuit.cz(9,5)
circuit.toffoli(4,8,9)
circuit.toffoli(6,7,8)
circuit.toffoli(2,3,7)
circuit.toffoli(0,1,6)
#Defining Oracle Circuit
oracle = QuantumCircuit(10)
oracle.h([0,1,2,3,4,5])
v_oracle(oracle)
oracle.x([1,3])
oracle.x([1,3])
#Displaying Oracle phase table
display_unitary(oracle, "U_\\text{oracle}=")
#Displaying Quantum Circuit Diagram
oracle.draw()
#Diffuser Construction
diffCircuit = QuantumCircuit(10)
diffCircuit.h([0,1,2,3,4,5])
diffCircuit.x([0,1,2,3,4,5])
v_oracle(diffCircuit)
diffCircuit.x([0,1,2,3,4,5])
diffCircuit.h([0,1,2,3,4,5])
diffCircuit.draw()
grover = QuantumCircuit(10,6)
grover = grover.compose(oracle)
grover = grover.compose(diffCircuit)
grover = grover.compose(diffCircuit)
grover = grover.compose(diffCircuit)
grover = grover.compose(diffCircuit)
grover = grover.compose(diffCircuit)
grover = grover.compose(diffCircuit)
grover = grover.compose(diffCircuit)
grover = grover.compose(diffCircuit)
grover = grover.compose(diffCircuit)
grover = grover.compose(diffCircuit)
grover = grover.compose(diffCircuit)
grover.x([1,3])
grover.measure([0,1,2,3,4,5],[0,1,2,3,4,5])
grover.draw()
sim = Aer.get_backend('aer_simulator')
counts = sim.run(grover).result().get_counts()
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
qc.draw('mpl')
|
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
|
bayesian-randomized-benchmarking
|
#Import general libraries (needed for functions)
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
#Import Qiskit classes
import qiskit
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error
#Import the RB Functions
import qiskit.ignis.verification.randomized_benchmarking as rb
import copy
# import the bayesian packages
import pymc3 as pm
import arviz as az
# initialize the Bayesian extension
%config InlineBackend.figure_format = 'retina'
# Initialize random number generator
RANDOM_SEED = 8927
np.random.seed(RANDOM_SEED)
az.style.use("arviz-darkgrid")
def obtain_priors_and_data_from_fitter(printout = True):
m_gates = copy.deepcopy(nCliffs)
# We choose the count matrix corresponding to 2 Qubit RB
Y = (np.array(rbfit._raw_data[0])*shots).astype(int)
# alpha prior and bounds
alpha_ref = rbfit._fit[0]['params'][1]
alpha_lower = alpha_ref - 5*rbfit._fit[0]['params_err'][1]
alpha_upper = alpha_ref + 5*rbfit._fit[0]['params_err'][1]
# priors for A anbd B
mu_AB = np.delete(rbfit._fit[0]['params'],1)
cov_AB=np.delete(rbfit._fit[0]['params_err'],1)**2
# prior for sigmatheta:
sigma_theta = 0.004
if printout:
print("priors:\nalpha_ref",alpha_ref)
print("alpha_lower", alpha_lower, "alpha_upper", alpha_upper)
print("A,B", mu_AB, "\ncov A,B", cov_AB)
print("sigma_theta", sigma_theta)
return m_gates, Y, alpha_ref, alpha_lower, alpha_upper, mu_AB, cov_AB, sigma_theta
def get_bayesian_model(model_type):
# Bayesian model
# from https://iopscience.iop.org/article/10.1088/1367-2630/17/1/013042/pdf
# see https://docs.pymc.io/api/model.html
RB_model = pm.Model()
with RB_model:
#Priors for unknown model parameters
alpha = pm.Uniform("alpha",lower=alpha_lower,
upper=alpha_upper, testval = alpha_ref)
BoundedMvNormal = pm.Bound(pm.MvNormal, lower=0.0)
AB = BoundedMvNormal("AB", mu=mu_AB,testval = mu_AB,
cov= np.diag(cov_AB),
shape = (2))
# Expected value of outcome
GSP = AB[0]*alpha**m_gates + AB[1]
if model_type == "pooled":
total_shots = np.full(Y.shape, shots)
theta = GSP
elif model_type == "hierarchical":
total_shots = np.full(Y.shape, shots)
theta = pm.Beta("GSP",
mu=GSP,
sigma = sigma_theta,
shape = Y.shape[1])
# Likelihood (sampling distribution) of observations
p = pm.Binomial("Counts", p=theta, observed=Y,
n = total_shots)
return RB_model
def get_trace(RB_model):
# Gradient-based sampling methods
# see also: https://docs.pymc.io/notebooks/sampler-stats.html
# and https://docs.pymc.io/notebooks/api_quickstart.html
with RB_model:
trace= pm.sample(draws = 2000, tune= 10000, target_accept=0.9, return_inferencedata=True)
with RB_model:
az.plot_trace(trace);
return trace
def get_summary(RB_model, trace, hdi_prob=.94, kind='all'):
with RB_model:
# (hdi_prob=.94 is default)
az_summary = az.summary(trace, round_to=4, hdi_prob=hdi_prob, kind=kind )
return az_summary
# obtain EPC from alpha (used by plot_posterior)
def alpha_to_EPC(alpha):
return 3*(1-alpha)/4
def get_EPC_and_legends(azs):
EPC_Bayes = alpha_to_EPC(azs['mean']['alpha'])
EPC_Bayes_err = EPC_Bayes - alpha_to_EPC(azs['mean']['alpha']+azs['sd']['alpha'])
Bayes_legend ="EPC Bayes {0:.5f} ({1:.5f})".format(EPC_Bayes, EPC_Bayes_err)
Fitter_legend ="EPC Fitter {0:.5f} ({1:.5f})".format(rbfit.fit[0]['epc']\
,rbfit._fit[0]['epc_err'])
pred_epc_legend = "EPC predicted {0:.5f}".format(pred_epc)
return EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend, pred_epc_legend
def EPC_compare_fitter_to_bayes(RB_model, azs, trace):
EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend, pred_epc_legend = get_EPC_and_legends(azs)
with RB_model:
az.plot_posterior(trace, var_names=['alpha'], round_to=4,
transform = alpha_to_EPC, point_estimate=None)
plt.title("Error per Clifford")
plt.axvline(x=alpha_to_EPC(alpha_ref),color='red')
plt.axvline(x=pred_epc,color='green')
plt.legend((Bayes_legend, "Higher density interval",Fitter_legend, pred_epc_legend), fontsize=10 )
plt.show()
def GSP_compare_fitter_to_bayes(RB_model, azs):
EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend,_ = get_EPC_and_legends(azs)
# plot ground state population ~ Clifford length
fig, axes = plt.subplots(1, 1, sharex=True, figsize=(10, 6))
axes.set_ylabel("Ground State Population")
axes.set_xlabel("Clifford Length")
axes.plot(m_gates, np.mean(Y/shots,axis=0), 'r.')
axes.plot(m_gates,azs['mean']['AB[0]']*azs['mean']['alpha']**m_gates+azs['mean']['AB[1]'],'--')
axes.plot(m_gates,mu_AB[0]*np.power(alpha_ref,m_gates)+mu_AB[1],':')
for i_seed in range(nseeds):
plt.scatter(m_gates, Y[i_seed,:]/shots, label = "data", marker="x")
axes.legend(["Mean Observed Frequencies",
"Bayesian Model\n"+Bayes_legend,
"Fitter Model\n"+Fitter_legend],fontsize=12)
#axes.set_title('2 Qubit RB with T1/T2 Noise', fontsize=18)
def get_predicted_EPC(error_source):
#Count the number of single and 2Q gates in the 2Q Cliffords
gates_per_cliff = rb.rb_utils.gates_per_clifford(transpile_list,xdata[0],basis_gates,rb_opts['rb_pattern'][0])
for basis_gate in basis_gates:
print("Number of %s gates per Clifford: %f "%(basis_gate ,
np.mean([gates_per_cliff[rb_pattern[0][0]][basis_gate],
gates_per_cliff[rb_pattern[0][1]][basis_gate]])))
# Calculate the predicted epc
# from the known depolarizing errors on the simulation
if error_source == "depolarization":
# Error per gate from noise model
epgs_1q = {'u1': 0, 'u2': p1Q/2, 'u3': 2*p1Q/2}
epg_2q = p2Q*3/4
pred_epc = rb.rb_utils.calculate_2q_epc(
gate_per_cliff=gates_per_cliff,
epg_2q=epg_2q,
qubit_pair=[0, 2],
list_epgs_1q=[epgs_1q, epgs_1q])
# using the predicted primitive gate errors from the coherence limit
if error_source == "from_T1_T2":
# Predicted primitive gate errors from the coherence limit
u2_error = rb.rb_utils.coherence_limit(1,[t1],[t2],gate1Q)
u3_error = rb.rb_utils.coherence_limit(1,[t1],[t2],2*gate1Q)
epg_2q = rb.rb_utils.coherence_limit(2,[t1,t1],[t2,t2],gate2Q)
epgs_1q = {'u1': 0, 'u2': u2_error, 'u3': u3_error}
pred_epc = rb.rb_utils.calculate_2q_epc(
gate_per_cliff=gates_per_cliff,
epg_2q=epg_2q,
qubit_pair=[0, 1],
list_epgs_1q=[epgs_1q, epgs_1q])
return pred_epc
#Number of qubits
nQ = 3
#There are 3 qubits: Q0,Q1,Q2.
#Number of seeds (random sequences)
nseeds = 8
#Number of Cliffords in the sequence (start, stop, steps)
nCliffs = np.arange(1,200,20)
#2Q RB on Q0,Q2 and 1Q RB on Q1
rb_pattern = [[0,2],[1]]
#Do three times as many 1Q Cliffords
length_multiplier = [1,3]
rb_pattern[0][1]
rb_opts = {}
rb_opts['length_vector'] = nCliffs
rb_opts['nseeds'] = nseeds
rb_opts['rb_pattern'] = rb_pattern
rb_opts['length_multiplier'] = length_multiplier
rb_circs, xdata = rb.randomized_benchmarking_seq(**rb_opts)
print(rb_circs[0][0])
noise_model = NoiseModel()
p1Q = 0.004 # this was doubled with respect to the original example
p2Q = 0.02 # this was doubled with respect to the original example
noise_model.add_all_qubit_quantum_error(depolarizing_error(p1Q, 1), 'u2')
noise_model.add_all_qubit_quantum_error(depolarizing_error(2*p1Q, 1), 'u3')
noise_model.add_all_qubit_quantum_error(depolarizing_error(p2Q, 2), 'cx')
backend = qiskit.Aer.get_backend('qasm_simulator')
basis_gates = ['u1','u2','u3','cx'] # use U,CX for now
shots = 1024
result_list = []
transpile_list = []
import time
for rb_seed,rb_circ_seed in enumerate(rb_circs):
print('Compiling seed %d'%rb_seed)
rb_circ_transpile = qiskit.transpile(rb_circ_seed,
basis_gates=basis_gates)
print('Simulating seed %d'%rb_seed)
job = qiskit.execute(rb_circ_transpile, noise_model=noise_model,
shots=shots,
backend=backend, max_parallel_experiments=0)
result_list.append(job.result())
transpile_list.append(rb_circ_transpile)
print("Finished Simulating")
#Create an RBFitter object
rbfit = rb.fitters.RBFitter(result_list, xdata, rb_opts['rb_pattern'])
m_gates, Y, alpha_ref, alpha_lower, alpha_upper, mu_AB, cov_AB, sigma_theta =\
obtain_priors_and_data_from_fitter(printout = True)
pooled = get_bayesian_model("pooled")
pm.model_to_graphviz(pooled)
trace_p = get_trace(pooled)
azp_summary = get_summary(pooled, trace_p)
azp_summary
hierarchical = get_bayesian_model("hierarchical")
pm.model_to_graphviz(hierarchical)
trace_h = get_trace(hierarchical)
azh_summary = get_summary(hierarchical, trace_h)
azh_summary
# Leave-one-out Cross-validation (LOO) comparison
df_comp_loo = az.compare({"hierarchical": trace_h, "pooled": trace_p})
df_comp_loo
az.plot_compare(df_comp_loo, insample_dev=False);
# predict EPC from the noisy model
pred_epc = get_predicted_EPC(error_source = 'depolarization')
print("Predicted 2Q Error per Clifford: %e"%pred_epc)
EPC_compare_fitter_to_bayes(pooled, azp_summary, trace_p)
EPC_compare_fitter_to_bayes(hierarchical, azh_summary, trace_h)
GSP_compare_fitter_to_bayes(pooled, azp_summary)
GSP_compare_fitter_to_bayes(hierarchical, azh_summary)
#Number of qubits
nQ = 2
#There are 2 qubits: Q0,Q1.
#Number of seeds (random sequences)
nseeds = 10 # more data for the Rev. Mr. Bayes
#Number of Cliffords in the sequence (start, stop, steps)
nCliffs = np.arange(1,200,20)
#2Q RB Q0,Q1
rb_pattern = [[0,1]]
length_multiplier = 1
rb_opts = {}
rb_opts ['length_vector'] = nCliffs
rb_opts ['nseeds'] = nseeds
rb_opts ['rb_pattern'] = rb_pattern
rb_opts ['length_multiplier'] = length_multiplier
rb_circs , xdata = rb.randomized_benchmarking_seq(**rb_opts )
noise_model = NoiseModel()
#Add T1/T2 noise to the simulation
t1 = 100.
t2 = 80.
gate1Q = 0.2 # this was doubled with respect to the original example
gate2Q = 1.0 # this was doubled with respect to the original example
noise_model.add_all_qubit_quantum_error(thermal_relaxation_error(t1,t2,gate1Q), 'u2')
noise_model.add_all_qubit_quantum_error(thermal_relaxation_error(t1,t2,2*gate1Q), 'u3')
noise_model.add_all_qubit_quantum_error(
thermal_relaxation_error(t1,t2,gate2Q).tensor(thermal_relaxation_error(t1,t2,gate2Q)), 'cx')
backend = qiskit.Aer.get_backend('qasm_simulator')
basis_gates = ['u1','u2','u3','cx'] # use U,CX for now
shots = 1024 # a typical experimental value
result_list = []
transpile_list = []
for rb_seed,rb_circ_seed in enumerate(rb_circs):
print('Compiling seed %d'%rb_seed)
rb_circ_transpile = qiskit.transpile(rb_circ_seed, basis_gates=basis_gates)
print('Simulating seed %d'%rb_seed)
job = qiskit.execute(rb_circ_transpile, noise_model=noise_model, shots=shots,
backend=backend, max_parallel_experiments=0)
result_list.append(job.result())
transpile_list.append(rb_circ_transpile)
print("Finished Simulating")
print(rb_circs[0][0])
#Create an RBFitter object
rbfit = rb.RBFitter(result_list, xdata, rb_opts['rb_pattern'])
m_gates, Y, alpha_ref, alpha_lower, alpha_upper, mu_AB, cov_AB, sigma_theta =\
obtain_priors_and_data_from_fitter(printout = True)
pooled = get_bayesian_model("pooled")
pm.model_to_graphviz(pooled)
trace_p = get_trace(pooled)
azp_summary = get_summary(pooled, trace_p)
azp_summary
hierarchical = get_bayesian_model("hierarchical")
pm.model_to_graphviz(hierarchical)
trace_h = get_trace(hierarchical)
azh_summary = get_summary(hierarchical, trace_h)
azh_summary
# Leave-one-out Cross-validation (LOO) comparison
df_comp_loo = az.compare({"hierarchical": trace_h, "pooled": trace_p})
df_comp_loo
az.plot_compare(df_comp_loo, insample_dev=False);
# predict EPC from the noisy model
pred_epc = get_predicted_EPC(error_source = 'from_T1_T2')
print("Predicted 2Q Error per Clifford: %e"%pred_epc)
EPC_compare_fitter_to_bayes(pooled, azp_summary, trace_p)
EPC_compare_fitter_to_bayes(hierarchical, azh_summary, trace_h)
GSP_compare_fitter_to_bayes(pooled, azp_summary)
GSP_compare_fitter_to_bayes(hierarchical, azh_summary)
%load_ext watermark
%watermark -n -u -v -iv -w
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# 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.
"""Randomized tests of quantum synthesis."""
import unittest
from test.python.quantum_info.test_synthesis import CheckDecompositions
from hypothesis import given, strategies, settings
import numpy as np
from qiskit import execute
from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.extensions import UnitaryGate
from qiskit.providers.basicaer import UnitarySimulatorPy
from qiskit.quantum_info.random import random_unitary
from qiskit.quantum_info.synthesis.two_qubit_decompose import (
two_qubit_cnot_decompose,
TwoQubitBasisDecomposer,
Ud,
)
class TestSynthesis(CheckDecompositions):
"""Test synthesis"""
seed = strategies.integers(min_value=0, max_value=2**32 - 1)
rotation = strategies.floats(min_value=-np.pi * 10, max_value=np.pi * 10)
@given(seed)
def test_1q_random(self, seed):
"""Checks one qubit decompositions"""
unitary = random_unitary(2, seed=seed)
self.check_one_qubit_euler_angles(unitary)
self.check_one_qubit_euler_angles(unitary, "U3")
self.check_one_qubit_euler_angles(unitary, "U1X")
self.check_one_qubit_euler_angles(unitary, "PSX")
self.check_one_qubit_euler_angles(unitary, "ZSX")
self.check_one_qubit_euler_angles(unitary, "ZYZ")
self.check_one_qubit_euler_angles(unitary, "ZXZ")
self.check_one_qubit_euler_angles(unitary, "XYX")
self.check_one_qubit_euler_angles(unitary, "RR")
@settings(deadline=None)
@given(seed)
def test_2q_random(self, seed):
"""Checks two qubit decompositions"""
unitary = random_unitary(4, seed=seed)
self.check_exact_decomposition(unitary.data, two_qubit_cnot_decompose)
@given(strategies.tuples(*[seed] * 5))
def test_exact_supercontrolled_decompose_random(self, seeds):
"""Exact decomposition for random supercontrolled basis and random target"""
k1 = np.kron(random_unitary(2, seed=seeds[0]).data, random_unitary(2, seed=seeds[1]).data)
k2 = np.kron(random_unitary(2, seed=seeds[2]).data, random_unitary(2, seed=seeds[3]).data)
basis_unitary = k1 @ Ud(np.pi / 4, 0, 0) @ k2
decomposer = TwoQubitBasisDecomposer(UnitaryGate(basis_unitary))
self.check_exact_decomposition(random_unitary(4, seed=seeds[4]).data, decomposer)
@given(strategies.tuples(*[rotation] * 6), seed)
def test_cx_equivalence_0cx_random(self, rnd, seed):
"""Check random circuits with 0 cx gates locally equivalent to identity."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 0)
@given(strategies.tuples(*[rotation] * 12), seed)
def test_cx_equivalence_1cx_random(self, rnd, seed):
"""Check random circuits with 1 cx gates locally equivalent to a cx."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 1)
@given(strategies.tuples(*[rotation] * 18), seed)
def test_cx_equivalence_2cx_random(self, rnd, seed):
"""Check random circuits with 2 cx gates locally equivalent to some circuit with 2 cx."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
qc.cx(qr[0], qr[1])
qc.u(rnd[12], rnd[13], rnd[14], qr[0])
qc.u(rnd[15], rnd[16], rnd[17], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 2)
@given(strategies.tuples(*[rotation] * 24), seed)
def test_cx_equivalence_3cx_random(self, rnd, seed):
"""Check random circuits with 3 cx gates are outside the 0, 1, and 2 qubit regions."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
qc.cx(qr[0], qr[1])
qc.u(rnd[12], rnd[13], rnd[14], qr[0])
qc.u(rnd[15], rnd[16], rnd[17], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[18], rnd[19], rnd[20], qr[0])
qc.u(rnd[21], rnd[22], rnd[23], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 3)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit
from qiskit import Aer, transpile
from qiskit.tools.visualization import plot_histogram, plot_state_city
import qiskit.quantum_info as qi
Aer.backends()
simulator = Aer.get_backend('aer_simulator')
# Create circuit
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.measure_all()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get counts
result = simulator.run(circ).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
# Run and get memory
result = simulator.run(circ, shots=10, memory=True).result()
memory = result.get_memory(circ)
print(memory)
# Increase shots to reduce sampling variance
shots = 10000
# Stabilizer simulation method
sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer')
job_stabilizer = sim_stabilizer.run(circ, shots=shots)
counts_stabilizer = job_stabilizer.result().get_counts(0)
# Statevector simulation method
sim_statevector = Aer.get_backend('aer_simulator_statevector')
job_statevector = sim_statevector.run(circ, shots=shots)
counts_statevector = job_statevector.result().get_counts(0)
# Density Matrix simulation method
sim_density = Aer.get_backend('aer_simulator_density_matrix')
job_density = sim_density.run(circ, shots=shots)
counts_density = job_density.result().get_counts(0)
# Matrix Product State simulation method
sim_mps = Aer.get_backend('aer_simulator_matrix_product_state')
job_mps = sim_mps.run(circ, shots=shots)
counts_mps = job_mps.result().get_counts(0)
plot_histogram([counts_stabilizer, counts_statevector, counts_density, counts_mps],
title='Counts for different simulation methods',
legend=['stabilizer', 'statevector',
'density_matrix', 'matrix_product_state'])
from qiskit_aer import AerError
# Initialize a GPU backend
# Note that the cloud instance for tutorials does not have a GPU
# so this will raise an exception.
try:
simulator_gpu = Aer.get_backend('aer_simulator')
simulator_gpu.set_options(device='GPU')
except AerError as e:
print(e)
# Configure a single-precision statevector simulator backend
simulator = Aer.get_backend('aer_simulator_statevector')
simulator.set_options(precision='single')
# Run and get counts
result = simulator.run(circ).result()
counts = result.get_counts(circ)
print(counts)
# Construct quantum circuit without measure
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.save_statevector()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get statevector
result = simulator.run(circ).result()
statevector = result.get_statevector(circ)
plot_state_city(statevector, title='Bell state')
# Construct quantum circuit without measure
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.save_unitary()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get unitary
result = simulator.run(circ).result()
unitary = result.get_unitary(circ)
print("Circuit unitary:\n", np.asarray(unitary).round(5))
# Construct quantum circuit without measure
steps = 5
circ = QuantumCircuit(1)
for i in range(steps):
circ.save_statevector(label=f'psi_{i}')
circ.rx(i * np.pi / steps, 0)
circ.save_statevector(label=f'psi_{steps}')
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
data = result.data(0)
data
# Generate a random statevector
num_qubits = 2
psi = qi.random_statevector(2 ** num_qubits, seed=100)
# Set initial state to generated statevector
circ = QuantumCircuit(num_qubits)
circ.set_statevector(psi)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Use initilize instruction to set initial state
circ = QuantumCircuit(num_qubits)
circ.initialize(psi, range(num_qubits))
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get result data
result = simulator.run(circ).result()
result.data(0)
num_qubits = 2
rho = qi.random_density_matrix(2 ** num_qubits, seed=100)
circ = QuantumCircuit(num_qubits)
circ.set_density_matrix(rho)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Generate a random Clifford C
num_qubits = 2
stab = qi.random_clifford(num_qubits, seed=100)
# Set initial state to stabilizer state C|0>
circ = QuantumCircuit(num_qubits)
circ.set_stabilizer(stab)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Generate a random unitary
num_qubits = 2
unitary = qi.random_unitary(2 ** num_qubits, seed=100)
# Set initial state to unitary
circ = QuantumCircuit(num_qubits)
circ.set_unitary(unitary)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
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.providers.fake_provider import FakeBoeblingen
backend = FakeBoeblingen()
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
circ = transpile(ghz, backend, scheduling_method="asap")
circ.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.visualization import dag_drawer
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
dag_drawer(dag)
|
https://github.com/Juan-Varela11/BNL_2020_Summer_Internship
|
Juan-Varela11
|
# Import useful packages
import os
import sys
import time
import pickle
import numpy as np
import pandas as pd
import seaborn as sns
from datetime import datetime
from tabulate import tabulate
import matplotlib.pyplot as plt
# Import QISKit
from qiskit import Aer, execute, BasicAer
from qiskit.aqua.components.initial_states import Zero
from qiskit.aqua.algorithms.adaptive import VQE
from qiskit.aqua import QuantumInstance, aqua_globals
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.aqua.algorithms import ExactEigensolver
from qiskit.aqua.components.initial_states import Custom
from qiskit.aqua.components.variational_forms import RY, RYRZ
from qiskit.aqua.operators.op_converter import to_weighted_pauli_operator
from qiskit.aqua.components.optimizers import COBYLA, SPSA, L_BFGS_B, SLSQP
from qiskit.aqua.operators import (TPBGroupedWeightedPauliOperator,
WeightedPauliOperator,
MatrixOperator)
# For IBMQ
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor, backend_monitor, backend_overview
class RunVQE:
"""Runs VQE via IBM's QISKit
Attributes:
file_path (str): File path to text file representation of Hamiltonian
file_name (str): File name of text file representation of Hamiltonian
init_state_name (QISKit object): Initial state
vf_name (QISKit object): Variational Form
depth (int): Quantum depth for circuit
shots (int): Number of shots
n_qubits (int): Number of qubits used
n_paulis (int): Number of pauli terms generated
ref (float): Exact energy of Hamiltonian
optimizers (list of strs): List of optimzers used in VQE run
The following dictionaries all have the optimzers used in VQE run as keys:
algos (dict of VQE objects): QISKit VQE objects
algo_results (dict): Dictionary of algorithm results from each VQE run
result_df (DataFrame): Contains all convergence values from each
optimizer used in the run. The index represents the convergence counts
"""
def __init__(self, kwargs, use_ibmq=False):
"""Constructor method
Args:
kwargs (dict): Key word argument dictionary containing parameters
for VQE run
save_figs (bool): If True will save figures generated in current
directory if the plt_state_vector(), plt_opt_convergence(), or
plt_energy_convergence() methods are called
use_ibmq (bool): If True will activate IBMQ account and run on an
IBMQ backend (default is least busy, see get_least_busy_device()
method below for more details)
"""
self.file_path = kwargs['file_path']
self.file_name = self.file_path.split("/")[-1].replace('.txt', '')
self.init_state_name = kwargs['init_state_name']
self.vf_name = kwargs['vf_name']
self.depth = kwargs['depth']
self.shots = kwargs['shots']
self.add_k_count = 0
if use_ibmq:
self.activate_ibmq()
self.device = self.get_least_busy_device()
self.backend = self.provider.get_backend(self.device)
else:
self.device = kwargs['simulator']
self.backend = BasicAer.get_backend(self.device)
self.run_VQE()
if 'nonzero' in self.file_name:
self._add_k(25)
print(self.result_table())
def construct_wpo_operator(self):
"""Returns Weighted Pauli Operator (WPO) constructed from Hamiltonian
text file.
Args:
None
Returns:
qubit_op (QISKit WPO object): Weighted Pauli Operator
"""
# Loading matrix representation of Hamiltonian txt file
H = np.loadtxt(self.file_path)
# Converting Hamiltonian to Matrix Operator
qubit_op = MatrixOperator(matrix=H)
# Converting to Pauli Operator
qubit_op = to_weighted_pauli_operator(qubit_op)
self.num_qubits = qubit_op.num_qubits
self.num_paulis = len(qubit_op.paulis)
return qubit_op
def exact_eigensolver(self, qubit_op):
"""Returns exact solution of eigen value problem
Args:
qubit_op (object): Weighted Pauli Operator
Returns:
exact_energy (float): Exact energy of Hamiltonian
"""
# Solving system exactly for reference value
ee = ExactEigensolver(qubit_op)
result = ee.run()
exact_energy = result['energy']
return exact_energy
def run_VQE(self):
"""Runs the Variational Quantum Eigensolver (VQE)"""
qubit_op = self.construct_wpo_operator()
self.ref = self.exact_eigensolver(qubit_op)
# Setting initial state, variational form, and backend
init_state = self.init_state_name(self.num_qubits)
var_form = self.vf_name(self.num_qubits,
depth=self.depth,
entanglement='linear',
initial_state=init_state)
# Don't use SPSA if using a noiseless simulator
if self.device == 'statevector_simulator':
optimizers = [COBYLA, L_BFGS_B, SLSQP]
else:
optimizers = [COBYLA, SPSA]
print(self.param_table())
# Initializing empty lists & dicts for storage
df = pd.DataFrame()
algos = {}
algo_results = {}
for optimizer in optimizers:
# For reproducibility
aqua_globals.random_seed = 250
print(f'\rOptimizer: {optimizer.__name__} ', end='')
counts = []
values = []
params = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
params.append(parameters)
# Running VQE
algo = VQE(qubit_op,
var_form,
optimizer(),
callback=store_intermediate_result)
quantum_instance = QuantumInstance(backend=self.backend, shots=self.shots)
algo_result = algo.run(quantum_instance)
df[optimizer.__name__] = pd.Series(data=values, index=counts)
algos[optimizer.__name__] = algo
algo_results[optimizer.__name__] = algo_result
print('\rOptimization complete')
self.algos = algos
self.result_df = df
self.algo_results = algo_results
self.optimizers = algo_results.keys()
self.results_to_save = {
'file_path': self.file_path,
'ref': self.ref,
'n_qubits': self.num_qubits,
'n_paulis': self.num_paulis,
'depth': self.depth,
'n_shots': self.shots,
'algo_results': self.algo_results,
'result_df': self.result_df
}
def _add_k(self, k):
"""Adds a constant k to energy to get around optimizer error when
optimizing near zero
Args:
k (int or float): constant to add
Returns:
None
"""
if self.add_k_count != 0:
return 'Method already called, to prevent adding k too many times no operation has been carried out.'
else:
self.ref += k
self.result_df = self.result_df.apply(lambda x: x + k)
for opt in self.optimizers:
self.algo_results[opt]['energy'] += 25
print('\n**WARNING** Outside operation has been performed on algorithm results')
self.add_k_count += 1
def save_data_to_pkl(self, out_name):
"""Saves results_to_save dict to pickle file
Args:
out_name (str): File name/path for data to be written to
Returns:
None
"""
with open(out_name, 'xb') as file:
pickle.dump(self.results_to_save, file)
print(f'Data wiitten to {out_name}')
def save_output(self, out_name):
"""Saves out put from param_table and result_table to text file
Args:
out_name (str): File name/path for data to be written to
Returns:
None
"""
with open(out_name, 'x') as file:
file.write(self.param_table())
file.write('\n')
file.write(self.result_table())
print(f'Output wiitten to {out_name}')
def load_data(self, data_file):
"""Loads data from pickle file
Args:
data_file (str): pickle file containing data to load
Returns:
None
"""
with open(data_file, 'rb') as file:
data = pickle.load(file)
return data
def find_total_time(self):
"""Finds total simulation time in seconds"""
eval_times = []
for opt in self.optimizers:
eval_times.append(self.algo_results[opt]['eval_time'])
return round(sum(eval_times))
def get_state(self):
"""Returns State of Hamiltonian based on state mapping"""
hamiltonian_info = self.file_name.split('_')
state_mapping = {
'E0':'Ground State',
'E1':'1st Excited',
'E2':'2nd Excited',
'E3':'3rd Excited',
'E4':'4th Excited'
}
for key in state_mapping:
if key in hamiltonian_info:
state = state_mapping[key]
else:
pass
return state
def get_basis(self):
"""Returns basis of Hamiltonian based on basis mapping"""
hamiltonian_info = self.file_name.split('_')
basis_mapping = {
'pos': 'Position',
'osc': 'Oscillator',
'finite': 'Finite Difference'
}
for key in basis_mapping:
if key in hamiltonian_info:
basis = basis_mapping[key]
else:
pass
return basis
def param_table(self):
"""Returns string outlining parameters for current VQE run"""
run_settings = [['State', self.get_state()],
['Basis', self.get_basis()],
['Backend', self.device],
['InitState', self.init_state_name.__name__],
['VarForm', self.vf_name.__name__],
['Depth', self.depth],
['# Shots', self.shots],
['# Qubits', self.num_qubits],
['# Paulis', self.num_paulis]
]
out_str = f"""{datetime.utcnow()}\nRunning: {self.file_path}\n{tabulate(run_settings, tablefmt="fancy_grid", stralign='right')}"""
return out_str
def result_table(self):
"""Returns string outlining results of VQE simulation for each optimizer"""
ref_str = f'Reference Value: {self.ref}'
t_str = f'\n{self.find_total_time()} s to complete'
vals = []
for opt in self.optimizers:
if 'nonzero' in self.file_name:
vals.append([opt,
self.algo_results[opt]['energy'],
abs((self.algo_results[opt]['energy'] - self.ref)/self.ref)*100])
sorted_vals = sorted(vals, key=lambda x: x[2])
headers = ['Optimizer', 'VQE Energy', '% Error']
out_str = f"""{t_str}\n{ref_str}\n{tabulate(sorted_vals,tablefmt="fancy_grid",headers=headers,numalign="right")}"""
return out_str
def plt_energy_convergence(self, save_figs=True):
"""Graphs optimizer energy convergence and convergence of most
effective optimizer.
"""
plt.figure(figsize=(10, 5))
for opt in self.optimizers:
self.result_df[opt].apply(lambda x: abs(x - self.ref)).plot(logy=True, label=opt)
plt.title('Optimizer Energy Convergence', size=24)
plt.xlabel('Evaluation Count', size=18)
plt.ylabel('Energy Difference', size=18)
plt.legend(fontsize='x-large')
sns.despine()
if save_figs:
if os.path.exists(fr'{self.file_name}_energy_convergence.png'):
plt.savefig(fr'{self.file_name}_energy_convergence(1).png');
else:
plt.savefig(fr'{self.file_name}_energy_convergence.png');
else:
plt.show()
def find_most_precise(self):
"""Returns name of most precise optimizer"""
p_err_mins = {}
for opt in self.optimizers:
p_err = self.result_df[opt].apply(lambda x: abs((x - self.ref)/self.ref)*100)
p_err_mins[opt] = p_err.min()
most_precise = sorted(p_err_mins.items(), key=lambda x: x[1])[0][0]
return most_precise
def plt_opt_convergence(self, save_figs=True):
"""Plots most effective optimizer"""
most_precise = self.find_most_precise()
fig, ax = plt.subplots(figsize=(10, 5))
self.result_df[most_precise].plot(label=f"{most_precise} = {self.algo_results[most_precise]['energy']:.6f}")
ax.hlines(y=self.ref,
xmin=0,
xmax=len(self.result_df[most_precise]),
colors='r',
label=f'Exact = {self.ref:.6f}')
plt.title('Convergence', size=24)
plt.xlabel('Optimization Steps', size=18)
plt.ylabel('Energy', size=18)
plt.legend(fontsize='x-large')
sns.despine()
if save_figs:
if os.path.exists(fr'{self.file_name}_opt_convergence.png'):
plt.savefig(fr'{self.file_name}_opt_convergence(1).png');
else:
plt.savefig(fr'{self.file_name}_opt_convergence.png');
else:
plt.show()
def plt_state_vector(self, save_figs=True):
"""Plots state vector for each optimizer"""
plt.figure(figsize=(10, 5))
for optimizer in self.optimizers:
circ = self.algos[optimizer].construct_circuit(self.algo_results[optimizer]['opt_params'])
e0wf = execute(circ[0],
Aer.get_backend(self.device),
shots=1).result().get_statevector(circ[0])
plt.plot(np.flip(e0wf.real), label=f'{optimizer}')
plt.title('State Vectors', size=24)
plt.legend(fontsize='x-large')
sns.despine()
if save_figs:
if os.path.exists(fr'{self.file_name}_st_vecs.png'):
plt.savefig(fr'{self.file_name}_st_vecs(1).png');
else:
plt.savefig(fr'{self.file_name}_st_vecs.png');
else:
plt.show()
def activate_ibmq(self):
"""Activates IBMQ account and gets IBMQ provider Note: you will get an
import error if you do not have a python scipt named my_secrets.py
with your IBMQ API token in the same directory as this file
"""
from my_secrets import pw
key = pw
try:
IBMQ.enable_account(key)
except:
print('IBMQAccountError: Account already activated')
finally:
self.provider = IBMQ.get_provider('ibm-q')
def get_least_busy_device(self):
"""Returns name (str) of least busy IBMQ backend that is not a
simulator and has more than one qubit.
"""
lb_backend = least_busy(self.provider.backends(filters=lambda x: not x.configuration().simulator and x.configuration().n_qubits > 1))
return lb_backend.name()
# Uncomment and run with valid Hamiltonian file
def main():
params = {
'file_path':fr'Morse_pos/Morse_pos_E0_16x16.txt',
'init_state_name':Zero,
'vf_name':RY,
'depth':1,
'shots':1,
'simulator': 'statevector_simulator'
}
v_q_e = RunVQE(params)
v_q_e.save_data_to_pkl(f'{v_q_e.file_name}_data.pkl')
v_q_e.save_output(f'{v_q_e.file_name}_output.txt')
v_q_e.plt_energy_convergence()
v_q_e.plt_opt_convergence()
v_q_e.plt_state_vector()
if __name__ == "__main__":
main()
|
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 2018, 2019.
#
# 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.
"""
This module contains the definition of a base class for quantum fourier transforms.
"""
from abc import abstractmethod
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua import Pluggable, AquaError
class QFT(Pluggable):
"""Base class for QFT.
This method should initialize the module and its configuration, and
use an exception if a component of the module is
available.
Args:
configuration (dict): configuration dictionary
"""
@abstractmethod
def __init__(self, *args, **kwargs):
super().__init__()
@classmethod
def init_params(cls, params):
qft_params = params.get(Pluggable.SECTION_KEY_QFT)
kwargs = {k: v for k, v in qft_params.items() if k != 'name'}
return cls(**kwargs)
@abstractmethod
def _build_matrix(self):
raise NotImplementedError
@abstractmethod
def _build_circuit(self, qubits=None, circuit=None, do_swaps=True):
raise NotImplementedError
def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True):
"""Construct the circuit.
Args:
mode (str): 'matrix' or 'circuit'
qubits (QuantumRegister or qubits): register or qubits to build the circuit on.
circuit (QuantumCircuit): circuit for construction.
do_swaps (bool): include the swaps.
Returns:
The matrix or circuit depending on the specified mode.
"""
if mode == 'circuit':
return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps)
elif mode == 'matrix':
return self._build_matrix()
else:
raise AquaError('Unrecognized mode: {}.'.format(mode))
|
https://github.com/GabrielPontolillo/QiskitPBT
|
GabrielPontolillo
|
# class that inherits from property based test
from qiskit import QuantumCircuit
from QiskitPBT.property import Property
from QiskitPBT.input_generators.random_unitary import RandomUnitary
from QiskitPBT.case_studies.quantum_fourier_transform.quantum_fourier_transform import qft_general
class IdentityProperty(Property):
# specify the inputs that are to be generated
def get_input_generators(self):
unitary = RandomUnitary(1, 10)
return [unitary]
# specify the preconditions for the test
def preconditions(self, unitary):
return True
# specify the operations to be performed on the input
def operations(self, unitary):
n = unitary.num_qubits
# perform Uxn ( Hxn ( QFT (0xn)) )
# QFT (0xn)
qft = qft_general(n)
# Hxn
for i in range(n):
qft.h(i)
# Uxn
qft.append(unitary, range(n))
# perform Uxn (0xn)
qc = QuantumCircuit(n, n)
qc.append(unitary, range(n))
self.statistical_analysis.assert_equal(self, list(range(n)), qft, list(range(n)), qc)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qsvm_datasets import *
from qiskit import Aer
from qiskit_aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name
from qiskit_aqua.input import SVMInput
from qiskit_aqua import run_algorithm, QuantumInstance
from qiskit_aqua.algorithms import QSVMKernel
from qiskit_aqua.components.feature_maps import SecondOrderExpansion
# setup aqua logging
import logging
from qiskit_aqua import set_aqua_logging
# set_aqua_logging(logging.DEBUG) # choose INFO, DEBUG to see the log
from qiskit import IBMQ
IBMQ.load_accounts()
feature_dim=2 # we support feature_dim 2 or 3
sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=20,
test_size=10,
n=feature_dim,
gap=0.3,
PLOT_DATA=True)
extra_test_data = sample_ad_hoc_data(sample_Total, 10, n=feature_dim)
datapoints, class_to_label = split_dataset_to_data_and_labels(extra_test_data)
print(class_to_label)
seed = 10598
feature_map = SecondOrderExpansion(num_qubits=feature_dim, depth=2, entanglement='linear')
qsvm = QSVMKernel(feature_map, training_input, test_input, datapoints[0])
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024, seed=seed, seed_mapper=seed)
result = qsvm.run(quantum_instance)
"""declarative approach
params = {
'problem': {'name': 'svm_classification', 'random_seed': 10598},
'algorithm': {
'name': 'QSVM.Kernel'
},
'backend': {'name': 'qasm_simulator', 'shots': 1024},
'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entanglement': 'linear'}
}
algo_input = SVMInput(training_input, test_input, datapoints[0])
result = run_algorithm(params, algo_input)
"""
print("testing success ratio: {}".format(result['testing_accuracy']))
print("preduction of datapoints:")
print("ground truth: {}".format(map_label_to_class_name(datapoints[1], qsvm.label_to_class)))
print("prediction: {}".format(result['predicted_classes']))
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
sample_Total, training_input, test_input, class_labels = Breast_cancer(training_size=20,
test_size=10,
n=2,
PLOT_DATA=True)
seed = 10598
feature_map = SecondOrderExpansion(num_qubits=feature_dim, depth=2, entanglement='linear')
qsvm = QSVMKernel(feature_map, training_input, test_input)
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024, seed=seed, seed_mapper=seed)
result = qsvm.run(quantum_instance)
"""declarative approach, re-use the params above
algo_input = SVMInput(training_input, test_input)
result = run_algorithm(params, algo_input)
"""
print("testing success ratio: ", result['testing_accuracy'])
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# Install the plugin
# !pip install -e .
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.collection import CollectPermutations
from qiskit_transpiler_service.ai.synthesis import AIPermutationSynthesis
from qiskit.circuit.library import Permutation
num_qubits = 27
circuit = QuantumCircuit(num_qubits)
circuit.append(
Permutation(
num_qubits=num_qubits, pattern=[(i + 1) % num_qubits for i in range(num_qubits)]
),
qargs=range(num_qubits),
)
circuit = circuit.decompose(reps=2)
print(
f"Original circuit -> Depth: {circuit.decompose(reps=3).depth()}, Gates(2q): {circuit.decompose(reps=3).num_nonlocal_gates()}"
)
circuit.draw(output="mpl", fold=-1, scale=0.3, style="iqp")
ai_optimize_perms = PassManager(
[
CollectPermutations(do_commutative_analysis=True),
AIPermutationSynthesis(backend_name="ibm_cairo"),
]
)
# AI Synthesis passes respect the coupling map and should run after transpiling
ai_optimized_circuit = ai_optimize_perms.run(circuit)
print(
f"AI-Optimized circuit -> Depth: {ai_optimized_circuit.decompose(reps=3).depth()}, Gates(2q): {ai_optimized_circuit.decompose(reps=3).num_nonlocal_gates()}"
)
ai_optimized_circuit.draw(output="mpl", fold=-1, scale=0.25, style="iqp")
|
https://github.com/JohnBurke4/qaoa_testing_framework
|
JohnBurke4
|
from Image_Reader import ImageReader
from DCT_Classic import DCT
import Quantum_Subroutines
import os
import Image_Compression
import cv2
import matplotlib.pyplot as plt
import numpy as np
from qiskit import QuantumCircuit, Aer, transpile
from qiskit_aer.backends.aerbackend import AerBackend
from qiskit.providers.fake_provider import FakeSydneyV2
from qiskit_aer import AerSimulator
from qiskit.circuit.library import Isometry, StatePreparation
import csv
import CustomUnitaryDecomp
import scipy
max = 8
blockSize = 4
np.set_printoptions(precision=3, suppress=True)
path = "StateCompression/images/camera.png"
image = ImageReader.getImage(path)
image = cv2.resize(image, (max, max)).astype(int)
basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']
basis_gates = ['u3', 'cx', 'id']
state = image.flatten() / np.linalg.norm(image)
qubits = int(np.log2(max**2))
qc = QuantumCircuit(qubits+1)
numOfBlocks = int((max / blockSize)**2)
indexQubits = int(np.log2(numOfBlocks))
# qc.initialize(state, range(0, qubits))
def recursiveBuildCircuit(state, qc, maxSize, controlQubit, currentQubit, allLeft, indexQubits, allRight):
if (len(state) == maxSize**2):
statePrep = StatePreparation(state).control(1)
qubitsForState = int(np.log2(maxSize**2))
# if (allLeft):
# qc.mcx(list(range(qubitsForState, qubitsForState + indexQubits)), controlQubit)
qubits = [controlQubit] + list(range(0, qubitsForState))
# qc.append(statePrep, qubits)
# if (allLeft):
# qc.mcx(list(range(qubitsForState, qubitsForState + indexQubits)), controlQubit)
# qc.mcx(list(range(qubitsForState, qubitsForState + indexQubits)), controlQubit)
return qc
else:
left = state[:len(state)//2]
right = state[len(state)//2:]
leftNorm = np.linalg.norm(left)
rightNorm = np.linalg.norm(right)
theta = 2 * np.arccos(rightNorm)
if (allLeft):
qc.ry(theta, currentQubit)
qc = recursiveBuildCircuit(left / leftNorm, qc, maxSize, controlQubit, currentQubit-1, allLeft*True, indexQubits, False)
# print(left / leftNorm)
# print(right / rightNorm)
# qc.x(currentQubit)
# qc.cx(currentQubit, controlQubit)
# if (currentQubit != 3):
qc = recursiveBuildCircuit(right / rightNorm, qc, maxSize, controlQubit, currentQubit-1, False, indexQubits, allRight * True)
# qc.x(currentQubit)
return qc
# qc = recursiveBuildCircuit(state, qc, blockSize, qubits, qubits-1, True, indexQubits, True)
# print(qc)
norms = []
for i in range(0, numOfBlocks):
print(state[i*blockSize**2:(i+1)*blockSize**2])
norms.append(np.linalg.norm(state[i*blockSize**2:(i+1)*blockSize**2]))
print(np.inner(norms, norms))
# qc.initialize(norms, range(qubits-indexQubits, qubits))
# for i in range(0, 1):
# currState = state[i*blockSize**2:(i+1)*blockSize**2]
# stateToPrepare = currState / np.linalg.norm(currState)
# stateCirc = StatePreparation(stateToPrepare).control(1)
# qc.x(list(range(qubits-indexQubits, qubits)))
# qc.mcx(list(range(qubits-indexQubits, qubits)), qubits)
# statePrepQubits = [qubits] + list(range(0, int(np.log2(blockSize**2))))
# qc.append(stateCirc, statePrepQubits)
# qc.mcx(list(range(qubits-indexQubits, qubits)), qubits)
# qc.x(list(range(qubits-indexQubits, qubits)))
qc.initialize(state, range(0, qubits))
# half1 = state[:max**2//2]
# half2 = state[max**2//2:]
# half1Norm = np.linalg.norm(half1)
# half2Norm = np.linalg.norm(half2)
# print(half1Norm, half2Norm)
# statePrep1 = StatePreparation(half1/half1Norm).control(1)
# statePrep2 = StatePreparation(half2/half2Norm).control(1)
# q = [qubits-1] + list(range(0, qubits-1))
# theta = 2 * np.arccos(half2Norm)
# qc.ry(theta, qubits-1)
# qc.append(statePrep1, q)
# qc.x(qubits-1)
# qc.append(statePrep2, q)
# qc.x(qubits-1)
# qc.x(qubits-1)
# print(qc)
sim = Aer.get_backend('aer_simulator')
circ = transpile(qc, sim, basis_gates=basis_gates)
depth = circ.depth()
gates = sum(dict(circ.count_ops()).values())
print(depth, gates)
circ.save_statevector()
result = sim.run(circ).result()
out_vector = result.get_statevector().data[0:max*max]
imageData = out_vector.real.reshape((max, max))
print(imageData)
# print(np.linalg.norm(imageData))
# print(state.reshape((max, max)))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Kraus, SuperOp
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,
pauli_error, depolarizing_error, thermal_relaxation_error)
# Construct a 1-qubit bit-flip and phase-flip errors
p_error = 0.05
bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)])
phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)])
print(bit_flip)
print(phase_flip)
# Compose two bit-flip and phase-flip errors
bitphase_flip = bit_flip.compose(phase_flip)
print(bitphase_flip)
# Tensor product two bit-flip and phase-flip errors with
# bit-flip on qubit-0, phase-flip on qubit-1
error2 = phase_flip.tensor(bit_flip)
print(error2)
# Convert to Kraus operator
bit_flip_kraus = Kraus(bit_flip)
print(bit_flip_kraus)
# Convert to Superoperator
phase_flip_sop = SuperOp(phase_flip)
print(phase_flip_sop)
# Convert back to a quantum error
print(QuantumError(bit_flip_kraus))
# Check conversion is equivalent to original error
QuantumError(bit_flip_kraus) == bit_flip
# Measurement miss-assignement probabilities
p0given1 = 0.1
p1given0 = 0.05
ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]])
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates
error = depolarizing_error(0.05, 1)
noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3'])
# Print noise model info
print(noise_model)
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only
error = depolarizing_error(0.05, 1)
noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0])
# Print noise model info
print(noise_model)
# System Specification
n_qubits = 4
circ = QuantumCircuit(n_qubits)
# Test Circuit
circ.h(0)
for qubit in range(n_qubits - 1):
circ.cx(qubit, qubit + 1)
circ.measure_all()
print(circ)
# Ideal simulator and execution
sim_ideal = AerSimulator()
result_ideal = sim_ideal.run(circ).result()
plot_histogram(result_ideal.get_counts(0))
# Example error probabilities
p_reset = 0.03
p_meas = 0.1
p_gate1 = 0.05
# QuantumError objects
error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)])
error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)])
error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)])
error_gate2 = error_gate1.tensor(error_gate1)
# Add errors to noise model
noise_bit_flip = NoiseModel()
noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset")
noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure")
noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"])
noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"])
print(noise_bit_flip)
# Create noisy simulator backend
sim_noise = AerSimulator(noise_model=noise_bit_flip)
# Transpile circuit for noisy basis gates
circ_tnoise = transpile(circ, sim_noise)
# Run and get counts
result_bit_flip = sim_noise.run(circ_tnoise).result()
counts_bit_flip = result_bit_flip.get_counts(0)
# Plot noisy output
plot_histogram(counts_bit_flip)
# T1 and T2 values for qubits 0-3
T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
# Truncate random T2s <= T1s
T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)])
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_reset[j], "reset", [j])
noise_thermal.add_quantum_error(errors_measure[j], "measure", [j])
noise_thermal.add_quantum_error(errors_u1[j], "u1", [j])
noise_thermal.add_quantum_error(errors_u2[j], "u2", [j])
noise_thermal.add_quantum_error(errors_u3[j], "u3", [j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k])
print(noise_thermal)
# Run the noisy simulation
sim_thermal = AerSimulator(noise_model=noise_thermal)
# Transpile circuit for noisy basis gates
circ_tthermal = transpile(circ, sim_thermal)
# Run and get counts
result_thermal = sim_thermal.run(circ_tthermal).result()
counts_thermal = result_thermal.get_counts(0)
# Plot noisy output
plot_histogram(counts_thermal)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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.draw('mpl')
|
https://github.com/C2QA/bosonic-qiskit
|
C2QA
|
# Copyright 2022-2023 Ohad Lev.
# 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,
# or in the root directory of this package("LICENSE.txt").
# 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.
"""Tests for `util.py` module."""
import unittest
from datetime import datetime
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from sat_circuits_engine.util import flatten_circuit, timestamp
class UtilTest(unittest.TestCase):
def test_timestamp(self):
"""Test for the `timestamp` function."""
self.assertEqual(timestamp(datetime(2022, 12, 3, 17, 0, 45, 0)), "D03.12.22_T17.00.45")
def test_flatten_circuit(self):
"""Test for the `flatten_circuit` function."""
bits_1 = 2
bits_2 = 3
qreg_1 = QuantumRegister(bits_1)
qreg_2 = QuantumRegister(bits_2)
creg_1 = ClassicalRegister(bits_1)
creg_2 = ClassicalRegister(bits_2)
circuit = QuantumCircuit(qreg_1, qreg_2, creg_1, creg_2)
self.assertEqual(circuit.num_qubits, bits_1 + bits_2)
self.assertEqual(circuit.num_clbits, bits_1 + bits_2)
self.assertEqual(len(circuit.qregs), 2)
self.assertEqual(len(circuit.cregs), 2)
flat_circuit = flatten_circuit(circuit)
self.assertEqual(flat_circuit.num_qubits, bits_1 + bits_2)
self.assertEqual(flat_circuit.num_clbits, bits_1 + bits_2)
self.assertEqual(len(flat_circuit.qregs), 1)
self.assertEqual(len(flat_circuit.cregs), 1)
if __name__ == "__main__":
unittest.main()
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
from qiskit.providers.basic_provider import BasicProvider # instead of BasicAer
import Our_Qiskit_Functions as oq
import numpy as np
import math as m
import random
import matplotlib
import matplotlib.pyplot as plt
S_simulator = Aer.backends(name='statevector_simulator')[0]
def Letter_Code(x):
'''
Input: integer --> Converts an integer between 0 and 26 into a letter of the alphabet (26 for space)
Input: string --> Converts a lower case letter or space to an integer
'''
if( type(x) == type(1) ):
code = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' ']
if( x < len(code) ):
return code[x]
else:
return '?'
if( type(x) == type('s') ):
code = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25,' ':26}
return code[x]
#====================================
p = 3
q = 11
n = p*q
e = 3
d = 7
message = 'hello qubits how are you'
#------------------------------------ Encrypt the message
M = list(message)
M_rsa = []
for i in np.arange(len(M)):
M[i] = Letter_Code(M[i])
M_rsa.append( M[i]**e%n )
#------------------------------------ Decrypt the message
encrypted_message = ''
decrypted_message = ''
for j in np.arange(len(M_rsa)):
encrypted_message = encrypted_message+Letter_Code( M_rsa[j] )
decrypted_message = decrypted_message+Letter_Code( (M_rsa[j]**d)%n )
print(' Encoded Messege: ',M,'\n\nEncrypted Message: ',M_rsa,'\n\n ',encrypted_message,'\n\nDecrypted Message: ', decrypted_message)
N = 1703
#N = 1827
S = int(m.ceil(m.sqrt(N)))
#====================
i = 0
found = False
while i<10000:
Y2 = (S+i)**2 % N
Y = m.sqrt(Y2)
if( ( Y == m.floor(Y) ) and (Y2!=1) ):
found = True
X = int(S+i)
X2 = X**2
break
else:
i = i + 1
if( found==True ):
print('N: ',N)
print('\nX: ', X, ' Y: ',Y)
print('\nX^2: ',X2,' Y^2: ',Y2)
print('\n(X+Y): ',int(X+Y),' (X-Y): ',int(X-Y))
print('\nfactors of N: ',int(oq.GCD(N,X+Y)),' ',int(oq.GCD(N,X-Y)) )
A_i = 462
B_i = 70
#---------------------
gcd = False
GCD = 0
#=====================
A = A_i
B = B_i
while( gcd == False ):
r = A - B
print('A: ',A,' B: ',B,' r:',r)
if( r == 0 ):
gcd = True
GCD = B
else:
if( r > B ):
A = r
else:
A = B
B = r
print('------------------------------------------------------\nGreatest Common Denominator between',A_i,'and',B_i,': ',GCD)
A = 123456
B = 789
print( A % B )
oq.Euclids_Alg(A_i, B_i)
N = 35
a = int( random.randint(2,N-2) )
print('N: ',N)
print('a: ',a)
gcd = oq.Euclids_Alg(N,a)
if(gcd > 1):
print('a has a common factor with N ---> GCD: ',gcd)
else:
print('a has no common factor with N ---> GCD: ',gcd)
r = oq.r_Finder(a,N)
print('period r: ',r)
print('\nVerify ',a,'^',r,' = 1 (mod ',N,'): ',(a**r)%N)
if( ((r)%2 == 0) and ( a**(int(r/2))%N != int(N-1) )):
print('r is a good, proceed')
else:
print('r is not good, start over')
if((r)%2 != 0):
print('r is odd: ',r)
if(a**(int(r/2))%N == int(N-1)):
print('a^(r/2) (mod N) = N-1')
print('a^(r/2): ',int(a**(r/2.0)))
factor1 = oq.Euclids_Alg(int(a**(r/2.0)+1),N)
factor2 = oq.Euclids_Alg(int(a**(r/2.0)-1),N)
print('\nfactors of N: ',int(factor1),' ',int(factor2),' ( N is',N,')')
N = 35
a = int( random.randint(2,N-2) )
print('a: ',a)
#-------------------------------#
if( oq.Euclids_Alg(N,a) == 1 ):
r = oq.r_Finder(a,N)
print( 'r: ',r )
if( ((r)%2 == 0) and (a**(int(r/2))%N != int(N-1) )):
print('\nfactors of N: ',int(oq.Euclids_Alg(int(a**(r/2.0)+1),N)),' ',int(oq.Euclids_Alg(int(a**(r/2.0)-1),N)),' ( N is',N,')')
else:
if((r)%2 != 0):
print('Condition Not Satisfied: r is odd: ',r)
if(a**(int(r/2))%N == int(N-1)):
print('Condition Not Satisfied: a^(r/2) (mod N) = N-1: ',a**(int(r/2))%N)
else:
print('a has a GCD with N: ',oq.Euclids_Alg(N,a))
N = 35
coprimes = [4,6,8,9,11,13,16]
a = coprimes[int( random.randint(0,len(coprimes)-1) )]
print('N = ',N,' a = ',a,'\n')
#-------------------------------
for i in np.arange(10):
mod_N = a**int(i) % N
print('a^',i,' (mod N): ',mod_N)
S1 = [round(random.random()),round(random.random()),round(random.random()),round(random.random())]
a = 8
N = 15
print('N: ',N,' a: ',a)
#====================================
q1 = QuantumRegister(4,name='q1')
q2 = QuantumRegister(4,name='q2')
qc = QuantumCircuit(q1,q2,name='qc')
#------------------------------------
for i in np.arange(4):
if(S1[i]==1):
qc.x( q1[int(i)] )
print('\n_____ Initial State _____')
oq.Wavefunction(qc,systems=[4,4])
#------------------------------------
S1_num = S1[0] + 2*S1[1] + 4*S1[2] + 8*S1[3]
S2_num = a**(S1_num) % N
print('\nState 1: ',S1_num,' Desired State 2: ',a,'^',S1_num,' ( mod ',N,') = ',S2_num)
#------------------------------------
for j in np.arange(4):
if( S2_num >= 2**(3-j) ):
qc.x( q2[int(3-j)] )
S2_num = S2_num - 2**(3-j)
print('\n_____ After Modulo Operation_____')
oq.Wavefunction(qc,systems=[4,4]);
a = 8
N = 15
q1_state = [1,0,1,0]
q2_state = oq.BinaryL( a**(int( oq.From_BinaryLSB(q1_state,'L') ))%N, 2**4 )
print('a = ',a,' N = ',N)
print('\nInput State: ',q1_state,' Desired Modulo State: ',q2_state)
#=====================================
q1 = QuantumRegister(4,name='q1')
q2 = QuantumRegister(4,name='q2')
an = QuantumRegister(3,name='a')
qc = QuantumCircuit(q1,q2,an,name='qc')
#--------------------------------------
qc.h(q1[0])
qc.h(q1[2])
qc.cx( q1[0], q1[1] )
qc.cx( q1[2], q1[1])
print('\n_____ Initial State _____')
oq.Wavefunction(qc,systems=[4,4,3],show_systems=[True,True,False])
qc.barrier()
#-------------------------------------- |1010> state
oq.X_Transformation(qc,q1,q1_state)
qc.ccx( q1[0], q1[1], an[0] )
qc.ccx( q1[2], an[0], an[1] )
qc.ccx( q1[3], an[1], an[2] )
for i in np.arange(len(q2_state)):
if( q2_state[i]==1 ):
qc.cx( an[2], q2[int(i)] )
qc.ccx( q1[3], an[1], an[2] )
qc.ccx( q1[2], an[0], an[1] )
qc.ccx( q1[0], q1[1], an[0] )
oq.X_Transformation(qc,q1,q1_state)
print('\n_____ After Modulo Operation _____')
oq.Wavefunction(qc,systems=[4,4,3],show_systems=[True,True,False])
print(qc)
a = 8
N = 15
Q = 4
print('a: ',a,' N: ',N)
#=====================================
q1 = QuantumRegister(Q,name='q1')
q2 = QuantumRegister(Q,name='q2')
an = QuantumRegister(Q-1,name='a')
qc = QuantumCircuit(q1,q2,an,name='qc')
#--------------------------------------
for i in np.arange(Q):
qc.h(q1[int(i)])
print('\n_____ Initial State _____')
oq.Wavefunction(qc,systems=[4,4,3],show_systems=[True,True,False])
oq.Mod_Op(Q,qc,q1,q2,an,a,N)
print('\n_____ After Modulo Operation _____')
oq.Wavefunction(qc,systems=[4,4,3],show_systems=[True,True,False]);
a = 8
N = 15
Q = 4
print('a: ',a,' N: ',N)
#=====================================
q1 = QuantumRegister(Q,name='q1')
q2 = QuantumRegister(Q,name='q2')
an = QuantumRegister(Q-1,name='a')
c = ClassicalRegister(Q,name='c')
qc = QuantumCircuit(q1,q2,an,c,name='qc')
#--------------------------------------
for i in np.arange(Q):
qc.h(q1[int(i)])
print('\n_____ Initial State _____')
oq.Wavefunction(qc,systems=[Q,Q,Q-1],show_systems=[True,True,False])
oq.Mod_Op(Q,qc,q1,q2,an,a,N)
print('\n_____ After Modulo Operation _____')
oq.Wavefunction(qc,systems=[Q,Q,Q-1],show_systems=[True,True,False])
qc.measure(q2,c)
print('\n_____ After Partial Measurement _____')
oq.Wavefunction(qc,systems=[Q,Q,Q-1],show_systems=[True,True,False]);
k = 3
r = 5
a0 = int( (r)*random.random() )
L = k*r
C = np.zeros(r)
C[a0] = 1
print('k = ',k,' r = ',r,' a0 = ',a0,'\n\nOne Cycle: ',C,' L = ',L)
#------------------------------------------
f = []
for i in np.arange(k):
for i2 in np.arange(r):
f.append( int( C[i2] ) )
print('\nPeriodic Function: ',f)
F = oq.DFT(f,inverse=True)
print('\nAfter DFT\u2020: ',F)
#------------------------------------------
F2 = []
for j in np.arange( len(F) ):
F2.append( round(abs(F[j]),3) )
print('\n |F|: ',F2 )
k = int( 2+4*random.random() )
r = int( 2+4*random.random() )
L = k*r
print('k: ',k,' r: ',r,' L: ',L,'\n------------------------------\n')
#================================================
for q in np.arange(L):
n = int(q)
Q = 0
for j in np.arange(k):
Q = Q + np.exp( ((-2*m.pi*1.0j)/L) * n * j * r )
print( 'n: ',n,' \u03A3 = ',round( Q.real,5 ),' + i',round(Q.imag,5) )
N_circle = 1000
x_c = []
y_c = []
#-----------------
for c in np.arange(N_circle+1):
t = (2*m.pi*c)/N_circle
x_c.append( np.cos(t) )
y_c.append( np.sin(t) )
#=================================================
k = 5
r = 4
L = k*r
a0= int(r*random.random())
print('k: ',k,' r: ',r,' L: ',L,' a0: ',a0,'\n--------------------------------------------\n')
for i in np.arange(L):
p1 = np.exp( (-2*m.pi*1.0j/L) * (a0+0*r) * i)
p2 = np.exp( (-2*m.pi*1.0j/L) * (a0+1*r) * i)
p3 = np.exp( (-2*m.pi*1.0j/L) * (a0+2*r) * i)
p4 = np.exp( (-2*m.pi*1.0j/L) * (a0+3*r) * i)
p5 = np.exp( (-2*m.pi*1.0j/L) * (a0+4*r) * i)
#=======================
print('x_'+str(int(i))+' QFT term: ',round((p1+p2+p3+p4+p5).real,4),' + i',round((p1+p2+p3+p4+p5).imag,4))
fig = plt.figure(figsize=(4,4))
plt.scatter( p1.real,p1.imag,s=40,color='blue' )
plt.scatter( p2.real,p2.imag,s=40,color='orange' )
plt.scatter( p3.real,p3.imag,s=40,color='red' )
plt.scatter( p4.real,p4.imag,s=40,color='green' )
plt.scatter( p5.real,p5.imag,s=40,color='purple' )
plt.plot( x_c,y_c,linewidth=0.5 )
plt.show()
a = 8
N = 15
Q = 4
print('a: ',a,' N: ',N)
#=====================================
q1 = QuantumRegister(Q,name='q1')
q2 = QuantumRegister(Q,name='q2')
an = QuantumRegister(Q-1,name='a')
c = ClassicalRegister(Q,name='c')
qc = QuantumCircuit(q1,q2,an,c,name='qc')
#--------------------------------------
for i in np.arange(Q):
qc.h(q1[int(i)])
print('\n_____ Initial State _____')
oq.Wavefunction(qc,systems=[Q,Q,Q-1],show_systems=[True,True,False])
oq.Mod_Op(Q,qc,q1,q2,an,a,N)
print('\n_____ After Modulo Operation _____')
oq.Wavefunction(qc,systems=[Q,Q,Q-1],show_systems=[True,True,False])
qc.measure(q2,c)
oq.QFT_dgr(qc,q1,Q)
print('\n_____ Partial Measurement + QFT\u2020_____')
oq.Wavefunction(qc,systems=[Q,Q,Q-1],show_systems=[True,True,False]);
N = 2.815
#=====================================
q,p,a = oq.ConFrac(N, return_a=True)
print('N = ',N,' = ',p,'/',q)
print('\na constants: ',a)
#-------------------------------------
accuracy = 4
q,p,a = oq.ConFrac(N, a_max=accuracy, return_a=True)
print('\n--------------------------------------\nN = ',N,' \u2248 ',p,'/',q)
print('\na constants: ',a)
a = 8
N = 15
Q = 4
print('a: ',a,' N: ',N)
#=====================================
q1 = QuantumRegister(Q,name='q1')
q2 = QuantumRegister(Q,name='q2')
an = QuantumRegister(Q-1,name='a')
c1 = ClassicalRegister(Q,name='c1')
c2 = ClassicalRegister(Q,name='c2')
qc = QuantumCircuit(q1,q2,an,c1,c2,name='qc')
#--------------------------------------
for i in np.arange(Q):
qc.h(q1[int(i)])
oq.Mod_Op(Q,qc,q1,q2,an,a,N)
print('\n_____ After Modulo Operation _____')
oq.Wavefunction(qc,systems=[Q,Q,Q-1],show_systems=[True,True,False])
qc.measure(q2,c2)
oq.QFT_dgr(qc,q1,Q)
qc.measure(q1,c1)
M = oq.Measurement(qc,shots=1,print_M=False,return_M=True)
print('\n Partial Measurement: |'+list(M.keys())[0][4:8]+'>')
print('\nSystem One Measurement: |'+list(M.keys())[0][0:4]+'>')
#--------------------------------------
S = int(oq.From_Binary(list(list(M.keys())[0][0:4])))
L = 2**Q
print('\nS = ',S,' L = ',L)
if( S != 0 ):
r,mult = oq.ConFrac(1.0*S/L)
print('\nContinued Fractions Result: m = ',mult,' r = ',r)
k = int( 2+4*random.random() )
r = int( 2+4*random.random() )
L = k*r + 1
print('k: ',k,' r: ',r,' L: ',L,'\n------------------------------\n')
#================================================
for q in np.arange(L):
n = int(q)
Q = 0
for j in np.arange(k):
Q = Q + np.exp( ((-2*m.pi*1.0j)/L) * n * j * r )
print( 'n: ',n,' \u03A3 = ',round( Q.real,5 ),' + i',round(Q.imag,5) )
k = int( 4 + 2*random.random() )
r = int( 3 + 5*random.random() )
a0 = int( (r-1)*random.random() )
print('k = ',k,' r = ',r,' a0 = ',a0)
#------------------------------------------
L = k*r
C = np.zeros(r)
C[a0] = 1
#------------------------------------------
f1 = []
f2 = []
for i in np.arange(k):
for i2 in np.arange(r):
f1.append( C[i2] )
f2.append( C[i2] )
f2.append(0)
F1 = oq.DFT(f1,inverse=True)
F2 = oq.DFT(f2,inverse=True)
for q in np.arange( len(F1) ):
F1[q] = round( abs(F1[q]/k)**2 ,4)
F2[q] = round( abs(F2[q]/k)**2 ,4)
F2[-1] = round( abs(F2[-1]/k)**2 ,4)
#==========================================
x_bar = []
for j in np.arange(len(F1)):
x_bar.append(int(j))
plt.bar(x_bar,F1)
x_bar.append(int(j+1))
plt.bar(x_bar,F2,width=0.5)
plt.legend(['Perfect L','L + 1'])
plt.axis([-1, len(F2), 0, 1.3])
plt.show()
r = 7
L = 36
print('r: ',r,' L: ',L,'\n==============================')
#=====================
S = 10
print('\nS = ',S,'\n-----------------------------')
for i in np.arange(4):
q,p = oq.ConFrac(S/L,a_max=int(i+2))
print('order ',int(i+1),' Continued Fractions: '+str(p)+'/'+str(q),' \u2248 ',round(p/q,4))
#---------------------
S = 21
print('\nS = ',S)
for i in np.arange(4):
q,p = oq.ConFrac(S/L,a_max=int(i+2))
print('order ',int(i+1),' Continued Fractions: '+str(p)+'/'+str(q),' \u2248 ',round(p/q,4))
S = 21
L = 36
order = 4
#==================
for i in np.arange(3):
S_new = int( S - 1 + i)
for j in np.arange(3):
L_new = int( L - 1 + j)
if( (S_new!=S) or (L_new!=L) ):
print('\nS = ',S_new,' L = ',L_new,'\n-----------------------------')
for i in np.arange(4):
q,p = oq.ConFrac(S_new/L_new,a_max=int(i+2))
print('order ',int(i+1),' Continued Fractions: '+str(p)+'/'+str(q),' \u2248 ',round(p/q,4))
N = 55
#N=11*13
Q = m.ceil( m.log(N,2) )
nrQubits = 3*Q - 1
print("Number of qubits: ", nrQubits)
L = 2**Q
a = int( 2+ (N-3)*random.random() )
r = oq.r_Finder(a,N)
#=================================================
print('N = ',N,' Q = ',Q,' a = ',a,' Searching For: r =',r)
if( oq.Euclids_Alg(a,N) > 1 ):
print('\na happens to have a factor in common with N: ',oq.Euclids_Alg(a,N))
else:
q1 = QuantumRegister(Q,name='q1')
q2 = QuantumRegister(Q,name='q2')
an = QuantumRegister(Q-1,name='a')
c1 = ClassicalRegister(Q,name='c1')
c2 = ClassicalRegister(Q,name='c2')
qc = QuantumCircuit(q1,q2,an,c1,c2,name='qc')
#----------------------------------------------
for i in np.arange(Q):
qc.h(q1[int(i)])
oq.Mod_Op(Q,qc,q1,q2,an,a,N)
qc.measure(q2,c2)
oq.QFT_dgr(qc,q1,Q)
qc.measure(q1,c1)
M = oq.Measurement(qc,shots=1,print_M=False,return_M=True)
S = int(oq.From_Binary(list(list(M.keys())[0][0:Q])))
#----------------------------------------------
print('\nSystem One Measurement: |'+list(M.keys())[0][0:Q]+'>')
print('\nS = ',S,' L = ',L)
if( S!= 0):
r = oq.Evaluate_S(S,L,a,N)
if( r!=0 ):
print('\nFound the period r = ',r)
if( ((r)%2 == 0) and ( a**(int(r/2))%N != int(N-1) )):
f1 = oq.Euclids_Alg(int(a**(int(r/2))+1),N)
f2 = oq.Euclids_Alg(int(a**(int(r/2))-1),N)
print('\nFactors of N: ',int(f1),' ',int(f2))
else:
if( (r)%2 != 0 ):
print('\nr does not meet criteria for factoring N: r is not even')
else:
print('\nr does not meet criteria for factoring N: a^(r/2) (mod N) = N-1')
else:
print('\nCould not find the period using S, start over')
else:
print('\nMeasured S = 0, start over')
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# 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=invalid-name
"""Tests for Choi quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators.channel import Choi
from .channel_test_case import ChannelTestCase
class TestChoi(ChannelTestCase):
"""Tests for Choi channel representation."""
def test_init(self):
"""Test initialization"""
mat4 = np.eye(4) / 2.0
chan = Choi(mat4)
assert_allclose(chan.data, mat4)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
mat8 = np.eye(8) / 2.0
chan = Choi(mat8, input_dims=4)
assert_allclose(chan.data, mat8)
self.assertEqual(chan.dim, (4, 2))
self.assertIsNone(chan.num_qubits)
chan = Choi(mat8, input_dims=2)
assert_allclose(chan.data, mat8)
self.assertEqual(chan.dim, (2, 4))
self.assertIsNone(chan.num_qubits)
mat16 = np.eye(16) / 4
chan = Choi(mat16)
assert_allclose(chan.data, mat16)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan.num_qubits, 2)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Choi, mat8, input_dims=[4], output_dims=[4])
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Choi(circuit)
target = Choi(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Choi, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(4, 4)
self.assertEqual(Choi(mat), Choi(mat))
def test_copy(self):
"""Test copy method"""
mat = np.eye(2)
with self.subTest("Deep copy"):
orig = Choi(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Choi(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = Choi(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Choi(self.depol_choi(0.25)).is_cptp())
# Non-CPTP should return false
self.assertFalse(Choi(1.25 * self.choiI - 0.25 * self.depol_choi(1)).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
# Test channel measures in Z basis and prepares in Y basis
# Zp -> Yp, Zm -> Ym
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2
chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym))
# Conjugate channel swaps Y-basis states
targ = Choi(np.kron(Zp, Ym) + np.kron(Zm, Yp))
chan_conj = chan.conjugate()
self.assertEqual(chan_conj, targ)
def test_transpose(self):
"""Test transpose method."""
# Test channel measures in Z basis and prepares in Y basis
# Zp -> Yp, Zm -> Ym
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2
chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym))
# Transpose channel swaps basis
targ = Choi(np.kron(Yp, Zp) + np.kron(Ym, Zm))
chan_t = chan.transpose()
self.assertEqual(chan_t, targ)
def test_adjoint(self):
"""Test adjoint method."""
# Test channel measures in Z basis and prepares in Y basis
# Zp -> Yp, Zm -> Ym
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2
chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym))
# Ajoint channel swaps Y-basis elements and Z<->Y bases
targ = Choi(np.kron(Ym, Zp) + np.kron(Yp, Zm))
chan_adj = chan.adjoint()
self.assertEqual(chan_adj, targ)
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Choi(np.eye(4)).compose, Choi(np.eye(8)))
self.assertRaises(QiskitError, Choi(np.eye(4)).compose, 2)
def test_compose(self):
"""Test compose method."""
# UnitaryChannel evolution
chan1 = Choi(self.choiX)
chan2 = Choi(self.choiY)
chan = chan1.compose(chan2)
targ = Choi(self.choiZ)
self.assertEqual(chan, targ)
# 50% depolarizing channel
chan1 = Choi(self.depol_choi(0.5))
chan = chan1.compose(chan1)
targ = Choi(self.depol_choi(0.75))
self.assertEqual(chan, targ)
# Measure and rotation
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2
chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
chan2 = Choi(self.choiX)
# X-gate second does nothing
targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
self.assertEqual(chan1.compose(chan2), targ)
self.assertEqual(chan1 & chan2, targ)
# X-gate first swaps Z states
targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm))
self.assertEqual(chan2.compose(chan1), targ)
self.assertEqual(chan2 & chan1, targ)
# Compose different dimensions
chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4)
chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2)
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
chan = chan2.compose(chan1)
self.assertEqual(chan.dim, (4, 4))
def test_dot(self):
"""Test dot method."""
# UnitaryChannel evolution
chan1 = Choi(self.choiX)
chan2 = Choi(self.choiY)
targ = Choi(self.choiZ)
self.assertEqual(chan1.dot(chan2), targ)
self.assertEqual(chan1 @ chan2, targ)
# 50% depolarizing channel
chan1 = Choi(self.depol_choi(0.5))
targ = Choi(self.depol_choi(0.75))
self.assertEqual(chan1.dot(chan1), targ)
self.assertEqual(chan1 @ chan1, targ)
# Measure and rotation
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2
chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
chan2 = Choi(self.choiX)
# X-gate second does nothing
targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
self.assertEqual(chan2.dot(chan1), targ)
self.assertEqual(chan2 @ chan1, targ)
# X-gate first swaps Z states
targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm))
self.assertEqual(chan1.dot(chan2), targ)
self.assertEqual(chan1 @ chan2, targ)
# Compose different dimensions
chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4)
chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2)
chan = chan1.dot(chan2)
self.assertEqual(chan.dim, (4, 4))
chan = chan1 @ chan2
self.assertEqual(chan.dim, (4, 4))
chan = chan2.dot(chan1)
self.assertEqual(chan.dim, (2, 2))
chan = chan2 @ chan1
self.assertEqual(chan.dim, (2, 2))
def test_compose_front(self):
"""Test front compose method."""
# UnitaryChannel evolution
chan1 = Choi(self.choiX)
chan2 = Choi(self.choiY)
chan = chan1.compose(chan2, front=True)
targ = Choi(self.choiZ)
self.assertEqual(chan, targ)
# 50% depolarizing channel
chan1 = Choi(self.depol_choi(0.5))
chan = chan1.compose(chan1, front=True)
targ = Choi(self.depol_choi(0.75))
self.assertEqual(chan, targ)
# Measure and rotation
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2
chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
chan2 = Choi(self.choiX)
# X-gate second does nothing
chan = chan2.compose(chan1, front=True)
targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
self.assertEqual(chan, targ)
# X-gate first swaps Z states
chan = chan1.compose(chan2, front=True)
targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm))
self.assertEqual(chan, targ)
# Compose different dimensions
chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4)
chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2)
chan = chan1.compose(chan2, front=True)
self.assertEqual(chan.dim, (4, 4))
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Choi(self.choiI)
chan2 = Choi(self.choiX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = Choi(self.depol_choi(1))
chan = chan_dep.expand(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Choi(self.choiI)
chan2 = Choi(self.choiX)
# X \otimes I
rho_targ = DensityMatrix(np.kron(rho1, rho0))
chan = chan2.tensor(chan1)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan2 ^ chan1
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
rho_targ = DensityMatrix(np.kron(rho0, rho1))
chan = chan1.tensor(chan2)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 ^ chan2
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
chan_dep = Choi(self.depol_choi(1))
chan = chan_dep.tensor(chan_dep)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan_dep ^ chan_dep
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
p_id = 0.9
depol = Choi(self.depol_choi(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = depol.power(3)
targ3 = Choi(self.depol_choi(1 - p_id3))
self.assertEqual(chan3, targ3)
def test_add(self):
"""Test add method."""
mat1 = 0.5 * self.choiI
mat2 = 0.5 * self.depol_choi(1)
chan1 = Choi(mat1)
chan2 = Choi(mat2)
targ = Choi(mat1 + mat2)
self.assertEqual(chan1._add(chan2), targ)
self.assertEqual(chan1 + chan2, targ)
targ = Choi(mat1 - mat2)
self.assertEqual(chan1 - chan2, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = Choi(mat)
op0 = Choi(mat0)
op1 = Choi(mat1)
op01 = op1.tensor(op0)
eye = Choi(self.choiI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = Choi(mat)
op0 = Choi(mat0)
op1 = Choi(mat1)
op01 = op1.tensor(op0)
eye = Choi(self.choiI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_add_except(self):
"""Test add method raises exceptions."""
chan1 = Choi(self.choiI)
chan2 = Choi(np.eye(8))
self.assertRaises(QiskitError, chan1._add, chan2)
self.assertRaises(QiskitError, chan1._add, 5)
def test_multiply(self):
"""Test multiply method."""
chan = Choi(self.choiI)
val = 0.5
targ = Choi(val * self.choiI)
self.assertEqual(chan._multiply(val), targ)
self.assertEqual(val * chan, targ)
targ = Choi(self.choiI * val)
self.assertEqual(chan * val, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Choi(self.choiI)
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
chan = Choi(self.choiI)
targ = Choi(-1 * self.choiI)
self.assertEqual(-chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice
from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel
line = LineLattice(2)
fermi = FermiHubbardModel.uniform_parameters(line, 2.0, 4.0, 3.0)
print(fermi.second_q_ops()) # Note: the trailing `s`
from qiskit_nature.second_q.hamiltonians.lattices import LineLattice
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
line = LineLattice(2)
fermi = FermiHubbardModel(line.uniform_parameters(2.0, 4.0), 3.0)
print(fermi.second_q_op()) # Note: NO trailing `s`
import numpy as np
from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
fermi = FermiHubbardModel.from_parameters(interaction, 3.0)
print(fermi.second_q_ops()) # Note: the trailing `s`
import numpy as np
from qiskit_nature.second_q.hamiltonians.lattices import Lattice
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
lattice = Lattice.from_adjacency_matrix(interaction)
fermi = FermiHubbardModel(lattice, 3.0)
print(fermi.second_q_op()) # Note: NO trailing `s`
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice
from qiskit_nature.problems.second_quantization.lattice.models import IsingModel
line = LineLattice(2)
ising = IsingModel.uniform_parameters(line, 2.0, 4.0)
print(ising.second_q_ops()) # Note: the trailing `s`
from qiskit_nature.second_q.hamiltonians.lattices import LineLattice
from qiskit_nature.second_q.hamiltonians import IsingModel
line = LineLattice(2)
ising = IsingModel(line.uniform_parameters(2.0, 4.0))
print(ising.second_q_op()) # Note: NO trailing `s`
import numpy as np
from qiskit_nature.problems.second_quantization.lattice.models import IsingModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
ising = IsingModel.from_parameters(interaction)
print(ising.second_q_ops()) # Note: the trailing `s`
import numpy as np
from qiskit_nature.second_q.hamiltonians.lattices import Lattice
from qiskit_nature.second_q.hamiltonians import IsingModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
lattice = Lattice.from_adjacency_matrix(interaction)
ising = IsingModel(lattice)
print(ising.second_q_op()) # Note: NO trailing `s`
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# 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.
"""
Kraus representation of a Quantum Channel.
"""
from __future__ import annotations
import copy
import math
from numbers import Number
import numpy as np
from qiskit import circuit
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.circuit.instruction import Instruction
from qiskit.exceptions import QiskitError
from qiskit.quantum_info.operators.predicates import is_identity_matrix
from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel
from qiskit.quantum_info.operators.op_shape import OpShape
from qiskit.quantum_info.operators.channel.choi import Choi
from qiskit.quantum_info.operators.channel.superop import SuperOp
from qiskit.quantum_info.operators.channel.transformations import _to_kraus
from qiskit.quantum_info.operators.mixins import generate_apidocs
from qiskit.quantum_info.operators.base_operator import BaseOperator
class Kraus(QuantumChannel):
r"""Kraus representation of a quantum channel.
For a quantum channel :math:`\mathcal{E}`, the Kraus representation is
given by a set of matrices :math:`[A_0,...,A_{K-1}]` such that the
evolution of a :class:`~qiskit.quantum_info.DensityMatrix`
:math:`\rho` is given by
.. math::
\mathcal{E}(\rho) = \sum_{i=0}^{K-1} A_i \rho A_i^\dagger
A general operator map :math:`\mathcal{G}` can also be written using the
generalized Kraus representation which is given by two sets of matrices
:math:`[A_0,...,A_{K-1}]`, :math:`[B_0,...,A_{B-1}]` such that
.. math::
\mathcal{G}(\rho) = \sum_{i=0}^{K-1} A_i \rho B_i^\dagger
See reference [1] for further details.
References:
1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus
for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015).
`arXiv:1111.6950 [quant-ph] <https://arxiv.org/abs/1111.6950>`_
"""
def __init__(
self,
data: QuantumCircuit | circuit.instruction.Instruction | BaseOperator | np.ndarray,
input_dims: tuple | None = None,
output_dims: tuple | None = None,
):
"""Initialize a quantum channel Kraus operator.
Args:
data: data to initialize superoperator.
input_dims: the input subsystem dimensions.
output_dims: the output subsystem dimensions.
Raises:
QiskitError: if input data cannot be initialized as a list of Kraus matrices.
Additional Information:
If the input or output dimensions are None, they will be
automatically determined from the input data. If the input data is
a list of Numpy arrays of shape :math:`(2^N,\\,2^N)` qubit systems will be
used. If the input does not correspond to an N-qubit channel, it
will assign a single subsystem with dimension specified by the
shape of the input.
"""
# If the input is a list or tuple we assume it is a list of Kraus
# matrices, if it is a numpy array we assume that it is a single Kraus
# operator
# TODO properly handle array construction from ragged data (like tuple(np.ndarray, None))
# and document these accepted input cases. See also Qiskit/qiskit-terra#9307.
if isinstance(data, (list, tuple, np.ndarray)):
# Check if it is a single unitary matrix A for channel:
# E(rho) = A * rho * A^\dagger
if _is_matrix(data):
# Convert single Kraus op to general Kraus pair
kraus = ([np.asarray(data, dtype=complex)], None)
shape = kraus[0][0].shape
# Check if single Kraus set [A_i] for channel:
# E(rho) = sum_i A_i * rho * A_i^dagger
elif isinstance(data, list) and len(data) > 0:
# Get dimensions from first Kraus op
kraus = [np.asarray(data[0], dtype=complex)]
shape = kraus[0].shape
# Iterate over remaining ops and check they are same shape
for i in data[1:]:
op = np.asarray(i, dtype=complex)
if op.shape != shape:
raise QiskitError("Kraus operators are different dimensions.")
kraus.append(op)
# Convert single Kraus set to general Kraus pair
kraus = (kraus, None)
# Check if generalized Kraus set ([A_i], [B_i]) for channel:
# E(rho) = sum_i A_i * rho * B_i^dagger
elif isinstance(data, tuple) and len(data) == 2 and len(data[0]) > 0:
kraus_left = [np.asarray(data[0][0], dtype=complex)]
shape = kraus_left[0].shape
for i in data[0][1:]:
op = np.asarray(i, dtype=complex)
if op.shape != shape:
raise QiskitError("Kraus operators are different dimensions.")
kraus_left.append(op)
if data[1] is None:
kraus = (kraus_left, None)
else:
kraus_right = []
for i in data[1]:
op = np.asarray(i, dtype=complex)
if op.shape != shape:
raise QiskitError("Kraus operators are different dimensions.")
kraus_right.append(op)
kraus = (kraus_left, kraus_right)
else:
raise QiskitError("Invalid input for Kraus channel.")
op_shape = OpShape.auto(dims_l=output_dims, dims_r=input_dims, shape=kraus[0][0].shape)
else:
# Otherwise we initialize by conversion from another Qiskit
# object into the QuantumChannel.
if isinstance(data, (QuantumCircuit, Instruction)):
# If the input is a Terra QuantumCircuit or Instruction we
# convert it to a SuperOp
data = SuperOp._init_instruction(data)
else:
# We use the QuantumChannel init transform to initialize
# other objects into a QuantumChannel or Operator object.
data = self._init_transformer(data)
op_shape = data._op_shape
output_dim, input_dim = op_shape.shape
# Now that the input is an operator we convert it to a Kraus
rep = getattr(data, "_channel_rep", "Operator")
kraus = _to_kraus(rep, data._data, input_dim, output_dim)
# Initialize either single or general Kraus
if kraus[1] is None or np.allclose(kraus[0], kraus[1]):
# Standard Kraus map
data = (kraus[0], None)
else:
# General (non-CPTP) Kraus map
data = kraus
super().__init__(data, op_shape=op_shape)
@property
def data(self):
"""Return list of Kraus matrices for channel."""
if self._data[1] is None:
# If only a single Kraus set, don't return the tuple
# Just the fist set
return self._data[0]
else:
# Otherwise return the tuple of both kraus sets
return self._data
def is_cptp(self, atol=None, rtol=None):
"""Return True if completely-positive trace-preserving."""
if self._data[1] is not None:
return False
if atol is None:
atol = self.atol
if rtol is None:
rtol = self.rtol
accum = 0j
for op in self._data[0]:
accum += np.dot(np.transpose(np.conj(op)), op)
return is_identity_matrix(accum, rtol=rtol, atol=atol)
def _evolve(self, state, qargs=None):
return SuperOp(self)._evolve(state, qargs)
# ---------------------------------------------------------------------
# BaseOperator methods
# ---------------------------------------------------------------------
def conjugate(self):
ret = copy.copy(self)
kraus_l, kraus_r = self._data
kraus_l = [np.conj(k) for k in kraus_l]
if kraus_r is not None:
kraus_r = [k.conj() for k in kraus_r]
ret._data = (kraus_l, kraus_r)
return ret
def transpose(self):
ret = copy.copy(self)
ret._op_shape = self._op_shape.transpose()
kraus_l, kraus_r = self._data
kraus_l = [np.transpose(k) for k in kraus_l]
if kraus_r is not None:
kraus_r = [np.transpose(k) for k in kraus_r]
ret._data = (kraus_l, kraus_r)
return ret
def adjoint(self):
ret = copy.copy(self)
ret._op_shape = self._op_shape.transpose()
kraus_l, kraus_r = self._data
kraus_l = [np.conj(np.transpose(k)) for k in kraus_l]
if kraus_r is not None:
kraus_r = [np.conj(np.transpose(k)) for k in kraus_r]
ret._data = (kraus_l, kraus_r)
return ret
def compose(self, other: Kraus, qargs: list | None = None, front: bool = False) -> Kraus:
if qargs is None:
qargs = getattr(other, "qargs", None)
if qargs is not None:
return Kraus(SuperOp(self).compose(other, qargs=qargs, front=front))
if not isinstance(other, Kraus):
other = Kraus(other)
new_shape = self._op_shape.compose(other._op_shape, qargs, front)
input_dims = new_shape.dims_r()
output_dims = new_shape.dims_l()
if front:
ka_l, ka_r = self._data
kb_l, kb_r = other._data
else:
ka_l, ka_r = other._data
kb_l, kb_r = self._data
kab_l = [np.dot(a, b) for a in ka_l for b in kb_l]
if ka_r is None and kb_r is None:
kab_r = None
elif ka_r is None:
kab_r = [np.dot(a, b) for a in ka_l for b in kb_r]
elif kb_r is None:
kab_r = [np.dot(a, b) for a in ka_r for b in kb_l]
else:
kab_r = [np.dot(a, b) for a in ka_r for b in kb_r]
ret = Kraus((kab_l, kab_r), input_dims, output_dims)
ret._op_shape = new_shape
return ret
def tensor(self, other: Kraus) -> Kraus:
if not isinstance(other, Kraus):
other = Kraus(other)
return self._tensor(self, other)
def expand(self, other: Kraus) -> Kraus:
if not isinstance(other, Kraus):
other = Kraus(other)
return self._tensor(other, self)
@classmethod
def _tensor(cls, a, b):
ret = copy.copy(a)
ret._op_shape = a._op_shape.tensor(b._op_shape)
# Get tensor matrix
ka_l, ka_r = a._data
kb_l, kb_r = b._data
kab_l = [np.kron(ka, kb) for ka in ka_l for kb in kb_l]
if ka_r is None and kb_r is None:
kab_r = None
else:
if ka_r is None:
ka_r = ka_l
if kb_r is None:
kb_r = kb_l
kab_r = [np.kron(a, b) for a in ka_r for b in kb_r]
ret._data = (kab_l, kab_r)
return ret
def __add__(self, other):
qargs = getattr(other, "qargs", None)
if not isinstance(other, QuantumChannel):
other = Choi(other)
return self._add(other, qargs=qargs)
def __sub__(self, other):
qargs = getattr(other, "qargs", None)
if not isinstance(other, QuantumChannel):
other = Choi(other)
return self._add(-other, qargs=qargs)
def _add(self, other, qargs=None):
# Since we cannot directly add two channels in the Kraus
# representation we try and use the other channels method
# or convert to the Choi representation
return Kraus(Choi(self)._add(other, qargs=qargs))
def _multiply(self, other):
if not isinstance(other, Number):
raise QiskitError("other is not a number")
ret = copy.copy(self)
# If the number is complex we need to convert to general
# kraus channel so we multiply via Choi representation
if isinstance(other, complex) or other < 0:
# Convert to Choi-matrix
ret._data = Kraus(Choi(self)._multiply(other))._data
return ret
# If the number is real we can update the Kraus operators
# directly
val = math.sqrt(other)
kraus_r = None
kraus_l = [val * k for k in self._data[0]]
if self._data[1] is not None:
kraus_r = [val * k for k in self._data[1]]
ret._data = (kraus_l, kraus_r)
return ret
def _is_matrix(data):
# return True if data is a 2-d array/tuple/list
if not isinstance(data, np.ndarray):
data = np.array(data, dtype=object)
return data.ndim == 2
# Update docstrings for API docs
generate_apidocs(Kraus)
|
https://github.com/lockwo/Paper-Review
|
lockwo
|
from qiskit import Aer, IBMQ
from qiskit.utils import QuantumInstance
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes.calibration import RZXCalibrationBuilderNoEcho
from qiskit_nature.drivers import UnitsType, Molecule
from qiskit_nature.drivers.second_quantization import ElectronicStructureDriverType, ElectronicStructureMoleculeDriver
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
from qiskit_nature.mappers.second_quantization import ParityMapper
from qiskit_nature.algorithms import GroundStateEigensolver
from qiskit_nature.runtime import VQEClient
from qiskit.algorithms import NumPyMinimumEigensolver, VQE
from qiskit.algorithms.optimizers import SPSA
from qiskit.circuit import QuantumCircuit, ParameterVector
from qiskit.utils import QuantumInstance
from qiskit.providers.aer import AerSimulator
import matplotlib.pyplot as plt
import numpy as np
IBMQ.load_account()
provider = IBMQ.get_provider()
hardware_backend = provider.get_backend('ibmq_quito')
def HEA_aware(num_q, depth):
circuit = QuantumCircuit(num_q)
params = ParameterVector("theta", length=num_q * (3 * depth + 2))
counter = 0
for q in range(num_q):
circuit.rx(params[counter], q)
counter += 1
circuit.rz(params[counter], q)
counter += 1
for d in range(depth):
for q in range(num_q - 1):
gate = QuantumCircuit(num_q)
gate.rzx(np.pi/2, q, q + 1)
pass_ = RZXCalibrationBuilderNoEcho(hardware_backend)
qc_cr = PassManager(pass_).run(gate)
circuit.compose(qc_cr, inplace=True)
for q in range(num_q):
circuit.rz(params[counter], q)
counter += 1
circuit.rx(params[counter], q)
counter += 1
circuit.rx(params[counter], q, label="last" if q == num_q - 1 else 'rz')
counter += 1
return circuit, params
dist = 0.82
qubit_converter = QubitConverter(ParityMapper(), two_qubit_reduction=True)
numpy_solver = NumPyMinimumEigensolver()
molecule = Molecule(geometry=[['H', [0., 0., 0.]], ['H', [0., 0., dist]]])
driver = ElectronicStructureMoleculeDriver(molecule, basis='sto3g', \
driver_type=ElectronicStructureDriverType.PYSCF)
es_problem = ElectronicStructureProblem(driver)
calc = GroundStateEigensolver(qubit_converter, numpy_solver)
res = calc.solve(es_problem)
ret_1 = np.real(res.total_energies[0])
target_energy = ret_1
shots = 1024
backend = provider.get_backend('ibmq_qasm_simulator')
qubits = 2
depth = 1
circuit, _ = HEA_aware(qubits, depth)
spsa = SPSA(200)
qubit_converter = QubitConverter(ParityMapper(), two_qubit_reduction=True)
numpy_solver = NumPyMinimumEigensolver()
molecule = Molecule(geometry=[['H', [0., 0., 0.]], ['H', [0., 0., dist]]])
driver = ElectronicStructureMoleculeDriver(molecule, basis='sto3g', \
driver_type=ElectronicStructureDriverType.PYSCF)
es_problem = ElectronicStructureProblem(driver)
runtime_vqe = VQEClient(
ansatz=circuit,
optimizer=spsa,
provider=provider,
backend=backend,
shots=shots
)
runtime_vqe_groundstate_solver = GroundStateEigensolver(qubit_converter, runtime_vqe)
runtime_vqe_result_soft = runtime_vqe_groundstate_solver.solve(es_problem)
runtime_result_soft = runtime_vqe_result_soft.raw_result
history_soft = runtime_result_soft.optimizer_history
loss_soft = history_soft["loss"]
target_energy = ret_1
plt.figure(figsize=(14, 8))
plt.plot(loss_soft + runtime_vqe_result_soft.nuclear_repulsion_energy, label="Noiseless Sim")
plt.axhline(y=target_energy, color="tab:red", ls="--", label="Target")
plt.legend()
plt.xlabel("Iteration")
plt.ylabel("Energy [H]")
plt.title("VQE energy")
plt.show()
from qiskit.tools.jupyter import *
%qiskit_version_table
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
import pylab
import numpy as np
from qiskit import BasicAer
from qiskit.tools.visualization import plot_histogram
from qiskit.aqua import QuantumInstance
from qiskit.aqua import run_algorithm
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle
input_3sat_instance = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
oracle = LogicalExpressionOracle(input_3sat_instance)
grover = Grover(oracle)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
result = grover.run(quantum_instance)
print(result['result'])
plot_histogram(result['measurement'])
params = {
'problem': {
'name': 'search',
},
'algorithm': {
'name': 'Grover'
},
'oracle': {
'name': 'LogicalExpressionOracle',
'expression': input_3sat_instance
},
'backend': {
'shots': 1000,
},
}
result_dict = run_algorithm(params, backend=backend)
plot_histogram(result_dict['measurement'])
expression = '(w ^ x) & ~(y ^ z) & (x & y & z)'
oracle = LogicalExpressionOracle(expression)
grover = Grover(oracle)
result = grover.run(QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024))
plot_histogram(result['measurement'])
truthtable = '1000000000000001'
oracle = TruthTableOracle(truthtable)
grover = Grover(oracle)
result = grover.run(QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024))
plot_histogram(result['measurement'])
#solution
from hide_toggle import hide_toggle
hide_toggle(for_next=True)
sat_cnf = '''
c prova.cnf
c
p cnf 2 2
1 -2 0
-1 2 0
'''
#print(sat_cnf)
#oracle_2 = LogicalExpressionOracle(sat_cnf)
#my_grover = Grover(oracle_2)
#backend = BasicAer.get_backend('qasm_simulator')
#quantum_grover = QuantumInstance(backend, shots=1024)
#result = grover.run(quantum_grover)
#print(result['result'])
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
print(qiskit.__version__)
from qiskit.aqua.algorithms import Shor
from qiskit.aqua import QuantumInstance
import numpy as np
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend=backend, shots=1024)
my_shor = Shor(N=2189,a=4,quantum_instance=quantum_instance)
Shor.run(my_shor)
|
https://github.com/jhlee29/quantum-meets-hangul
|
jhlee29
|
from PIL import Image, ImageOps
import os, glob
import numpy as np
from sklearn import model_selection #cross_validation
# from keras.utils import np_utils
# General imports
import os
import gzip
import numpy as np
import matplotlib.pyplot as plt
from pylab import cm
import warnings
warnings.filterwarnings("ignore")
# scikit-learn imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# Qiskit imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# input
classes = ["g", "h"]
# image size of 28 x 28
image_size = 28
# Maximum number of sheets to read
max_read = 75
num_classes = len(classes)
# load the image
X = []
Y = []
for index, classlabel in enumerate(classes):
images_dir = "./hangul_characters/" + classlabel
files = glob.glob(images_dir + "/*.jpg")
for i, file in enumerate(files):
# Stop if you read more than max_read to make the number of sheets for each class
if i >= max_read: break
# open the file, read as data, add to X
# Repeatedly add labels with the same index to Y
image = Image.open(file)
image = ImageOps.invert(image)
image = image.convert("L")
image = image.resize((image_size, image_size))
data = np.asarray(image)
X.append(data)
Y.append(index)
X = np.array(X)
Y = np.array(Y)
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, Y, test_size=0.2, random_state=42)
X_train = X_train.reshape(len(X_train), -1).astype(np.float64)
X_test = X_test.reshape(len(X_test), -1).astype(np.float64)
fig = plt.figure()
LABELS = [0, 1]
num_labels = len(LABELS)
for i in range(num_labels):
ax = fig.add_subplot(1, num_labels, i+1)
img = X[Y==LABELS[i]][0].reshape((28,28))
ax.imshow(img, cmap="Greys")
# Standardize
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)
# Reduce dimensions
N_DIM = 5
pca = PCA(n_components=N_DIM)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
# 3 features, depth 1, linear entanglement
map_zz = ZZFeatureMap(feature_dimension=5, reps=1, entanglement='linear')
map_zz.decompose().draw('mpl')
zz_kernel = QuantumKernel(feature_map=map_zz, quantum_instance=Aer.get_backend('statevector_simulator'))
matrix_train = zz_kernel.evaluate(x_vec=X_train)
matrix_val = zz_kernel.evaluate(x_vec=X_test, y_vec=X_train)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(np.asmatrix(matrix_train),
interpolation='nearest', origin='upper', cmap='Blues')
axs[0].set_title("training kernel matrix")
axs[1].imshow(np.asmatrix(matrix_val),
interpolation='nearest', origin='upper', cmap='Reds')
axs[1].set_title("validation kernel matrix")
plt.show()
zz_svc = SVC(kernel='precomputed')
zz_svc.fit(matrix_train, y_train)
zz_score = zz_svc.score(matrix_val, y_test)
print(f'Precomputed kernel classification test score: {zz_score}')
|
https://github.com/DRA-chaos/Solutions-to-the-Lab-Exercises---IBM-Qiskit-Summer-School-2021
|
DRA-chaos
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.sdg(0)
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.cx(0,1)
qc.x(0)
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
#
#
# FILL YOUR CODE IN HERE
#
#
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.y(1)
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
oraclenr = 4 # determines the oracle (can range from 1 to 5)
oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles
oracle.name = "DJ-Oracle"
def dj_classical(n, input_str):
# build a quantum circuit with n qubits and 1 classical readout bit
dj_circuit = QuantumCircuit(n+1,1)
# Prepare the initial state corresponding to your input bit string
for i in range(n):
if input_str[i] == '1':
dj_circuit.x(i)
# append oracle
dj_circuit.append(oracle, range(n+1))
# measure the fourth qubit
dj_circuit.measure(n,0)
return dj_circuit
n = 4 # number of qubits
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
dj_circuit.draw() # draw the circuit
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit, qasm_sim)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def lab1_ex7():
min_nr_inputs = 2
max_nr_inputs = 9
return [min_nr_inputs, max_nr_inputs]
from qc_grader import grade_lab1_ex7
# Note that the grading function is expecting a list of two integers
grade_lab1_ex7(lab1_ex7())
n=4
def psi_0(n):
qc = QuantumCircuit(n+1,n)
# Build the state (|00000> - |10000>)/sqrt(2)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(4)
qc.h(4)
return qc
dj_circuit = psi_0(n)
dj_circuit.draw()
def psi_1(n):
# obtain the |psi_0> = |00001> state
qc = psi_0(n)
# create the superposition state |psi_1>
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
#
#
qc.barrier()
return qc
dj_circuit = psi_1(n)
dj_circuit.draw()
def psi_2(oracle,n):
# circuit to obtain psi_1
qc = psi_1(n)
# append the oracle
qc.append(oracle, range(n+1))
return qc
dj_circuit = psi_2(oracle, n)
dj_circuit.draw()
def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25])
qc = psi_2(oracle, n)
# apply n-fold hadamard gate
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
# add the measurement by connecting qubits to classical bits
#
#
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
#
#
return qc
dj_circuit = lab1_ex8(oracle, n)
dj_circuit.draw()
from qc_grader import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit with measurements
grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n))
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# 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 EnlargeWithAncilla pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import Layout
from qiskit.transpiler.passes import EnlargeWithAncilla
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestEnlargeWithAncilla(QiskitTestCase):
"""Tests the EnlargeWithAncilla pass."""
def setUp(self):
super().setUp()
self.qr3 = QuantumRegister(3, "qr")
circuit = QuantumCircuit(self.qr3)
circuit.h(self.qr3)
self.dag = circuit_to_dag(circuit)
def test_no_extension(self):
"""There are no virtual qubits to extend."""
layout = Layout({self.qr3[0]: 0, self.qr3[1]: 1, self.qr3[2]: 2})
pass_ = EnlargeWithAncilla()
pass_.property_set["layout"] = layout
after = pass_.run(self.dag)
qregs = list(after.qregs.values())
self.assertEqual(1, len(qregs))
self.assertEqual(self.qr3, qregs[0])
def test_with_extension(self):
"""There are 2 virtual qubit to extend."""
ancilla = QuantumRegister(2, "ancilla")
layout = Layout(
{0: self.qr3[0], 1: ancilla[0], 2: self.qr3[1], 3: ancilla[1], 4: self.qr3[2]}
)
layout.add_register(ancilla)
pass_ = EnlargeWithAncilla()
pass_.property_set["layout"] = layout
after = pass_.run(self.dag)
qregs = list(after.qregs.values())
self.assertEqual(2, len(qregs))
self.assertEqual(self.qr3, qregs[0])
self.assertEqual(ancilla, qregs[1])
if __name__ == "__main__":
unittest.main()
|
https://github.com/soultanis/Quantum-Database-Search
|
soultanis
|
from math import sqrt, pi
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import oracle_simple
import composed_gates
def get_circuit(n, oracles):
"""
Build the circuit composed by the oracle black box and the other quantum gates.
:param n: The number of qubits (not including the ancillas)
:param oracles: A list of black box (quantum) oracles; each of them selects a specific state
:returns: The proper quantum circuit
:rtype: qiskit.QuantumCircuit
"""
cr = ClassicalRegister(n)
## Testing
if n > 3:
#anc = QuantumRegister(n - 1, 'anc')
# n qubits for the real number
# n - 1 qubits for the ancillas
qr = QuantumRegister(n + n - 1)
qc = QuantumCircuit(qr, cr)
else:
# We don't need ancillas
qr = QuantumRegister(n)
qc = QuantumCircuit(qr, cr)
## /Testing
print("Number of qubits is {0}".format(len(qr)))
print(qr)
# Initial superposition
for j in range(n):
qc.h(qr[j])
# The length of the oracles list, or, in other words, how many roots of the function do we have
m = len(oracles)
# Grover's algorithm is a repetition of an oracle box and a diffusion box.
# The number of repetitions is given by the following formula.
print("n is ", n)
r = int(round((pi / 2 * sqrt((2**n) / m) - 1) / 2))
print("Repetition of ORACLE+DIFFUSION boxes required: {0}".format(r))
oracle_t1 = oracle_simple.OracleSimple(n, 5)
oracle_t2 = oracle_simple.OracleSimple(n, 0)
for j in range(r):
for i in range(len(oracles)):
oracles[i].get_circuit(qr, qc)
diffusion(n, qr, qc)
for j in range(n):
qc.measure(qr[j], cr[j])
return qc, len(qr)
def diffusion(n, qr, qc):
"""
The Grover diffusion operator.
Given the arry of qiskit QuantumRegister qr and the qiskit QuantumCircuit qc, it adds the diffusion operator to the appropriate qubits in the circuit.
"""
for j in range(n):
qc.h(qr[j])
# D matrix, flips state |000> only (instead of flipping all the others)
for j in range(n):
qc.x(qr[j])
# 0..n-2 control bits, n-1 target, n..
if n > 3:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1],
[qr[j] for j in range(n, n + n - 1)])
else:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1], None)
for j in range(n):
qc.x(qr[j])
for j in range(n):
qc.h(qr[j])
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import pylab
from qiskit_chemistry import QiskitChemistry
# Input dictionary to configure Qiskit Chemistry for the chemistry problem.
qiskit_chemistry_dict = {
'driver': {'name': 'PYSCF'},
'PYSCF': {'atom': '', 'basis': 'sto3g'},
'operator': {'name': 'hamiltonian', 'transformation': 'full',
'qubit_mapping': 'parity', 'two_qubit_reduction': True},
'algorithm': {'name': 'VQE'},
'optimizer': {'name': 'SPSA', 'max_trials': 350},
'variational_form': {'name': 'RYRZ', 'depth': 3, 'entanglement': 'full'}
}
molecule = 'H .0 .0 -{0}; H .0 .0 {0}'
algorithms = ['VQE', 'ExactEigensolver']
backends = [{'name': 'qasm_simulator', 'shots': 1024},
None
]
start = 0.5 # Start distance
by = 0.5 # How much to increase distance by
steps = 20 # Number of steps to increase by
energies = np.empty([len(algorithms), steps+1])
hf_energies = np.empty(steps+1)
distances = np.empty(steps+1)
print('Processing step __', end='')
for i in range(steps+1):
print('\b\b{:2d}'.format(i), end='', flush=True)
d = start + i*by/steps
qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2)
for j in range(len(algorithms)):
qiskit_chemistry_dict['algorithm']['name'] = algorithms[j]
if backends[j] is not None:
qiskit_chemistry_dict['backend'] = backends[j]
else:
qiskit_chemistry_dict.pop('backend')
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict)
energies[j][i] = result['energy']
hf_energies[i] = result['hf_energy']
distances[i] = d
print(' --- complete')
print('Distances: ', distances)
print('Energies:', energies)
print('Hartree-Fock energies:', hf_energies)
pylab.plot(distances, hf_energies, label='Hartree-Fock')
for j in range(len(algorithms)):
pylab.plot(distances, energies[j], label=algorithms[j])
pylab.xlabel('Interatomic distance (Angstrom)')
pylab.ylabel('Energy (Hartree)')
pylab.title('H2 Ground State Energy')
pylab.legend(loc='upper right')
pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock')
pylab.plot(distances, np.subtract(energies[0], energies[1]), label=algorithms[0])
pylab.xlabel('Interatomic distance (Angstrom)')
pylab.ylabel('Energy (Hartree)')
pylab.title('Energy difference from ExactEigensolver')
pylab.legend(loc='upper left')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import transpile
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc_basis = transpile(qc, backend)
qc_basis.draw(output='mpl')
|
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.
"""Piecewise polynomial Chebyshev approximation to a given f(x)."""
from __future__ import annotations
from typing import Callable
import numpy as np
from numpy.polynomial.chebyshev import Chebyshev
from qiskit.circuit import QuantumRegister, AncillaRegister
from qiskit.circuit.library.blueprintcircuit import BlueprintCircuit
from qiskit.circuit.exceptions import CircuitError
from .piecewise_polynomial_pauli_rotations import PiecewisePolynomialPauliRotations
class PiecewiseChebyshev(BlueprintCircuit):
r"""Piecewise Chebyshev approximation to an input function.
For a given function :math:`f(x)` and degree :math:`d`, this class implements a piecewise
polynomial Chebyshev approximation on :math:`n` qubits to :math:`f(x)` on the given intervals.
All the polynomials in the approximation are of degree :math:`d`.
The values of the parameters are calculated according to [1] and see [2] for a more
detailed explanation of the circuit construction and how it acts on the qubits.
Examples:
.. plot::
:include-source:
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
pw_approximation._build()
qc = QuantumCircuit(pw_approximation.num_qubits)
qc.h(list(range(num_state_qubits)))
qc.append(pw_approximation.to_instruction(), qc.qubits)
qc.draw(output='mpl')
References:
[1]: Haener, T., Roetteler, M., & Svore, K. M. (2018).
Optimizing Quantum Circuits for Arithmetic.
`arXiv:1805.12445 <http://arxiv.org/abs/1805.12445>`_
[2]: Carrera Vazquez, A., Hiptmair, H., & Woerner, S. (2022).
Enhancing the Quantum Linear Systems Algorithm Using Richardson Extrapolation.
`ACM Transactions on Quantum Computing 3, 1, Article 2 <https://doi.org/10.1145/3490631>`_
"""
def __init__(
self,
f_x: float | Callable[[int], float],
degree: int | None = None,
breakpoints: list[int] | None = None,
num_state_qubits: int | None = None,
name: str = "pw_cheb",
) -> None:
r"""
Args:
f_x: the function to be approximated. Constant functions should be specified
as f_x = constant.
degree: the degree of the polynomials.
Defaults to ``1``.
breakpoints: the breakpoints to define the piecewise-linear function.
Defaults to the full interval.
num_state_qubits: number of qubits representing the state.
name: The name of the circuit object.
"""
super().__init__(name=name)
# define internal parameters
self._num_state_qubits = None
# Store parameters
self._f_x = f_x
self._degree = degree if degree is not None else 1
self._breakpoints = breakpoints if breakpoints is not None else [0]
self._polynomials: list[list[float]] | None = None
self.num_state_qubits = num_state_qubits
def _check_configuration(self, raise_on_failure: bool = True) -> bool:
"""Check if the current configuration is valid."""
valid = True
if self._f_x is None:
valid = False
if raise_on_failure:
raise AttributeError("The function to be approximated has not been set.")
if self._degree is None:
valid = False
if raise_on_failure:
raise AttributeError("The degree of the polynomials has not been set.")
if self._breakpoints is None:
valid = False
if raise_on_failure:
raise AttributeError("The breakpoints have not been set.")
if self.num_state_qubits is None:
valid = False
if raise_on_failure:
raise AttributeError("The number of qubits has not been set.")
if self.num_qubits < self.num_state_qubits + 1:
valid = False
if raise_on_failure:
raise CircuitError(
"Not enough qubits in the circuit, need at least "
"{}.".format(self.num_state_qubits + 1)
)
return valid
@property
def f_x(self) -> float | Callable[[int], float]:
"""The function to be approximated.
Returns:
The function to be approximated.
"""
return self._f_x
@f_x.setter
def f_x(self, f_x: float | Callable[[int], float] | None) -> None:
"""Set the function to be approximated.
Note that this may change the underlying quantum register, if the number of state qubits
changes.
Args:
f_x: The new function to be approximated.
"""
if self._f_x is None or f_x != self._f_x:
self._invalidate()
self._f_x = f_x
self._reset_registers(self.num_state_qubits)
@property
def degree(self) -> int:
"""The degree of the polynomials.
Returns:
The degree of the polynomials.
"""
return self._degree
@degree.setter
def degree(self, degree: int | None) -> None:
"""Set the error tolerance.
Note that this may change the underlying quantum register, if the number of state qubits
changes.
Args:
degree: The new degree.
"""
if self._degree is None or degree != self._degree:
self._invalidate()
self._degree = degree
self._reset_registers(self.num_state_qubits)
@property
def breakpoints(self) -> list[int]:
"""The breakpoints for the piecewise approximation.
Returns:
The breakpoints for the piecewise approximation.
"""
breakpoints = self._breakpoints
# it the state qubits are set ensure that the breakpoints match beginning and end
if self.num_state_qubits is not None:
num_states = 2**self.num_state_qubits
# If the last breakpoint is < num_states, add the identity polynomial
if breakpoints[-1] < num_states:
breakpoints = breakpoints + [num_states]
# If the first breakpoint is > 0, add the identity polynomial
if breakpoints[0] > 0:
breakpoints = [0] + breakpoints
return breakpoints
@breakpoints.setter
def breakpoints(self, breakpoints: list[int] | None) -> None:
"""Set the breakpoints for the piecewise approximation.
Note that this may change the underlying quantum register, if the number of state qubits
changes.
Args:
breakpoints: The new breakpoints for the piecewise approximation.
"""
if self._breakpoints is None or breakpoints != self._breakpoints:
self._invalidate()
self._breakpoints = breakpoints if breakpoints is not None else [0]
self._reset_registers(self.num_state_qubits)
@property
def polynomials(self) -> list[list[float]]:
"""The polynomials for the piecewise approximation.
Returns:
The polynomials for the piecewise approximation.
Raises:
TypeError: If the input function is not in the correct format.
"""
if self.num_state_qubits is None:
return [[]]
# note this must be the private attribute since we handle missing breakpoints at
# 0 and 2 ^ num_qubits here (e.g. if the function we approximate is not defined at 0
# and the user takes that into account we just add an identity)
breakpoints = self._breakpoints
# Need to take into account the case in which no breakpoints were provided in first place
if breakpoints == [0]:
breakpoints = [0, 2**self.num_state_qubits]
num_intervals = len(breakpoints)
# Calculate the polynomials
polynomials = []
for i in range(0, num_intervals - 1):
# Calculate the polynomial approximating the function on the current interval
try:
# If the function is constant don't call Chebyshev (not necessary and gives errors)
if isinstance(self.f_x, (float, int)):
# Append directly to list of polynomials
polynomials.append([self.f_x])
else:
poly = Chebyshev.interpolate(
self.f_x, self.degree, domain=[breakpoints[i], breakpoints[i + 1]]
)
# Convert polynomial to the standard basis and rescale it for the rotation gates
poly = 2 * poly.convert(kind=np.polynomial.Polynomial).coef
# Convert to list and append
polynomials.append(poly.tolist())
except ValueError as err:
raise TypeError(
" <lambda>() missing 1 required positional argument: '"
+ self.f_x.__code__.co_varnames[0]
+ "'."
+ " Constant functions should be specified as 'f_x = constant'."
) from err
# If the last breakpoint is < 2 ** num_qubits, add the identity polynomial
if breakpoints[-1] < 2**self.num_state_qubits:
polynomials = polynomials + [[2 * np.arcsin(1)]]
# If the first breakpoint is > 0, add the identity polynomial
if breakpoints[0] > 0:
polynomials = [[2 * np.arcsin(1)]] + polynomials
return polynomials
@polynomials.setter
def polynomials(self, polynomials: list[list[float]] | None) -> None:
"""Set the polynomials for the piecewise approximation.
Note that this may change the underlying quantum register, if the number of state qubits
changes.
Args:
polynomials: The new breakpoints for the piecewise approximation.
"""
if self._polynomials is None or polynomials != self._polynomials:
self._invalidate()
self._polynomials = polynomials
self._reset_registers(self.num_state_qubits)
@property
def num_state_qubits(self) -> int:
r"""The number of state qubits representing the state :math:`|x\rangle`.
Returns:
The number of state qubits.
"""
return self._num_state_qubits
@num_state_qubits.setter
def num_state_qubits(self, num_state_qubits: int | None) -> None:
"""Set the number of state qubits.
Note that this may change the underlying quantum register, if the number of state qubits
changes.
Args:
num_state_qubits: The new number of qubits.
"""
if self._num_state_qubits is None or num_state_qubits != self._num_state_qubits:
self._invalidate()
self._num_state_qubits = num_state_qubits
# Set breakpoints if they haven't been set
if num_state_qubits is not None and self._breakpoints is None:
self.breakpoints = [0, 2**num_state_qubits]
self._reset_registers(num_state_qubits)
def _reset_registers(self, num_state_qubits: int | None) -> None:
"""Reset the registers."""
self.qregs = []
if num_state_qubits is not None:
qr_state = QuantumRegister(num_state_qubits, "state")
qr_target = QuantumRegister(1, "target")
self.qregs = [qr_state, qr_target]
num_ancillas = num_state_qubits
if num_ancillas > 0:
qr_ancilla = AncillaRegister(num_ancillas)
self.add_register(qr_ancilla)
def _build(self):
"""Build the circuit if not already build. The operation is considered successful
when q_objective is :math:`|1>`"""
if self._is_built:
return
super()._build()
poly_r = PiecewisePolynomialPauliRotations(
self.num_state_qubits, self.breakpoints, self.polynomials, name=self.name
)
# qr_state = self.qubits[: self.num_state_qubits]
# qr_target = [self.qubits[self.num_state_qubits]]
# qr_ancillas = self.qubits[self.num_state_qubits + 1 :]
# Apply polynomial approximation
self.append(poly_r.to_gate(), self.qubits)
|
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
|
bayesian-randomized-benchmarking
|
import numpy as np
import copy
from qiskit_experiments.library import StandardRB, InterleavedRB
from qiskit_experiments.framework import ParallelExperiment
from qiskit_experiments.library.randomized_benchmarking import RBUtils
import qiskit.circuit.library as circuits
# for retrieving gate calibration
from datetime import datetime
import qiskit.providers.aer.noise.device as dv
# import the bayesian packages
import pymc3 as pm
import arviz as az
import unif_bayesian_fitter as bf
simulation = False # make your choice here
if simulation:
from qiskit.providers.aer import AerSimulator
from qiskit.test.mock import FakeParis
backend = AerSimulator.from_backend(FakeParis())
else:
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_bogota') # type here hardware backend
# for WIP
import importlib
importlib.reload(bf)
lengths = np.arange(1, 2225, 225)
num_samples = 10
seed = 1010
qubits = [4]
# last backend's recorded EPG before experiments
print(RBUtils.get_error_dict_from_backend(backend, qubits))
# backend's recorded EPG after experiments
print(RBUtils.get_error_dict_from_backend(backend, qubits))
# Correct reference for shift
# example of interpolated EPC_cal for hardware experiments
# EPC0 + (t_exp - tO) * (EPC1 - EPC0) / (t1 - t0)
# code here:
epc_calib = 0.0001600 + (18+25/60-7)*(0.0001772 - 0.0001600)/24
print('EPC calibration: {0:1.4e}'.format(epc_calib))
# Run an RB experiment on qubit 0
exp1 = StandardRB(qubits, lengths, num_samples=num_samples, seed=seed)
expdata1 = exp1.run(backend).block_for_results()
results1 = expdata1.analysis_results()
# View result data
display(expdata1.figure(0))
for result in results1:
print(result)
popt = expdata1.analysis_results()[0].value.value
pcov = expdata1.analysis_results()[0].extra['covariance_mat']
epc_est_fm = expdata1.analysis_results()[2].value.value
epc_est_fm_err = expdata1.analysis_results()[2].value.stderr
EPG_dic = {}
for i in range(3,6):
EPG_key = expdata1.analysis_results()[i].name
EPG_dic[EPG_key] = expdata1.analysis_results()[i].value.value
nQ = len(qubits)
scale = (2 ** nQ - 1) / 2 ** nQ
interleaved_gate =''
# get count data
Y = bf.get_GSP_counts(expdata1._data, len(lengths),range(num_samples))
expdata1._data[1]
experiment_type = expdata1._data[0]['metadata']['experiment_type']
physical_qubits = expdata1._data[0]['metadata']['physical_qubits']
shots = expdata1._data[0]['shots']
#build model
pooled_model = bf.build_bayesian_model(model_type="pooled",Y=Y,
shots=shots,m_gates=lengths,
popt = popt,
pcov = pcov)
pm.model_to_graphviz(pooled_model)
trace_p = bf.get_trace(pooled_model, target_accept = 0.95)
bf.RB_bayesian_results(pooled_model, trace_p, lengths,
epc_est_fm,
epc_est_fm_err,
experiment_type,
scale,
num_samples, Y, shots, physical_qubits, interleaved_gate, backend,
EPG_dic = EPG_dic,
routine = 'build_bayesian_model')
#build model
hierarchical_model = bf.build_bayesian_model(model_type="h_sigma",Y=Y,
shots=shots,m_gates=lengths,
popt = popt,
pcov = pcov,
sigma_theta=0.001,sigma_theta_l=0.0005,sigma_theta_u=0.0015)
pm.model_to_graphviz(hierarchical_model)
trace_h = bf.get_trace(hierarchical_model, target_accept = 0.99)
bf.RB_bayesian_results(hierarchical_model, trace_h, lengths,
epc_est_fm, epc_est_fm_err, experiment_type, scale,
num_samples, Y, shots, physical_qubits, interleaved_gate, backend,
EPG_dic = EPG_dic, routine = 'build_bayesian_model')
# describe RB experiment
interleaved_gate = "x"
qubits = [4]
interleaved_circuit = circuits.XGate()
lengths = np.arange(1, 2250, 225)
num_samples = 10
seed = 1010
# Run an interleaved RB experiment
int_exp1 = InterleavedRB(interleaved_circuit, qubits,
lengths, num_samples=num_samples, seed=seed)
# Run
int_expdata1 = int_exp1.run(backend).block_for_results()
int_results1 = int_expdata1.analysis_results()
# View result data
display(int_expdata1.figure(0))
for result in int_results1:
print(result)
popt = int_expdata1.analysis_results()[0].value.value
pcov = int_expdata1.analysis_results()[0].extra['covariance_mat']
popt[2] = popt[1]/popt[2] # replace alpha_C by p_tilde
# WIP rigorously the covariance matrix could be modified too if used
epc_est_fm = int_expdata1.analysis_results()[3].value.value
epc_est_fm_err = int_expdata1.analysis_results()[3].value.stderr
nQ = len(qubits)
scale = (2 ** nQ - 1) / 2 ** nQ
interleaved_gate ='x'
# get count data
Y1 = bf.get_GSP_counts(int_expdata1._data, len(lengths),
range(0,2*num_samples-1,2))
Y2 = bf.get_GSP_counts(int_expdata1._data, len(lengths),
range(1,2*num_samples,2))
int_expdata1._data[1]
experiment_type = int_expdata1._data[0]['metadata']['experiment_type']
physical_qubits = int_expdata1._data[0]['metadata']['physical_qubits']
shots = int_expdata1._data[0]['shots']
Y=np.vstack((Y1,Y2))
RvsI = np.vstack((np.ones_like(Y1),np.zeros_like(Y2)))
IvsR = np.vstack((np.zeros_like(Y1),np.ones_like(Y2)))
tilde1 = bf.build_bayesian_model("tilde",Y=Y,shots=shots,
m_gates=lengths,
popt = popt,
pcov = pcov,
RvsI=RvsI,IvsR=IvsR)
pm.model_to_graphviz(tilde1)
trace_t = bf.get_trace(tilde1)
bf.RB_bayesian_results(tilde1, trace_t, lengths,
epc_est_fm, epc_est_fm_err, experiment_type, scale,
num_samples, Y, shots, physical_qubits, interleaved_gate, backend,
epc_calib = epc_calib, Y1 = Y1, Y2 = Y2,
routine = 'build_bayesian_model')
# Correct reference for shift
# example of interpolated EPC_cal for hardware experiments
# EPC0 + (t_exp - tO) * (EPC1 - EPC0) / (t1 - t0)
# code here:
epc_calib = 0.0001600 + (17+36/60-7)*(0.0001772 - 0.0001600)/24
print('EPC calibration: {0:.6f}'.format(epc_calib))
import importlib
importlib.reload(bf)
Y=np.hstack((Y1,Y2))
RvsI_h = np.ravel(np.vstack((np.ones_like(lengths),np.zeros_like(lengths))))
IvsR_h = np.ravel(np.vstack((np.zeros_like(lengths),np.ones_like(lengths))))
tilde2 = bf.build_bayesian_model("h_tilde",Y=Y,shots=shots, m_gates=lengths,
popt = popt,
pcov = pcov,
RvsI = RvsI_h, IvsR = IvsR_h,
sigma_theta=0.001,sigma_theta_l=0.0005,sigma_theta_u=0.0015)
pm.model_to_graphviz(tilde2)
trace_t3 = bf.get_trace(tilde2, target_accept = .95)
bf.RB_bayesian_results(tilde2, trace_t3, lengths,
epc_est_fm, epc_est_fm_err, experiment_type, scale,
num_samples, Y, shots, physical_qubits, interleaved_gate, backend,
epc_calib = epc_calib, Y1 = Y1, Y2 = Y2,
routine = 'build_bayesian_model')
# Correct reference for shift
# example of interpolated EPC_cal for hardware experiments
# EPC0 + (t_exp - tO) * (EPC1 - EPC0) / (t1 - t0)
# code here:
epc_calib = 0.0001600 + (17+36/60-7)*(0.0001772 - 0.0001600)/24
print('EPC calibration: {0:.6f}'.format(epc_calib))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import GroverOptimizer, MinimumEigenOptimizer
from qiskit_optimization.translators import from_docplex_mp
from docplex.mp.model import Model
model = Model()
x0 = model.binary_var(name="x0")
x1 = model.binary_var(name="x1")
x2 = model.binary_var(name="x2")
model.minimize(-x0 + 2 * x1 - 3 * x2 - 2 * x0 * x2 - 1 * x1 * x2)
qp = from_docplex_mp(model)
print(qp.prettyprint())
grover_optimizer = GroverOptimizer(6, num_iterations=10, sampler=Sampler())
results = grover_optimizer.solve(qp)
print(results.prettyprint())
exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
exact_result = exact_solver.solve(qp)
print(exact_result.prettyprint())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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/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
|
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
# TODO: This example should use a real mock backend.
backend = FakeOpenPulse3Q()
d2 = pulse.DriveChannel(2)
with pulse.build(backend) as bell_prep:
pulse.u2(0, math.pi, 0)
pulse.cx(0, 1)
with pulse.build(backend) as decoupled_bell_prep_and_measure:
# We call our bell state preparation schedule constructed above.
with pulse.align_right():
pulse.call(bell_prep)
pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2)
pulse.barrier(0, 1, 2)
registers = pulse.measure_all()
decoupled_bell_prep_and_measure.draw()
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
from qiskit import QuantumCircuit, Aer, execute, IBMQ
from qiskit.utils import QuantumInstance
import numpy as np
from qiskit.algorithms import Shor
IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here
provider = IBMQ.get_provider(hub='ibm-q')
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1000)
my_shor = Shor(quantum_instance)
result_dict = my_shor.factor(15)
print(result_dict)
|
https://github.com/qiskit-community/prototype-qrao
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# 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.
"""Magic bases rounding"""
from typing import List, Dict, Tuple, Optional
from collections import defaultdict
import numbers
import time
import warnings
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers import Backend
from qiskit.opflow import PrimitiveOp
from qiskit.utils import QuantumInstance
from .encoding import z_to_31p_qrac_basis_circuit, z_to_21p_qrac_basis_circuit
from .rounding_common import (
RoundingSolutionSample,
RoundingScheme,
RoundingContext,
RoundingResult,
)
_invalid_backend_names = [
"aer_simulator_unitary",
"aer_simulator_superop",
"unitary_simulator",
"pulse_simulator",
]
def _backend_name(backend: Backend) -> str:
"""Return the backend name in a way that is agnostic to Backend version"""
# See qiskit.utils.backend_utils in qiskit-terra for similar examples
if backend.version <= 1:
return backend.name()
return backend.name
def _is_original_statevector_simulator(backend: Backend) -> bool:
"""Return True if the original statevector simulator"""
return _backend_name(backend) == "statevector_simulator"
class MagicRoundingResult(RoundingResult):
"""Result of magic rounding"""
def __init__(
self,
samples: List[RoundingSolutionSample],
*,
bases=None,
basis_shots=None,
basis_counts=None,
time_taken=None,
):
self._bases = bases
self._basis_shots = basis_shots
self._basis_counts = basis_counts
super().__init__(samples, time_taken=time_taken)
@property
def bases(self):
return self._bases
@property
def basis_shots(self):
return self._basis_shots
@property
def basis_counts(self):
return self._basis_counts
class MagicRounding(RoundingScheme):
""" "Magic rounding" method
This method is described in https://arxiv.org/abs/2111.03167v2.
"""
_DECODING = {
3: ( # Eq. (8)
{"0": [0, 0, 0], "1": [1, 1, 1]}, # I mu+ I, I mu- I
{"0": [0, 1, 1], "1": [1, 0, 0]}, # X mu+ X, X mu- X
{"0": [1, 0, 1], "1": [0, 1, 0]}, # Y mu+ Y, Y mu- Y
{"0": [1, 1, 0], "1": [0, 0, 1]}, # Z mu+ Z, Z mu- Z
),
2: ( # Sec. VII
{"0": [0, 0], "1": [1, 1]}, # I xi+ I, I xi- I
{"0": [0, 1], "1": [1, 0]}, # X xi+ X, X xi- X
),
1: ({"0": [0], "1": [1]},),
}
# Pauli op string to label index in ops
_OP_INDICES = {1: {"Z": 0}, 2: {"X": 0, "Z": 1}, 3: {"X": 0, "Y": 1, "Z": 2}}
def __init__(
self,
quantum_instance: QuantumInstance,
*,
basis_sampling: str = "uniform",
seed: Optional[int] = None,
):
"""
Args:
quantum_instance: Provides the ``Backend`` for quantum execution
and the ``shots`` count (i.e., the number of samples to collect
from the magic bases).
basis_sampling: Method to use for sampling the magic bases. Must
be either ``"uniform"`` (default) or ``"weighted"``.
``"uniform"`` samples all magic bases uniformly, and is the
method described in https://arxiv.org/abs/2111.03167v2.
``"weighted"`` attempts to choose bases strategically using the
Pauli expectation values from the minimum eigensolver.
However, the approximation bounds given in
https://arxiv.org/abs/2111.03167v2 apply only to ``"uniform"``
sampling.
seed: Seed for random number generator, which is used to sample the
magic bases.
"""
if basis_sampling not in ("uniform", "weighted"):
raise ValueError(
f"'{basis_sampling}' is not an implemented sampling method. "
"Please choose either 'uniform' or 'weighted'."
)
self.quantum_instance = quantum_instance
self.rng = np.random.RandomState(seed)
self._basis_sampling = basis_sampling
super().__init__()
@property
def shots(self) -> int:
"""Shots count as configured by the given ``quantum_instance``."""
return self.quantum_instance.run_config.shots
@property
def basis_sampling(self):
"""Basis sampling method (either ``"uniform"`` or ``"weighted"``)."""
return self._basis_sampling
@property
def quantum_instance(self) -> QuantumInstance:
"""Provides the ``Backend`` and the ``shots`` (samples) count."""
return self._quantum_instance
@quantum_instance.setter
def quantum_instance(self, quantum_instance: QuantumInstance) -> None:
backend_name = _backend_name(quantum_instance.backend)
if backend_name in _invalid_backend_names:
raise ValueError(f"{backend_name} is not supported.")
if _is_original_statevector_simulator(quantum_instance.backend):
warnings.warn(
'Use of "statevector_simulator" is discouraged because it effectively '
"brute-forces all possible solutions. We suggest using the newer "
'"aer_simulator_statevector" instead.'
)
self._quantum_instance = quantum_instance
def _unpack_measurement_outcome(
self,
bits: str,
basis: List[int],
var2op: Dict[int, Tuple[int, PrimitiveOp]],
vars_per_qubit: int,
) -> List[int]:
output_bits = []
# iterate in order over decision variables
# (assumes variables are numbered consecutively beginning with 0)
for var in range(len(var2op)): # pylint: disable=consider-using-enumerate
q, op = var2op[var]
# get the decoding outcome index for the variable
# corresponding to this Pauli op.
op_index = self._OP_INDICES[vars_per_qubit][str(op)]
# get the bits associated to this magic basis'
# measurement outcomes
bit_outcomes = self._DECODING[vars_per_qubit][basis[q]]
# select which measurement outcome we observed
# this gives up to 3 bits of information
magic_bits = bit_outcomes[bits[q]]
# Assign our variable's value depending on
# which pauli our variable was associated to
variable_value = magic_bits[op_index]
output_bits.append(variable_value)
return output_bits
@staticmethod
def _make_circuits(
circ: QuantumCircuit, bases: List[List[int]], measure: bool, vars_per_qubit: int
) -> List[QuantumCircuit]:
circuits = []
for basis in bases:
if vars_per_qubit == 3:
qc = circ.compose(
z_to_31p_qrac_basis_circuit(basis).inverse(), inplace=False
)
elif vars_per_qubit == 2:
qc = circ.compose(
z_to_21p_qrac_basis_circuit(basis).inverse(), inplace=False
)
elif vars_per_qubit == 1:
qc = circ.copy()
if measure:
qc.measure_all()
circuits.append(qc)
return circuits
def _evaluate_magic_bases(self, circuit, bases, basis_shots, vars_per_qubit):
"""
Given a circuit you wish to measure, a list of magic bases to measure,
and a list of the shots to use for each magic basis configuration.
Measure the provided circuit in the magic bases given and return the counts
dictionaries associated with each basis measurement.
len(bases) == len(basis_shots) == len(basis_counts)
"""
measure = not _is_original_statevector_simulator(self.quantum_instance.backend)
circuits = self._make_circuits(circuit, bases, measure, vars_per_qubit)
# Execute each of the rotated circuits and collect the results
# Batch the circuits into jobs where each group has the same number of
# shots, so that you can wait for the queue as few times as possible if
# using hardware.
circuit_indices_by_shots: Dict[int, List[int]] = defaultdict(list)
assert len(circuits) == len(basis_shots)
for i, shots in enumerate(basis_shots):
circuit_indices_by_shots[shots].append(i)
basis_counts: List[Optional[Dict[str, int]]] = [None] * len(circuits)
overall_shots = self.quantum_instance.run_config.shots
try:
for shots, indices in sorted(
circuit_indices_by_shots.items(), reverse=True
):
self.quantum_instance.set_config(shots=shots)
result = self.quantum_instance.execute([circuits[i] for i in indices])
counts_list = result.get_counts()
if not isinstance(counts_list, List):
# This is the only case where this should happen, and that
# it does at all (namely, when a single-element circuit
# list is provided) is a weird API quirk of Qiskit.
# https://github.com/Qiskit/qiskit-terra/issues/8103
assert len(indices) == 1
counts_list = [counts_list]
assert len(indices) == len(counts_list)
for i, counts in zip(indices, counts_list):
basis_counts[i] = counts
finally:
# We've temporarily modified quantum_instance; now we restore it to
# its initial state.
self.quantum_instance.set_config(shots=overall_shots)
assert None not in basis_counts
# Process the outcomes and extract expectation of decision vars
# The "statevector_simulator", unlike all the others, returns
# probabilities instead of integer counts. So if probabilities are
# detected, we rescale them.
if any(
any(not isinstance(x, numbers.Integral) for x in counts.values())
for counts in basis_counts
):
basis_counts = [
{key: val * basis_shots[i] for key, val in counts.items()}
for i, counts in enumerate(basis_counts)
]
return basis_counts
def _compute_dv_counts(self, basis_counts, bases, var2op, vars_per_qubit):
"""
Given a list of bases, basis_shots, and basis_counts, convert
each observed bitstrings to its corresponding decision variable
configuration. Return the counts of each decision variable configuration.
"""
dv_counts = {}
for i, counts in enumerate(basis_counts):
base = bases[i]
# For each measurement outcome...
for bitstr, count in counts.items():
# For each bit in the observed bitstring...
soln = self._unpack_measurement_outcome(
bitstr, base, var2op, vars_per_qubit
)
soln = "".join([str(int(bit)) for bit in soln])
if soln in dv_counts:
dv_counts[soln] += count
else:
dv_counts[soln] = count
return dv_counts
def _sample_bases_uniform(self, q2vars, vars_per_qubit):
bases = [
self.rng.choice(2 ** (vars_per_qubit - 1), size=len(q2vars)).tolist()
for _ in range(self.shots)
]
bases, basis_shots = np.unique(bases, axis=0, return_counts=True)
return bases, basis_shots
def _sample_bases_weighted(self, q2vars, trace_values, vars_per_qubit):
"""Perform weighted sampling from the expectation values.
The goal is to make smarter choices about which bases to measure in
using the trace values.
"""
# First, we make sure all Pauli expectation values have absolute value
# at most 1. Otherwise, some of the probabilities computed below might
# be negative.
tv = np.clip(trace_values, -1, 1)
# basis_probs will have num_qubits number of elements.
# Each element will be a list of length 4 specifying the
# probability of picking the corresponding magic basis on that qubit.
basis_probs = []
for dvars in q2vars:
if vars_per_qubit == 3:
x = 0.5 * (1 - tv[dvars[0]])
y = 0.5 * (1 - tv[dvars[1]]) if (len(dvars) > 1) else 0
z = 0.5 * (1 - tv[dvars[2]]) if (len(dvars) > 2) else 0
# ppp: mu± = .5(I ± 1/sqrt(3)( X + Y + Z))
# pmm: X mu± X = .5(I ± 1/sqrt(3)( X - Y - Z))
# mpm: Y mu± Y = .5(I ± 1/sqrt(3)(-X + Y - Z))
# mmp: Z mu± Z = .5(I ± 1/sqrt(3)(-X - Y + Z))
# fmt: off
ppp_mmm = x * y * z + (1-x) * (1-y) * (1-z)
pmm_mpp = x * (1-y) * (1-z) + (1-x) * y * z
mpm_pmp = (1-x) * y * (1-z) + x * (1-y) * z
ppm_mmp = x * y * (1-z) + (1-x) * (1-y) * z
# fmt: on
basis_probs.append([ppp_mmm, pmm_mpp, mpm_pmp, ppm_mmp])
elif vars_per_qubit == 2:
x = 0.5 * (1 - tv[dvars[0]])
z = 0.5 * (1 - tv[dvars[1]]) if (len(dvars) > 1) else 0
# pp: xi± = .5(I ± 1/sqrt(2)( X + Z ))
# pm: X xi± X = .5(I ± 1/sqrt(2)( X - Z ))
# fmt: off
pp_mm = x * z + (1-x) * (1-z)
pm_mp = x * (1-z) + (1-x) * z
# fmt: on
basis_probs.append([pp_mm, pm_mp])
elif vars_per_qubit == 1:
basis_probs.append([1.0])
bases = [
[
self.rng.choice(2 ** (vars_per_qubit - 1), p=probs)
for probs in basis_probs
]
for _ in range(self.shots)
]
bases, basis_shots = np.unique(bases, axis=0, return_counts=True)
return bases, basis_shots
def round(self, ctx: RoundingContext) -> MagicRoundingResult:
"""Perform magic rounding"""
start_time = time.time()
trace_values = ctx.trace_values
circuit = ctx.circuit
if circuit is None:
raise NotImplementedError(
"Magic rounding requires a circuit to be available. Perhaps try "
"semideterministic rounding instead."
)
# We've already checked that it is one of these two in the constructor
if self.basis_sampling == "uniform":
bases, basis_shots = self._sample_bases_uniform(
ctx.q2vars, ctx._vars_per_qubit
)
elif self.basis_sampling == "weighted":
if trace_values is None:
raise NotImplementedError(
"Magic rounding with weighted sampling requires the trace values "
"to be available, but they are not."
)
bases, basis_shots = self._sample_bases_weighted(
ctx.q2vars, trace_values, ctx._vars_per_qubit
)
else: # pragma: no cover
raise NotImplementedError(
f'No such basis sampling method: "{self.basis_sampling}".'
)
assert self.shots == np.sum(basis_shots)
# For each of the Magic Bases sampled above, measure
# the appropriate number of times (given by basis_shots)
# and return the circuit results
basis_counts = self._evaluate_magic_bases(
circuit, bases, basis_shots, ctx._vars_per_qubit
)
# keys will be configurations of decision variables
# values will be total number of observations.
soln_counts = self._compute_dv_counts(
basis_counts, bases, ctx.var2op, ctx._vars_per_qubit
)
soln_samples = [
RoundingSolutionSample(
x=np.asarray([int(bit) for bit in soln]),
probability=count / self.shots,
)
for soln, count in soln_counts.items()
]
assert np.isclose(
sum(soln_counts.values()), self.shots
), f"{sum(soln_counts.values())} != {self.shots}"
assert len(bases) == len(basis_shots) == len(basis_counts)
stop_time = time.time()
return MagicRoundingResult(
samples=soln_samples,
bases=bases,
basis_shots=basis_shots,
basis_counts=basis_counts,
time_taken=stop_time - start_time,
)
|
https://github.com/SambitPrabhu/Boolean-SAT-using-Grovers-algorithm
|
SambitPrabhu
|
# Allowed combinations for the party according to the following guidelines:
# 1.It is Alice and Bob's engagement party so they must be invited
# 2.Charles will come only if Dave comes without Eve (iff Dave comes and Eve doesn't)
# A B C D E
# 1 1 0 0 0
# 1 1 0 0 1
# 1 1 0 1 0
# 1 1 0 1 1
# 1 1 1 1 0
# Karnaugh map:
# CD
# 00 01 11 10
# E 0 1 1 1 0
# 1 1 1 0 0
# The minimized boolean expression turns out to be:
# A.B.(C'+ E'.D)
# or
# A^B^(~C U ~E^D)
# This can be converted into CNF form:
# A.B.(C'+D).(C'+E')
# Later on, I realised that another expression is more convenient to implement from scratch using quantum gates:
# A.B.~(C.E).~(C.~D)
# Grover's algorithm must search through all possible values of A,B,C,D and E and output the 5 valid combinations we have tabulated above.
# In this project I have shown both the library implementation of Grover's algorithm and the from-scratch quantum circuit implementation, both of which yield the same correct results :D
from qiskit import QuantumCircuit, assemble, Aer
from qiskit.visualization import plot_histogram
from qiskit_textbook.widgets import binary_widget
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle
from qiskit.circuit.library import PhaseOracle
from qiskit.circuit import QuantumRegister
from qiskit.circuit import ClassicalRegister
from qiskit.compiler import transpile
import numpy as np
bool_exp = '''
c examples
p cnf 5 4
5 0
4 0
-3 2 0
-3 -1 0
'''
algorithm = Grover(LogicalExpressionOracle(bool_exp))
backend = Aer.get_backend('aer_simulator')
result = algorithm.run(backend)
plot_histogram(result['measurement'],title='Combinations A B C D E')
#Functions to append hadamard gate and diffuser oracle
def hadamard(qc, qubits):
for q in qubits:
qc.h(q)
return qc
def diffuser(nqubits):
qc = QuantumCircuit(nqubits)
for qubit in range(nqubits):
qc.h(qubit)
for qubit in range(nqubits):
qc.x(qubit)
qc.h(nqubits-1)
qc.mct(list(range(nqubits-1)), nqubits-1)
qc.h(nqubits-1)
for qubit in range(nqubits):
qc.x(qubit)
for qubit in range(nqubits):
qc.h(qubit)
U_s = qc.to_gate()
U_s.name = "U$_s$"
return U_s
n= 5
var_qubits = QuantumRegister(5, name='v')
clause_qubits = QuantumRegister(4, name='c')
output_qubit = QuantumRegister(1, name='out')
cbits = ClassicalRegister(5, name='cbits')
grover_circuit = QuantumCircuit(var_qubits, clause_qubits, output_qubit, cbits)
grover_circuit.initialize([1, -1]/np.sqrt(2), output_qubit)
grover_circuit.initialize([1, 0], clause_qubits[0])
grover_circuit.initialize([1, 0], clause_qubits[1])
grover_circuit.initialize([1, 0], clause_qubits[2])
grover_circuit.initialize([1, 0], clause_qubits[3])
grover_circuit = QuantumCircuit(var_qubits, clause_qubits, output_qubit, cbits)
grover_circuit = hadamard(grover_circuit, var_qubits)
grover_circuit.barrier()
#Implementing boolean exp A.B.~(C.E).~(~D.~E) using Toffoli, CNOT and Bit-flip gates
#individual clauses evaluated using CNOT and X gates
grover_circuit.cx(var_qubits[0],clause_qubits[0])
grover_circuit.cx(var_qubits[1],clause_qubits[1])
grover_circuit.ccx(var_qubits[2],var_qubits[4],clause_qubits[2])
grover_circuit.x(clause_qubits[2])
grover_circuit.x(var_qubits[3])
grover_circuit.ccx(var_qubits[2],var_qubits[3],clause_qubits[3])
grover_circuit.x(clause_qubits[3])
#all clauses are ANDed using Toffoli gate
grover_circuit.mct(clause_qubits, output_qubit)
grover_circuit.barrier()
#Uncomputing to revert clause bits to their original state
grover_circuit.cx(var_qubits[0],clause_qubits[0])
grover_circuit.cx(var_qubits[1],clause_qubits[1])
grover_circuit.x(clause_qubits[2])
grover_circuit.ccx(var_qubits[2],var_qubits[4],clause_qubits[2])
grover_circuit.x(clause_qubits[3])
grover_circuit.ccx(var_qubits[2],var_qubits[3],clause_qubits[3])
grover_circuit.x(var_qubits[3])
grover_circuit.barrier()
grover_circuit.append(diffuser(n), [0,1,2,3,4])
#Implementing boolean exp A.B.~(C.E).~(~D.~E) using Toffoli, CNOT and Bit-flip gates
#individual clauses evaluated using CNOT and X gates
grover_circuit.cx(var_qubits[0],clause_qubits[0])
grover_circuit.cx(var_qubits[1],clause_qubits[1])
grover_circuit.ccx(var_qubits[2],var_qubits[4],clause_qubits[2])
grover_circuit.x(clause_qubits[2])
grover_circuit.x(var_qubits[3])
grover_circuit.ccx(var_qubits[2],var_qubits[3],clause_qubits[3])
grover_circuit.x(clause_qubits[3])
#all clauses are ANDed using Toffoli gate
grover_circuit.mct(clause_qubits, output_qubit)
grover_circuit.barrier()
#Uncomputing to revert clause bits to their original state
grover_circuit.cx(var_qubits[0],clause_qubits[0])
grover_circuit.cx(var_qubits[1],clause_qubits[1])
grover_circuit.x(clause_qubits[2])
grover_circuit.ccx(var_qubits[2],var_qubits[4],clause_qubits[2])
grover_circuit.x(clause_qubits[3])
grover_circuit.ccx(var_qubits[2],var_qubits[3],clause_qubits[3])
grover_circuit.x(var_qubits[3])
grover_circuit.barrier()
grover_circuit.append(diffuser(n), [0,1,2,3,4])
grover_circuit.measure(var_qubits,cbits)
grover_circuit.draw('mpl')
grover_circuit=grover_circuit.reverse_bits()
backend = Aer.get_backend('aer_simulator')
transpiled_qc = transpile(grover_circuit, backend)
qobj = assemble(transpiled_qc)
result = backend.run(qobj).result()
plot_histogram(result.get_counts(),title='Combinations: A B C D E')
|
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/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/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
# with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
# with open(filename, "wb") as f:
# pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
# with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump(backend.properties(), f)
retrieved_jobs = jobs
retrieved_cal_job = cal_job
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/Axect/QuantumAlgorithms
|
Axect
|
import pennylane as qml
from pennylane import numpy as np
import matplotlib.pyplot as plt
qml.drawer.use_style(style='sketch')
dev = qml.device('default.qubit', wires=['psi', 'a', 'b'])
def teleport(theta):
# Prepare the state to be teleported
qml.QubitStateVector([np.cos(theta), np.sin(theta)], wires='psi')
# Prepare the Bell state
qml.Hadamard(wires='a')
qml.CNOT(wires=['a', 'b'])
# Alice applies a reverse bell gate to her qubit, controlled by theta
qml.CNOT(wires=['psi', 'a'])
qml.Hadamard(wires='psi')
qml.Barrier(['psi', 'a'], only_visual=True)
# Measure alice's qubits
a1 = qml.measure('psi')
a2 = qml.measure('a')
# Send the classical bits to Bob
qml.cond(a2, qml.PauliX)('b')
qml.cond(a1, qml.PauliZ)('b')
return qml.density_matrix(wires='b')
qml.draw_mpl(teleport)(np.pi/4)
plt.show()
@qml.qnode(dev)
def teleport(theta):
# Prepare the state to be teleported
qml.QubitStateVector([np.cos(theta), np.sin(theta)], wires='psi')
# Prepare the Bell state
qml.Hadamard(wires='a')
qml.CNOT(wires=['a', 'b'])
# Alice applies a reverse bell gate to her qubit, controlled by theta
qml.CNOT(wires=['psi', 'a'])
qml.Hadamard(wires='psi')
qml.Barrier(['psi', 'a'], only_visual=True)
# Measure alice's qubits
a1 = qml.measure('psi')
a2 = qml.measure('a')
# Send the classical bits to Bob
qml.cond(a2, qml.PauliX)('b')
qml.cond(a1, qml.PauliZ)('b')
return qml.probs(wires='b')
qml.draw_mpl(teleport)(np.pi/4)
plt.show()
theta = np.pi/6
print("Input state: ", np.cos(theta), "|0> +", np.sin(theta), "|1>")
print()
print("Input probability vector: ")
print(np.array([np.cos(theta)**2, np.sin(theta)**2]))
print()
print("Output probability vector: ")
print(teleport(theta))
|
https://github.com/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
"""
# Import the required Qiskit classes
from qiskit import IBMQ, QuantumCircuit, transpile
from qiskit.providers.ibmq import least_busy
# Import the backend visualization methods
from qiskit.visualization import plot_gate_map, plot_error_map, plot_circuit_layout
from IPython.core.display import display
print("Ch 5: Backend visualization")
print("---------------------------")
print("Getting provider...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
# Get all available and operational backends.
print("Getting the available backends...")
available_backends = provider.backends(filters=lambda b: not b.configuration().simulator and b.configuration().num_qubits > 1 and b.status().operational)
# Fish out criteria to compare
print("{0:20} {1:<10}".format("Name","#Qubits"))
print("{0:20} {1:<10}".format("----","-------"))
for n in range(0, len(available_backends)):
backend = provider.get_backend(str(available_backends[n]))
print("{0:20} {1:<10}".format(backend.name(),backend.configuration().num_qubits))
# Select a backend or go for the least busy backend with more than 1 qubits
backend_input = input("Enter the name of a backend, or X for the least busy:")
if backend_input not in ["X","x"]:
backend = provider.get_backend(backend_input)
else:
backend = least_busy(provider.backends(filters=lambda b: not b.configuration().simulator and b.configuration().num_qubits > 1 and b.status().operational))
# Display the gate and error map for the backend.
print("\nQubit data for backend:",backend.status().backend_name)
display(plot_gate_map(backend, plot_directed=True))
display(plot_error_map(backend))
# Create and transpile a 2 qubit Bell circuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
display(qc.draw('mpl'))
qc_transpiled = transpile(qc, backend=backend, optimization_level=3)
display(qc_transpiled.draw('mpl'))
# Display the circuit layout for the backend.
display(plot_circuit_layout(qc_transpiled, backend, view='physical'))
|
https://github.com/qiskit-community/qiskit-jku-provider
|
qiskit-community
|
# -*- coding: utf-8 -*-
# Copyright 2019, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Example use of the JKU Provider and the Qasm Simulator backend for creating the
state '01 10'.
"""
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, execute
from qiskit_jku_provider import JKUProvider
JKU = JKUProvider()
qreg0 = QuantumRegister(2, 'q0')
creg0 = ClassicalRegister(2, 'c0')
qreg1 = QuantumRegister(2, 'q1')
creg1 = ClassicalRegister(2, 'c1')
circ = QuantumCircuit(qreg0, qreg1)
circ.x(qreg0[1])
circ.x(qreg1[0])
meas = QuantumCircuit(qreg0, qreg1, creg0, creg1)
meas.measure(qreg0, creg0)
meas.measure(qreg1, creg1)
qc = circ + meas
backend_sim = JKU.get_backend('qasm_simulator')
job = execute(qc, backend_sim)
result = job.result()
counts = result.get_counts(qc)
print(counts)
|
https://github.com/jdellaverson19/qiskit2020
|
jdellaverson19
|
"""Qiskit code for running Simon's algorithm on quantum hardware for 2 qubits and b = '11' """
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit_textbook.tools import simon_oracle
#set b equal to '11'
b = '11'
#1) initialize qubits
n = 2
simon_circuit_2 = QuantumCircuit(n*2, n)
#2) Apply Hadamard gates before querying the oracle
simon_circuit_2.h(range(n))
#3) Query oracle
simon_circuit_2 += simon_oracle(b)
#5) Apply Hadamard gates to the input register
simon_circuit_2.h(range(n))
#3) and 6) Measure qubits
simon_circuit_2.measure(range(n), range(n))
# Load saved IBMQ accounts and get the least busy backend device
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Execute and monitor the job
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
# Get results and plot counts
device_counts = job.result().get_counts()
plot_histogram(device_counts)
#additionally, function for calculating dot product of results
def bdotz(b, z):
accum = 0
for i in range(len(b)):
accum += int(b[i]) * int(z[i])
return (accum % 2)
print('b = ' + b)
for z in device_counts:
print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots))
#the most significant results are those for which b dot z=0(mod 2).
'''b = 11
11.00 = 0 (mod 2) (45.0%)
11.01 = 1 (mod 2) (6.2%)
11.10 = 1 (mod 2) (6.4%)
11.11 = 0 (mod 2) (42.4%)'''
|
https://github.com/bartubisgin/QSVTinQiskit-2021-Europe-Hackathon-Winning-Project-
|
bartubisgin
|
using GenericLinearAlgebra
using LinearAlgebra
using SpecialFunctions
using Dates
using PolynomialRoots
using Printf
using FFTW
using PyPlot
using MAT
function GSLW(P, p_P, stop_criteria, R_init, R_max, if_polish = false)
#------------------------------------------------------------------------------------------------------------
# Input:
# P: Chebyshev coefficients of polynomial P, only need to provide non-zero coefficient.
# P should satisfy parity constraint and |P|^2 \le 1
# p_P: parity of P, 0 -- even, 1 -- odd
# stop_eps: algorithm will stop if it find factors that approximate polynomials with error less than
# stop_eps on Chebyshev points
# R_init: number of bits used at the beginning
# R_max: number of bits available
# if_polish: whether polish the roots, it cost more time but may improve performance
#
# Output:
# Phase factor Phi such that real part of (0,0)-component of U_\Phi(x) approximates P(x),
# where U_\Phi(x) = e^{\I \phi_0 \sigma_z} \prod_{j=1}^{\qspdeg} \left[ W(x) e^{\I \phi_j \sigma_z} \right]
#
# Besides, the algorithm will return the L^∞ error of such approximation on Chebyshev points
#
#------------------------------------------------------------------------------------------------------------
#
# Reference:
# A. Gily ́en, Y. Su, G. H. Low, and N. Wiebe.
# Quantum singular value transformation and beyond: exponentialimprovements for quantum matrix arithmetics.
#
# Author: X.Meng, Y. Dong
# Version 1.0 .... 02/2020
#
#------------------------------------------------------------------------------------------------------------
# Step 1: Find all the roots of 1-P^2
R = R_init
while(true)
if(R>=R_max)
return Inf,[]
end
setprecision(BigFloat, R)
P = big.(P)
degree = length(P)
if(p_P==0)
coef_PQ = zeros(BigFloat,degree*2)
for j=1:degree
for k=1:degree
coef_PQ[j+k-1] -= P[j]*P[k]
end
end
coef_PQ[1] += 1
coef_PQ1 = zeros(BigFloat,degree)
for j=1:degree
coef_PQ1[j] -= P[j]
end
coef_PQ1[1] += 1
coef_PQ2 = zeros(BigFloat,degree)
for j=1:degree
coef_PQ2[j] += P[j]
end
coef_PQ2[1] += 1
Proot1 = roots(coef_PQ1, polish = if_polish, epsilon = big.(0.0))
Proot2 = roots(coef_PQ2, polish = if_polish, epsilon = big.(0.0))
Proot = [Proot1;Proot2]
else
coef_PQ = zeros(BigFloat,degree*2)
for j=1:degree
for k=1:degree
coef_PQ[j+k] -= P[j]*P[k]
end
end
coef_PQ[1] += 1
Proot = roots(coef_PQ, polish = if_polish, epsilon = big.(0.0))
end
# Step 2: Find root of 1-P^2, construct full P and Q by FFT
# recover full root list
all_root = zeros(Complex{BigFloat},length(Proot)*2)
for i=1:length(Proot)
tmpnorm = norm(Proot[i])
tmpangle = angle(Proot[i])
all_root[2*i-1] = sqrt(tmpnorm)*exp(1im*tmpangle/2)
all_root[2*i] = -sqrt(tmpnorm)*exp(1im*tmpangle/2)
end
# Construct W such that W(x)W(x)^*=1-P^2(x)
eps = 1e-16
S_0 = 0
S_1 = 0
S_2 = 0
S_3 = 0
S_4 = 0
S1_list = zeros(Complex{BigFloat},length(all_root))
S2_list = zeros(Complex{BigFloat},length(all_root))
S3_list = zeros(Complex{BigFloat},length(all_root))
S4_list = zeros(Complex{BigFloat},length(all_root))
for i=1:length(all_root)
if(abs(all_root[i])<eps)
S_0 += 1
continue
end
if(abs(imag(all_root[i]))<eps&&real(all_root[i])>0)
if(real(all_root[i])<1-eps)
S_1 += 1
S1_list[S_1] = real(all_root[i])
else
S_2 += 1
S2_list[S_2] = findmax([real(all_root[i]),1])[1]
end
continue
end
if(abs(real(all_root[i]))<eps&&imag(all_root[i])>0)
S_3 += 1
S3_list[S_3] = all_root[i]
continue
end
if(imag(all_root[i])>0&&real(all_root[i])>0)
S_4 += 1
S4_list[S_4] = all_root[i]
end
end
K = abs(P[end])
function get_w(x,use_real = true) # W(x)
x = big.(x)
Wx = K*x^(S_0/2)
eps3 = 1e-24
if(x==1) # if x==\pm 1, silghtly move x such that make \sqrt{1-x^2}>0
x -= eps3
elseif(x==-1)
x += eps3
end
for i=1:S_1
Wx *= sqrt(x^2-S1_list[i]^2)
end
for i=1:S_2
Wx *= sqrt(S2_list[i]^2-big.(1))*x+im*S2_list[i]*sqrt(big.(1)-x^2)
end
for i=1:S_3
Wx *= sqrt(abs(S3_list[i])^2+big.(1))*x+im*abs(S3_list[i])*sqrt(big.(1)-x^2)
end
for i=1:S_4
tmpre = real(S4_list[i])
tmpim = imag(S4_list[i])
tmpc = tmpre^2+tmpim^2+sqrt(2*(tmpre^2+1)*tmpim^2+(tmpre^2-1)^2+tmpim^4)
Wx *= tmpc*x^2-(tmpre^2+tmpim^2)+im*sqrt(tmpc^2-1)*x*sqrt(big.(1)-x^2)
end
if(use_real)
return real(Wx)
else
return imag(Wx)/sqrt(big.(1)-x^2)
end
end
function get_p(x) # P(x)
P_t = big.(0)
for j=1:length(P)
if(p_P==1)
P_t += P[j]*x^big.(2*j-1)
else
P_t += P[j]*x^big.(2*j-2)
end
end
return P_t
end
# Represent full P and Q under Chevyshev basis
get_wr(x) = get_w(x,true)
get_wi(x) = get_w(x,false)
DEG = 2^ceil(Int,log2(degree)+1)
coef_r = ChebyExpand(get_wr, DEG)
coef_i = ChebyExpand(get_wi, DEG)
coef_p = ChebyExpand(get_p, DEG)
if(p_P==0)
P_new = 1im.*coef_r[1:2*degree-1]+coef_p[1:2*degree-1]
Q_new = coef_i[1:2*degree-2].*1im
else
P_new = 1im.*coef_r[1:2*degree]+coef_p[1:2*degree]
Q_new = coef_i[1:2*degree-1].*1im
end
# Step 3: Get phase factors and check convergence
phi = get_factor(P_new,Q_new)
max_err = 0
t = cos.(collect(1:2:(2*degree-1))*big.(pi)/big.(4)/big.(degree))
for i=1:length(t)
targ, ret = QSPGetUnitary(phi, t[i])
P_t = big.(0)
for j=1:degree
if(p_P==1)
P_t += P[j]*t[i]^big.(2*j-1)
else
P_t += P[j]*t[i]^big.(2*j-2)
end
end
t_err = norm(real(ret[1,1])-P_t)
if(t_err>max_err)
max_err = t_err
end
end
@printf("For degree N = %d, precision R = %d, the estimated inf norm of err is %5.4e\n",length(phi)-1,R,max_err)
if(max_err<stop_criteria)
return max_err,phi
else
@printf("Error is too big, increase R.\n")
end
R = R*2
end
end
function get_factor(P,Q)
# From polynomials P, Q generate phase factors phi such that
# U_\Phi(x) = [P & i\sqrt{1-x^2}Q \\ i\sqrt{1-x^2}Q^* & P]
# phase factors are generated via a reduction procedure under Chebyshev basis
phi = zeros(BigFloat,length(P))
lenP = length(P)
for i=1:lenP-1
P, Q, phit = ReducePQ(P, Q)
phi[end+1-i] = real(phit)
end
phi[1] = angle(P[1])
return phi
end
function ReducePQ(P, Q)
# A single reduction step
P = big.(P)
Q = big.(Q)
colP = length(P)
colQ = length(Q)
degQ = colQ-1
tmp1 = zeros(Complex{BigFloat},colP+1)
tmp2 = zeros(Complex{BigFloat},colP+1)
tmp1[2:end] = big.(0.5)*P
tmp2[1:end-2] = big.(0.5)*P[2:end]
Px = tmp1 + tmp2
Px[2] = Px[2] + big.(0.5)*P[1]
if(degQ>0)
tmp1 = zeros(Complex{BigFloat},colQ+2)
tmp2 = zeros(Complex{BigFloat},colQ+2)
tmp3 = zeros(Complex{BigFloat},colQ+2)
tmp1[1:end-2] = big.(0.5)*Q
tmp2[3:end] = -big.(1)/big.(4)*Q
tmp3[1:end-4] = -big.(1)/big.(4)*Q[3:end]
Q1_x2 = tmp1 + tmp2 + tmp3
Q1_x2[2] = Q1_x2[2] - 1/big.(4)*Q[2]
Q1_x2[3] = Q1_x2[3] - 1/big.(4)*Q[1]
else
Q1_x2 = zeros(Complex{BigFloat},3)
Q1_x2[1] = big.(0.5)*Q[1]
Q1_x2[end] = -big.(0.5)*Q[1]
end
tmp1 = zeros(Complex{BigFloat},colQ+1)
tmp2 = zeros(Complex{BigFloat},colQ+1)
tmp1[2:end] = big.(0.5)*Q
tmp2[1:end-2] = big.(0.5)*Q[2:end]
Qx = tmp1 + tmp2
Qx[2] = Qx[2] + big.(0.5)*Q[1];
if(degQ>0)
ratio = P[end]/Q[end]*big.(2)
else
ratio = P[end]/Q[end]
end
phi = big.(0.5)*angle(ratio)
rexp = exp(-1im*phi)
Ptilde = rexp * (Px + ratio*Q1_x2)
Qtilde = rexp * (ratio*Qx - P)
Ptilde = Ptilde[1:degQ+1]
Qtilde = Qtilde[1:degQ]
return Ptilde,Qtilde,phi
end
function QSPGetUnitary(phase, x)
# Given phase factors Phi and x, yield U_\Phi(x)
phase = big.(phase)
Wx = zeros(Complex{BigFloat},2,2)
Wx[1,1] = x
Wx[2,2] = x
Wx[1,2] = sqrt(1-x^2)*1im
Wx[2,1] = sqrt(1-x^2)*1im
expphi = exp.(1im*phase)
ret = zeros(Complex{BigFloat},2,2)
ret[1,1] = expphi[1]
ret[2,2] = conj(expphi[1])
for k = 2:length(expphi)
temp = zeros(Complex{BigFloat},2,2)
temp[1,1] = expphi[k]
temp[2,2] = conj(expphi[k])
ret = ret * Wx * temp
end
targ = real(ret[1,1])
return targ,ret
end
function ChebyExpand(func, maxorder)
# Evaluate Chebyshev coefficients of a polynomial of degree at most maxorder
M = maxorder
theta = zeros(BigFloat,2*M)
for i=1:2*M
theta[i] = (i-1)*big.(pi)/M
end
f = func.(-cos.(theta))
c = real.(BigFloatFFT(f))
c = copy(c[1:M+1])
c[2:end-1] = c[2:end-1]*2
c[2:2:end] = -copy(c[2:2:end])
c = c./(big.(2)*big.(M))
return c
end
function Chebytonormal(coef)
#Convert Chebyshev basis to normal basis
coef = big.(coef)
coef2 = zeros(BigFloat,length(coef))
A = zeros(BigFloat,length(coef),length(coef))
b = zeros(BigFloat,length(coef))
t = cos.(collect(1:2:(2*length(coef)-1))*big.(pi)/big.(4)/big.(length(coef)))
t2 = collect(1:2:(2*length(coef)-1))*big.(pi)/big.(4)/big.(length(coef))
for i=1:length(coef)
for j=1:length(coef)
A[i,j] = t[i]^(j-1)
b[i] += coef[j]*cos((j-1)*t2[i])
end
end
coef2 = A\b
#@printf("Error is %5.4e\n",norm(A*coef2-b))
return coef2
end
function BigFloatFFT(x)
# Perform FFT on vector x
# This function only works for length(x) = 2^k
N = length(x);
xp = x[1:2:end];
xpp = x[2:2:end];
if(N>=8)
Xp = BigFloatFFT(xp);
Xpp = BigFloatFFT(xpp);
X = zeros(Complex{BigFloat},N,1);
Wn = exp.(big.(-2)im*big.(pi)*(big.(0:N/2-1))/big.(N));
tmp = Wn .* Xpp;
X = [(Xp + tmp);(Xp -tmp)];
elseif(N==2)
X = big.([1 1;1 -1])*x;
elseif(N==4)
X = big.([1 0 1 0; 0 1 0 -1im; 1 0 -1 0;0 1 0 1im]*[1 0 1 0;1 0 -1 0;0 1 0 1;0 1 0 -1])*x;
end
return X
end
# Test case 1: Hamiltonian simulation
#
# Here we want to approxiamte e^{-i\tau x} by Jacobi-Anger expansion:
#
# e^{-i\tau x} = J_0(\tau)+2\sum_{k even} (-1)^{k/2}J_{k}(\tau)T_k(x)+2i\sum_{k odd} (-1)^{(k-1)/2}J_{k}(\tau) T_k(x)
#
# We truncate the series up to N = 1.4\tau+log(10^{14}), which gives an polynomial approximation of e^{-i\tau x} with
# accuracy 10^{-14}. Besides, we deal with real and imaginary part of the truncated series seperatly and divide them
# by a constant factor 2 to enhance stability.
#
# parameters
# stop_eps: desired accuracy
# tau: the duration \tau in Hamiltonian simulation
# R_init: number of bits used at the beginning
# R_max: number of bits available
stop_eps = 1e-12
tau = 100
R_init = 1024
R_max = 1025
#------------------------------------------------------------------
phi1 = []
phi2 = []
for p_P=0:1
N = ceil.(Int,tau*1.4+log(1e14))
if(p_P==0)
setprecision(BigFloat,4096)
if(mod(N,2)==1)
N -= 1
end
coef = zeros(BigFloat,N+1)
for i=1:(round(Int,N/2)+1)
coef[2*i-1] = (-1)^(i-1)*besselj(big.(2.0*(i-1)),tau)
end
coef[1] = coef[1]/2
P = Chebytonormal(coef)
P = P[1:2:end]
else
setprecision(BigFloat,4096)
if(mod(N,2)==0)
N += 1
end
coef = zeros(BigFloat,N+1)
for i=1:round(Int,(N+1)/2)
coef[2*i] = (-1)^(i-1)*besselj(big.(2*i-1),tau)
end
P = Chebytonormal(coef)[2:2:end]
end
start_time = time()
err,phi = GSLW(P,p_P,stop_eps,R_init,R_max)
elpased_time = time()-start_time
@printf("Elapsed time is %4.2e s\n", elpased_time)
end
# Test case 2: Eigenstate filter
#
# Here we want to generate factors for the eigenstate filter function:
#
# f_n(x,\delta)=\frac{T_n(-1+2\frac{x^2-\delta^2}{1-\delta^2})}{T_n(-1+2\frac{-\delta^2}{1-\delta^2})}.
#
# We divide f_n by a constant factor \sqrt{2} to enhance stability.
#
# Reference: Lin Lin and Yu Tong
# Solving quantum linear system problem with near-optimal complexity
#
# parameters
# stop_eps: desired accuracy
# n, \delta: parameters of f_n
# R_init: number of bits used at the beginning
# R_max: number of bits available
#
stop_eps = 1e-12
n = 100
delta = 0.03
R_init = 1024
R_max = 1025
#------------------------------------------------------------------
function f_n(x,n,delta)
val = copy(x)
delta = big.(delta)
fact = chebyshev(-big.(1)-big.(2)*delta^2/(big.(1)-delta^2),n)
if(length(x)==1)
return chebyshev(-big.(1)+big.(2)*(x^2-delta^2)/(big.(1)-delta^2),n)/fact
else
for i=1:length(x)
val[i] = chebyshev(-1+2*(x[i]^2-delta^2)/(1-delta^2),n)/fact
end
return val
end
end
function chebyshev(x,n) # T_n(x)
if(abs(x)<=1)
return cos(big.(n)*acos(x))
elseif(x>1)
return cosh(big.(n)*acosh(x))
else
return big.((-1)^n)*cosh(big.(n)*acosh(-x))
end
end
# Obtain expansion of f_n under Chebyshev basis via FFT
setprecision(BigFloat,1024)
M = 2*n
theta = range(0, stop=2*pi, length=2*M+1)
theta = theta[1:2*M]
f = f_n(-cos.(theta),n,delta)
c = real(fft(f))
c = c[1:M+1]
c[2:end-1] = c[2:end-1]*2
c[2:2:end] = - c[2:2:end]
c = c / (2*M)
setprecision(BigFloat,4096)
P = Chebytonormal(c)[1:2:end]/sqrt(big.(2.0))
p_P = 0
start_time = time()
err,phi = GSLW(P,p_P,stop_eps,R_init,R_max)
elpased_time = time()-start_time
@printf("Elapsed time is %4.2e s\n", elpased_time)
# Test case 3: Matrix inversion
#
# We would like to approximate 1/x over [1/kappa,1] by a polynomial, such polynomial is generated
# by Remez algorithm and the approximation error is bounded by 10^{-6}
#
# parameters
# stop_eps: desired accuracy
# kappa: parameters of polynomial approximation
# R_init: number of bits used at the beginning
# R_max: number of bits available
#
stop_eps = 1e-12
kappa = 20
R_init = 2048
R_max = 2049
#------------------------------------------------------------------
# even approximation
# enter your path here
matpath2 = "Data\\inversex\\"
vars = matread(matpath2 * "coef_xeven_" * string(kappa)*"_6"* ".mat")
coef = vars["coef"]
setprecision(BigFloat,4096)
coef2 = zeros(2*length(coef)-1)
coef2[1:2:end] = coef
P = Chebytonormal(coef2)[1:2:end]
p_P = 0
start_time = time()
err,phi1 = GSLW(P,p_P,stop_eps,R_init,R_max)
elpased_time = time()-start_time
@printf("Elapsed time is %4.2e s\n", elpased_time)
# odd approximation
vars = matread(matpath2 * "coef_xodd_" * string(kappa)*"_6"* ".mat")
coef = vars["coef"]
setprecision(BigFloat,4096)
coef2 = zeros(2*length(coef))
coef2[2:2:end] = coef
P = Chebytonormal(coef2)[2:2:end]
start_time = time()
p_P = 1
err,phi = GSLW(P,p_P,stop_eps,R_init,R_max)
elpased_time = time()-start_time
@printf("Elapsed time is %4.2e s\n", elpased_time)
## Test case whatever: QSVT
stop_eps = 1e-12
tau = 100
R_init = 65536
R_max = 65537
#------------------------------------------------------------------
phi1 = []
phi2 = []
coeff = [0, 1.15635132, 0, 0, 0, 0.225911198, 0, 0, 0, 0.11899033, 0, 0, 0, 0.0760566958, 0, 0, 0, 0.0525742336, 0, 0, 0, 0.0379644735, 0, 0, 0, 0.0283926438, 0, 0, 0, 0.0221076246, 0]
# coeff = [1.15635132, 0.225911198, 0.11899033, 0.0760566958, 0.0525742336, 0.0379644735, 0.0283926438, 0.0221076246]
setprecision(BigFloat,4096)
start_time = time()
p_P = 1
c = Chebytonormal(coeff)[2:2:end]
err, phi = GSLW(c, p_P, stop_eps, R_init, R_max)
elapsed_time = time() - start_time
# for p_P=0:1
# N = ceil.(Int,tau*1.4+log(1e14))
# if(p_P==0)
# setprecision(BigFloat,4096)
# if(mod(N,2)==1)
# N -= 1
# end
# coef = zeros(BigFloat,N+1)
# for i=1:(round(Int,N/2)+1)
# coef[2*i-1] = (-1)^(i-1)*besselj(big.(2.0*(i-1)),tau)
# end
# coef[1] = coef[1]/2
# P = Chebytonormal(coef)
# P = P[1:2:end]
# else
# setprecision(BigFloat,4096)
# if(mod(N,2)==0)
# N += 1
# end
# coef = zeros(BigFloat,N+1)
# for i=1:round(Int,(N+1)/2)
# coef[2*i] = (-1)^(i-1)*besselj(big.(2*i-1),tau)
# end
# P = Chebytonormal(coef)[2:2:end]
# end
# start_time = time()
# err,phi = GSLW(P,p_P,stop_eps,R_init,R_max)
# elpased_time = time()-start_time
# @printf("Elapsed time is %4.2e s\n", elpased_time)
# end
|
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
|
Qiskit-Extensions
|
# This code is a Qiskit project.
# (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.
"""Tests for CKT transpilation passes."""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import DAGFixedPoint
from qiskit.passmanager.flow_controllers import DoWhileController
from qiskit.converters import circuit_to_dag
from circuit_knitting.utils.transpiler_passes import RemoveFinalReset, ConsolidateResets
class TestRemoveFinalReset(unittest.TestCase):
"""Test remove-reset-in-zero-state optimizations."""
def test_optimize_single_reset(self):
"""Remove a single final reset
qr0:--[H]--|0>-- ==> qr0:--[H]--
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(0)
circuit.reset(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.h(0)
pass_ = RemoveFinalReset()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_dont_optimize_non_final_reset(self):
"""Do not remove reset if not final instruction
qr0:--|0>--[H]-- ==> qr0:--|0>--[H]--
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.reset(qr)
circuit.h(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.reset(qr)
expected.h(qr)
pass_ = RemoveFinalReset()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_single_reset_in_diff_qubits(self):
"""Remove a single final reset in different qubits
qr0:--[H]--|0>-- qr0:--[H]--
==>
qr1:--[X]--|0>-- qr1:--[X]----
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(0)
circuit.x(1)
circuit.reset(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.h(0)
expected.x(1)
pass_ = RemoveFinalReset()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
class TestRemoveFinalResetFixedPoint(unittest.TestCase):
"""Test RemoveFinalReset in a transpiler, using fixed point."""
def test_two_resets(self):
"""Remove two final resets
qr0:--[H]-|0>-|0>-- ==> qr0:--[H]--
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.reset(qr[0])
circuit.reset(qr[0])
expected = QuantumCircuit(qr)
expected.h(qr[0])
pass_manager = PassManager()
passes = [RemoveFinalReset(), DAGFixedPoint()]
pass_manager.append(
DoWhileController(
passes,
do_while=lambda property_set: not property_set["dag_fixed_point"],
)
)
after = pass_manager.run(circuit)
self.assertEqual(expected, after)
class TestConsolidateResets(unittest.TestCase):
"""Test consolidate-resets optimization."""
def test_consolidate_double_reset(self):
"""Consolidate a pair of resets.
qr0:--|0>--|0>-- ==> qr0:--|0>--
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.reset(qr)
circuit.reset(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.reset(qr)
pass_ = ConsolidateResets()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
|
https://github.com/DRA-chaos/Quantum-Classical-Hyrid-Neural-Network-for-binary-image-classification-using-PyTorch-Qiskit-pipeline
|
DRA-chaos
|
!pip install qiskit
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.autograd import Function
from torchvision import datasets, transforms
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import qiskit
from qiskit import transpile, assemble
from qiskit.visualization import *
import numpy as np
import torch
from torch.autograd import Function
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute
from qiskit.circuit import Parameter
from qiskit import Aer
from tqdm import tqdm
from matplotlib import pyplot as plt
%matplotlib inline
def to_numbers(tensor_list):
num_list = []
for tensor in tensor_list:
num_list += [tensor.item()]
return num_list
class QuantumCircuit:
"""
This class provides a simple interface for interaction
with the quantum circuit
"""
def __init__(self, n_qubits, backend, shots):
# --- Circuit definition ---
self._circuit = qiskit.QuantumCircuit(n_qubits)
all_qubits = [i for i in range(n_qubits)]
self.theta = qiskit.circuit.Parameter('theta')
self._circuit.h(all_qubits)
self._circuit.barrier()
self._circuit.ry(self.theta, all_qubits)
self._circuit.measure_all()
# ---------------------------
self.backend = backend
self.shots = shots
def run(self, thetas):
t_qc = transpile(self._circuit,
self.backend)
qobj = assemble(t_qc,
shots=self.shots,
parameter_binds = [{self.theta: theta} for theta in thetas])
job = self.backend.run(qobj)
result = job.result().get_counts()
counts = np.array(list(result.values()))
states = np.array(list(result.keys())).astype(float)
# Compute probabilities for each state
probabilities = counts / self.shots
# Get state expectation
expectation = np.sum(states * probabilities)
return np.array([expectation])
class HybridFunction(Function):
""" Hybrid quantum - classical function definition """
@staticmethod
def forward(ctx, input, quantum_circuit, shift):
""" Forward pass computation """
ctx.shift = shift
ctx.quantum_circuit = quantum_circuit
expectation_z = ctx.quantum_circuit.run(input[0].tolist())
result = torch.tensor([expectation_z])
ctx.save_for_backward(input, result)
return result
@staticmethod
def backward(ctx, grad_output):
""" Backward pass computation """
input, expectation_z = ctx.saved_tensors
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.shift
shift_left = input_list - np.ones(input_list.shape) * ctx.shift
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients.append(gradient)
gradients = np.array([gradients]).T
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class Hybrid(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, shift):
super(Hybrid, self).__init__()
self.quantum_circuit = QuantumCircuit(1, backend, shots)
self.shift = shift
def forward(self, input):
return HybridFunction.apply(input, self.quantum_circuit, self.shift)
import torchvision
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors
cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform)
len(cifar_trainset)
from torch.utils.data import DataLoader, random_split
cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform)
labels = cifar_trainset.targets # get the labels for the data
labels = np.array(labels)
idx1 = np.where(labels == 0) # filter on aeroplanes
idx2 = np.where(labels == 1) # filter on automobiles
# Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set)
n=100
# concatenate the data indices
idx = np.concatenate((idx1[0][0:n],idx2[0][0:n]))
# create the filtered dataset for our training set
cifar_trainset.targets = labels[idx]
cifar_trainset.data = cifar_trainset.data[idx]
cifar_trainset, valid = random_split(cifar_trainset,[150,50])
train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True)
valid_loader = torch.utils.data.DataLoader(valid, batch_size=1, shuffle=True)
@torch.no_grad()
def get_all_preds(model, train_loader):
all_preds = torch.tensor([])
for batch in train_loader:
images, labels = batch
preds = model(images)
all_preds = torch.cat(
(all_preds, preds)
,dim=0
)
return all_preds
import numpy as np
import matplotlib.pyplot as plt
n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 2))
while n_samples_show > 0:
images, targets = data_iter.__next__()
images=images.squeeze()
axes[n_samples_show - 1].imshow(images[0].numpy(), cmap='gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
import torchvision
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors
cifar_testset = datasets.CIFAR10(root='./data1', train=False, download=True, transform=transform)
labels = cifar_testset.targets # get the labels for the data
labels = np.array(labels)
idx1 = np.where(labels == 0) # filter on aeroplanes
idx2 = np.where(labels == 1) # filter on automobiles
# Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set)
n=100
# concatenate the data indices
idx = np.concatenate((idx1[0][0:n],idx2[0][0:n]))
# create the filtered dataset for our training set
cifar_testset.targets = labels[idx]
cifar_testset.data = cifar_testset.data[idx]
test_loader = torch.utils.data.DataLoader(cifar_testset, batch_size=1, shuffle=False)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(500, 500)
self.fc2 = nn.Linear(500, 1)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(1, -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x)
return torch.cat((x, 1 - x), -1)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 5
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Now plotting the training graph
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 5
loss_list_V = []
model.train()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list_V)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Validation Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(valid_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
validation_loss = loss_func(output, target)
valid_loss.append(validation_loss.item())
print('Performance on test data:\n\tValidation Loss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(valid_loss) / len(valid_loss),
correct / len(valid_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0005)
loss_func = nn.CrossEntropyLoss()
epochs = 5
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Now plotting the training graph
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0005)
loss_func = nn.CrossEntropyLoss()
epochs = 5
loss_list_V = []
model.train()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list_V)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Validation Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(valid_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
validation_loss = loss_func(output, target)
valid_loss.append(validation_loss.item())
print('Performance on test data:\n\tValidation Loss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(valid_loss) / len(valid_loss),
correct / len(valid_loader) * 100)
)
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform)
labels = cifar_trainset.targets # get the labels for the data
labels = np.array(labels)
idx1 = np.where(labels == 0) # filter on aeroplanes
idx2 = np.where(labels == 1) # filter on automobiles
# Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set)
n=100
# concatenate the data indices
idx = np.concatenate((idx1[0][0:n],idx2[0][0:n]))
# create the filtered dataset for our training set
cifar_trainset.targets = labels[idx]
cifar_trainset.data = cifar_trainset.data[idx]
cifar_trainset, valid = random_split(cifar_trainset,[160,40])
train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True)
valid_loader = torch.utils.data.DataLoader(valid, batch_size=1, shuffle=True)
|
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/MonitSharma/Learn-Quantum-Computing-with-Qiskit
|
MonitSharma
|
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
from math import pi
qc = QuantumCircuit(2)
c = 0
t = 1
# a controlled-Z
qc.cz(c,t)
qc.draw('mpl')
qc = QuantumCircuit(2)
# also a controlled-Z
qc.h(t)
qc.cx(c,t)
qc.h(t)
qc.draw('mpl')
qc = QuantumCircuit(2)
# a controlled-Y
qc.sdg(t)
qc.cx(c,t)
qc.s(t)
qc.draw('mpl')
qc = QuantumCircuit(2)
# a controlled-H
qc.ry(pi/4,t)
qc.cx(c,t)
qc.ry(-pi/4,t)
qc.draw('mpl')
a = 0
b = 1
qc = QuantumCircuit(2)
# swaps states of qubits a and b
qc.swap(a,b)
qc.draw('mpl')
qc = QuantumCircuit(2)
# swap a 1 from a to b
qc.cx(a,b) # copies 1 from a to b
qc.cx(b,a) # uses the 1 on b to rotate the state of a to 0
qc.draw('mpl')
# swap a q from b to a
qc.cx(b,a) # copies 1 from b to a
qc.cx(a,b) # uses the 1 on a to rotate the state of b to 0
qc.draw('mpl')
qc = QuantumCircuit(2)
qc.cx(b,a)
qc.cx(a,b)
qc.cx(b,a)
qc.draw('mpl')
qc = QuantumCircuit(2)
# swaps states of qubits a and b
qc.cx(b,a)
qc.cx(a,b)
qc.cx(b,a)
qc.draw('mpl')
qc = QuantumCircuit(2)
# swaps states of qubits a and b
qc.cx(a,b)
qc.cx(b,a)
qc.cx(a,b)
qc.draw('mpl')
qc = QuantumCircuit(2)
theta = pi # theta can be anything (pi chosen arbitrarily)
qc.ry(theta/2,t)
qc.cx(c,t)
qc.ry(-theta/2,t)
qc.cx(c,t)
qc.draw('mpl')
A = Gate('A', 1, [])
B = Gate('B', 1, [])
C = Gate('C', 1, [])
alpha = 1 # arbitrarily define alpha to allow drawing of circuit
qc = QuantumCircuit(2)
qc.append(C, [t])
qc.cz(c,t)
qc.append(B, [t])
qc.cz(c,t)
qc.append(A, [t])
qc.p(alpha,c)
qc.draw('mpl')
qc = QuantumCircuit(3)
a = 0
b = 1
t = 2
# Toffoli with control qubits a and b and target t
qc.ccx(a,b,t)
qc.draw('mpl')
qc = QuantumCircuit(3)
qc.cp(theta,b,t)
qc.cx(a,b)
qc.cp(-theta,b,t)
qc.cx(a,b)
qc.cp(theta,a,t)
qc.draw('mpl')
qc = QuantumCircuit(3)
qc.ch(a,t)
qc.cz(b,t)
qc.ch(a,t)
qc.draw('mpl')
qc = QuantumCircuit(1)
qc.t(0) # T gate on qubit 0
qc.draw('mpl')
qc = QuantumCircuit(1)
qc.h(0)
qc.t(0)
qc.h(0)
qc.draw('mpl')
qc = QuantumCircuit(1)
qc.h(0)
qc.t(0)
qc.h(0)
qc.t(0)
qc.draw('mpl')
|
https://github.com/drobiu/quantum-project
|
drobiu
|
from qiskit import ClassicalRegister
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.circuit.quantumregister import QuantumRegister
from src.logic.query import query_cd
from src.arithmetic.increment import control_increment, control_decrement
from src.logic.oracles import oracle_a
from src.util.util import run_qc
def FCP(circuit, y_register, qy_register, s_register, secret_string, c, d, d_positions=None):
# init
# q1 = QuantumRegister(num_position, "q1")
# q2 = QuantumRegister(num_bits_color * num_position)
# out = QuantumRegister(num_bits_color + 1, "o")
# step 1: apply H gate
circuit.h(y_register[:])
circuit.barrier()
# step 2: query
circuit = circuit.compose(query_cd(c, d), [*y_register, *qy_register])
# _build_query_two_colours(qc, qy_register, y_register, c, d)
circuit.barrier()
# step 3: ask oracle
circuit = oracle_a(circuit, qy_register, s_register, secret_string)
circuit.barrier()
# step 3.alt: compensate for d positions
if d_positions is not None:
for (i, j) in enumerate(d_positions):
if j == 1:
# apply x gets to y
circuit.x(y_register[i])
# apply decrement with y control
circuit = control_decrement(circuit, s_register, [y_register[i]])
circuit.x(y_register[i])
circuit.barrier()
# step 4: apply Z to LSB
circuit.z(s_register[0])
circuit.barrier()
# step 5: undo step 2 and 3
circuit = oracle_a(circuit, qy_register, s_register, secret_string, do_inverse=True)
circuit = circuit.compose(query_cd(c, d), [*y_register, *qy_register])
# _build_query_two_colours(qc, qy_register, y_register, c, d)
circuit.barrier()
# step 5.alt: undo step 3.alt
if d_positions is not None:
for (i, j) in enumerate(d_positions):
if j == 1:
# apply x gets to y
circuit.x(y_register[i])
# apply decrement with y control
circuit = control_increment(circuit, s_register, [y_register[i]])
circuit.x(y_register[i])
circuit.barrier()
# step 6: apply H gate
circuit.h(y_register[:])
circuit.barrier()
if c + d != 3:
circuit.x(y_register)
return circuit
# d
# x 0 1 2 3
# c 0 - x x v
# 1 x - v x
# 2 x v - x
# 3 v x x -
#
# x - bit flip
# v - correct
if __name__ == "__main__":
qy = QuantumRegister(8, name='qy')
y = QuantumRegister(4, name='y')
s = QuantumRegister(3)
cr = ClassicalRegister(4)
qc = QuantumCircuit(y, qy, s, cr)
# qc.x(qy[0])
qc = FCP(qc, y, qy, s, [1, 0, 3, 3], 1, 2)
qc.barrier()
qc.measure(y[:], cr[::-1])
run_qc(qc, with_QI=False)
qc.draw(output="mpl")
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 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.
"""Tests for drawing of timeline drawer."""
import numpy as np
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import drawings, types
class TestDrawingObjects(QiskitTestCase):
"""Tests for drawings."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
# bits
self.qubits = list(qiskit.QuantumRegister(2))
# metadata
self.meta1 = {"val1": 0, "val2": 1}
self.meta2 = {"val1": 2, "val2": 3}
# style data
self.style1 = {"property1": 0, "property2": 1}
self.style2 = {"property1": 2, "property2": 3}
def test_line_data_equivalent(self):
"""Test LineData equivalent check."""
xs = list(np.arange(10))
ys = list(np.ones(10))
obj1 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_line_data_equivalent_abstract_coord(self):
"""Test LineData equivalent check with abstract coordinate."""
xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP]
obj1 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_box_data_equivalent(self):
"""Test BoxData equivalent check."""
xs = [0, 1]
ys = [0, 1]
obj1 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_box_data_equivalent_abstract_coord(self):
"""Test BoxData equivalent check with abstract coordinate."""
xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP]
obj1 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_text_data_equivalent(self):
"""Test TextData equivalent check."""
obj1 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=0,
yval=0,
text="test",
latex="test",
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=0,
yval=0,
text="test",
latex="test",
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_text_data_equivalent_abstract_coord(self):
"""Test TextData equivalent check with abstract coordinate."""
obj1 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=types.AbstractCoordinate.LEFT,
yval=types.AbstractCoordinate.BOTTOM,
text="test",
latex="test",
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=types.AbstractCoordinate.LEFT,
yval=types.AbstractCoordinate.BOTTOM,
text="test",
latex="test",
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_bit_link_data_equivalent(self):
"""Test BitLinkData equivalent check."""
obj1 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style1
)
obj2 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style2
)
self.assertEqual(obj1, obj2)
def test_bit_link_data_equivalent_abstract_coord(self):
"""Test BitLinkData equivalent check with abstract coordinate."""
obj1 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]],
xval=types.AbstractCoordinate.LEFT,
styles=self.style1,
)
obj2 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]],
xval=types.AbstractCoordinate.LEFT,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
|
https://github.com/msramalho/Teach-Me-Quantum
|
msramalho
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Choose the drawer you like best:
from qiskit.tools.visualization import matplotlib_circuit_drawer as draw
#from qiskit.tools.visualization import circuit_drawer as draw
from qiskit import IBMQ
IBMQ.load_accounts() # make sure you have setup your token locally to use this
%matplotlib inline
import matplotlib.pyplot as plt
def show_results(D):
# D is a dictionary with classical bits as keys and count as value
# example: D = {'000': 497, '001': 527}
plt.bar(range(len(D)), list(D.values()), align='center')
plt.xticks(range(len(D)), list(D.keys()))
plt.show()
from qiskit import Aer
# See a list of available local simulators
print("Aer backends: ", Aer.backends())
# see a list of available remote backends (these are freely given by IBM)
print("IBMQ Backends: ", IBMQ.backends())
# execute circuit and either display a histogram of the results
def execute_locally(qc, draw_circuit=False, show_results=False):
# Compile and run the Quantum circuit on a simulator backend
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
result_counts = result_sim.get_counts(qc)
if draw_circuit or show_results: # Print the results
print("simulation: ", result_sim, result_counts)
if draw_circuit: # draw the circuit
draw(qc)
elif show_results: # or show the results
show_results(result_counts)
return result_counts
from qiskit.backends.ibmq import least_busy
import time
# Compile and run on a real device backend
def execute_remotely(qc, draw_circuit=False, show_results=False):
if draw_circuit: # draw the circuit
draw(qc)
try:
# select least busy available device and execute.
least_busy_device = least_busy(IBMQ.backends(simulator=False))
print("Running on current least busy device: ", least_busy_device)
# running the job
job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10)
lapse, interval = 0, 10
while job_exp.status().name != 'DONE':
print('Status @ {} seconds'.format(interval * lapse))
print(job_exp.status())
time.sleep(interval)
lapse += 1
print(job_exp.status())
exp_result = job_exp.result()
result_counts = exp_result.get_counts(qc)
# Show the results
print("experiment: ", exp_result, result_counts)
if show_results: # show the results
show_results(result_counts)
return result_counts
except:
print("All devices are currently unavailable.")
return {}
def new_circuit(size):
# Create a Quantum Register with size qubits
qr = QuantumRegister(size)
# Create a Classical Register with size bits
cr = ClassicalRegister(size)
# Create a Quantum Circuit acting on the qr and cr register
return qr, cr, QuantumCircuit(qr, cr)
ERROR_MESSAGE = "Looks like your Deutsch has a bug"
def quantum_oracle_1(qr, cr, circuit):
pass
def quantum_oracle_2(qr, cr, circuit):
circuit.cx(qr[0], qr[1])
def quantum_oracle_3(qr, cr, circuit):
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
def quantum_oracle_4(qr, cr, circuit):
circuit.z(qr[1])
circuit.cx(qr[0], qr[1])
qr, cr, circuit = new_circuit(2)
# X gate on qubit 1 (bit flip)
circuit.x(qr[1]);
circuit.h(qr);
quantum_oracle_1(qr, cr, circuit)
circuit.h(qr[0]);
# measure the specific qubit
circuit.measure(qr[0], cr[0]);
# Try both commands:
# results = execute_locally(circuit, draw_circuit=False, show_results=False) # silent mode
results = execute_locally(circuit, draw_circuit=True, show_results=False)
# results = execute_locally(circuit, draw_circuit=False, show_results=True)
# results = execute_locally(circuit, draw_circuit=True, show_results=True) # this will be the same as True, False
if '00' in results:
print("CONSTANT")
elif '10' in results:
print("BALANCED")
def get_deutsch_verdict(res): # should be improved for error handling
if '00' in res:
return "CONSTANT"
elif '01' in res:
return "BALANCED"
print(get_deutsch_verdict(results))
def deutsch(black_box):
qr, cr, circuit = new_circuit(2)
circuit.x(qr[1]) # X gate on qubit 1 (bit flip)
circuit.h(qr) # Hadamard on both qubits
black_box(qr, cr, circuit)
circuit.h(qr[0]) # Hadamard on interesting qubit
circuit.measure(qr[0], cr[0]) # measure the specific qubit
results = execute_locally(circuit, draw_circuit=False, show_results=False) # silent mode
return get_deutsch_verdict(results)
deutsch(quantum_oracle_1)
assert deutsch(quantum_oracle_1) == 'CONSTANT', ERROR_MESSAGE
assert deutsch(quantum_oracle_2) == 'BALANCED', "Looks like your Deutsch has a bug"
assert deutsch(quantum_oracle_3) == 'BALANCED', "Looks like your Deutsch has a bug"
assert deutsch(quantum_oracle_4) == 'CONSTANT', "Looks like your Deutsch has a bug"
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
# Construct quantum circuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure([0,1], [0,1])
# Select the AerSimulator from the Aer provider
simulator = AerSimulator(method='matrix_product_state')
# Run and get counts, using the matrix_product_state method
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
counts = result.get_counts(0)
counts
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
# Define a snapshot that shows the current state vector
circ.save_statevector(label='my_sv')
circ.save_matrix_product_state(label='my_mps')
circ.measure([0,1], [0,1])
# Execute and get saved data
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
data = result.data(0)
#print the result data
data
num_qubits = 50
circ = QuantumCircuit(num_qubits, num_qubits)
# Create EPR state
circ.h(0)
for i in range (0, num_qubits-1):
circ.cx(i, i+1)
# Measure
circ.measure(range(num_qubits), range(num_qubits))
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
print("Time taken: {} sec".format(result.time_taken))
result.get_counts()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
from random import randrange
# the angle of rotation
r = randrange(1,11)
print("the picked angle is",r,"times of 2pi/11")
print()
theta = r*2*pi/11
# we read streams of length from 1 to 11
for i in range(1,12):
# quantum circuit with one qubit and one bit
qreg = QuantumRegister(1)
creg = ClassicalRegister(1)
mycircuit = QuantumCircuit(qreg,creg)
# the stream of length i
for j in range(i):
mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol
# we measure after reading the whole stream
mycircuit.measure(qreg[0],creg[0])
# execute the circuit 1000 times
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit)
print("stream of lenght",i,"->",counts)
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
from random import randrange
# for each stream of length from 1 to 10
for i in range(1,11):
# we try each angle of the form k*2*pi/11 for k=1,...,10
# we try to find the best k for which we observe 1 the most
number_of_one_state = 0
best_k = 1
all_outcomes_for_i = "length "+str(i)+"-> "
for k in range(1,11):
theta = k*2*pi/11
# quantum circuit with one qubit and one bit
qreg = QuantumRegister(1)
creg = ClassicalRegister(1)
mycircuit = QuantumCircuit(qreg,creg)
# the stream of length i
for j in range(i):
mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol
# we measure after reading the whole stream
mycircuit.measure(qreg[0],creg[0])
# execute the circuit 10000 times
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=10000)
counts = job.result().get_counts(mycircuit)
all_outcomes_for_i = all_outcomes_for_i + str(k)+ ":" + str(counts['1']) + " "
if int(counts['1']) > number_of_one_state:
number_of_one_state = counts['1']
best_k = k
print(all_outcomes_for_i)
print("for length",i,", the best k is",best_k)
print()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
from random import randrange
# the angles of rotations
theta1 = 3*2*pi/31
theta2 = 7*2*pi/31
theta3 = 11*2*pi/31
# we read streams of length from 1 to 30
for i in range(1,31):
# quantum circuit with three qubits and three bits
qreg = QuantumRegister(3)
creg = ClassicalRegister(3)
mycircuit = QuantumCircuit(qreg,creg)
# the stream of length i
for j in range(i):
# apply rotations for each symbol
mycircuit.ry(2*theta1,qreg[0])
mycircuit.ry(2*theta2,qreg[1])
mycircuit.ry(2*theta3,qreg[2])
# we measure after reading the whole stream
mycircuit.measure(qreg,creg)
# execute the circuit N times
N = 1000
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N)
counts = job.result().get_counts(mycircuit)
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)
print("the ratio of 000 is ",percentange,"%")
print()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
from random import randrange
# randomly picked angles of rotations
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
print("k1 =",k1,"k2 =",k2,"k3 =",k3)
print()
max_percentange = 0
# we read streams of length from 1 to 30
for i in range(1,31):
# quantum circuit with three qubits and three bits
qreg = QuantumRegister(3)
creg = ClassicalRegister(3)
mycircuit = QuantumCircuit(qreg,creg)
# the stream of length i
for j in range(i):
# apply rotations for each symbol
mycircuit.ry(2*theta1,qreg[0])
mycircuit.ry(2*theta2,qreg[1])
mycircuit.ry(2*theta3,qreg[2])
# we measure after reading the whole stream
mycircuit.measure(qreg,creg)
# execute the circuit N times
N = 1000
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N)
counts = job.result().get_counts(mycircuit)
# 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: max_percentange = percentange
# print("the ration of 000 is ",percentange,"%")
# print()
print("max percentage is",max_percentange)
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
from random import randrange
number_of_qubits = 4
#number_of_qubits = 5
# randomly picked angles of rotations
theta = []
for i in range(number_of_qubits):
k = randrange(1,31)
print("k",str(i),"=",k)
theta += [k*2*pi/31]
# print(theta)
# we count the number of zeros
zeros = ''
for i in range(number_of_qubits):
zeros = zeros + '0'
print("zeros = ",zeros)
print()
max_percentange = 0
# we read streams of length from 1 to 30
for i in range(1,31):
# quantum circuit with qubits and bits
qreg = QuantumRegister(number_of_qubits)
creg = ClassicalRegister(number_of_qubits)
mycircuit = QuantumCircuit(qreg,creg)
# the stream of length i
for j in range(i):
# apply rotations for each symbol
for k in range(number_of_qubits):
mycircuit.ry(2*theta[k],qreg[k])
# we measure after reading the whole stream
mycircuit.measure(qreg,creg)
# execute the circuit N times
N = 1000
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N)
counts = job.result().get_counts(mycircuit)
# print(counts)
if zeros in counts.keys():
c = counts[zeros]
else:
c = 0
# print('000 is observed',c,'times out of',N)
percentange = round(c/N*100,1)
if max_percentange < percentange: max_percentange = percentange
# print("the ration of 000 is ",percentange,"%")
# print()
print("max percentage is",max_percentange)
|
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
|
ronitd2002
|
### Install Qiskit and relevant packages, if needed
### IMPORTANT: Make sure you are on 3.10 > python < 3.12
'''
%pip install qiskit[visualization]==1.0.2
%pip install qiskit-ibm-runtime
%pip install qiskit-aer
%pip install graphviz
%pip install qiskit-serverless -U
%pip install qiskit-transpiler-service -U
'''
%pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U
# Import all in one cell
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit.circuit.library import RealAmplitudes
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.visualization import plot_gate_map, plot_circuit_layout, plot_distribution
from qiskit.circuit import ParameterVector
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import (
QiskitRuntimeService,
EstimatorV2 as Estimator,
SamplerV2 as Sampler,
EstimatorOptions
)
import warnings
warnings.filterwarnings('ignore')
# qc-grader should be 0.18.13 (or higher)
import qc_grader
qc_grader.__version__
from qc_grader.challenges.iqc_2024 import grade_lab_bonus_ex1, grade_lab_bonus_ex2, grade_lab_bonus_ex3
def old_amplitude_embedding(num_qubits, bird_index):
"""Create amplitude embedding circuit
Parameters:
num_qubits (int): Number of qubits for the ansatz
bird_index (int): Data index of the bird
Returns:
qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird
"""
def generate_GHZ(qc):
qc.h(0)
for i, j in zip(range(num_qubits-1), range(1,num_qubits)):
qc.cx(i, j)
### Write your code below here ###
qc = QuantumCircuit(num_qubits)
if bird_index < 5:
generate_GHZ(qc)
bin_string = format(bird_index, '0{0}b'.format(num_qubits))
for i in reversed(range(len(bin_string))):
if bin_string[i] == '1':
qc.x(num_qubits-i-1)
### Don't change any code past this line ###
return qc
num_qubits = 50
# Choose a real backend
service = QiskitRuntimeService()
backend = service.backend("ibm_osaka")
# Define a fake backend with the same properties as the real backend
fake_backend = AerSimulator.from_backend(backend)
index_bird = 0 # You can check different birds by changing the index
qc = old_amplitude_embedding(num_qubits, index_bird)
pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend)
transpiled_qc = pm.run(qc)
print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2))
transpiled_qc.draw(output="mpl", fold=False, idle_wires=False)
def new_amplitude_embedding(num_qubits, bird_index):
"""Create efficient amplitude embedding circuit
Parameters:
num_qubits (int): Number of qubits for the ansatz
bird_index (int): Data index of the bird
Returns:
qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird
"""
### Write your code below here ###
### Don't change any code past this line ###
return qc
num_qubits = 50
index = 0 # Change to different values for testing
qc = new_amplitude_embedding(num_qubits, index)
qc.measure_all()
# Define the backend and the pass manager
aer_sim = AerSimulator(method='matrix_product_state')
pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3)
isa_circuit = pm.run(qc)
# Define the sampler with the number of shots
sampler = Sampler(backend=aer_sim)
result = sampler.run([isa_circuit]).result()
samp_dist = result[0].data.meas.get_counts()
plot_distribution(samp_dist, figsize=(10, 3))
num_qubits = 50
# Choose a real backend
service = QiskitRuntimeService()
backend = service.backend("ibm_kyoto")
# Define a fake backend with the same properties as the real backend
fake_backend = AerSimulator.from_backend(backend)
index_bird = 0 #You can check different birds by changing the index
qc = new_amplitude_embedding(num_qubits, index_bird)
pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend)
transpiled_qc = pm.run(qc)
print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2))
transpiled_qc.draw(output="mpl", fold=False, idle_wires=False)
# Submit your answer using following code
grade_lab_bonus_ex1(new_amplitude_embedding(50,3)) # Expected answer type: QuantumCircuit
def generate_old_ansatz(qubits):
qc = RealAmplitudes(qubits, reps=1, entanglement='pairwise')
return qc
num_qubits = 50
# Choose a real backend
service = QiskitRuntimeService()
backend = service.backend("ibm_kyoto")
# Define a fake backend with the same properties as the real backend
fake_backend = AerSimulator.from_backend(backend)
index_bird = 0 # You can check different birds by changing the index
qc = new_amplitude_embedding(num_qubits, index_bird)
ansatz = generate_old_ansatz(num_qubits)
pm = generate_preset_pass_manager(optimization_level=3, backend=backend)
transpiled_qc = pm.run(qc.compose(ansatz))
print('Depth new mapping + old ansatz: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2))
# transpiled_qc.draw(output="mpl", fold=False, idle_wires=False)
def generate_ansatz(num_qubits):
"""Generate a `RealAmplitudes` ansatz where all qubits are entangled with each other
Parameters:
num_qubits (int): Number of qubits for the ansatz
Returns:
qc (QuantumCircuit): Quantum circuit with the generated ansatz
"""
### Write your code below here ###
### Don't change any code past this line ###
return qc
index_bird = 0 # You can check different birds by changing the index
new_mapping_qc = new_amplitude_embedding(num_qubits, index_bird)
ansatz = generate_ansatz(num_qubits)
pm = generate_preset_pass_manager(optimization_level=3, backend=backend)
transpiled_qc = pm.run(new_mapping_qc.compose(ansatz))
print('Depth new mapping + new ansatz: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2))
# transpiled_qc.draw(output="mpl", fold=False, idle_wires=False)
# Submit your answer using following code
grade_lab_bonus_ex2(transpiled_qc) # Expected answer type: QuantumCircuit
# Generate this to match your ansatz
source_list = # Add your code here
def generalize_optimal_params(num_qubits, ansatz, source_list):
"""Generate a `list of optimal parameters for N qubits
Parameters:
num_qubits (int): Number of qubits for the ansatz
ansatz (QuantumCircuit): Ansatz for our VQC
source_list (list): List of qubits used as source to entangle other qubits
Returns:
opt_params (list): List of optimal parameters generated for N qubits
"""
opt_params = np.zeros(ansatz.num_parameters)
for i in range(ansatz.num_parameters//2):
if i in source_list:
opt_params[i] = np.pi
return opt_params
def test_shallow_VQC_QPU(num_qubits, list_labels, obs, opt_params, options, backend):
"""Tests the shallow VQC on a QPU
Parameters:
num_qubits (int): Number of qubits for the ansatz
list_labels (list): List of labels
obs: (SparsePauliOp): Observable
opt_params (ndarray): Array of optimized parameters
options (EstimatorOptions): Options for Estimator primitive
backend (Backend): Real backend from IBM Quantum to run the job
Returns:
job_id (str): Job ID for Quantum job
"""
### Write your code below here ###
### Don't change any code past this line ###
return job_id
def retrieve_job(job_id):
"""Retrieve test results from job id
Parameters:
job_id (str): Job ID
Returns:
results_test (list): List of test results
errors_test (list): List of test errors
"""
job = service.job(job_id)
results_test = []
errors_test = []
for result in job.result():
results_test.append(abs(abs(result.data.evs)-1)) #COST FUNCTION HAS A -1 NOW!!!
errors_test.append(abs(result.data.stds))
return results_test, errors_test
def test_shallow_VQC_CPU(num_qubits, list_labels, obs, opt_params, options, backend):
"""Tests the shallow VQC on a QPU
Parameters:
num_qubits (int): Number of qubits for the ansatz
list_labels (list): List of labels
obs: (SparsePauliOp): Observable
opt_params (ndarray): Array of optimized parameters
options (EstimatorOptions): Options for Estimator primitive
backend (Backend): AerSimulator backend to run the job
Returns:
results_test (list): List of test results
"""
results_test = []
### Write your code below here ###
### Don't change any code past this line ###
result = job.result()[0].data.evs
results_test.append(abs(abs(result)-1)) # COST FUNCTION NOW HAS A -1!!!
return results_test
def compute_performance(result_list, list_labels):
"""Return the performance of the classifier
Parameters:
result_list (list): List of results
list_labels (list): List of labels
Returns:
performance (float): Performance of the classifier
"""
### Write your code below here ###
### Don't change any code past this line ###
return performance
num_qubits = 50
aer_sim = AerSimulator(method='matrix_product_state')
pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3)
isa_circuit = pm.run(new_mapping_qc)
list_labels = np.append(np.ones(5), np.zeros(5))
obs = SparsePauliOp("Z"*num_qubits)
opt_params = generalize_optimal_params(num_qubits, generate_ansatz(num_qubits), source_list)
options = EstimatorOptions()
results_test_aer_sim = test_shallow_VQC_CPU(num_qubits, list_labels, obs, opt_params, options, aer_sim)
fig, ax = plt.subplots(1, 1, figsize=(7,5))
ax.set_title('Cost on test data MPS')
ax.set_ylabel('Cost')
ax.set_xlabel('State index')
print(f"Performance for resilience 0: {compute_performance(results_test_aer_sim, list_labels)}")
ax.plot(results_test_aer_sim, 'o-', color='tab:red', label='MPS Num qubits = ' + str(num_qubits))
ax.plot(list_labels, 'k-', label='Labels')
ax.legend()
# Submit your answer using following code
grade_lab_bonus_ex3(results_test_aer_sim) # Expected variable types: List
service = QiskitRuntimeService()
backend = service.backend("select_your_device")
# RUN JOBS
num_qubits = 50
obs = SparsePauliOp("Z"*num_qubits)
opt_params = generalize_optimal_params(num_qubits, generate_ansatz(num_qubits), source_list)
for resilience in [0,1]:
DD = True
options = EstimatorOptions(default_shots = 5_000,
optimization_level=0,
resilience_level=resilience)
options.dynamical_decoupling.enable = DD
options.dynamical_decoupling.sequence_type = 'XpXm'
# OPTIONAL
# options.resilience.zne_mitigation = True
# options.resilience.zne.noise_factors = (1, 1.2, 1.5)
# options.resilience.zne.extrapolator = ('exponential', 'linear', 'polynomial_degree_2') #order matters
job_id = test_shallow_VQC_QPU(num_qubits, list_labels, obs, opt_params, options, backend)
results_test_0_DD, errors_test_0_DD = retrieve_job('Enter your JobID for resilience level 0')
results_test_1_DD, errors_test_1_DD = retrieve_job('Enter your JobID for resilience level 1')
fig, ax = plt.subplots(1, 1, figsize=(7,5))
ax.set_title(f'Test of a {num_qubits} qubit VQC on {backend.name}')
ax.set_ylabel('Cost')
ax.set_xlabel('State index')
print(f"Performance for no DD + no TREX: {compute_performance(results_test_0_DD, list_labels):.3f}")
print(f"Performance for DD + TREX: {compute_performance(results_test_1_DD, list_labels):.3f}")
ax.errorbar(range(10), results_test_0_DD, fmt='--o', yerr=errors_test_0_DD, color='tab:orange', label=f'{backend.name} RL=0 shots={options.default_shots} DD={options.dynamical_decoupling.enable}')
ax.errorbar(range(10), results_test_1_DD, fmt='--o', yerr=errors_test_1_DD, color='tab:blue', label=f'{backend.name} RL=1 shots={options.default_shots} DD={options.dynamical_decoupling.enable}')
ax.plot(list_labels, 'k-', label='Labels')
ax.legend()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can make the bars more transparent to better see the ones that are behind
# if they overlap.
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
state = Statevector(qc)
plot_state_city(state, alpha=0.6)
|
https://github.com/Interlin-q/diskit
|
Interlin-q
|
import numpy as np
from numpy import pi
# importing Qiskit
from qiskit import QuantumCircuit, transpile, assemble, Aer
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(3)
qc.h(2)
qc.cp(pi/2, 1, 2)
qc.cp(pi/4, 0, 2)
qc.h(1)
qc.cp(pi/2, 0, 1)
qc.h(0)
qc.swap(0, 2)
qc.draw()
def qft_rotations(circuit, n):
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
qft_rotations(circuit, n)
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
qc = QuantumCircuit(4)
qft(qc,4)
qc.draw()
# Create the circuit
qc = QuantumCircuit(3)
# Encode the state 5 (101 in binary)
qc.x(0)
qc.x(2)
qc.draw()
sim = Aer.get_backend("aer_simulator")
qc_init = qc.copy()
qc_init.save_statevector()
statevector = sim.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
qft(qc, 3)
qc.draw()
qc.save_statevector()
statevector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(statevector)
|
https://github.com/derivation/ThinkQuantum
|
derivation
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, Aer
from qiskit.tools.visualization import circuit_drawer, plot_histogram
import numpy as np
from numpy import pi
num_measurements = 5
q = QuantumRegister(1)
c = ClassicalRegister(num_measurements)
circ = QuantumCircuit(q,c)
for m in range(num_measurements):
circ.measure(q[0],c[m])
circuit_drawer(circ, output='mpl')
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(circ, backend_sim, shots=1)
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
print(counts)
num_measurements = 5
q = QuantumRegister(1)
c = ClassicalRegister(num_measurements)
circ = QuantumCircuit(q,c)
for m in range(num_measurements):
circ.measure(q[0],c[m])
circ.rx(pi, q[0])
circuit_drawer(circ, output='mpl')
job_sim = execute(circ, backend_sim, shots=1)
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
print(counts)
num_measurements = 1
q = QuantumRegister(1)
c = ClassicalRegister(num_measurements)
circ = QuantumCircuit(q,c)
circ.rx(pi/2, q)
circ.measure(q, c)
circuit_drawer(circ, output='mpl')
job_sim = execute(circ, backend_sim, shots=1)
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
print(counts)
repetitions = 1024
job_sim = execute(circ, backend_sim, shots=repetitions)
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
print(counts)
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit
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 A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
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.896
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price]
slopes = [0, 1]
offsets = [0, 0]
f_min = 0
f_max = high - strike_price
european_call_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
rescaling_factor=c_approx,
)
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
num_qubits = european_call_objective.num_qubits
european_call = QuantumCircuit(num_qubits)
european_call.append(uncertainty_model, range(num_uncertainty_qubits))
european_call.append(european_call_objective, range(num_qubits))
# draw the circuit
european_call.draw()
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = uncertainty_model.values
y = np.maximum(0, x - strike_price)
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[x >= strike_price])
print("exact expected value:\t%.4f" % exact_value)
print("exact delta value: \t%.4f" % exact_delta)
european_call.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=european_call,
objective_qubits=[3],
post_processing=european_call_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))
from qiskit_finance.applications.estimation import EuropeanCallPricing
european_call_pricing = EuropeanCallPricing(
num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
rescaling_factor=c_approx,
bounds=(low, high),
uncertainty_model=uncertainty_model,
)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_pricing.to_estimation_problem()
# 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" % (european_call_pricing.interpret(result)))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
from qiskit_finance.applications.estimation import EuropeanCallDelta
european_call_delta = EuropeanCallDelta(
num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
bounds=(low, high),
uncertainty_model=uncertainty_model,
)
european_call_delta._objective.decompose().draw()
european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits)
european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits))
european_call_delta_circ.append(
european_call_delta._objective, range(european_call_delta._objective.num_qubits)
)
european_call_delta_circ.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_delta.to_estimation_problem()
# 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_processed)
print("Exact delta: \t%.4f" % exact_delta)
print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
gate_counts = []
non_local_gate_counts = []
levels = [str(x) for x in range(4)]
for level in range(4):
circ = transpile(ghz, backend, optimization_level=level)
depths.append(circ.depth())
gate_counts.append(sum(circ.count_ops().values()))
non_local_gate_counts.append(circ.num_nonlocal_gates())
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.bar(levels, depths, label='Depth')
ax1.set_xlabel("Optimization Level")
ax1.set_ylabel("Depth")
ax1.set_title("Output Circuit Depth")
ax2.bar(levels, gate_counts, label='Number of Circuit Operations')
ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates')
ax2.set_xlabel("Optimization Level")
ax2.set_ylabel("Number of gates")
ax2.legend()
ax2.set_title("Number of output circuit gates")
fig.tight_layout()
plt.show()
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import SparsePauliOp
def heisenberg_hamiltonian(
length: int, jx: float = 1.0, jy: float = 0.0, jz: float = 0.0
) -> SparsePauliOp:
terms = []
for i in range(length - 1):
if jx:
terms.append(("XX", [i, i + 1], jx))
if jy:
terms.append(("YY", [i, i + 1], jy))
if jz:
terms.append(("ZZ", [i, i + 1], jz))
return SparsePauliOp.from_sparse_list(terms, num_qubits=length)
def state_prep_circuit(num_qubits: int, layers: int = 1) -> QuantumCircuit:
qubits = QuantumRegister(num_qubits, name="q")
circuit = QuantumCircuit(qubits)
circuit.h(qubits)
for _ in range(layers):
for i in range(0, num_qubits - 1, 2):
circuit.cx(qubits[i], qubits[i + 1])
circuit.ry(0.1, qubits)
for i in range(1, num_qubits - 1, 2):
circuit.cx(qubits[i], qubits[i + 1])
circuit.ry(0.1, qubits)
return circuit
length = 5
hamiltonian = heisenberg_hamiltonian(length, 1.0, 1.0)
circuit = state_prep_circuit(length, layers=2)
print(hamiltonian)
circuit.draw("mpl")
from qiskit_aer.primitives import Estimator
estimator = Estimator(approximation=True)
job = estimator.run(circuit, hamiltonian, shots=None)
result = job.result()
exact_value = result.values[0]
print(f"Exact energy: {exact_value}")
from qiskit_ibm_runtime import QiskitRuntimeService
hub = "ibm-q-internal"
group = "deployed"
project = "default"
service = QiskitRuntimeService(instance=f"{hub}/{group}/{project}")
from qiskit_ibm_runtime import Estimator, Options, Session
from qiskit.transpiler import CouplingMap
backend = service.get_backend("simulator_statevector")
# set simulation options
simulator = {
"basis_gates": ["id", "rz", "sx", "cx", "reset"],
"coupling_map": list(CouplingMap.from_line(length + 1)),
}
shots = 10000
import math
options = Options(
simulator=simulator,
resilience_level=0,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
from qiskit_aer.noise import NoiseModel, ReadoutError
noise_model = NoiseModel()
##### your code here #####
# P(A|B) = [P(A|0), P(A|1)] = [ 1 - q0_01, q0_01 ] = [ 0.8, 0.2 ]
q0_10 = 0.5
q0_01 = 0.2
qn_10 = 0.05
qn_01 = 0.02
re_l = [ReadoutError(
[
[1 - q0_01, q0_01],
[q0_10, 1 - q0_10],
]
)]
n_qubits = 6
for _ in range(n_qubits - 1):
re_l.append(ReadoutError(
[
[1 - qn_01, qn_01],
[qn_10, 1 - qn_10],
]
))
for q in range(n_qubits):
noise_model.add_readout_error(re_l[q], (q, ))
print(noise_model.to_dict())
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex1
grade_lab5_ex1(noise_model)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=0,
transpilation=dict(initial_layout=list(range(length))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=0,
transpilation=dict(initial_layout=list(range(1, length + 1))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
transpilation=dict(initial_layout=list(range(1, length + 1))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
new_shots: int
##### your code here #####
new_shots = 20000
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex2
grade_lab5_ex2(new_shots)
from qiskit_aer.noise import depolarizing_error
noise_model = NoiseModel()
##### your code here #####
error = depolarizing_error(0.01, 2)
noise_model.add_all_qubit_quantum_error(error, ['cx'])
print(noise_model)
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex3
grade_lab5_ex3(noise_model)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=2,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
|
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_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
|
jonasmaziero
|
import math; import numpy as np; phmax = 4*math.pi; npt = 100; dth = phmax/npt; ph = np.arange(0,phmax+dth,dth)
from matplotlib import pyplot as plt; PrD0 = 0.5*(1+np.cos(ph)); plt.plot(ph,PrD0, label=r'$Pr(D_0)$')
PrD0 = 0.5*(1-np.cos(ph)); plt.plot(ph,PrD0, label=r'$Pr(D_1)$'); plt.legend(); plt.xlabel(r'$\phi$'); plt.show()
from sympy import Matrix, sqrt
S = Matrix([[1,0],[0,1j]]); H = (1/sqrt(2))*Matrix([[1,1],[1,-1]])
S*H*S
Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]]); Y*Z
from qiskit import QuantumCircuit
def qc_df(): # divisor de feixes 50:50
qc = QuantumCircuit(1, name='DF')
qc.s(0)
qc.h(0)
qc.s(0)
return qc
qcdf = qc_df(); qcdf.draw('mpl')
def qc_espelhos():
qc = QuantumCircuit(1, name='E')
qc.z(0)
qc.y(0)
return qc
qce = qc_espelhos(); qce.draw('mpl')
def qc_imz(ph): # retorna o circuito quântico para o IMZ (sem as medidas)
qc = QuantumCircuit(1, name='IMZ')
qcdf = qc_df(); qc.append(qcdf, [0])
qce = qc_espelhos(); qc.append(qce, [0])
qc.p(ph, [0])
qcdf = qc_df(); qc.append(qcdf, [0])
return qc
qcimz = qc_imz(0); qcimz.draw('mpl')
# Simulação clássica
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
import numpy as np; import math
phmax = 2*math.pi
npe = 6
dth = phmax/npe
ph = np.arange(0,phmax+dth,dth)
PD0sim = np.zeros(len(ph))
for j in range(0,len(ph)):
qc = QuantumCircuit(1,1)
qcimz = qc_imz(ph[j])
qc.append(qcimz,[0])
qc.measure(0,0)
job = execute(qc, backend=simulator, shots=nshots)
counts = job.result().get_counts()
if '0' in counts:
PD0sim[j] = counts['0']/nshots
print(PD0sim)
npt = 100
dtht = phmax/npt
pht = np.arange(0,phmax+dtht,dtht)
PD0teo = 0.5*(1+np.cos(pht))
from matplotlib import pyplot as plt
plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$')
plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$')
plt.legend(); plt.xlabel(r'$\phi$')
plt.show()
import qiskit
qiskit.IBMQ.save_account('a221013b3d88dd070a495178c3f732ac683a494e5af4e641383f16d361e9fa7fa22af7f09cad3f88988a3e6e5621c7fe951d8ca6ff0c0371422b211ec0ae9709',
overwrite = True)
qiskit.IBMQ.load_account()
#provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main')
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
import numpy as np; import math
phmax = 2*math.pi
npe = 6
dth = phmax/npe
ph = np.arange(0,phmax+dth,dth)
job_ids = []
for j in range(0,len(ph)):
qc = QuantumCircuit(1,1)
qcimz = qc_imz(ph[j])
qc.append(qcimz,[0])
qc.measure(0,0)
job = execute(qc, backend=device, shots=nshots)
jobid = job.job_id()
job_ids.append(jobid)
print(jobid)
f = open("jobs_ids_IMZ.txt", "w")
f.write(str(job_ids))
f.close()
device = provider.get_backend('ibm_nairobi')
f = open("jobs_ids_IMZ.txt","r")
list_ids_IMZ = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
PD0exp = np.zeros(len(ph))
for j in range(0,len(ph)):
job = device.retrieve_job(list_ids_IMZ[j])
counts = job.result().get_counts()
if '0' in counts:
PD0exp[j] = counts['0']/nshots
print(PD0exp)
npt = 100; dtht = phmax/npt; pht = np.arange(0,phmax+dtht,dtht)
PD0teo = 0.5*(1+np.cos(pht))
from matplotlib import pyplot as plt
plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$')
plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$')
plt.plot(ph,PD0exp, '*', label=r'$Pr(D_0)_{exp}$')
plt.legend()
plt.xlabel(r'$\phi$')
plt.show()
Vsim = (np.max(PD0sim)-np.min(PD0sim))/(np.max(PD0sim)+np.min(PD0sim)); print('Vsim = ',Vsim)
Vexp = (np.max(PD0exp)-np.min(PD0exp))/(np.max(PD0exp)+np.min(PD0exp)); print('Vexp = ',Vexp)
from sympy import Matrix, eye; P0 = Matrix([[1,0],[0,0]]); P1 = Matrix([[0,0],[0,1]]); X = Matrix([[0,1],[1,0]])
from sympy.physics.quantum import TensorProduct as tp; tp(eye(2),P0) + tp(X,P1)
def qc_bbo():
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, name='BBO')
qc.x(1)
qc.h(0)
qc.cx(0,1)
return qc
qcbbo = qc_bbo(); qcbbo.draw('mpl')
def qc_dfp():
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, name='DFP')
qc.cz(0,1)
qc.cy(0,1)
return qc
qcdfp = qc_dfp()
qcdfp.draw('mpl')
def qc_pmo():
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, name='PMO')
qc.cx(1,0)
return qc
qcpmo = qc_pmo()
qcpmo.draw('mpl')
def qc_imz_ic(ph): # não consideramos o caminho do fóton A
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, name='IMZIC')
qcbbo = qc_bbo(); qc.append(qcbbo, [0,1])
qcdfp = qc_dfp(); qc.append(qcdfp, [1,2])
qcpmo = qc_pmo(); qc.append(qcpmo, [1,2])
qce = qc_espelhos(); qc.append(qce, [2])
qc.p(ph, [2])
qcdf = qc_df(); qc.append(qcdf, [2])
return qc
qcimzic = qc_imz_ic(0); qcimzic.draw('mpl')
qcimzic.decompose().draw('mpl')
qcimzic.decompose().decompose().decompose().draw('mpl')
# Simulação clássica
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
import numpy as np; import math
phmax = 2*math.pi
npe = 5
dth = phmax/npe
ph = np.arange(0,phmax+dth,dth)
PD0sim = np.zeros(len(ph))
for j in range(0,len(ph)):
qc = QuantumCircuit(3,2)
qcimzic = qc_imz_ic(ph[j])
qc.append(qcimzic,[0,1,2])
qc.measure([0,2],[0,1])
job = execute(qc, backend=simulator, shots=nshots)
counts = job.result().get_counts()
if '00' in counts:
PD0sim[j] = counts['00']/nshots
if '10' in counts:
PD0sim[j] += counts['10']/nshots
print(PD0sim)
qc.draw('mpl')
import numpy as np; import math
phmax = 2*math.pi; npt = 100; dpht = phmax/npt
pht = np.arange(0,phmax+dtht,dtht)
PD0teo = 0.5*np.ones(len(pht))
from matplotlib import pyplot as plt
plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$')
plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$')
plt.ylim(0,1); plt.legend()
plt.xlabel(r'$\phi$')
plt.show()
import qiskit
qiskit.IBMQ.save_account('e20d3045c7c23a3be753606794714e9b47d4331ec46a41b2281e2d601bae27b2b3c1baa0b5cb54f3282a8b5248e552b14c9c556699010660fb94b11d00ff1073',
overwrite = True)
qiskit.IBMQ.load_account()
#provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main')
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
import numpy as np; import math
phmax=2*math.pi
npe=5
dth=phmax/npe
ph=np.arange(0,phmax+dth,dth)
job_ids=[]
for j in range(0,len(ph)):
qc = QuantumCircuit(3,2)
qcimzic = qc_imz_ic(ph[j])
qc.append(qcimzic,[0,1,2])
qc.measure([0,2],[0,1])
job = execute(qc, backend=device, shots=nshots)
jobid = job.job_id()
job_ids.append(jobid)
f = open("jobs_ids_IMZIC.txt", "w")
f.write(str(job_ids))
f.close()
print(job_ids)
f = open("jobs_ids_IMZIC.txt","r")
list_ids_IMZIC = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
phmax = 2*math.pi
npe=5
dth = phmax/npe
ph = np.arange(0,phmax+dth,dth)
PD0exp = np.zeros(len(ph))
device = provider.get_backend('ibm_nairobi')
for j in range(0,len(ph)):
job = device.retrieve_job(list_ids_IMZIC[j])
counts = job.result().get_counts()
if '00' in counts:
PD0exp[j] = counts['00']/nshots
if '10' in counts:
PD0exp[j] += counts['10']/nshots
print(PD0exp)
import numpy as np; import math
phmax = 2*math.pi; npt = 100; dpht = phmax/npt
pht = np.arange(0,phmax+dtht,dtht)
PD0teo = 0.5*np.ones(len(pht))
from matplotlib import pyplot as plt
plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$')
plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$')
plt.plot(ph,PD0exp, '*', label=r'$Pr(D_0)_{exp}$')
plt.ylim(0,1); plt.legend(); plt.xlabel(r'$\phi$'); plt.show()
Vsim = (np.max(PD0sim)-np.min(PD0sim))/(np.max(PD0sim)+np.min(PD0sim)); print('Vsim = ',Vsim)
Vexp = (np.max(PD0exp)-np.min(PD0exp))/(np.max(PD0exp)+np.min(PD0exp)); print('Vexp = ',Vexp)
import numpy as np; import math; phmax = 2*math.pi; npt = 100; dpht = phmax/npt; pht = np.arange(0,phmax+dpht,dpht)
PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht))
from matplotlib import pyplot as plt
plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$'); plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$')
plt.xlim(0,2*math.pi); plt.xlim(-0.1,phmax+0.1); plt.ylim(-0.01,1.01); plt.legend(); plt.xlabel(r'$\phi$'); plt.show()
def qc_pqo():
from qiskit import QuantumCircuit
qc = QuantumCircuit(1, name='PQO')
qc.h(0)
qc.s(0)
return qc
qcpqo = qc_pqo()
qcpqo.draw('mpl')
def qc_apagadorQ(ph):
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
qcimzic = qc_imz_ic(ph)
qc.append(qcimzic, [0,1,2])
qcpqo = qc_pqo()
qc.append(qcpqo, [0])
return qc
qcaq = qc_apagadorQ(0)
qcaq.decompose().draw('mpl')
# Simulação clássica
from qiskit import Aer, execute; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13
import numpy as np; import math; phmax = 2*math.pi; npe = 6; dth = phmax/npe; ph = np.arange(0,phmax+dth,dth)
PA0sim = np.zeros(len(ph)); PA1sim = np.zeros(len(ph)); PD0A0sim = np.zeros(len(ph)); PD0A1sim = np.zeros(len(ph))
for j in range(0,len(ph)):
qc = QuantumCircuit(3,2)
qcaq = qc_apagadorQ(ph[j])
qc.append(qcaq,[0,1,2])
qc.measure([0,2],[0,1])
job = execute(qc, backend=simulator, shots=nshots)
counts = job.result().get_counts()
if '00' in counts:
PA0sim[j] = counts['00']/nshots
if '01' in counts:
PA0sim[j] += counts['01']/nshots
if '10' in counts:
PA1sim[j] = counts['10']/nshots
if '11' in counts:
PA1sim[j] += counts['11']/nshots
if PA0sim[j] != 0 and '00' in counts:
PD0A0sim[j] = (counts['00']/nshots)/PA0sim[j]
if PA1sim[j] != 0 and '10' in counts:
PD0A1sim[j] = (counts['10']/nshots)/PA1sim[j]
print(PD0A0sim, PD0A1sim)
import numpy as np; import math
phmax = 2*math.pi; npt = 100; dpht = phmax/npt; pht = np.arange(0,phmax+dpht,dpht)
PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht))
from matplotlib import pyplot as plt
plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$')
plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$')
plt.plot(ph,PD0A0sim, 'o', label=r'$Pr(D_0|A=0)_{sim}$')
plt.plot(ph,PD0A1sim, 's', label=r'$Pr(D_0|A=1)_{sim}$')
plt.xlim(-0.1,2*math.pi+0.1); plt.ylim(-0.01,1.02); plt.legend(); plt.xlabel(r'$\phi$'); plt.show()
import qiskit
qiskit.IBMQ.save_account('dabd4674f7b3794f740813fec0c5478bfefdebb7d1dca9b7acd41e3f90ed2c8a8b80af26fb3236289fbfc70d0ea334829a836453ac46f96fee68abcb22495ef4',
overwrite = True)
qiskit.IBMQ.load_account()
#provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main')
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
import numpy as np; import math
phmax=2*math.pi
npe=6
dth=phmax/npe
ph=np.arange(0,phmax+dth,dth)
job_ids=[]
for j in range(0,len(ph)):
qc = QuantumCircuit(3,2)
qcaq = qc_apagadorQ(ph[j])
qc.append(qcaq,[0,1,2])
qc.measure([0,2],[0,1])
job = execute(qc, backend=device, shots=nshots)
jobid = job.job_id()
job_ids.append(jobid)
print(jobid)
f = open("jobs_ids_apagador.txt", "w")
f.write(str(job_ids))
f.close()
f = open("jobs_ids_apagador.txt","r")
list_ids_apagador = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
phmax = 2*math.pi; npe=6; dth = phmax/npe; ph = np.arange(0,phmax+dth,dth)
PD0A0exp = np.zeros(len(ph)); PD0A1exp = np.zeros(len(ph)); PA0exp = np.zeros(len(ph)); PA1exp = np.zeros(len(ph))
device = provider.get_backend('ibm_nairobi')
for j in range(0,len(ph)):
job = device.retrieve_job(list_ids_apagador[j])
counts = job.result().get_counts()
if '00' in counts:
PA0exp[j] = counts['00']/nshots
if '01' in counts:
PA0exp[j] += counts['01']/nshots
if '10' in counts:
PA1exp[j] = counts['10']/nshots
if '11' in counts:
PA1exp[j] += counts['11']/nshots
if PA0exp[j] != 0 and '00' in counts:
PD0A0exp[j] = (counts['00']/nshots)/PA0exp[j]
if PA1exp[j] != 0 and '10' in counts:
PD0A1exp[j] = (counts['10']/nshots)/PA1exp[j]
print(PD0A0exp,PD0A1exp)
import numpy as np; import math
phmax = 2*math.pi; npt = 100; dpht = phmax/npt
pht = np.arange(0,phmax+dpht,dpht)
PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht))
from matplotlib import pyplot as plt
plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$'); plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$')
plt.plot(ph,PD0A0sim, 'o', label=r'$Pr(D_0|A=0)_{sim}$'); plt.plot(ph,PD0A1sim, 's', label=r'$Pr(D_0|A=1)_{sim}$')
plt.plot(ph,PD0A0exp, '*', label=r'$Pr(D_0|A=0)_{exp}$'); plt.plot(ph,PD0A1exp, '+', label=r'$Pr(D_0|A=1)_{exp}$')
plt.xlim(-0.1,2*math.pi+0.1); plt.ylim(-0.02,1.02); plt.legend(bbox_to_anchor=(1.4, 1.0),loc='upper right')
plt.xlabel(r'$\phi$'); plt.show()
VsimA0 = (np.max(PD0A0sim)-np.min(PD0A0sim))/(np.max(PD0A0sim)+np.min(PD0A0sim))
print('VsimA0 = ',VsimA0)
VsimA1 = (np.max(PD0A1sim)-np.min(PD0A1sim))/(np.max(PD0A1sim)+np.min(PD0A1sim))
print('VsimA1 = ',VsimA1)
VexpA0 = (np.max(PD0A0exp)-np.min(PD0A0exp))/(np.max(PD0A0exp)+np.min(PD0A0exp))
print('VexpA0 = ',VexpA0)
VexpA1 = (np.max(PD0A1exp)-np.min(PD0A1exp))/(np.max(PD0A1exp)+np.min(PD0A1exp))
print('VexpA1 = ',VexpA1)
import qiskit
qiskit.IBMQ.save_account('e20d3045c7c23a3be753606794714e9b47d4331ec46a41b2281e2d601bae27b2b3c1baa0b5cb54f3282a8b5248e552b14c9c556699010660fb94b11d00ff1073',
overwrite = True)
qiskit.IBMQ.load_account()
#provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main')
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
from qiskit import QuantumRegister, execute
from qiskit.ignis.mitigation.measurement import complete_meas_cal
qr = QuantumRegister(3)
qubit_list = [0, 2]
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr)
job = execute(meas_calibs, backend=device, shots=nshots)
print(job.job_id())
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
job = device.retrieve_job('cmp2xzqyj8fg0080m0e0')
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels)
f = open("jobs_ids_apagador.txt","r")
list_ids_apagador = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
phmax = 2*math.pi; npe=6; dth = phmax/npe; ph = np.arange(0,phmax+dth,dth)
PD0A0exp_mit = np.zeros(len(ph)); PD0A1exp_mit = np.zeros(len(ph)); PA0exp_mit = np.zeros(len(ph)); PA1exp_mit = np.zeros(len(ph))
device = provider.get_backend('ibm_nairobi')
for j in range(0,len(ph)):
job = device.retrieve_job(list_ids_apagador[j])
mitigated_results = meas_fitter.filter.apply(job.result())
mitigated_counts = mitigated_results.get_counts()
if '00' in counts:
PA0exp_mit[j] = mitigated_counts['00']/nshots
if '01' in counts:
PA0exp_mit[j] += mitigated_counts['01']/nshots
if '10' in counts:
PA1exp_mit[j] = mitigated_counts['10']/nshots
if '11' in counts:
PA1exp_mit[j] += mitigated_counts['11']/nshots
if PA0exp_mit[j] != 0 and '00' in mitigated_counts:
PD0A0exp_mit[j] = (mitigated_counts['00']/nshots)/PA0exp[j]
if PA1exp[j] != 0 and '10' in mitigated_counts:
PD0A1exp_mit[j] = (mitigated_counts['10']/nshots)/PA1exp[j]
print(PD0A0exp_mit, PD0A1exp_mit)
import matplotlib; matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (7,5), dpi = 100)
import numpy as np; import math; phmax = 2*math.pi; npt = 100; dpht = phmax/npt; pht = np.arange(0,phmax+dpht,dpht)
PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht)); from matplotlib import pyplot as plt
plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$'); plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$')
plt.plot(ph,PD0A0sim, 'o', label=r'$Pr(D_0|A=0)_{sim}$'); plt.plot(ph,PD0A1sim, 's', label=r'$Pr(D_0|A=1)_{sim}$')
plt.plot(ph,PD0A0exp, '*', label=r'$Pr(D_0|A=0)_{exp}$'); plt.plot(ph,PD0A1exp, 'v', label=r'$Pr(D_0|A=1)_{exp}$')
plt.plot(ph,PD0A0exp_mit, '^', label=r'$Pr(D_0|A=0)_{expmit}$'); plt.plot(ph,PD0A1exp_mit, '+', label=r'$Pr(D_0|A=1)_{expmit}$')
plt.xlim(-0.1,2*math.pi+0.1); plt.ylim(-0.03,1.03); plt.legend(bbox_to_anchor=(1.4, 1.0),loc='upper right')
plt.xlabel(r'$\phi$'); plt.show()
VsimA0 = (np.max(PD0A0sim)-np.min(PD0A0sim))/(np.max(PD0A0sim)+np.min(PD0A0sim)); print('VsimA0 = ',VsimA0)
VsimA1 = (np.max(PD0A1sim)-np.min(PD0A1sim))/(np.max(PD0A1sim)+np.min(PD0A1sim)); print('VsimA1 = ',VsimA1)
VexpA0 = (np.max(PD0A0exp)-np.min(PD0A0exp))/(np.max(PD0A0exp)+np.min(PD0A0exp)); print('VexpA0 = ',VexpA0)
VexpA1 = (np.max(PD0A1exp)-np.min(PD0A1exp))/(np.max(PD0A1exp)+np.min(PD0A1exp)); print('VexpA1 = ',VexpA1)
VexpA0_mit = (np.max(PD0A0exp_mit)-np.min(PD0A0exp_mit))/(np.max(PD0A0exp_mit)+np.min(PD0A0exp_mit))
print('VexpA0_mit = ',VexpA0_mit)
VexpA1_mit = (np.max(PD0A1exp_mit)-np.min(PD0A1exp_mit))/(np.max(PD0A1exp_mit)+np.min(PD0A1exp_mit))
print('VexpA1_mit = ',VexpA1_mit)
import math; import numpy as np
al_max = math.pi/4; npt = 100; dalt = al_max/npt
alt = np.arange(0,al_max+dalt,dalt)
Vteo = np.sin(2*alt)
from matplotlib import pyplot as plt
plt.plot(alt,Vteo, label=r'$V_{teo}(A=0)$')
plt.xlim(-0.01,al_max+0.01); plt.ylim(-0.01,1.01)
plt.xlabel(r'$\alpha$'); plt.legend()
plt.show()
from qiskit import QuantumCircuit
def qc_Psi(al): # prepara o estado parcialmente emaranhado
qc = QuantumCircuit(2, name = r'$|\Psi\rangle$')
qc.u(2*al,0,0, 0)
qc.cx(0,1)
qc.z(0)
qc.x(1)
return qc
qcpsi = qc_Psi(0.1); qcpsi.draw('mpl')
# simulação clássica
from qiskit import Aer, execute; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13
import math; import numpy as np
almax = math.pi/4; npa=2; dal = almax/npa; al = np.arange(0,almax+dal,dal)
phmax = 2*math.pi; npe=4; dph = phmax/npe; ph = np.arange(0,phmax+dph,dph); VA0sim = np.zeros(len(al))
for j in range(0,len(al)):
PD0A0sim = np.zeros(len(ph)); PA0sim = np.zeros(len(ph))
for k in range(0,len(ph)):
qc = QuantumCircuit(3,2)
qcpsi = qc_Psi(al[j]); qc.append(qcpsi, [0,1])
qcdfp = qc_dfp(); qc.append(qcdfp, [1,2]); qcpmo = qc_pmo(); qc.append(qcpmo, [1,2])
qce = qc_espelhos(); qc.append(qce, [2]); qc.p(ph[k], [2])
qcdf = qc_df(); qc.append(qcdf, [2]); qcpqo = qc_pqo(); qc.append(qcpqo, [0])
qc.measure([0,2],[0,1])
job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts()
if '00' in counts:
PA0sim[k] = counts['00']/nshots
if '01' in counts:
PA0sim[k] += counts['01']/nshots
if PA0sim[k] != 0:
if '00' in counts:
PD0A0sim[k] = (counts['00']/nshots)/PA0sim[k]
VA0sim[j] = (np.max(PD0A0sim)-np.min(PD0A0sim))/(np.max(PD0A0sim)+np.min(PD0A0sim))
VA0sim
PD0A0sim
qc.draw('mpl')
import math; import numpy as np
al_max = math.pi/4; npt = 100; dalt = al_max/npt; alt = np.arange(0,al_max+dalt,dalt)
Vteo = np.sin(2*alt)
from matplotlib import pyplot as plt
plt.plot(alt,Vteo, label=r'$V_{teo}(A=0)$')
plt.plot(al,VA0sim, 'o', label=r'$V_{sim}(A=0)$')
plt.xlim(-0.01,al_max+0.01); plt.ylim(-0.01,1.02); plt.xlabel(r'$\alpha$'); plt.legend()
plt.show()
# Experimento (simulação quântica)
from qiskit import execute; import math; import numpy as np
almax = math.pi/4; npa = 2; dal = almax/npa; al = np.arange(0,almax+dal,dal)
phmax = 2*math.pi; npe=4; dph = phmax/npe; ph = np.arange(0,phmax+dph,dph)
job_ids=[]
for j in range(0,len(al)):
for k in range(0,len(ph)):
qc = QuantumCircuit(3,2); qcpsi = qc_Psi(al[j]); qc.append(qcpsi, [0,1])
qcdfp = qc_dfp(); qc.append(qcdfp, [1,2]); qcpmo = qc_pmo(); qc.append(qcpmo, [1,2])
qce = qc_espelhos(); qc.append(qce, [2]); qc.p(ph[k], [2])
qcdf = qc_df(); qc.append(qcdf, [2]); qcpqo = qc_pqo(); qc.append(qcpqo, [0]); qc.measure([0,2],[0,1])
job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); job_ids.append(jobid); print(jobid)
f = open("jobs_ids_apagador_parcial.txt", "w"); f.write(str(job_ids)); f.close()
f = open("jobs_ids_apagador_parcial.txt","r")
list_ids_apagador_parcial = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
import math; import numpy as np
almax = math.pi/4; npa=2; dal = almax/npa; al = np.arange(0,almax+dal,dal)
phmax = 2*math.pi; npe=4; dph = phmax/npe; ph = np.arange(0,phmax+dph,dph); VA0exp = np.zeros(len(al))
for j in range(0,len(al)):
PD0A0exp = np.zeros(len(ph)); PA0exp = np.zeros(len(ph))
for k in range(0,len(ph)):
job = device.retrieve_job(list_ids_apagador_parcial[(npe+1)*j+k])
counts = job.result().get_counts()
if '00' in counts:
PA0exp[k] = counts['00']/nshots
if '01' in counts:
PA0exp[k] += counts['01']/nshots
if PA0exp[k] != 0:
if '00' in counts:
PD0A0exp[k] = (counts['00']/nshots)/PA0exp[k]
VA0exp[j] = (np.max(PD0A0exp)-np.min(PD0A0exp))/(np.max(PD0A0exp)+np.min(PD0A0exp))
VA0exp
import math; import numpy as np
al_max = math.pi/4; npt = 100; dalt = al_max/npt; alt = np.arange(0,al_max+dalt,dalt); Vteo = np.sin(2*alt)
from matplotlib import pyplot as plt
plt.plot(alt,Vteo, label=r'$V_{teo}(A=0)$')
plt.plot(al,VA0sim, 'o', label=r'$V_{sim}(A=0)$')
plt.plot(al,VA0exp, '^', label=r'$V_{exp}(A=0)$')
plt.xlim(-0.01,al_max+0.01); plt.ylim(-0.01,1.02); plt.xlabel(r'$\alpha$'); plt.legend()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.barrier()
circuit.h(0)
circuit = RemoveBarriers()(circuit)
circuit.draw('mpl')
|
https://github.com/mistryiam/IBM-Qiskit-Machine-Learning
|
mistryiam
|
# General Imports
import numpy as np
# Visualisation Imports
import matplotlib.pyplot as plt
# Scikit Imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Qiskit Imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# Load digits dataset
digits = datasets.load_digits(n_class=2)
# Plot example '0' and '1'
fig, axs = plt.subplots(1, 2, figsize=(6,3))
axs[0].set_axis_off()
axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest')
axs[1].set_axis_off()
axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
# Split dataset
sample_train, sample_test, label_train, label_test = train_test_split(
digits.data, digits.target, test_size=0.2, random_state=22)
# Reduce dimensions
n_dim = 4
pca = PCA(n_components=n_dim).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Normalise
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Scale
samples = np.append(sample_train, sample_test, axis=0)
minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
sample_train = minmax_scale.transform(sample_train)
sample_test = minmax_scale.transform(sample_test)
# Select
train_size = 100
sample_train = sample_train[:train_size]
label_train = label_train[:train_size]
test_size = 20
sample_test = sample_test[:test_size]
label_test = label_test[:test_size]
print(sample_train[0], label_train[0])
print(sample_test[0], label_test[0])
# 3 features, depth 2
map_z = ZFeatureMap(feature_dimension=3, reps=2)
map_z.draw('mpl')
# 3 features, depth 1
map_zz = ZZFeatureMap(feature_dimension=3, reps=1)
map_zz.draw('mpl')
# 3 features, depth 1, linear entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear')
map_zz.draw('mpl')
# 3 features, depth 1, circular entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular')
map_zz.draw('mpl')
# 3 features, depth 1
map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ'])
map_pauli.draw('mpl')
def custom_data_map_func(x):
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x))
return coeff
map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'],
data_map_func=custom_data_map_func)
#map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map
twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'],
entanglement_blocks='cx', entanglement='circular', insert_barriers=True)
twolocal.draw('mpl')
twolocaln = NLocal(num_qubits=3, reps=2,
rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))],
entanglement_blocks=CXGate(),
entanglement='circular', insert_barriers=True)
twolocaln.draw('mpl')
# rotation block:
rot = QuantumCircuit(2)
params = ParameterVector('r', 2)
rot.ry(params[0], 0)
rot.rz(params[1], 1)
# entanglement block:
ent = QuantumCircuit(4)
params = ParameterVector('e', 3)
ent.crx(params[0], 0, 1)
ent.crx(params[1], 1, 2)
ent.crx(params[2], 2, 3)
nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent,
entanglement='linear', insert_barriers=True)
nlocal.draw('mpl')
qubits = 3
repeats = 2
x = ParameterVector('x', length=qubits)
var_custom = QuantumCircuit(qubits)
for _ in range(repeats):
for i in range(qubits):
var_custom.rx(x[i], i)
for i in range(qubits):
for j in range(i + 1, qubits):
var_custom.cx(i, j)
var_custom.p(x[i] * x[j], j)
var_custom.cx(i, j)
var_custom.barrier()
var_custom.draw('mpl')
print(sample_train[0])
encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
encode_circuit = encode_map.bind_parameters(sample_train[0])
encode_circuit.draw(output='mpl')
x = [-0.1,0.2]
# YOUR CODE HERE
encode_map_x =ZZFeatureMap(feature_dimension=2, reps=4)
ex1_circuit =encode_map_x.bind_parameters(x)
ex1_circuit.draw(output='mpl')
from qc_grader import grade_lab3_ex1
# Note that the grading function is expecting a quantum circuit
grade_lab3_ex1(ex1_circuit)
zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator'))
print(sample_train[0])
print(sample_train[1])
zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1])
zz_circuit.decompose().decompose().draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(zz_circuit, backend, shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts = job.result().get_counts(zz_circuit)
counts['0000']/sum(counts.values())
matrix_train = zz_kernel.evaluate(x_vec=sample_train)
matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(np.asmatrix(matrix_train),
interpolation='nearest', origin='upper', cmap='Blues')
axs[0].set_title("training kernel matrix")
axs[1].imshow(np.asmatrix(matrix_test),
interpolation='nearest', origin='upper', cmap='Reds')
axs[1].set_title("testing kernel matrix")
plt.show()
x = [-0.1,0.2]
y = [0.4,-0.6]
# YOUR CODE HERE
encode_map_x2 = ZZFeatureMap(feature_dimension=2, reps=4)
zz_kernel_x2 =QuantumKernel(feature_map=encode_map_x2,quantum_instance=Aer.get_backend('statevector_simulator'))
zz_circuit_x2 =zz_kernel_x2.construct_circuit(x,y)
backend =Aer.get_backend('qasm_simulator')
job = execute(zz_circuit_x2,backend,shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts_x2 = job.result().get_counts(zz_circuit_x2)
amplitude= counts_x2['00']/sum(counts_x2.values())
from qc_grader import grade_lab3_ex2
# Note that the grading function is expecting a floating point number
grade_lab3_ex2(amplitude)
zzpc_svc = SVC(kernel='precomputed')
zzpc_svc.fit(matrix_train, label_train)
zzpc_score = zzpc_svc.score(matrix_test, label_test)
print(f'Precomputed kernel classification test score: {zzpc_score}')
zzcb_svc = SVC(kernel=zz_kernel.evaluate)
zzcb_svc.fit(sample_train, label_train)
zzcb_score = zzcb_svc.score(sample_test, label_test)
print(f'Callable kernel classification test score: {zzcb_score}')
classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid']
for kernel in classical_kernels:
classical_svc = SVC(kernel=kernel)
classical_svc.fit(sample_train, label_train)
classical_score = classical_svc.score(sample_test, label_test)
print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from collections import OrderedDict
from qiskit import LegacySimulators
from qiskit.transpiler import PassManager
from qiskit_aqua import AquaError
from qiskit_aqua import QuantumInstance
from qiskit_aqua.algorithms import ExactEigensolver
from qiskit_aqua.algorithms import QPE
from qiskit_aqua.components.iqfts import Standard
from qiskit_chemistry import FermionicOperator
from qiskit_chemistry import QiskitChemistry
from qiskit_chemistry.drivers import ConfigurationManager
from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock
import time
distance = 0.735
cfg_mgr = ConfigurationManager()
pyscf_cfg = OrderedDict([
('atom', 'H .0 .0 .0; H .0 .0 {}'.format(distance)),
('unit', 'Angstrom'),
('charge', 0),
('spin', 0),
('basis', 'sto3g')
])
section = {}
section['properties'] = pyscf_cfg
try:
driver = cfg_mgr.get_driver_instance('PYSCF')
except ModuleNotFoundError:
raise AquaError('PYSCF driver does not appear to be installed')
molecule = driver.run(section)
qubit_mapping = 'parity'
fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals)
qubit_op = fer_op.mapping(map_type=qubit_mapping,threshold=1e-10).two_qubit_reduced_operator(2)
exact_eigensolver = ExactEigensolver(qubit_op, k=1)
result_ee = exact_eigensolver.run()
reference_energy = result_ee['energy']
print('The exact ground state energy is: {}'.format(result_ee['energy']))
num_particles = molecule.num_alpha + molecule.num_beta
two_qubit_reduction = True
num_orbitals = qubit_op.num_qubits + (2 if two_qubit_reduction else 0)
num_time_slices = 50
n_ancillae = 9
state_in = HartreeFock(qubit_op.num_qubits, num_orbitals,
num_particles, qubit_mapping, two_qubit_reduction)
iqft = Standard(n_ancillae)
qpe = QPE(qubit_op, state_in, iqft, num_time_slices, n_ancillae,
paulis_grouping='random', expansion_mode='suzuki',
expansion_order=2, shallow_circuit_concat=True)
backend = LegacySimulators.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=100, pass_manager=PassManager())
result_qpe = qpe.run(quantum_instance)
print('The ground state energy as computed by QPE is: {}'.format(result_qpe['energy']))
molecule = 'H .0 .0 0; H .0 .0 {}'.format(distance)
# Input dictionary to configure Qiskit Chemistry for the chemistry problem.
qiskit_chemistry_qpe_dict = {
'driver': {'name': 'PYSCF'},
'PYSCF': {
'atom': molecule,
'basis': 'sto3g'
},
'operator': {'name': 'hamiltonian', 'transformation': 'full', 'qubit_mapping': 'parity'},
'algorithm': {
'name': 'QPE',
'num_ancillae': 9,
'num_time_slices': 50,
'expansion_mode': 'suzuki',
'expansion_order': 2,
},
'initial_state': {'name': 'HartreeFock'},
'backend': {'shots': 100}
}
qiskit_chemistry_ees_dict = {
'driver': {'name': 'PYSCF'},
'PYSCF': {'atom': molecule, 'basis': 'sto3g'},
'operator': {'name': 'hamiltonian', 'transformation': 'full', 'qubit_mapping': 'parity'},
'algorithm': {
'name': 'ExactEigensolver',
}
}
result_qpe = QiskitChemistry().run(qiskit_chemistry_qpe_dict, backend=backend)
result_ees = QiskitChemistry().run(qiskit_chemistry_ees_dict)
print('The groundtruth total ground state energy is {}.'.format(
result_ees['energy'] - result_ees['nuclear_repulsion_energy']
))
print('The total ground state energy as computed by QPE is {}.'.format(
result_qpe['energy'] - result_qpe['nuclear_repulsion_energy']
))
print('In comparison, the Hartree-Fock ground state energy is {}.'.format(
result_ees['hf_energy'] - result_ees['nuclear_repulsion_energy']
))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.