repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/mentesniker/Quantum-error-mitigation
|
mentesniker
|
# Import libraries for use
from qiskit import *
import numpy as np
from random import random
from qiskit.extensions import Initialize
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit_textbook.tools import random_state, array_to_latex
## SETUP
# Protocol uses 4 qubits and 1 classical bit in a register
qr = QuantumRegister(4, name="q") # Protocol uses 4 qubits
cr = ClassicalRegister(1, name="cr") # and 1 classical bit cr
sign_flip_circuit = QuantumCircuit(qr, cr)
def encoding(qc, q0, q1, q2):
"""Creates encoding process using qubits q0 & q1 & q2"""
qc.cx(q0,q1) # CNOT with q1 as control and q0 as target (Use q1 to control q0.)
qc.cx(q0,q2) # CNOT with q2 as control and q0 as target
# initialization instruction to create
# |ψ⟩ from the state |0⟩:
p = 1 # p stands for the probability of sign-fliping the state of the qubit
psi = [np.sqrt(1-p), np.sqrt(p)]
init_gate = Initialize(psi) # initialize the superposition state
init_gate.label = "init"
def error_simulation(qc, q0, q1, q2, q3):
"""Creates error simulation using qubits q0 & q1 & q2 & q3"""
qc.append(init_gate, [3]) # create the superposition state for |q3>
measure(qc, 3, 0) # measure the state on |q3>
qc.z(q0).c_if(cr, 1) # apply z gate on q0 if |1> was measured by |q3>
qc.append(init_gate, [3])
measure(qc, 3, 0)
qc.z(q1).c_if(cr, 1) # apply z gate on q1 if |1> was measured by |q3>
qc.append(init_gate, [3])
measure(qc, 3, 0)
qc.z(q2).c_if(cr, 1) # apply z gate on q2 if |1> was measured by |q3>
def measure(qc, q0, cr):
"""Measures qubit q0 """
qc.barrier()
qc.measure(q0,cr)
def decoding(qc, q0, q1, q2):
"""Creates decoding process using qubits q0 & q1 & q2"""
qc.cx(q0,q1) # CNOT with q1 as control and q0 as target
qc.cx(q0,q2) # CNOT with q2 as control and q0 as target
qc.ccx(q2,q1,q0) # Apply a Toffoli gate |011> <-> |111>
# Let's apply the process above to our circuit:
# step 0. input |0> -> |+>
sign_flip_circuit.h(0)
# step 1. encoding
encoding(sign_flip_circuit, 0, 1, 2)
sign_flip_circuit.h(0)
sign_flip_circuit.h(1)
sign_flip_circuit.h(2)
# step 2. error simulation
error_simulation(sign_flip_circuit, 0, 1, 2, p)
sign_flip_circuit.barrier()
# step 3. decoding
sign_flip_circuit.h(0)
sign_flip_circuit.h(1)
sign_flip_circuit.h(2)
decoding(sign_flip_circuit, 0, 1, 2)
# step 4. measurement
sign_flip_circuit.h(0)
measure(sign_flip_circuit, 0, 0)
# View the circuit:
%matplotlib inline
sign_flip_circuit.draw(output='mpl')
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(sign_flip_circuit, backend, shots=1024).result().get_counts() # No. of measurement shots = 1024
plot_histogram(counts)
|
https://github.com/lvillasen/Quantum-Teleportation-with-Qiskit-on-a-Real-Computer
|
lvillasen
|
!pip install qiskit
!pip install pylatexenc
import numpy as np
from qiskit.visualization import array_to_latex
from qiskit.quantum_info import random_statevector
psi = random_statevector(2)
display(array_to_latex(psi, prefix="|\\psi\\rangle ="))
from qiskit import QuantumCircuit, assemble, Aer
import qiskit.quantum_info as qi
import numpy as np
import qiskit.quantum_info as qi
qc = QuantumCircuit(3,2)
qc.initialize(psi, 0)
stv0 = qi.Statevector.from_instruction(qc)
qc.barrier()
qc.h(1) # Hadamard
qc.cx(1,2) # CNOT
qc.barrier()
qc.cx(0,1)
qc.h(0)
qc.barrier()
stv = qi.Statevector.from_instruction(qc)
qc.measure(0,0)
qc.measure(1,1)
qc.draw("mpl")
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(stv0)
from qiskit import QuantumCircuit, Aer,execute
from qiskit.visualization import plot_histogram
backend = Aer.get_backend("qasm_simulator")
shots = 1000
#backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1)
print(job.result().get_counts(qc))
plot_histogram(job.result().get_counts())
import qiskit.quantum_info as qi
import numpy as np
qc1 = QuantumCircuit(3,2)
print(job.result().get_counts())
for key in job.result().data()["counts"]:
if int(key,0) == 0 :
print("Result: 00")
q2_state = [np.round(stv[0],3),np.round(stv[4],3)]
qc1.initialize(0, 0)
qc1.initialize(0, 1)
elif int(key,0) == 1 :
print("Result: 01")
q2_state = [np.round(stv[1],3),np.round(stv[5],3)]
qc1.initialize(1, 0)
qc1.initialize(0, 1)
elif int(key,0) == 2 :
print("Result: 10")
q2_state = [np.round(stv[2],3),np.round(stv[6],3)]
qc1.initialize(0, 0)
qc1.initialize(1, 1)
elif int(key,0) == 3 :
print("Result: 11")
q2_state = [np.round(stv[3],3),np.round(stv[7],3)]
qc1.initialize(1, 0)
qc1.initialize(1, 1)
q2_normalizado = q2_state/np.linalg.norm(q2_state)
qc1.barrier()
qc1.initialize(q2_normalizado, 2)
for key in job.result().data()["counts"]:
if int(key,0) == 1 :
qc1.z(2)
if int(key,0) == 2 :
qc1.x(2)
if int(key,0) == 3 :
qc1.x(2)
qc1.z(2)
stv1 = qi.Statevector.from_instruction(qc1)
stv1.draw('latex', prefix='Estado \quad del \quad qubit \quad 2 = ')
import qiskit.quantum_info as qi
import numpy as np
qc2 = QuantumCircuit(3,2)
for key in job.result().data(qc)["counts"]:
if int(key,0) != 0 :
qc2.initialize(psi, 2)
qcc = qc.compose(qc1)
qc3 = qcc.compose(qc2)
qc3.draw("mpl")
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(stv1)
from qiskit import IBMQ
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.ibmq import least_busy
IBMQ.save_account('CLAVE',overwrite=True) # See https://quantum-computing.ibm.com/
IBMQ.load_account() # Load account from disk
print(IBMQ.providers()) # List all available providers
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
from qiskit_aer.noise import NoiseModel
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_manila')
noise_model = NoiseModel.from_backend(backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)
from qiskit import QuantumCircuit, assemble, Aer
from qiskit import IBMQ, transpile
from qiskit.providers.ibmq import least_busy
from qiskit.tools.visualization import plot_histogram
import qiskit.quantum_info as qi
import numpy as np
import qiskit.quantum_info as qi
theta=np.pi*np.random.rand()
phi = 2*np.pi*np.random.rand()
print("theta =",np.round(theta,2),"rad, theta =",np.round(180*theta/np.pi,2),"degrees")
print("phi=",np.round(phi,2),"rad, phi =",np.round(180*phi/np.pi,2),"degrees")
qc = QuantumCircuit(3,3)
qc.ry(theta,0)
qc.rz(phi,0)
stv0 = qi.Statevector.from_instruction(qc)
qc.barrier()
qc.h(1) # Hadamard
qc.cx(1,2) # CNOT
qc.barrier()
qc.cx(0,1)
qc.h(0)
qc.barrier()
qc.rz(-phi,2)
qc.ry(-theta,2)
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.draw("mpl")
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(stv0)
from qiskit import IBMQ, transpile
sim_backend = AerSimulator.from_backend(backend)
print("least busy backend: ", sim_backend)
# Transpile the circuit for the noisy basis gates
tqc = transpile(qc, sim_backend,optimization_level=3)
# Execute noisy simulation and get counts
job = sim_backend.run(tqc,shots=1000)
print("Counts for teleportation with simulated noise model for", backend,"\n\n")
try :
n_error = job.result().get_counts(qc)['100']
except:
n_error = 0
import matplotlib.pyplot as plt
try :
n_error = job.result().get_counts(qc)['100']
except:
n_error = 0
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,6))
states = ['000', '100']
counts = [job.result().get_counts(qc)['000'],n_error]
plt.rcParams.update({'font.size': 20})
plt.bar(states,counts,width=0.4, bottom=None,align='center', data=None)
for index, value in enumerate(counts):
plt.text(index, value, str(value),fontsize=20)
plt.xlabel('States',fontsize=20)
plt.ylabel('Counts',fontsize=20)
plt.show()
tqc.draw("mpl")
from qiskit import IBMQ
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.ibmq import least_busy
IBMQ.load_account() # Load account from disk
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)
from qiskit import QuantumCircuit, assemble, Aer
from qiskit.providers.ibmq import least_busy
from qiskit.tools.visualization import plot_histogram
import qiskit.quantum_info as qi
import numpy as np
import qiskit.quantum_info as qi
theta=np.pi*np.random.rand()
phi = 2*np.pi*np.random.rand()
print("theta =",np.round(theta,2),"rad, theta =",np.round(180*theta/np.pi,2),"degrees")
print("phi=",np.round(phi,2),"rad, phi =",np.round(180*phi/np.pi,2),"degrees")
qc = QuantumCircuit(3,3)
qc.ry(theta,0)
qc.rz(phi,0)
stv0 = qi.Statevector.from_instruction(qc)
qc.barrier()
qc.h(1) # Hadamard
qc.cx(1,2) # CNOT
qc.barrier()
qc.cx(0,1)
qc.h(0)
qc.barrier()
qc.rz(-phi,2)
qc.ry(-theta,2)
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.draw("mpl")
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(stv0)
from qiskit import IBMQ, transpile
tqc = transpile(qc, backend, optimization_level=3)
job_teleportation = backend.run(tqc,shots = 1000)
print(job_teleportation.status(),job_teleportation.queue_position())
print("Counts for teleportation on", backend,"\n\n")
try :
n_error = job.result().get_counts(qc)['100']
except:
n_error = 0
import matplotlib.pyplot as plt
try :
n_error = job.result().get_counts(qc)['100']
except:
n_error = 0
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,6))
states = ['000', '100']
counts = [job_teleportation.result().get_counts(qc)['000'],n_error]
plt.rcParams.update({'font.size': 20})
plt.bar(states,counts,width=0.4, bottom=None,align='center', data=None)
for index, value in enumerate(counts):
plt.text(index, value, str(value),fontsize=20)
plt.xlabel('States',fontsize=20)
plt.ylabel('Counts',fontsize=20)
plt.show()
|
https://github.com/AbeerVaishnav13/4-qubit-design
|
AbeerVaishnav13
|
import warnings
warnings.filterwarnings('ignore')
from qiskit_metal import designs, MetalGUI
design = designs.DesignPlanar()
design.overwrite_enabled = True
design.chips.main.size_x = '12mm'
design.chips.main.size_y = '10mm'
gui = MetalGUI(design)
from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL
design.delete_all_components()
# Some local variables to modularize the deesign
design_span_x = 5
design_span_y = 3
half_chip_width = design_span_x / 2
half_chip_height = design_span_y / 2
connection_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
b = dict(loc_W=1, loc_H=1),
c = dict(loc_W=-1, loc_H=-1)
)
transmons = []
transmons.append(TransmonPocketCL(design, 'Q1',
options=dict(pos_x=f'-{half_chip_width}mm',
pos_y=f'{-half_chip_height}mm',
connection_pads=dict(**connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q2',
options=dict(pos_x=f'0mm',
pos_y=f'{half_chip_height}mm',
orientation=-90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q3',
options=dict(pos_x=f'0mm',
pos_y=f'{-half_chip_height}mm',
orientation=90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q4',
options=dict(pos_x=f'{half_chip_width}mm',
pos_y=f'{half_chip_height}mm',
orientation=180,
connection_pads=dict(**connection_pads_options))))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
from qiskit_metal import Dict
# Options for the meaders
fillet='99.99um'
options = Dict(
meander=Dict(
lead_start='0.1mm',
lead_end='0.1mm',
asymmetry='0 um')
)
# Helper function to connect thee meandered routes
def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str,
length: str,
asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False):
"""Connect two pins with a CPW."""
myoptions = Dict(
pin_inputs=Dict(
start_pin=Dict(
component=component1,
pin=pin1),
end_pin=Dict(
component=component2,
pin=pin2)),
lead=Dict(
start_straight=start_strght,
end_straight=end_strght
),
total_length=length,
fillet = '99.9um')
myoptions.update(options)
myoptions.meander.asymmetry = asymmetry
myoptions.meander.lead_direction_inverted = 'true' if flip else 'false'
return RouteMeander(design, component_name, myoptions)
# Define asymmetry (itrative process)
asym_h = 100
asym_v = 100
cpw = []
# Connect CPW coulers between qubits (with some arbitrary length initially)
cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw2', 'Q3', 'b', 'Q2', 'b', '8 mm', f'-{asym_v}um', '0.6mm', '0.4mm'))
cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
gui.rebuild()
gui.autoscale()
from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength
def find_resonator_length(frequency, line_width, line_gap, N):
#frequency in GHz
#line_width/line_gap in um
#N -> 2 for lambda/2, 4 for lambda/4
[lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6,
line_gap*10**-6, 750*10**-6, 200*10**-9)
return str(lambdaG/N*10**3)+" mm"
find_resonator_length(6.5, 15, 1, 2)
from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled
readouts_lwc = []
cl_lwc = []
offset_x = 0
offset_y = 1
#Readouts
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1',
options = dict(
pos_x = '-5mm',
pos_y = f'-{half_chip_height+offset_y}mm',
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2',
options = dict(
pos_x = '-1mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3',
options = dict(
pos_x = '1mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4',
options = dict(
pos_x = '5mm',
pos_y = f'{half_chip_height+offset_y}mm',
orientation = 180,
lead_length = '30um')))
#Controls
cl_lwc.append(LaunchpadWirebondCoupled(design, 'CL1',
options = dict(
pos_x = '-5mm',
pos_y = '2mm',
lead_length = '30um')))
cl_lwc.append(LaunchpadWirebondCoupled(design, 'CL2',
options = dict(
pos_x = '4mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
cl_lwc.append(LaunchpadWirebondCoupled(design, 'CL3',
options = dict(
pos_x = '-4mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
cl_lwc.append(LaunchpadWirebondCoupled(design, 'CL4',
options = dict(
pos_x = '5mm',
pos_y = '-2mm',
orientation = 180,
lead_length = '30um')))
gui.rebuild()
gui.autoscale()
readout_lines = []
asym_14 = 700
asym_23 = 700
options = Dict(
lead=Dict(
start_straight='430um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um'))
readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um'))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors
from collections import OrderedDict
import numpy as np
control_lines = []
def connectRouteAnchor(name: str,
component1: str, pin1: str, component2: str, pin2: str,
anchor_points: OrderedDict) -> RouteAnchors:
options_line_cl = dict(
pin_inputs = dict(start_pin = dict(component = component1, pin = pin1),
end_pin = dict(component = component2, pin = pin2)),
anchors = anchor_points,
lead = dict(start_straight = '200um',
end_straight = '225um'),
fillet = fillet
)
return RouteAnchors(design, name, options_line_cl)
anchors1c = OrderedDict()
anchors1c[0] = np.array([-4, -1.42])
anchors1c[1] = np.array([-4, 2])
control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c))
anchors2c = OrderedDict()
anchors2c[0] = np.array([0.08, 3.25])
anchors2c[1] = np.array([4, 3.25])
control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c))
anchors3c = OrderedDict()
anchors3c[0] = np.array([-0.08, -3.25])
anchors3c[1] = np.array([-4, -3.25])
control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c))
anchors4c = OrderedDict()
anchors4c[0] = np.array([4, 1.42])
anchors4c[1] = np.array([4, -2])
control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c))
gui.rebuild()
gui.autoscale()
# Qubit Frequencies
# Q1 : 5
# Q2 : 5.1
# Q3 : 5.2
# Q4 : 5.3
# Readout Frequencies
# R1 : 7
# R2 : 7.1
# R3 : 7.2
# R4 : 7.3
# CPW Frequencies
# cpw1 : 7.5
# cpw2 : 7.6
# cpw3 : 7.7
# cpw4 : 7.8
# cpw5 : 7.9
gui.screenshot()
|
https://github.com/AbeerVaishnav13/4-qubit-design
|
AbeerVaishnav13
|
import warnings
warnings.filterwarnings('ignore')
from qiskit_metal import designs, MetalGUI
design = designs.DesignPlanar()
design.overwrite_enabled = True
design.chips.main.size_x = '12mm'
design.chips.main.size_y = '10mm'
gui = MetalGUI(design)
from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL
design.delete_all_components()
design_span_x = 5
design_span_y = 3
half_chip_width = design_span_x / 2
half_chip_height = design_span_y / 2
connection_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
b = dict(loc_W=1, loc_H=1),
c = dict(loc_W=-1, loc_H=-1)
)
transmons = []
transmons.append(TransmonPocketCL(design, 'Q1',
options=dict(pos_x=f'-{half_chip_width}mm',
pos_y=f'{-half_chip_height}mm',
connection_pads=dict(**connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q2',
options=dict(pos_x=f'0mm',
pos_y=f'{half_chip_height}mm',
orientation=-90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q3',
options=dict(pos_x=f'0mm',
pos_y=f'{-half_chip_height}mm',
orientation=90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q4',
options=dict(pos_x=f'{half_chip_width}mm',
pos_y=f'{half_chip_height}mm',
orientation=180,
connection_pads=dict(**connection_pads_options))))
gui.rebuild()
gui.autoscale()
gui.screenshot(name="transmons")
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
from qiskit_metal import Dict
fillet='99.99um'
options = Dict(
meander=Dict(
lead_start='0.1mm',
lead_end='0.1mm',
asymmetry='0 um')
)
def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str,
length: str,
asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False):
"""Connect two pins with a CPW."""
myoptions = Dict(
pin_inputs=Dict(
start_pin=Dict(
component=component1,
pin=pin1),
end_pin=Dict(
component=component2,
pin=pin2)),
lead=Dict(
start_straight=start_strght,
end_straight=end_strght
),
total_length=length,
fillet = '99.9um')
myoptions.update(options)
myoptions.meander.asymmetry = asymmetry
myoptions.meander.lead_direction_inverted = 'true' if flip else 'false'
return RouteMeander(design, component_name, myoptions)
asym_h = 100
asym_v = 100
cpw = []
cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw2', 'Q3', 'b', 'Q2', 'b', '8 mm', f'-{asym_v}um', '0.6mm', '0.4mm'))
cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
gui.rebuild()
gui.autoscale()
gui.screenshot(name="cpws")
from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled
readouts_lwc = []
control_lwc = []
offset_x = 0
offset_y = 1
#Readouts
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1',
options = dict(
pos_x = '-5mm',
pos_y = f'-{half_chip_height+offset_y}mm',
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2',
options = dict(
pos_x = '-1mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3',
options = dict(
pos_x = '1mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4',
options = dict(
pos_x = '5mm',
pos_y = f'{half_chip_height+offset_y}mm',
orientation = 180,
lead_length = '30um')))
#Controls
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1',
options = dict(
pos_x = '-5mm',
pos_y = '2mm',
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2',
options = dict(
pos_x = '4mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3',
options = dict(
pos_x = '-4mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4',
options = dict(
pos_x = '5mm',
pos_y = '-2mm',
orientation = 180,
lead_length = '30um')))
gui.rebuild()
gui.autoscale()
gui.screenshot(name="launchpads")
readout_lines = []
asym_14 = 700
asym_23 = 700
options = Dict(
lead=Dict(
start_straight='430um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um'))
readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um'))
gui.rebuild()
gui.autoscale()
gui.screenshot(name="readouts")
from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors
from collections import OrderedDict
import numpy as np
control_lines = []
def connectRouteAnchor(name: str,
component1: str, pin1: str, component2: str, pin2: str,
anchor_points: OrderedDict) -> RouteAnchors:
options_line_cl = dict(
pin_inputs = dict(start_pin = dict(component = component1, pin = pin1),
end_pin = dict(component = component2, pin = pin2)),
anchors = anchor_points,
lead = dict(start_straight = '200um',
end_straight = '225um'),
fillet = fillet
)
return RouteAnchors(design, name, options_line_cl)
anchors1c = OrderedDict()
anchors1c[0] = np.array([-4, -1.42])
anchors1c[1] = np.array([-4, 2])
control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c))
anchors2c = OrderedDict()
anchors2c[0] = np.array([0.08, 3.25])
anchors2c[1] = np.array([4, 3.25])
control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c))
anchors3c = OrderedDict()
anchors3c[0] = np.array([-0.08, -3.25])
anchors3c[1] = np.array([-4, -3.25])
control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c))
anchors4c = OrderedDict()
anchors4c[0] = np.array([4, 1.42])
anchors4c[1] = np.array([4, -2])
control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c))
gui.rebuild()
gui.autoscale()
gui.screenshot(name="full_design")
# Qubit Frequencies
# Q1 : 5
# Q2 : 5.1
# Q3 : 5.2
# Q4 : 5.3
# Readout Frequencies
# R1 : 7
# R2 : 7.1
# R3 : 7.2
# R4 : 7.3
# CPW Frequencies
# cpw1 : 7.5
# cpw2 : 7.6
# cpw3 : 7.7
# cpw4 : 7.8
# cpw5 : 7.9
from qiskit_metal.analyses.quantization import EPRanalysis
eig_res1 = EPRanalysis(design, "hfss")
hfss1 = eig_res1.sim.renderer
hfss1.start()
transmons[0].options.pad_gap = '40um'
transmons[0].options.pad_width = '405um'
transmons[0].options.pad_height = '90um'
gui.rebuild()
hfss1.activate_ansys_design("Tune_Q1", 'eigenmode')
hfss1.render_design(['Q1'], [('Q1', 'c'), ('Q1', 'a'),('Q1', 'b'),('Q1', 'Charge_Line')])
# Analysis properties
setup1 = hfss1.pinfo.setup
setup1.passes = 10
setup1.n_modes = 3
print(f"""
Number of eigenmodes to find = {setup1.n_modes}
Number of simulation passes = {setup1.passes}
Convergence freq max delta percent diff = {setup1.delta_f}
""")
# Next 2 lines are counterinuitive, since there is no junction in this resonator.
# However, these are necessary to make pyEPR work correctly. Please do note delete
hfss1.pinfo.design.set_variable('Lj', '12 nH')
hfss1.pinfo.design.set_variable('Cj', '1 fF')
setup1.analyze()
eig_res1.sim.convergence_t, eig_res1.sim.convergence_f, _ = hfss1.get_convergences()
eig_res1.sim.plot_convergences()
# eig_res1.sim.plot_fields("main")
# hfss1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q1_epr_e-field.png")
hfss1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q1_epr_e-field.png")
from qiskit_metal.analyses.quantization import EPRanalysis
eig_res2 = EPRanalysis(design, "hfss")
hfss2 = eig_res2.sim.renderer
hfss2.start()
transmons[1].options.pad_gap = '40um'
transmons[1].options.pad_width = '378um'
transmons[1].options.pad_height = '90um'
gui.rebuild()
hfss2.activate_ansys_design("Tune_Q2", 'eigenmode')
hfss2.render_design(['Q2'], [('Q2', 'c'), ('Q2', 'a'),('Q2', 'b'),('Q2', 'd'),('Q2', 'Charge_Line')])
# Analysis properties
setup2 = hfss2.pinfo.setup
setup2.passes = 10
setup2.n_modes = 3
print(f"""
Number of eigenmodes to find = {setup2.n_modes}
Number of simulation passes = {setup2.passes}
Convergence freq max delta percent diff = {setup2.delta_f}
""")
# Next 2 lines are counterinuitive, since there is no junction in this resonator.
# However, these are necessary to make pyEPR work correctly. Please do note delete
hfss2.pinfo.design.set_variable('Lj', '12 nH')
hfss2.pinfo.design.set_variable('Cj', '1 fF')
setup2.analyze()
eig_res2.sim.convergence_t, eig_res2.sim.convergence_f, _ = hfss2.get_convergences()
eig_res2.sim.plot_convergences()
# eig_res2.sim.plot_fields("main")
# hfss2.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q2_epr_e-field.png")
hfss2.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q2_epr_e-field.png")
from qiskit_metal.analyses.quantization import EPRanalysis
eig_res3 = EPRanalysis(design, "hfss")
hfss3 = eig_res3.sim.renderer
hfss3.start()
transmons[2].options.pad_gap = '40um'
transmons[2].options.pad_width = '353um'
transmons[2].options.pad_height = '90um'
gui.rebuild()
hfss3.activate_ansys_design("Tune_Q3", 'eigenmode')
hfss3.render_design(['Q3'], [('Q3', 'c'), ('Q3', 'a'),('Q3', 'b'),('Q3', 'd'),('Q3', 'Charge_Line')])
# Analysis properties
setup3 = hfss3.pinfo.setup
setup3.passes = 10
setup3.n_modes = 3
print(f"""
Number of eigenmodes to find = {setup3.n_modes}
Number of simulation passes = {setup3.passes}
Convergence freq max delta percent diff = {setup3.delta_f}
""")
# Next 2 lines are counterinuitive, since there is no junction in this resonator.
# However, these are necessary to make pyEPR work correctly. Please do note delete
hfss3.pinfo.design.set_variable('Lj', '12 nH')
hfss3.pinfo.design.set_variable('Cj', '1 fF')
setup3.analyze()
eig_res3.sim.convergence_t, eig_res3.sim.convergence_f, _ = hfss3.get_convergences()
eig_res3.sim.plot_convergences()
# eig_res3.sim.plot_fields("main")
# hfss3.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q3_epr_e-field.png")
hfss3.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q3_epr_e-field.png")
from qiskit_metal.analyses.quantization import EPRanalysis
eig_res4 = EPRanalysis(design, "hfss")
hfss4 = eig_res4.sim.renderer
hfss4.start()
transmons[3].options.pad_gap = '40um'
transmons[3].options.pad_width = '344um'
transmons[3].options.pad_height = '90um'
gui.rebuild()
hfss4.activate_ansys_design("Tune_Q4", 'eigenmode')
hfss4.render_design(['Q4'], [('Q4', 'c'), ('Q4', 'a'),('Q4', 'b'),('Q4', 'Charge_Line')])
# Analysis properties
setup4 = hfss4.pinfo.setup
setup4.passes = 10
setup4.n_modes = 3
print(f"""
Number of eigenmodes to find = {setup4.n_modes}
Number of simulation passes = {setup4.passes}
Convergence freq max delta percent diff = {setup4.delta_f}
""")
# Next 2 lines are counterinuitive, since there is no junction in this resonator.
# However, these are necessary to make pyEPR work correctly. Please do note delete
hfss4.pinfo.design.set_variable('Lj', '12 nH')
hfss4.pinfo.design.set_variable('Cj', '1 fF')
setup4.analyze()
eig_res4.sim.convergence_t, eig_res4.sim.convergence_f, _ = hfss4.get_convergences()
eig_res4.sim.plot_convergences()
# eig_res4.sim.plot_fields("main")
# hfss4.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q4_epr_e-field.png")
hfss4.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q4_epr_e-field.png")
|
https://github.com/AbeerVaishnav13/4-qubit-design
|
AbeerVaishnav13
|
import warnings
warnings.filterwarnings('ignore')
from qiskit_metal import designs, MetalGUI
design = designs.DesignPlanar()
design.overwrite_enabled = True
design.chips.main.size_x = '12mm'
design.chips.main.size_y = '10mm'
gui = MetalGUI(design)
from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL
design.delete_all_components()
design_span_x = 5
design_span_y = 3
half_chip_width = design_span_x / 2
half_chip_height = design_span_y / 2
connection_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
b = dict(loc_W=1, loc_H=1),
c = dict(loc_W=-1, loc_H=-1)
)
transmons = []
transmons.append(TransmonPocketCL(design, 'Q1',
options=dict(pos_x=f'-{half_chip_width}mm',
pos_y=f'{-half_chip_height}mm',
connection_pads=dict(**connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q2',
options=dict(pos_x=f'0mm',
pos_y=f'{half_chip_height}mm',
orientation=-90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q3',
options=dict(pos_x=f'0mm',
pos_y=f'{-half_chip_height}mm',
orientation=90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q4',
options=dict(pos_x=f'{half_chip_width}mm',
pos_y=f'{half_chip_height}mm',
orientation=180,
connection_pads=dict(**connection_pads_options))))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
from qiskit_metal import Dict
fillet='99.99um'
options = Dict(
meander=Dict(
lead_start='0.1mm',
lead_end='0.1mm',
asymmetry='0 um')
)
def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str,
length: str,
asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False):
"""Connect two pins with a CPW."""
myoptions = Dict(
pin_inputs=Dict(
start_pin=Dict(
component=component1,
pin=pin1),
end_pin=Dict(
component=component2,
pin=pin2)),
lead=Dict(
start_straight=start_strght,
end_straight=end_strght
),
total_length=length,
fillet = '99.9um')
myoptions.update(options)
myoptions.meander.asymmetry = asymmetry
myoptions.meander.lead_direction_inverted = 'true' if flip else 'false'
return RouteMeander(design, component_name, myoptions)
asym_h = 100
asym_v = 100
cpw = []
cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw2', 'Q3', 'b', 'Q2', 'b', '8 mm', f'-{asym_v}um', '0.6mm', '0.4mm'))
cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled
readouts_lwc = []
control_lwc = []
offset_x = 0
offset_y = 1
#Readouts
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1',
options = dict(
pos_x = '-5mm',
pos_y = f'-{half_chip_height+offset_y}mm',
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2',
options = dict(
pos_x = '-1mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3',
options = dict(
pos_x = '1mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4',
options = dict(
pos_x = '5mm',
pos_y = f'{half_chip_height+offset_y}mm',
orientation = 180,
lead_length = '30um')))
#Controls
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1',
options = dict(
pos_x = '-5mm',
pos_y = '2mm',
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2',
options = dict(
pos_x = '4mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3',
options = dict(
pos_x = '-4mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4',
options = dict(
pos_x = '5mm',
pos_y = '-2mm',
orientation = 180,
lead_length = '30um')))
gui.rebuild()
gui.autoscale()
readout_lines = []
asym_14 = 700
asym_23 = 700
options = Dict(
lead=Dict(
start_straight='430um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um'))
readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um'))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors
from collections import OrderedDict
import numpy as np
control_lines = []
def connectRouteAnchor(name: str,
component1: str, pin1: str, component2: str, pin2: str,
anchor_points: OrderedDict) -> RouteAnchors:
options_line_cl = dict(
pin_inputs = dict(start_pin = dict(component = component1, pin = pin1),
end_pin = dict(component = component2, pin = pin2)),
anchors = anchor_points,
lead = dict(start_straight = '200um',
end_straight = '225um'),
fillet = fillet
)
return RouteAnchors(design, name, options_line_cl)
anchors1c = OrderedDict()
anchors1c[0] = np.array([-4, -1.42])
anchors1c[1] = np.array([-4, 2])
control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c))
anchors2c = OrderedDict()
anchors2c[0] = np.array([0.08, 3.25])
anchors2c[1] = np.array([4, 3.25])
control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c))
anchors3c = OrderedDict()
anchors3c[0] = np.array([-0.08, -3.25])
anchors3c[1] = np.array([-4, -3.25])
control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c))
anchors4c = OrderedDict()
anchors4c[0] = np.array([4, 1.42])
anchors4c[1] = np.array([4, -2])
control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c))
gui.rebuild()
gui.autoscale()
gui.screenshot()
# Qubit Frequencies
# Q1 : 5
# Q2 : 5.1
# Q3 : 5.2
# Q4 : 5.3
# Readout Frequencies
# R1 : 7
# R2 : 7.1
# R3 : 7.2
# R4 : 7.3
# CPW Frequencies
# cpw1 : 7.5
# cpw2 : 7.6
# cpw3 : 7.7
# cpw4 : 7.8
# cpw5 : 7.9
from qiskit_metal.analyses.quantization import LOManalysis
c1 = LOManalysis(design, "q3d")
q3d1 = c1.sim.renderer
q3d1.start()
transmons[0].options.pad_gap = '40um'
transmons[0].options.pad_width = '405um'
transmons[0].options.pad_height = '90um'
gui.rebuild() # IMPORTANT
q3d1.activate_ansys_design("Tune_Q1", 'capacitive')
q3d1.render_design(['Q1'], [('Q1', 'c'), ('Q1', 'a'),('Q1', 'b'),('Q1', 'Charge_Line')])
#q3d1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/q1.png")
q3d1.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05 )
q3d1.analyze_setup("Setup")
c1.sim.capacitance_matrix, c1.sim.units = q3d1.get_capacitance_matrix()
c1.sim.capacitance_all_passes, _ = q3d1.get_capacitance_all_passes()
c1.sim.capacitance_matrix
c1.setup.junctions = Dict(Lj=12, Cj=1)
c1.setup.freq_readout = 7.5
c1.setup.freq_bus = [7.8, 7.5, 15]
c1.run_lom()
c1.lumped_oscillator_all
c1.plot_convergence()
c1.plot_convergence_chi()
from qiskit_metal.analyses.quantization import LOManalysis
c2 = LOManalysis(design, "q3d")
q3d2 = c2.sim.renderer
q3d2.start()
transmons[1].options.pad_gap = '40um'
transmons[1].options.pad_width = '378um'
transmons[1].options.pad_height = '90um'
gui.rebuild()
q3d2.activate_ansys_design("Tune_Q2", 'capacitive')
q3d2.render_design(['Q2'], [('Q2', 'c'), ('Q2', 'a'),('Q2', 'b'),('Q2', 'd'),('Q2', 'Charge_Line')])
#q3d2.save_screenshot(path="C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/q2.png")
q3d2.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05 )
q3d2.analyze_setup("Setup")
c2.sim.capacitance_matrix, c2.sim.units = q3d2.get_capacitance_matrix()
c2.sim.capacitance_all_passes, _ = q3d2.get_capacitance_all_passes()
c2.sim.capacitance_matrix
c2.setup.junctions = Dict(Lj=12, Cj=1)
c2.setup.freq_readout = 7.1
c2.setup.freq_bus = [7.5, 7.6, 7.9, 17]
c2.run_lom()
c2.lumped_oscillator_all
c2.plot_convergence()
c2.plot_convergence_chi()
from qiskit_metal.analyses.quantization import LOManalysis
c3 = LOManalysis(design, "q3d")
q3d3 = c3.sim.renderer
q3d3.start()
transmons[2].options.pad_gap = '40um'
transmons[2].options.pad_width = '353um'
transmons[2].options.pad_height = '90um'
gui.rebuild()
q3d3.activate_ansys_design("Tune_Q3", 'capacitive')
q3d3.render_design(['Q3'], [('Q3', 'c'), ('Q3', 'a'),('Q3', 'b'),('Q3', 'd'),('Q3', 'Charge_Line')])
#q3d3.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/q3.png")
q3d3.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05 )
q3d3.analyze_setup("Setup")
c3.sim.capacitance_matrix, c3.sim.units = q3d3.get_capacitance_matrix()
c3.sim.capacitance_all_passes, _ = q3d3.get_capacitance_all_passes()
c3.sim.capacitance_matrix
c3.setup.junctions = Dict(Lj=12, Cj=1)
c3.setup.freq_readout = 7.3
c3.setup.freq_bus = [7.7, 7.6, 7.8, 17]
c3.run_lom()
c3.lumped_oscillator_all
c3.plot_convergence()
c3.plot_convergence_chi()
from qiskit_metal.analyses.quantization import LOManalysis
c4 = LOManalysis(design, "q3d")
q3d4 = c4.sim.renderer
q3d4.start()
transmons[3].options.pad_gap = '40um'
transmons[3].options.pad_width = '344um'
transmons[3].options.pad_height = '90um'
gui.rebuild()
q3d4.activate_ansys_design("Tune_Q4", 'capacitive')
q3d4.render_design(['Q4'], [('Q4', 'c'), ('Q4', 'a'),('Q4', 'b'),('Q4', 'Charge_Line')])
#q3d4.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/q4.png")
q3d4.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05 )
q3d4.analyze_setup("Setup")
c4.sim.capacitance_matrix, c4.sim.units = q3d4.get_capacitance_matrix()
c4.sim.capacitance_all_passes, _ = q3d4.get_capacitance_all_passes()
c4.sim.capacitance_matrix
c4.setup.junctions = Dict(Lj=12, Cj=1)
c4.setup.freq_readout = 7.4
c4.setup.freq_bus = [7.9, 7.7, 15]
c4.run_lom()
c4.lumped_oscillator_all
c4.plot_convergence()
c4.plot_convergence_chi()
|
https://github.com/AbeerVaishnav13/4-qubit-design
|
AbeerVaishnav13
|
import warnings
warnings.filterwarnings('ignore')
from qiskit_metal import designs, MetalGUI
design = designs.DesignPlanar()
design.overwrite_enabled = True
design.chips.main.size_x = '12mm'
design.chips.main.size_y = '10mm'
gui = MetalGUI(design)
from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL
design.delete_all_components()
design_span_x = 5
design_span_y = 3
half_chip_width = design_span_x / 2
half_chip_height = design_span_y / 2
connection_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
b = dict(loc_W=1, loc_H=1),
c = dict(loc_W=-1, loc_H=-1)
)
transmons = []
transmons.append(TransmonPocketCL(design, 'Q1',
options=dict(pos_x=f'-{half_chip_width}mm',
pos_y=f'{-half_chip_height}mm',
connection_pads=dict(**connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q2',
options=dict(pos_x=f'0mm',
pos_y=f'{half_chip_height}mm',
orientation=-90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q3',
options=dict(pos_x=f'0mm',
pos_y=f'{-half_chip_height}mm',
orientation=90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q4',
options=dict(pos_x=f'{half_chip_width}mm',
pos_y=f'{half_chip_height}mm',
orientation=180,
connection_pads=dict(**connection_pads_options))))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
from qiskit_metal import Dict
fillet='99.99um'
options = Dict(
meander=Dict(
lead_start='0.1mm',
lead_end='0.1mm',
asymmetry='0 um')
)
def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str,
length: str,
asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False):
"""Connect two pins with a CPW."""
myoptions = Dict(
pin_inputs=Dict(
start_pin=Dict(
component=component1,
pin=pin1),
end_pin=Dict(
component=component2,
pin=pin2)),
lead=Dict(
start_straight=start_strght,
end_straight=end_strght
),
total_length=length,
fillet = '99.9um')
myoptions.update(options)
myoptions.meander.asymmetry = asymmetry
myoptions.meander.lead_direction_inverted = 'true' if flip else 'false'
return RouteMeander(design, component_name, myoptions)
asym_h = 100
asym_v = 100
cpw = []
cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw2', 'Q3', 'b', 'Q2', 'b', '8 mm', f'-{asym_v}um', '0.6mm', '0.4mm'))
cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled
readouts_lwc = []
control_lwc = []
offset_x = 0
offset_y = 1
#Readouts
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1',
options = dict(
pos_x = '-5mm',
pos_y = f'-{half_chip_height+offset_y}mm',
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2',
options = dict(
pos_x = '-1mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3',
options = dict(
pos_x = '1mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4',
options = dict(
pos_x = '5mm',
pos_y = f'{half_chip_height+offset_y}mm',
orientation = 180,
lead_length = '30um')))
#Controls
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1',
options = dict(
pos_x = '-5mm',
pos_y = '2mm',
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2',
options = dict(
pos_x = '4mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3',
options = dict(
pos_x = '-4mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4',
options = dict(
pos_x = '5mm',
pos_y = '-2mm',
orientation = 180,
lead_length = '30um')))
gui.rebuild()
gui.autoscale()
readout_lines = []
asym_14 = 700
asym_23 = 700
options = Dict(
lead=Dict(
start_straight='430um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um'))
readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um'))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors
from collections import OrderedDict
import numpy as np
control_lines = []
def connectRouteAnchor(name: str,
component1: str, pin1: str, component2: str, pin2: str,
anchor_points: OrderedDict) -> RouteAnchors:
options_line_cl = dict(
pin_inputs = dict(start_pin = dict(component = component1, pin = pin1),
end_pin = dict(component = component2, pin = pin2)),
anchors = anchor_points,
lead = dict(start_straight = '200um',
end_straight = '225um'),
fillet = fillet
)
return RouteAnchors(design, name, options_line_cl)
anchors1c = OrderedDict()
anchors1c[0] = np.array([-4, -1.42])
anchors1c[1] = np.array([-4, 2])
control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c))
anchors2c = OrderedDict()
anchors2c[0] = np.array([0.08, 3.25])
anchors2c[1] = np.array([4, 3.25])
control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c))
anchors3c = OrderedDict()
anchors3c[0] = np.array([-0.08, -3.25])
anchors3c[1] = np.array([-4, -3.25])
control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c))
anchors4c = OrderedDict()
anchors4c[0] = np.array([4, 1.42])
anchors4c[1] = np.array([4, -2])
control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c))
gui.rebuild()
gui.autoscale()
# Qubit Frequencies
# Q1 : 5
# Q2 : 5.1
# Q3 : 5.2
# Q4 : 5.3
# Readout Frequencies
# R1 : 7
# R2 : 7.1
# R3 : 7.2
# R4 : 7.3
# CPW Frequencies
# cpw1 : 7.5
# cpw2 : 7.6
# cpw3 : 7.7
# cpw4 : 7.8
# cpw5 : 7.9
# CPW rough length calculator
freq_new = 7.3
freq = (freq_new + 1.80) * (10**9)
c = 3 * (10**8)
lamb = c / freq * (10**6)
lamb/4
# To set the global variable for CPW width
design.variables['cpw_width'] = '20um'
gui.rebuild()
readout_lines[0].options.total_length = '8522.72 um'
readout_lines[1].options.total_length = '8426.96 um'
readout_lines[2].options.total_length = '8333.33 um'
readout_lines[3].options.total_length = '8241.75 um'
cpw[0].options.total_length = '8064.51 um'
cpw[1].options.total_length = '7978.72 um'
cpw[2].options.total_length = '7894.73 um'
cpw[3].options.total_length = '7812.50 um'
cpw[4].options.total_length = '7731.96 um'
gui.rebuild()
gui.screenshot()
from qiskit_metal.analyses.quantization import EPRanalysis
eig_res1 = EPRanalysis(design, "hfss")
hfss1 = eig_res1.sim.renderer
hfss1.start()
cpw[0].options.total_length = '8064.51 um'
gui.rebuild()
hfss1.activate_ansys_design("Tune_CPW1", 'eigenmode')
hfss1.render_design(['cpw1'], [('cpw1', 'start'), ('cpw1', 'end')])
hfss1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/cpw1.png")
# Analysis properties
setup1 = hfss1.pinfo.setup
setup1.passes = 10
setup1.n_modes = 1
print(f"""
Number of eigenmodes to find = {setup1.n_modes}
Number of simulation passes = {setup1.passes}
Convergence freq max delta percent diff = {setup1.delta_f}
""")
# Next 2 lines are counterinuitive, since there is no junction in this resonator.
# However, these are necessary to make pyEPR work correctly. Please do note delete
hfss1.pinfo.design.set_variable('Lj', '12 nH')
hfss1.pinfo.design.set_variable('Cj', '1 fF')
setup1.analyze()
eig_res1.sim.convergence_t, eig_res1.sim.convergence_f, _ = hfss1.get_convergences()
eig_res1.sim.plot_convergences()
eig_res1.sim.plot_fields("main")
hfss1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/cpw1_e-field.png")
hfss1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/cpw1_e-field.png")
eig_res1.epr_start(no_junctions=True)
eprd = hfss1.epr_distributed_analysis
ℰ_elec = eprd.calc_energy_electric()
ℰ_elec_substrate = eprd.calc_energy_electric(None, 'main')
ℰ_mag = eprd.calc_energy_magnetic()
print(f"""
ℰ_elec_all = {ℰ_elec}
ℰ_elec_substrate = {ℰ_elec_substrate}
EPR of substrate = {ℰ_elec_substrate / ℰ_elec * 100 :.1f}%
ℰ_mag = {ℰ_mag}
""")
eig_res1.sim.close()
from qiskit_metal.analyses.quantization import EPRanalysis
eig_res2 = EPRanalysis(design, "hfss")
hfss2 = eig_res2.sim.renderer
hfss2.start()
cpw[1].options.total_length = '7978.72 um'
gui.rebuild()
hfss2.activate_ansys_design("Tune_CPW2", 'eigenmode')
hfss2.render_design(['cpw2'], [('cpw2', 'start'), ('cpw2', 'end')])
hfss2.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/cpw2.png")
# Analysis properties
setup2 = hfss2.pinfo.setup
setup2.passes = 10
setup2.n_modes = 1
print(f"""
Number of eigenmodes to find = {setup2.n_modes}
Number of simulation passes = {setup2.passes}
Convergence freq max delta percent diff = {setup2.delta_f}
""")
# Next 2 lines are counterinuitive, since there is no junction in this resonator.
# However, these are necessary to make pyEPR work correctly. Please do note delete
hfss2.pinfo.design.set_variable('Lj', '12 nH')
hfss2.pinfo.design.set_variable('Cj', '1 fF')
setup2.analyze()
eig_res2.sim.convergence_t, eig_res2.sim.convergence_f, _ = hfss2.get_convergences()
eig_res2.sim.plot_convergences()
hfss1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/cpw2_e-field.png")
from qiskit_metal.analyses.quantization import EPRanalysis
eig_res3 = EPRanalysis(design, "hfss")
hfss3 = eig_res3.sim.renderer
hfss3.start()
cpw[2].options.total_length = '7894.73 um'
gui.rebuild()
hfss3.activate_ansys_design("Tune_CPW3", 'eigenmode')
hfss3.render_design(['cpw3'], [('cpw3', 'start'), ('cpw3', 'end')])
hfss3.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/cpw3.png")
# Analysis properties
setup3 = hfss3.pinfo.setup
setup3.passes = 10
setup3.n_modes = 1
print(f"""
Number of eigenmodes to find = {setup3.n_modes}
Number of simulation passes = {setup3.passes}
Convergence freq max delta percent diff = {setup3.delta_f}
""")
# Next 2 lines are counterinuitive, since there is no junction in this resonator.
# However, these are necessary to make pyEPR work correctly. Please do note delete
hfss3.pinfo.design.set_variable('Lj', '12 nH')
hfss3.pinfo.design.set_variable('Cj', '1 fF')
setup3.analyze()
eig_res3.sim.convergence_t, eig_res3.sim.convergence_f, _ = hfss3.get_convergences()
eig_res3.sim.plot_convergences()
hfss1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/cpw3_e-field.png")
from qiskit_metal.analyses.quantization import EPRanalysis
eig_res4 = EPRanalysis(design, "hfss")
hfss4 = eig_res4.sim.renderer
hfss4.start()
cpw[3].options.total_length = '7812.50 um'
gui.rebuild()
hfss4.activate_ansys_design("Tune_CPW4", 'eigenmode')
hfss4.render_design(['cpw4'], [('cpw4', 'start'), ('cpw4', 'end')])
hfss4.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/cpw4.png")
# Analysis properties
setup4 = hfss4.pinfo.setup
setup4.passes = 10
setup4.n_modes = 1
print(f"""
Number of eigenmodes to find = {setup4.n_modes}
Number of simulation passes = {setup4.passes}
Convergence freq max delta percent diff = {setup4.delta_f}
""")
# Next 2 lines are counterinuitive, since there is no junction in this resonator.
# However, these are necessary to make pyEPR work correctly. Please do note delete
hfss4.pinfo.design.set_variable('Lj', '12 nH')
hfss4.pinfo.design.set_variable('Cj', '1 fF')
setup4.analyze()
eig_res4.sim.convergence_t, eig_res4.sim.convergence_f, _ = hfss4.get_convergences()
eig_res4.sim.plot_convergences()
hfss1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/cpw4_e-field.png")
from qiskit_metal.analyses.quantization import EPRanalysis
eig_res5 = EPRanalysis(design, "hfss")
hfss5 = eig_res5.sim.renderer
hfss5.start()
cpw[4].options.total_length = '7731.96 um'
gui.rebuild()
hfss5.activate_ansys_design("Tune_CPW5", 'eigenmode')
hfss5.render_design(['cpw5'], [('cpw5', 'start'), ('cpw5', 'end')])
hfss5.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/cpw5.png")
# Analysis properties
setup5 = hfss5.pinfo.setup
setup5.passes = 10
setup5.n_modes = 1
print(f"""
Number of eigenmodes to find = {setup5.n_modes}
Number of simulation passes = {setup5.passes}
Convergence freq max delta percent diff = {setup5.delta_f}
""")
# Next 2 lines are counterinuitive, since there is no junction in this resonator.
# However, these are necessary to make pyEPR work correctly. Please do note delete
hfss5.pinfo.design.set_variable('Lj', '12 nH')
hfss5.pinfo.design.set_variable('Cj', '1 fF')
setup5.analyze()
eig_res5.sim.convergence_t, eig_res5.sim.convergence_f, _ = hfss5.get_convergences()
eig_res5.sim.plot_convergences()
hfss1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/cpw5_e-field.png")
from qiskit_metal.analyses.quantization import EPRanalysis
eig_res6 = EPRanalysis(design, "hfss")
hfss6 = eig_res6.sim.renderer
hfss6.start()
readout_lines[0].options.total_length = '8522.72 um'
gui.rebuild()
hfss6.activate_ansys_design("Tune_ol1", 'eigenmode')
hfss6.render_design(['ol1'], [('ol1', 'start'), ('ol1', 'end')])
hfss6.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/ol1.png")
# Analysis properties
setup6 = hfss6.pinfo.setup
setup6.passes = 10
setup6.n_modes = 1
print(f"""
Number of eigenmodes to find = {setup6.n_modes}
Number of simulation passes = {setup6.passes}
Convergence freq max delta percent diff = {setup6.delta_f}
""")
# Next 2 lines are counterinuitive, since there is no junction in this resonator.
# However, these are necessary to make pyEPR work correctly. Please do note delete
hfss6.pinfo.design.set_variable('Lj', '12 nH')
hfss6.pinfo.design.set_variable('Cj', '1 fF')
setup6.analyze()
eig_res6.sim.convergence_t, eig_res6.sim.convergence_f, _ = hfss6.get_convergences()
eig_res6.sim.plot_convergences()
hfss1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/ol1_e-field.png")
from qiskit_metal.analyses.quantization import EPRanalysis
eig_res7 = EPRanalysis(design, "hfss")
hfss7 = eig_res7.sim.renderer
hfss7.start()
readout_lines[1].options.total_length = '8426.96 um'
gui.rebuild()
hfss7.activate_ansys_design("Tune_ol2", 'eigenmode')
hfss7.render_design(['ol2'], [('ol2', 'start'), ('ol2', 'end')])
hfss7.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/ol2.png")
# Analysis properties
setup7 = hfss7.pinfo.setup
setup7.passes = 10
setup7.n_modes = 1
print(f"""
Number of eigenmodes to find = {setup7.n_modes}
Number of simulation passes = {setup7.passes}
Convergence freq max delta percent diff = {setup7.delta_f}
""")
# Next 2 lines are counterinuitive, since there is no junction in this resonator.
# However, these are necessary to make pyEPR work correctly. Please do note delete
hfss7.pinfo.design.set_variable('Lj', '12 nH')
hfss7.pinfo.design.set_variable('Cj', '1 fF')
setup7.analyze()
eig_res7.sim.convergence_t, eig_res7.sim.convergence_f, _ = hfss7.get_convergences()
eig_res7.sim.plot_convergences()
hfss5.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/ol2_e-field.png")
from qiskit_metal.analyses.quantization import EPRanalysis
eig_res8 = EPRanalysis(design, "hfss")
hfss8 = eig_res8.sim.renderer
hfss8.start()
readout_lines[2].options.total_length = '8333.33 um'
gui.rebuild()
hfss8.activate_ansys_design("Tune_ol3", 'eigenmode')
hfss8.render_design(['ol3'], [('ol3', 'start'), ('ol3', 'end')])
hfss8.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/ol3.png")
# Analysis properties
setup8 = hfss8.pinfo.setup
setup8.passes = 10
setup8.n_modes = 1
print(f"""
Number of eigenmodes to find = {setup8.n_modes}
Number of simulation passes = {setup8.passes}
Convergence freq max delta percent diff = {setup8.delta_f}
""")
# Next 2 lines are counterinuitive, since there is no junction in this resonator.
# However, these are necessary to make pyEPR work correctly. Please do note delete
hfss8.pinfo.design.set_variable('Lj', '12 nH')
hfss8.pinfo.design.set_variable('Cj', '1 fF')
setup8.analyze()
eig_res8.sim.convergence_t, eig_res8.sim.convergence_f, _ = hfss8.get_convergences()
eig_res8.sim.plot_convergences()
hfss1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/ol3_e-field.png")
from qiskit_metal.analyses.quantization import EPRanalysis
eig_res9 = EPRanalysis(design, "hfss")
hfss9 = eig_res9.sim.renderer
hfss9.start()
readout_lines[3].options.total_length = '8241.75 um'
gui.rebuild()
hfss9.activate_ansys_design("Tune_ol4", 'eigenmode')
hfss9.render_design(['ol4'], [('ol4', 'start'), ('ol4', 'end')])
hfss9.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/ol4.png")
# Analysis properties
setup9 = hfss9.pinfo.setup
setup9.passes = 10
setup9.n_modes = 1
print(f"""
Number of eigenmodes to find = {setup9.n_modes}
Number of simulation passes = {setup9.passes}
Convergence freq max delta percent diff = {setup9.delta_f}
""")
# Next 2 lines are counterinuitive, since there is no junction in this resonator.
# However, these are necessary to make pyEPR work correctly. Please do note delete
hfss9.pinfo.design.set_variable('Lj', '12 nH')
hfss9.pinfo.design.set_variable('Cj', '1 fF')
setup9.analyze()
eig_res9.sim.convergence_t, eig_res9.sim.convergence_f, _ = hfss9.get_convergences()
eig_res9.sim.plot_convergences()
hfss1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/ol4_e-field.png")
|
https://github.com/AbeerVaishnav13/4-qubit-design
|
AbeerVaishnav13
|
%load_ext autoreload
%autoreload 2
import scqubits as scq
from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix
from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem, QuantumSystemRegistry
from scipy.constants import speed_of_light as c_light
import matplotlib.pyplot as plt
%matplotlib inline
QuantumSystemRegistry.registry()
# Q1
path1 = "./capacitance_matrices/Q1_cap_matrix.txt"
t1_mat, _, _, _ = load_q3d_capacitance_matrix(path1)
# Q2
path2 = "./capacitance_matrices/Q2_cap_matrix.txt"
t2_mat, _, _, _ = load_q3d_capacitance_matrix(path2)
# Q3
path3 = "./capacitance_matrices/Q3_cap_matrix.txt"
t3_mat, _, _, _ = load_q3d_capacitance_matrix(path3)
# Q4
path4 = "./capacitance_matrices/Q4_cap_matrix.txt"
t4_mat, _, _, _ = load_q3d_capacitance_matrix(path4)
# Cell 2: Transmon-2
opt2 = dict(
node_rename = {'b_connector_pad_Q2': 'coupler23',
'c_connector_pad_Q2': 'readout2'},
cap_mat = t2_mat,
ind_dict = {('pad_top_Q2', 'pad_bot_Q2'): 12}, # junction inductance in nH
jj_dict = {('pad_top_Q2', 'pad_bot_Q2'): 'j2'},
cj_dict = {('pad_top_Q2', 'pad_bot_Q2'): 1}, # junction capacitance in fF
)
cell_2 = Cell(opt2)
# Cell 3: Transmon-3
opt3 = dict(
node_rename = {'b_connector_pad_Q3': 'coupler23',
'c_connector_pad_Q3': 'readout3'},
cap_mat = t3_mat,
ind_dict = {('pad_top_Q3', 'pad_bot_Q3'): 12}, # junction inductance in nH
jj_dict = {('pad_top_Q3', 'pad_bot_Q3'): 'j3'},
cj_dict = {('pad_top_Q3', 'pad_bot_Q3'): 1}, # junction capacitance in fF
)
cell_3 = Cell(opt3)
# subsystem 1: Transmon-2
transmon2 = Subsystem(name='transmon2', sys_type='TRANSMON', nodes=['j2'])
# subsystem 2: Transmon-3
transmon3 = Subsystem(name='transmon3', sys_type='TRANSMON', nodes=['j3'])
# Resonator Subsystems
q_opts = dict(
Z0 = 50, # characteristic impedance in Ohm
vp = 0.404314 * c_light # phase velocity
)
# subsystem 3: Q2 readout resonator
ro2 = Subsystem(name='readout2', sys_type='TL_RESONATOR', nodes=['readout2'], q_opts=dict(f_res = 6.96, **q_opts))
# subsystem 4: Q3 readout resonator
ro3 = Subsystem(name='readout3', sys_type='TL_RESONATOR', nodes=['readout3'], q_opts=dict(f_res = 6.98, **q_opts))
# subsystem 15: Q2-Q3 coupling resonator
coup23 = Subsystem(name='coupler23', sys_type='TL_RESONATOR', nodes=['coupler23'], q_opts=dict(f_res = 7.36, **q_opts))
composite_sys = CompositeSystem(
subsystems=[transmon2, transmon3, coup23, ro2, ro3],
cells=[cell_2, cell_3],
grd_node='ground_main_plane',
nodes_force_keep=['readout2', 'readout3', 'coupler23']
)
cg = composite_sys.circuitGraph()
print(cg)
hilbertspace = composite_sys.create_hilbertspace()
print(hilbertspace)
# Convert the hilbert space into
# "Interaction Picture"
hilbertspace = composite_sys.add_interaction()
hilbertspace.hamiltonian()
hamiltonian_results = composite_sys.hamiltonian_results(hilbertspace, evals_count=30)
composite_sys.compute_gs()
|
https://github.com/pochangl/qiskit-experiment
|
pochangl
|
'''
This program sets up the Half Adder and the Full Adder and creates a .tex file
with the gate geometry. It also evaluates the result with a qasm quantum
simulator
'''
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, \
execute, result, Aer
import os
import shutil
import numpy as np
import lib.adder as adder
import lib.quantum_logic as logic
LaTex_folder_Adder_gates = str(os.getcwd())+'/Latex_quantum_gates/Adder-gates/'
if not os.path.exists(LaTex_folder_Adder_gates):
os.makedirs(LaTex_folder_Adder_gates)
else:
shutil.rmtree(LaTex_folder_Adder_gates)
os.makedirs(LaTex_folder_Adder_gates)
qubit_space = ['0','1']
## Half Adder (my version)
print("Test Half Adder (my version",'\n')
for add0 in qubit_space: # loop over all possible additions
for add1 in qubit_space:
q = QuantumRegister(3, name = 'q')
c = ClassicalRegister(2, name = 'c')
qc = QuantumCircuit(q,c)
for qubit in q:
qc.reset(qubit)
# initialisation
if(add0== '1'):
qc.x(q[0])
if(add1 == '1'):
qc.x(q[1])
adder.Half_Adder(qc, q[0],q[1],q[2])
qc.measure(q[0], c[0])
qc.measure(q[2], c[1])
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
results = job.result()
count = results.get_counts()
print('|0', add0, '>', '+', '|0', add1, '>', '\t', count)
## Plot a sketch of the gate
q = QuantumRegister(3, name = 'q')
c = ClassicalRegister(2, name = 'c')
qc = QuantumCircuit(q,c)
qc.reset(q[2])
adder.Half_Adder(qc, q[0],q[1],q[2])
qc.measure(q[1], c[0])
qc.measure(q[2], c[1])
LaTex_code = qc.draw(output='latex_source',
justify=None) # draw the circuit
f_name = 'Half_Adder_gate_Benjamin.tex'
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
## Half Adder for two qubits (Beyond Classical book version)
print("Test Half Adder Beyond Classical")
for add0 in qubit_space: # loop over all possible additions
for add1 in qubit_space:
q = QuantumRegister(5, name = 'q')
c = ClassicalRegister(2, name = 'c')
qc = QuantumCircuit(q,c)
# initialisation
if(add0 == '1'):
qc.x(q[0])
if(add1 == '1'):
qc.x(q[1])
logic.XOR(qc, q[0],q[1],q[2])
qc.barrier(q)
logic.AND(qc, q[0], q[1], q[3])
qc.barrier(q)
qc.measure(q[2], c[0])
qc.measure(q[3], c[1])
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
results = job.result()
count = results.get_counts()
print('|0', add0, '>', '+', '|0', add1, '>', '\t', count)
if(add0=='0' and add1=='1'):
LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit
f_name = 'Half_Adder_gate_Beyond_Classical.tex'
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
## Full Adder for addition of two-qubits |q1>, |q2>, and a carry bit |qd>
# from another calculation using a anxiliary bit |q0> with a carry qubit |cq>
# which is initialised to |0>
# iteration over all possible values for |q1>, |q2>, and |qd>
print('\n',"Full Adder Test (my version)")
for qubit_2 in qubit_space:
for qubit_1 in qubit_space:
for qubit_d in qubit_space:
string_q1 = str(qubit_1)
string_q2 = str(qubit_2)
string_qd = str(qubit_d)
q1 = QuantumRegister(1, name ='q1')
q2 = QuantumRegister(1, name = 'q2')
qd = QuantumRegister(1, name = 'qd')
q0 = QuantumRegister(1, name = 'q0')
c = ClassicalRegister(2, name = 'c')
qc = QuantumCircuit(q1,q2,qd,q0,c)
for qubit in q1:
qc.reset(qubit)
for qubit in q2:
qc.reset(qubit)
for qubit in qd:
qc.reset(qubit)
for qubit in q0:
qc.reset(qubit)
# initialise qubits which should be added
for i, qubit in enumerate(q1):
if(string_q1[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
for i, qubit in enumerate(q2):
if(string_q2[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
for i, qubit in enumerate(qd):
if(string_qd[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
adder.Full_Adder(qc, q1, q2, qd, q0, c[0])
qc.measure(q0, c[1])
# check the results
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
results = job.result()
count = results.get_counts()
print('|', qubit_1, '>', '+', '|', qubit_2, '>', '+', '|', qubit_d, '> = ' , '\t', count)
if(qubit_1 == '0' and qubit_2 == '0' and qubit_d == '0'):
LaTex_code = qc.draw(output='latex_source') # draw the circuit
f_name = 'Full_Adder_gate_Benjamin.tex'
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
## Test for adding two two-qubit numbers |q1> and |q2>
for qubit1_0 in qubit_space:
for qubit1_1 in qubit_space:
for qubit2_0 in qubit_space:
for qubit2_1 in qubit_space:
string_q1 = str(qubit1_1)+str(qubit1_0)
string_q2 = str(qubit2_1)+str(qubit2_0)
q1 = QuantumRegister(2, name ='q1')
q2 = QuantumRegister(2, name = 'q2')
# qubit to store carry over for significiant bit
q0 = QuantumRegister(1, name = 'q0')
c = ClassicalRegister(3, name = 'c')
qc = QuantumCircuit(q1,q2,q0,c)
for qubit in q1:
qc.reset(qubit)
qc.reset(q2)
qc.reset(q0)
# initialise qubits which should be added
for i, qubit in enumerate(q1):
if(string_q1[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
for i, qubit in enumerate(q2):
if(string_q2[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
adder.Half_Adder(qc,q1[-1],q2[-1],q0)
qc.measure(q2[-1],c[0])
adder.Full_Adder(qc, q1[-2],q2[-2], q0, q2[-1], c[1])
qc.measure(q2[-1], c[2])
# check the results
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
results = job.result()
count = results.get_counts()
print('|', qubit1_1, qubit1_0, '>', '+', '|', qubit2_1,
qubit2_0, '> = ' , '\t', count)
if(qubit1_1 == '0' and qubit1_0 == '1'
and qubit2_1 == '0' and qubit2_0 == '0'):
LaTex_code = qc.draw(output='latex_source') # draw the circuit
# export QASM code
qc.qasm(filename="one_plus_one.qasm")
f_name = 'Adder_gate_for_two_two-qubit_numbers.tex'
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
## Adder for two arbitrary binary numbers
# randomly draw number of bits from the numbers to add
bit_number_q1 = int(np.ceil(10*np.random.rand()))+2
bit_number_q2 = int(np.ceil(10*np.random.rand()))+2
# prepare two random binary numbers
string_q1 = []
string_q2 = []
for i in range(bit_number_q1):
#string_q1.append(1)
string_q1.append(int(np.round(np.random.rand())))
for i in range(bit_number_q2):
string_q2.append(int(np.round(np.random.rand())))
while(len(string_q1)<len(string_q2)):
string_q1 = np.insert(string_q1, 0, 0, axis=0)
while(len(string_q1)>len(string_q2)):
string_q2 = np.insert(string_q2, 0, 1, axis=0)
string_q1 = np.array(string_q1)
string_q2 = np.array(string_q2)
q1 = QuantumRegister(len(string_q1), name = 'q1')
q2 = QuantumRegister(len(string_q2), name = 'q2')
# qubit to store carry over for initial half adder
q0 = QuantumRegister(1, name = 'q0')
c = ClassicalRegister(len(string_q1)+1, name = 'c')
qc = QuantumCircuit(q1,q2,q0,c)
for qubit in q1:
qc.reset(qubit)
for qubit in q2:
qc.reset(qubit)
qc.reset(q0)
# initialise qubits which should be added
for i, qubit in enumerate(q1):
if(string_q1[i] == 1):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\n',end="")
for i, qubit in enumerate(q2):
if(string_q2[i] == 1):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\n')
# initial addition of least significant bits and determining carry bit
adder.Half_Adder(qc, q1[-1], q2[-1], q0)
qc.measure(q2[-1], c[0])
# adding of next significant bits
adder.Full_Adder(qc, q1[-2], q2[-2], q0, q2[-1], c[1])
# adding of other digits by full adder cascade
for i in range(2, len(string_q1)):
adder.Full_Adder(qc,
q1[-i-1], # bit to add
q2[-i-1], # bit to add
#(and to measure as next significant bit)
q2[-i+1], # carry from last calculation
q2[-i], # carry for next calculation
c[i])
qc.measure(q2[-len(string_q1)+1], c[len(string_q1)])
# check the results
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=10)
results = job.result()
count = results.get_counts()
print(count)
LaTex_code = qc.draw(output='latex_source') # draw the circuit
f_name = 'Adder_gate_for_'+str(string_q1)+'_and_'+str(string_q2)+'.tex'
print(f_name)
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
|
https://github.com/pochangl/qiskit-experiment
|
pochangl
|
from argparse import ArgumentParser, Namespace, BooleanOptionalAction
from qiskit import QuantumCircuit as qc
from qiskit import QuantumRegister as qr
from qiskit import transpile
from qiskit_aer import AerSimulator
from qiskit.result import Counts
from matplotlib.pyplot import show, subplots, xticks, yticks
from math import pi, sqrt
from heapq import nlargest
class GroversAlgorithm:
def __init__(self,
title: str = "Grover's Algorithm",
n_qubits: int = 5,
search: set[int] = { 11, 9, 0, 3 },
shots: int = 1000,
fontsize: int = 10,
print: bool = False,
combine_states: bool = False) -> None:
"""
_summary_
Args:
title (str, optional): Window title. Defaults to "Grover's Algorithm".
n_qubits (int, optional): Number of qubits. Defaults to 5.
search (set[int], optional): Set of nonnegative integers to search for using Grover's algorithm. Defaults to { 11, 9, 0, 3 }.
shots (int, optional): Amount of times the algorithm is simulated. Defaults to 10000.
fontsize (int, optional): Histogram's font size. Defaults to 10.
print (bool, optional): Whether or not to print quantum circuit(s). Defaults to False.
combine_states (bool, optional): Whether to combine all non-winning states into 1 bar labeled "Others" or not. Defaults to False.
"""
# Parsing command line arguments
self._parser: ArgumentParser = ArgumentParser(description = "Run grover's algorithm via command line", add_help = False)
self._init_parser(title, n_qubits, search, shots, fontsize, print, combine_states)
self._args: Namespace = self._parser.parse_args()
# Set of nonnegative ints to search for
self.search: set[int] = set(self._args.search)
# Set of m N-qubit binary strings representing target state(s) (i.e. self.search in base 2)
self._targets: set[str] = { f"{s:0{self._args.n_qubits}b}" for s in self.search }
# N-qubit quantum register
self._qubits: qr = qr(self._args.n_qubits, "qubit")
def _print_circuit(self, circuit: qc, name: str) -> None:
"""Print quantum circuit.
Args:
circuit (qc): Quantum circuit to print.
name (str): Quantum circuit's name.
"""
print(f"\n{name}:\n{circuit}")
def _oracle(self, targets: set[str]) -> qc:
"""Mark target state(s) with negative phase.
Args:
targets (set[str]): N-qubit binary string(s) representing target state(s).
Returns:
qc: Quantum circuit representation of oracle.
"""
# Create N-qubit quantum circuit for oracle
oracle = qc(self._qubits, name = "Oracle")
for target in targets:
# Reverse target state since Qiskit uses little-endian for qubit ordering
target = target[::-1]
# Flip zero qubits in target
for i in range(self._args.n_qubits):
if target[i] == "0":
# Pauli-X gate
oracle.x(i)
# Simulate (N - 1)-control Z gate
# 1. Hadamard gate
oracle.h(self._args.n_qubits - 1)
# 2. (N - 1)-control Toffoli gate
oracle.mcx(list(range(self._args.n_qubits - 1)), self._args.n_qubits - 1)
# 3. Hadamard gate
oracle.h(self._args.n_qubits - 1)
# Flip back to original state
for i in range(self._args.n_qubits):
if target[i] == "0":
# Pauli-X gate
oracle.x(i)
# Display oracle, if applicable
if self._args.print: self._print_circuit(oracle, "ORACLE")
return oracle
def _diffuser(self) -> qc:
"""Amplify target state(s) amplitude, which decreases the amplitudes of other states
and increases the probability of getting the correct solution (i.e. target state(s)).
Returns:
qc: Quantum circuit representation of diffuser (i.e. Grover's diffusion operator).
"""
# Create N-qubit quantum circuit for diffuser
diffuser = qc(self._qubits, name = "Diffuser")
# Hadamard gate
diffuser.h(self._qubits)
# Oracle with all zero target state
diffuser.append(self._oracle({"0" * self._args.n_qubits}), list(range(self._args.n_qubits)))
# Hadamard gate
diffuser.h(self._qubits)
# Display diffuser, if applicable
if self._args.print: self._print_circuit(diffuser, "DIFFUSER")
return diffuser
def _grover(self) -> qc:
"""Create quantum circuit representation of Grover's algorithm,
which consists of 4 parts: (1) state preparation/initialization,
(2) oracle, (3) diffuser, and (4) measurement of resulting state.
Steps 2-3 are repeated an optimal number of times (i.e. Grover's
iterate) in order to maximize probability of success of Grover's algorithm.
Returns:
qc: Quantum circuit representation of Grover's algorithm.
"""
# Create N-qubit quantum circuit for Grover's algorithm
grover = qc(self._qubits, name = "Grover Circuit")
# Intialize qubits with Hadamard gate (i.e. uniform superposition)
grover.h(self._qubits)
# # Apply barrier to separate steps
grover.barrier()
# Apply oracle and diffuser (i.e. Grover operator) optimal number of times
for _ in range(int((pi / 4) * sqrt((2 ** self._args.n_qubits) / len(self._targets)))):
grover.append(self._oracle(self._targets), list(range(self._args.n_qubits)))
grover.append(self._diffuser(), list(range(self._args.n_qubits)))
# Measure all qubits once finished
grover.measure_all()
# Display grover circuit, if applicable
if self._args.print: self._print_circuit(grover, "GROVER CIRCUIT")
return grover
def _outcome(self, winners: list[str], counts: Counts) -> None:
"""Print top measurement(s) (state(s) with highest frequency)
and target state(s) in binary and decimal form, determine
if top measurement(s) equals target state(s), then print result.
Args:
winners (list[str]): State(s) (N-qubit binary string(s))
with highest probability of being measured.
counts (Counts): Each state and its respective frequency.
"""
print("WINNER(S):")
print(f"Binary = {winners}\nDecimal = {[ int(key, 2) for key in winners ]}\n")
print("TARGET(S):")
print(f"Binary = {self._targets}\nDecimal = {self.search}\n")
if not all(key in self._targets for key in winners): print("Target(s) not found...")
else:
winners_frequency, total = 0, 0
for value, frequency in counts.items():
if value in winners:
winners_frequency += frequency
total += frequency
print(f"Target(s) found with {winners_frequency / total:.2%} accuracy!")
def _show_histogram(self, histogram_data) -> None:
"""Print outcome and display histogram of simulation results.
Args:
data: Each state and its respective frequency.
"""
# State(s) with highest count and their frequencies
winners = { winner : histogram_data.get(winner) for winner in nlargest(len(self._targets), histogram_data, key = histogram_data.get) }
# Print outcome
self._outcome(list(winners.keys()), histogram_data)
# X-axis and y-axis value(s) for winners, respectively
winners_x_axis = [ str(winner) for winner in [*winners] ]
winners_y_axis = [ *winners.values() ]
# All other states (i.e. non-winners) and their frequencies
others = { state : frequency for state, frequency in histogram_data.items() if state not in winners }
# X-axis and y-axis value(s) for all other states, respectively
other_states_x_axis = "Others" if self._args.combine else [*others]
other_states_y_axis = [ sum([*others.values()]) ] if self._args.combine else [ *others.values() ]
# Create histogram for simulation results
figure, axes = subplots(num = "Grover's Algorithm — Results", layout = "constrained")
axes.bar(winners_x_axis, winners_y_axis, color = "green", label = "Target")
axes.bar(other_states_x_axis, other_states_y_axis, color = "red", label = "Non-target")
axes.legend(fontsize = self._args.fontsize)
axes.grid(axis = "y", ls = "dashed")
axes.set_axisbelow(True)
# Set histogram title, x-axis title, and y-axis title respectively
axes.set_title(f"Outcome of {self._args.shots} Simulations", fontsize = int(self._args.fontsize * 1.45))
axes.set_xlabel("States (Qubits)", fontsize = int(self._args.fontsize * 1.3))
axes.set_ylabel("Frequency", fontsize = int(self._args.fontsize * 1.3))
# Set font properties for x-axis and y-axis labels respectively
xticks(fontsize = self._args.fontsize, family = "monospace", rotation = 0 if self._args.combine else 70)
yticks(fontsize = self._args.fontsize, family = "monospace")
# Set properties for annotations displaying frequency above each bar
annotation = axes.annotate("",
xy = (0, 0),
xytext = (5, 5),
xycoords = "data",
textcoords = "offset pixels",
ha = "center",
va = "bottom",
family = "monospace",
weight = "bold",
fontsize = self._args.fontsize,
bbox = dict(facecolor = "white", alpha = 0.4, edgecolor = "None", pad = 0)
)
def _hover(event) -> None:
"""Display frequency above each bar upon hovering over it.
Args:
event: Matplotlib event.
"""
visibility = annotation.get_visible()
if event.inaxes == axes:
for bars in axes.containers:
for bar in bars:
cont, _ = bar.contains(event)
if cont:
x, y = bar.get_x() + bar.get_width() / 2, bar.get_y() + bar.get_height()
annotation.xy = (x, y)
annotation.set_text(y)
annotation.set_visible(True)
figure.canvas.draw_idle()
return
if visibility:
annotation.set_visible(False)
figure.canvas.draw_idle()
# Display histogram
id = figure.canvas.mpl_connect("motion_notify_event", _hover)
show()
figure.canvas.mpl_disconnect(id)
def run(self) -> None:
"""
Run Grover's algorithm simulation.
"""
# Simulate Grover's algorithm locally
backend = AerSimulator(method = "density_matrix")
# Generate optimized grover circuit for simulation
transpiled_circuit = transpile(self._grover(), backend, optimization_level = 2)
# Run Grover's algorithm simulation
job = backend.run(transpiled_circuit, shots = self._args.shots)
# Get simulation results
results = job.result()
# Get each state's histogram data (including frequency) from simulation results
data = results.get_counts()
# Display simulation results
self._show_histogram(data)
def _init_parser(self,
title: str,
n_qubits: int,
search: set[int],
shots: int,
fontsize: int,
print: bool,
combine_states: bool) -> None:
"""
Helper method to initialize command line argument parser.
Args:
title (str): Window title.
n_qubits (int): Number of qubits.
search (set[int]): Set of nonnegative integers to search for using Grover's algorithm.
shots (int): Amount of times the algorithm is simulated.
fontsize (int): Histogram's font size.
print (bool): Whether or not to print quantum circuit(s).
combine_states (bool): Whether to combine all non-winning states into 1 bar labeled "Others" or not.
"""
self._parser.add_argument("-H, --help",
action = "help",
help = "show this help message and exit")
self._parser.add_argument("-T, --title",
type = str,
default = title,
dest = "title",
metavar = "<title>",
help = f"window title (default: \"{title}\")")
self._parser.add_argument("-n, --n-qubits",
type = int,
default = n_qubits,
dest = "n_qubits",
metavar = "<n_qubits>",
help = f"number of qubits (default: {n_qubits})")
self._parser.add_argument("-s, --search",
default = search,
type = int,
nargs = "+",
dest = "search",
metavar = "<search>",
help = f"nonnegative integers to search for with Grover's algorithm (default: {search})")
self._parser.add_argument("-S, --shots",
type = int,
default = shots,
dest = "shots",
metavar = "<shots>",
help = f"amount of times the algorithm is simulated (default: {shots})")
self._parser.add_argument("-f, --font-size",
type = int,
default = fontsize,
dest = "fontsize",
metavar = "<font_size>",
help = f"histogram's font size (default: {fontsize})")
self._parser.add_argument("-p, --print",
action = BooleanOptionalAction,
type = bool,
default = print,
dest = "print",
help = f"whether or not to print quantum circuit(s) (default: {print})")
self._parser.add_argument("-c, --combine",
action = BooleanOptionalAction,
type = bool,
default = combine_states,
dest = "combine",
help = f"whether to combine all non-winning states into 1 bar labeled \"Others\" or not (default: {combine_states})")
if __name__ == "__main__":
GroversAlgorithm().run()
|
https://github.com/pochangl/qiskit-experiment
|
pochangl
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Utils for using with Qiskit unit tests."""
import logging
import os
import unittest
from enum import Enum
from qiskit import __path__ as qiskit_path
class Path(Enum):
"""Helper with paths commonly used during the tests."""
# Main SDK path: qiskit/
SDK = qiskit_path[0]
# test.python path: qiskit/test/python/
TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python'))
# Examples path: examples/
EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples'))
# Schemas path: qiskit/schemas
SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas'))
# VCR cassettes path: qiskit/test/cassettes/
CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes'))
# Sample QASMs path: qiskit/test/python/qasm
QASMS = os.path.normpath(os.path.join(TEST, 'qasm'))
def setup_test_logging(logger, log_level, filename):
"""Set logging to file and stdout for a logger.
Args:
logger (Logger): logger object to be updated.
log_level (str): logging level.
filename (str): name of the output file.
"""
# Set up formatter.
log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
' %(message)s'.format(logger.name))
formatter = logging.Formatter(log_fmt)
# Set up the file handler.
file_handler = logging.FileHandler(filename)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Set the logging level from the environment variable, defaulting
# to INFO if it is not a valid level.
level = logging._nameToLevel.get(log_level, logging.INFO)
logger.setLevel(level)
class _AssertNoLogsContext(unittest.case._AssertLogsContext):
"""A context manager used to implement TestCase.assertNoLogs()."""
# pylint: disable=inconsistent-return-statements
def __exit__(self, exc_type, exc_value, tb):
"""
This is a modified version of TestCase._AssertLogsContext.__exit__(...)
"""
self.logger.handlers = self.old_handlers
self.logger.propagate = self.old_propagate
self.logger.setLevel(self.old_level)
if exc_type is not None:
# let unexpected exceptions pass through
return False
if self.watcher.records:
msg = 'logs of level {} or higher triggered on {}:\n'.format(
logging.getLevelName(self.level), self.logger.name)
for record in self.watcher.records:
msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname,
record.lineno,
record.getMessage())
self._raiseFailure(msg)
|
https://github.com/JavaFXpert/quantum-pong
|
JavaFXpert
|
#
# Copyright 2019 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from model import circuit_node_types as node_types
class CircuitGridModel():
"""Grid-based model that is built when user interacts with circuit"""
def __init__(self, max_wires, max_columns):
self.max_wires = max_wires
self.max_columns = max_columns
self.nodes = np.empty((max_wires, max_columns),
dtype = CircuitGridNode)
def __str__(self):
retval = ''
for wire_num in range(self.max_wires):
retval += '\n'
for column_num in range(self.max_columns):
# retval += str(self.nodes[wire_num][column_num]) + ', '
retval += str(self.get_node_gate_part(wire_num, column_num)) + ', '
return 'CircuitGridModel: ' + retval
# def set_node(self, wire_num, column_num, node_type, radians=0, ctrl_a=-1, ctrl_b=-1, swap=-1):
def set_node(self, wire_num, column_num, circuit_grid_node):
self.nodes[wire_num][column_num] = \
CircuitGridNode(circuit_grid_node.node_type,
circuit_grid_node.radians,
circuit_grid_node.ctrl_a,
circuit_grid_node.ctrl_b,
circuit_grid_node.swap)
# TODO: Decide whether to protect as shown below
# if not self.nodes[wire_num][column_num]:
# self.nodes[wire_num][column_num] = CircuitGridNode(node_type, radians)
# else:
# print('Node ', wire_num, column_num, ' not empty')
def get_node(self, wire_num, column_num):
return self.nodes[wire_num][column_num]
def get_node_gate_part(self, wire_num, column_num):
requested_node = self.nodes[wire_num][column_num]
if requested_node and requested_node.node_type != node_types.EMPTY:
# Node is occupied so return its gate
return requested_node.node_type
else:
# Check for control nodes from gates in other nodes in this column
nodes_in_column = self.nodes[:, column_num]
for idx in range(self.max_wires):
if idx != wire_num:
other_node = nodes_in_column[idx]
if other_node:
if other_node.ctrl_a == wire_num or other_node.ctrl_b == wire_num:
return node_types.CTRL
elif other_node.swap == wire_num:
return node_types.SWAP
return node_types.EMPTY
def get_gate_wire_for_control_node(self, control_wire_num, column_num):
"""Get wire for gate that belongs to a control node on the given wire"""
gate_wire_num = -1
nodes_in_column = self.nodes[:, column_num]
for wire_idx in range(self.max_wires):
if wire_idx != control_wire_num:
other_node = nodes_in_column[wire_idx]
if other_node:
if other_node.ctrl_a == control_wire_num or \
other_node.ctrl_b == control_wire_num:
gate_wire_num = wire_idx
print("Found gate: ",
self.get_node_gate_part(gate_wire_num, column_num),
" on wire: " , gate_wire_num)
return gate_wire_num
# def avail_gate_parts_for_node(self, wire_num, column_num):
# retval = np.empty(0, dtype = np.int8)
# node_gate_part = self.get_node_gate_part(wire_num, column_num)
# if node_gate_part == node_types.EMPTY:
# # No gate part in this node
def compute_circuit(self):
qr = QuantumRegister(self.max_wires, 'q')
qc = QuantumCircuit(qr)
for column_num in range(self.max_columns):
for wire_num in range(self.max_wires):
node = self.nodes[wire_num][column_num]
if node:
if node.node_type == node_types.IDEN:
# Identity gate
qc.iden(qr[wire_num])
elif node.node_type == node_types.X:
if node.radians == 0:
if node.ctrl_a != -1:
if node.ctrl_b != -1:
# Toffoli gate
qc.ccx(qr[node.ctrl_a], qr[node.ctrl_b], qr[wire_num])
else:
# Controlled X gate
qc.cx(qr[node.ctrl_a], qr[wire_num])
else:
# Pauli-X gate
qc.x(qr[wire_num])
else:
# Rotation around X axis
qc.rx(node.radians, qr[wire_num])
elif node.node_type == node_types.Y:
if node.radians == 0:
if node.ctrl_a != -1:
# Controlled Y gate
qc.cy(qr[node.ctrl_a], qr[wire_num])
else:
# Pauli-Y gate
qc.y(qr[wire_num])
else:
# Rotation around Y axis
qc.ry(node.radians, qr[wire_num])
elif node.node_type == node_types.Z:
if node.radians == 0:
if node.ctrl_a != -1:
# Controlled Z gate
qc.cz(qr[node.ctrl_a], qr[wire_num])
else:
# Pauli-Z gate
qc.z(qr[wire_num])
else:
if node.ctrl_a != -1:
# Controlled rotation around the Z axis
qc.crz(node.radians, qr[node.ctrl_a], qr[wire_num])
else:
# Rotation around Z axis
qc.rz(node.radians, qr[wire_num])
elif node.node_type == node_types.S:
# S gate
qc.s(qr[wire_num])
elif node.node_type == node_types.SDG:
# S dagger gate
qc.sdg(qr[wire_num])
elif node.node_type == node_types.T:
# T gate
qc.t(qr[wire_num])
elif node.node_type == node_types.TDG:
# T dagger gate
qc.tdg(qr[wire_num])
elif node.node_type == node_types.H:
if node.ctrl_a != -1:
# Controlled Hadamard
qc.ch(qr[node.ctrl_a], qr[wire_num])
else:
# Hadamard gate
qc.h(qr[wire_num])
elif node.node_type == node_types.SWAP:
if node.ctrl_a != -1:
# Controlled Swap
qc.cswap(qr[node.ctrl_a], qr[wire_num], qr[node.swap])
else:
# Swap gate
qc.swap(qr[wire_num], qr[node.swap])
return qc
class CircuitGridNode():
"""Represents a node in the circuit grid"""
def __init__(self, node_type, radians=0.0, ctrl_a=-1, ctrl_b=-1, swap=-1):
self.node_type = node_type
self.radians = radians
self.ctrl_a = ctrl_a
self.ctrl_b = ctrl_b
self.swap = swap
def __str__(self):
string = 'type: ' + str(self.node_type)
string += ', radians: ' + str(self.radians) if self.radians != 0 else ''
string += ', ctrl_a: ' + str(self.ctrl_a) if self.ctrl_a != -1 else ''
string += ', ctrl_b: ' + str(self.ctrl_b) if self.ctrl_b != -1 else ''
return string
|
https://github.com/JavaFXpert/quantum-pong
|
JavaFXpert
|
#measurement.py
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.visualization import plot_histogram
def measurement(qc,n_l,n_b,CU,backend,shots):
t = transpile(qc, backend)
qobj = assemble(t, shots=shots)
results = backend.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer, title="Output Histogram").savefig('./outputs/output_histogram.png',facecolor='#eeeeee')
return answer
|
https://github.com/JavaFXpert/quantum-pong
|
JavaFXpert
|
#!/usr/bin/env python
#
# Copyright 2019 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pygame
from qiskit import BasicAer, QuantumRegister, ClassicalRegister, QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram
from utils import load_image
DEFAULT_NUM_SHOTS = 100
class MeasurementsHistogram(pygame.sprite.Sprite):
"""Displays a histogram with measurements"""
def __init__(self, circuit, num_shots=DEFAULT_NUM_SHOTS):
pygame.sprite.Sprite.__init__(self)
self.image = None
self.rect = None
self.set_circuit(circuit, num_shots)
# def update(self):
# # Nothing yet
# a = 1
def set_circuit(self, circuit, num_shots=DEFAULT_NUM_SHOTS):
backend_sim = BasicAer.get_backend('qasm_simulator')
qr = QuantumRegister(circuit.width(), 'q')
cr = ClassicalRegister(circuit.width(), 'c')
meas_circ = QuantumCircuit(qr, cr)
meas_circ.barrier(qr)
meas_circ.measure(qr, cr)
complete_circuit = circuit + meas_circ
job_sim = execute(complete_circuit, backend_sim, shots=num_shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(complete_circuit)
print(counts)
histogram = plot_histogram(counts)
histogram.savefig("utils/data/bell_histogram.png")
self.image, self.rect = load_image('bell_histogram.png', -1)
self.image.convert()
|
https://github.com/JavaFXpert/quantum-pong
|
JavaFXpert
|
#!/usr/bin/env python
#
# Copyright 2019 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pygame
from qiskit import BasicAer, execute
from qiskit.tools.visualization import plot_state_qsphere
from utils import load_image
class QSphere(pygame.sprite.Sprite):
"""Displays a qsphere"""
def __init__(self, circuit):
pygame.sprite.Sprite.__init__(self)
self.image = None
self.rect = None
self.set_circuit(circuit)
# def update(self):
# # Nothing yet
# a = 1
def set_circuit(self, circuit):
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circuit, backend_sv_sim)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circuit, decimals=3)
qsphere = plot_state_qsphere(quantum_state)
qsphere.savefig("utils/data/bell_qsphere.png")
self.image, self.rect = load_image('bell_qsphere.png', -1)
self.rect.inflate_ip(-100, -100)
self.image.convert()
|
https://github.com/JavaFXpert/quantum-pong
|
JavaFXpert
|
#!/usr/bin/env python
#
# Copyright 2019 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pygame
from qiskit import BasicAer, execute, ClassicalRegister
from utils.colors import *
from utils.fonts import ARIAL_30
from utils.states import comp_basis_states
from copy import deepcopy
#from utils.paddle import *
class StatevectorGrid(pygame.sprite.Sprite):
"""Displays a statevector grid"""
def __init__(self, circuit, qubit_num, num_shots):
pygame.sprite.Sprite.__init__(self)
self.image = None
self.rect = None
self.basis_states = comp_basis_states(circuit.width())
self.set_circuit(circuit, qubit_num, num_shots)
# def update(self):
# # Nothing yet
# a = 1ot
def set_circuit(self, circuit, qubit_num, shot_num):
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circuit, backend_sv_sim, shots=shot_num)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circuit, decimals=3)
# This square represent the probability of state after measurement
self.image = pygame.Surface([(circuit.width()+1) * 50, 500])
self.image.convert()
self.image.fill(BLACK)
self.rect = self.image.get_rect()
block_size = int(round(500 / 2 ** qubit_num))
x_offset = 50
y_offset = 15
self.paddle = pygame.Surface([10, block_size])
self.paddle.convert()
for y in range(len(quantum_state)):
text_surface = ARIAL_30.render("|"+self.basis_states[y]+">", False, (255, 255, 255))
self.image.blit(text_surface,(120, y * block_size + y_offset))
if abs(quantum_state[y]) > 0:
#pygame.draw.rect(self.image, WHITE, rect, 0)
self.paddle.fill(WHITE)
self.paddle.set_alpha(int(round(abs(quantum_state[y])*255)))
self.image.blit(self.paddle,(80,y * block_size))
def set_circuit_measure(self, circuit, qubit_num, shot_num):
backend_sv_sim = BasicAer.get_backend('qasm_simulator')
cr = ClassicalRegister(qubit_num)
circuit2 = deepcopy(circuit)
circuit2.add_register(cr)
circuit2.measure(circuit2.qregs[0],circuit2.cregs[0])
job_sim = execute(circuit2, backend_sv_sim, shots=shot_num)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
print(counts)
#quantum_state = result_sim.get_statevector(circuit, decimals=3)
# This square represent the probability of state after measurement
self.image = pygame.Surface([(circuit.width()+1) * 50, 500])
self.image.convert()
self.image.fill(BLACK)
self.rect = self.image.get_rect()
block_size = int(round(500 / 2 ** qubit_num))
x_offset = 50
y_offset = 15
self.paddle = pygame.Surface([10, block_size])
self.paddle.convert()
self.paddle.fill(WHITE)
#for y in range(len(quantum_state)):
# text_surface = ARIAL_30.render(self.basis_states[y], False, (0, 0, 0))
# self.image.blit(text_surface,(120, y * block_size + y_offset))
# if abs(quantum_state[y]) > 0:
#pygame.draw.rect(self.image, WHITE, rect, 0)
#self.paddle.fill(WHITE)
# self.paddle.set_alpha(int(round(abs(quantum_state[y])*255)))
print(counts.keys())
print(int(list(counts.keys())[0],2))
self.image.blit(self.paddle,(80,int(list(counts.keys())[0],2) * block_size))
#pygame.time.wait(100)
return int(list(counts.keys())[0],2)
|
https://github.com/JavaFXpert/quantum-pong
|
JavaFXpert
|
#!/usr/bin/env python
#
# Copyright 2019 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pygame
from qiskit import BasicAer, execute
from utils.colors import *
from utils.fonts import ARIAL_30
from utils.states import comp_basis_states
class StatevectorGrid1(pygame.sprite.Sprite):
"""Displays a statevector grid"""
def __init__(self, circuit):
pygame.sprite.Sprite.__init__(self)
self.image = None
self.rect = None
self.basis_states = comp_basis_states(circuit.width())
self.set_circuit(circuit)
# def update(self):
# # Nothing yet
# a = 1
def set_circuit(self, circuit):
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circuit, backend_sv_sim)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circuit, decimals=3)
self.image = pygame.Surface([(circuit.width() + 1) * 50, 100 + len(quantum_state) * 50])
self.image.convert()
self.image.fill(BLACK)
self.rect = self.image.get_rect()
block_size = 50
x_offset = 50
y_offset = 50
for y in range(len(quantum_state)):
#text_surface = ARIAL_30.render(self.basis_states[y], False, (0, 0, 0))
#self.image.blit(text_surface,(x_offset, (y + 1) * block_size + y_offset))
rect = pygame.Rect(80, y * block_size, 10, block_size)
if abs(quantum_state[y]) > 0:
pygame.draw.rect(self.image, WHITE, rect, 0)
|
https://github.com/JavaFXpert/quantum-pong
|
JavaFXpert
|
#!/usr/bin/env python
#
# Copyright 2019 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pygame
from qiskit import BasicAer, execute
from utils.colors import *
from utils.fonts import *
from utils.states import comp_basis_states
class UnitaryGrid(pygame.sprite.Sprite):
"""Displays a unitary matrix grid"""
def __init__(self, circuit):
pygame.sprite.Sprite.__init__(self)
self.image = None
self.rect = None
self.basis_states = comp_basis_states(circuit.width())
self.set_circuit(circuit)
# def update(self):
# # Nothing yet
# a = 1
def set_circuit(self, circuit):
backend_unit_sim = BasicAer.get_backend('unitary_simulator')
job_sim = execute(circuit, backend_unit_sim)
result_sim = job_sim.result()
unitary = result_sim.get_unitary(circuit, decimals=3)
# print('unitary: ', unitary)
self.image = pygame.Surface([100 + len(unitary) * 50, 100 + len(unitary) * 50])
self.image.convert()
self.image.fill(WHITE)
self.rect = self.image.get_rect()
block_size = 30
x_offset = 50
y_offset = 50
for y in range(len(unitary)):
text_surface = ARIAL_16.render(self.basis_states[y], False, (0, 0, 0))
self.image.blit(text_surface,(x_offset, (y + 1) * block_size + y_offset))
for x in range(len(unitary)):
text_surface = ARIAL_16.render(self.basis_states[x], False, (0, 0, 0))
self.image.blit(text_surface, ((x + 1) * block_size + x_offset, y_offset))
rect = pygame.Rect((x + 1) * block_size + x_offset,
(y + 1) * block_size + y_offset,
abs(unitary[y][x]) * block_size,
abs(unitary[y][x]) * block_size)
if abs(unitary[y][x]) > 0:
pygame.draw.rect(self.image, BLACK, rect, 1)
|
https://github.com/Anastasia-Sim/PoW-QCSA-fa22
|
Anastasia-Sim
|
hash_dict = {
'0000': '1111',
'0001': '0010',
'0010': '0000',
'0011': '0101',
'0100': '1010',
'0101': '1101',
'0110': '1000',
'0111': '1011',
'1000': '0111',
'1001': '1100',
'1010': '0110',
'1011': '1001',
'1100': '0011',
'1101': '1110',
'1110': '0001',
'1111': '0100'
}
import random
def get_strings(bit_count):
strarr = []
def generate(n, s=''):
if len(s) == n:
strarr.append(s)
else:
generate(n, s + '0')
generate(n, s + '1')
generate(bit_count)
random.shuffle(strarr)
return strarr
def proof_of_work(level, bitlen):
strarr = get_strings(bitlen)
count = 1
for i in strarr:
if hash_dict[i].startswith('0'*level):
# print("found hash", i, "in", count, " tries")
random.shuffle(strarr)
break;
else:
count += 1
return count
def getAvgTries(tries, level=4, bitlen=4):
sum = 0
for i in range(tries):
sum += proof_of_work(level, bitlen)
return sum/tries
getAvgTries(100)
|
https://github.com/Anastasia-Sim/PoW-QCSA-fa22
|
Anastasia-Sim
|
#Importing all the necessary libraries
!pip install qiskit matplotlib
import qiskit
import matplotlib
from qiskit import QuantumCircuit, assemble, Aer, circuit, QuantumRegister, ClassicalRegister
from qiskit.visualization import plot_histogram
from qiskit.quantum_info.operators import Operator
from qiskit.extensions import UnitaryGate
hash_gate = Operator([
[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0],
[0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
])
hash_gate.name = "Hash Gate"
hash_dagger = hash_gate.conjugate().transpose()
hash_gate.name = "Hash Dagger"
#Testing input 0110 -> should get 1000
n_qubits = 4
controls = QuantumRegister(n_qubits)
outputs = ClassicalRegister(n_qubits)
circuit = QuantumCircuit(controls, outputs)
circuit.x(controls[1:3])
circuit.draw()
circuit.append(hash_gate, [0,1,2,3])
circuit.barrier(controls)
circuit.measure(controls, outputs)
circuit.draw()
sim = Aer.get_backend('aer_simulator')
result = sim.run(circuit).result()
counts = result.get_counts()
plot_histogram(counts)
n_qubits = 4
controls = QuantumRegister(n_qubits)
outputs = ClassicalRegister(n_qubits)
circuit = QuantumCircuit(controls, outputs)
circuit.x(controls[1:3])
circuit.draw()
circuit.append(hash_gate, [0,1,2,3])
circuit.append(hash_dagger, [0,1,2,3])
circuit.barrier(controls)
circuit.measure(controls, outputs)
circuit.draw()
# We begin by declaring a simulator for our circuit to run on
sim = Aer.get_backend('aer_simulator')
# We run the simulator with sim.run(QUANTUM CIRCUIT),
# And we get the resulting values with .result()
result = sim.run(circuit).result()
# We then collect the results using .get_counts()
counts = result.get_counts()
# Visualization
plot_histogram(counts)
|
https://github.com/Anastasia-Sim/PoW-QCSA-fa22
|
Anastasia-Sim
|
!pip install qiskit matplotlib
import qiskit
import matplotlib
from qiskit import QuantumCircuit, assemble, Aer, circuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.visualization import plot_histogram
from qiskit.quantum_info.operators import Operator
def hash_operator():
hash_gate = Operator([
[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0],
[0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
])
hash_gate.name = "Hash Gate"
return hash_gate
def dehash_operator():
hash_dagger = hash_operator().conjugate().transpose()
hash_dagger.name = "Hash Dagger"
return hash_dagger
def oracle():
qreg_q = QuantumRegister(4, 'q')
oracle = QuantumCircuit(qreg_q, name='oracle')
oracle.x(qreg_q[2:4])
oracle.cz(qreg_q[2], qreg_q[3])
oracle.x(qreg_q[2:4])
oracle_op = oracle.to_gate()
oracle_op.name = 'oracle'
return oracle
oracle().draw()
# diffuser from https://qiskit.org/textbook/ch-algorithms/grover.html
def diffuser(nqubits):
qc = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qc.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qc.x(qubit)
# Do multi-controlled-Z gate
qc.h(nqubits-1)
qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qc.h(nqubits-1)
# Apply transformation |11..1> -> |00..0>
for qubit in range(nqubits):
qc.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qc.h(qubit)
# We will return the diffuser as a gate
U_s = qc.to_gate()
U_s.name = "diffusor"
return U_s
n_qubits = 4
controls = QuantumRegister(n_qubits)
circuit = QuantumCircuit(controls)
circuit.append(hash_operator(), [0, 1, 2, 3])
circuit.append(oracle(), [0, 1, 2, 3])
circuit.append(dehash_operator(), [0, 1, 2, 3])
circuit.append(diffuser(n_qubits), [0, 1, 2, 3])
#circuit.measure_all()
circuit.draw()
n_qubits = 4
controls = QuantumRegister(n_qubits)
circuit = QuantumCircuit(controls)
#Create uniform superposition of possible inputs
circuit.h([0,1,2,3])
#Run Grover's 2^(4/2) times
circuit.append(hash_operator(), [0, 1, 2, 3])
circuit.append(oracle(), [0, 1, 2, 3])
circuit.append(dehash_operator(), [0, 1, 2, 3])
circuit.append(diffuser(n_qubits), [0, 1, 2, 3])
circuit.append(hash_operator(), [0, 1, 2, 3])
circuit.append(oracle(), [0, 1, 2, 3])
circuit.append(dehash_operator(), [0, 1, 2, 3])
circuit.append(diffuser(n_qubits), [0, 1, 2, 3])
circuit.append(hash_operator(), [0, 1, 2, 3])
circuit.append(oracle(), [0, 1, 2, 3])
circuit.append(dehash_operator(), [0, 1, 2, 3])
circuit.append(diffuser(n_qubits), [0, 1, 2, 3])
circuit.append(hash_operator(), [0, 1, 2, 3])
circuit.append(oracle(), [0, 1, 2, 3])
circuit.append(dehash_operator(), [0, 1, 2, 3])
circuit.append(diffuser(n_qubits), [0, 1, 2, 3])
circuit.measure_all()
circuit.draw()
sim = Aer.get_backend('aer_simulator')
# We run the simulator with sim.run(QUANTUM CIRCUIT),
# And we get the resulting values with .result()
transpiled_grover_circuit = transpile(circuit, sim)
qobj = assemble(transpiled_grover_circuit)
result = sim.run(qobj).result()
# We then collect the results using .get_counts()
counts = result.get_counts()
# Visualization
plot_histogram(counts)
|
https://github.com/Anastasia-Sim/PoW-QCSA-fa22
|
Anastasia-Sim
|
print("hello word")
hash_dict = {
'0000': '1111',
'1000': '0111',
'0001': '0010',
'1001': '1100',
'0010': '0000',
'1010': '0110',
'0011': '0101',
'1011': '1001',
'0100': '1010',
'1100': '0011',
'0101': '1101',
'1101': '1110',
'0110': '1000',
'1110': '0001',
'0111': '1011',
'1111': '0100'
}
import random
def get_strings(usr_input, nonce_len):
strarr = []
#generate all input + nonce combinations
def generate(n, s=usr_input):
if len(s) == n:
strarr.append(s)
else:
generate(n, s + '0')
generate(n, s + '1')
generate(len(usr_input) + nonce_len)
random.shuffle(strarr)
return strarr
def proof_of_work(usr_input, level, nonce_len):
strarr = get_strings(usr_input, nonce_len)
count = 1
for i in strarr:
if hash_dict[i].startswith('0'*level):
# print("found hash", i, "in", count, " tries")
random.shuffle(strarr)
break;
else:
count += 1
return count
def getAvgTries(tries, level=2, nonce_len=3):
sum = 0
usr_input = '1'
for i in range(tries):
sum += proof_of_work(usr_input, level, nonce_len)
return sum/tries
getAvgTries(100)
|
https://github.com/Anastasia-Sim/PoW-QCSA-fa22
|
Anastasia-Sim
|
!pip install qiskit matplotlib
import qiskit
import matplotlib
from qiskit import QuantumCircuit, assemble, Aer, circuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.visualization import plot_histogram
from qiskit.quantum_info.operators import Operator
def hash_operator():
hash_gate = Operator([
[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0],
[0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
])
hash_gate.name = "Hash Gate"
return hash_gate
def dehash_operator():
hash_dagger = hash_operator().conjugate().transpose()
hash_dagger.name = "Hash Dagger"
return hash_dagger
def oracle():
qreg_q = QuantumRegister(4, 'q')
oracle = QuantumCircuit(qreg_q, name='oracle')
oracle.x(qreg_q[2:4])
oracle.cz(qreg_q[2], qreg_q[3])
oracle.x(qreg_q[2:4])
oracle_op = oracle.to_gate()
oracle_op.name = 'oracle'
return oracle
oracle().draw()
# diffuser from https://qiskit.org/textbook/ch-algorithms/grover.html
def diffuser(nqubits):
qc = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qc.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qc.x(qubit)
# Do multi-controlled-Z gate
qc.h(nqubits-1)
qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qc.h(nqubits-1)
# Apply transformation |11..1> -> |00..0>
for qubit in range(nqubits):
qc.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qc.h(qubit)
# We will return the diffuser as a gate
U_s = qc.to_gate()
U_s.name = "diffusor"
return U_s
n_qubits = 4
controls = QuantumRegister(n_qubits)
circuit = QuantumCircuit(controls)
circuit.append(hash_operator(), [0, 1, 2, 3])
circuit.append(oracle(), [0, 1, 2, 3])
circuit.append(dehash_operator(), [0, 1, 2, 3])
circuit.append(diffuser(n_qubits), [0, 1, 2, 3])
#circuit.measure_all()
circuit.draw()
n_qubits = 4
controls = QuantumRegister(n_qubits)
circuit = QuantumCircuit(controls)
#input 0
circuit.i(3)
#Create uniform superposition of possible nonces
circuit.h([0,1,2])
#Run Grover's 2^(4/2) times
circuit.append(hash_operator(), [0, 1, 2, 3])
circuit.append(oracle(), [0, 1, 2, 3])
circuit.append(dehash_operator(), [0, 1, 2, 3])
circuit.append(diffuser(n_qubits), [0, 1, 2, 3])
circuit.append(hash_operator(), [0, 1, 2, 3])
circuit.append(oracle(), [0, 1, 2, 3])
circuit.append(dehash_operator(), [0, 1, 2, 3])
circuit.append(diffuser(n_qubits), [0, 1, 2, 3])
circuit.append(hash_operator(), [0, 1, 2, 3])
circuit.append(oracle(), [0, 1, 2, 3])
circuit.append(dehash_operator(), [0, 1, 2, 3])
circuit.append(diffuser(n_qubits), [0, 1, 2, 3])
circuit.append(hash_operator(), [0, 1, 2, 3])
circuit.append(oracle(), [0, 1, 2, 3])
circuit.append(dehash_operator(), [0, 1, 2, 3])
circuit.append(diffuser(n_qubits), [0, 1, 2, 3])
circuit.measure_all()
circuit.draw()
sim = Aer.get_backend('aer_simulator')
# We run the simulator with sim.run(QUANTUM CIRCUIT),
# And we get the resulting values with .result()
transpiled_grover_circuit = transpile(circuit, sim)
qobj = assemble(transpiled_grover_circuit)
result = sim.run(qobj).result()
# We then collect the results using .get_counts()
counts = result.get_counts()
# Visualization
plot_histogram(counts)
n_qubits = 4
controls = QuantumRegister(n_qubits)
circuit = QuantumCircuit(controls)
#input 1
circuit.x(3)
#Create uniform superposition of possible nonces
circuit.h([0,1,2])
#Run Grover's 2^(4/2) times
circuit.append(hash_operator(), [0, 1, 2, 3])
circuit.append(oracle(), [0, 1, 2, 3])
circuit.append(dehash_operator(), [0, 1, 2, 3])
circuit.append(diffuser(n_qubits), [0, 1, 2, 3])
circuit.append(hash_operator(), [0, 1, 2, 3])
circuit.append(oracle(), [0, 1, 2, 3])
circuit.append(dehash_operator(), [0, 1, 2, 3])
circuit.append(diffuser(n_qubits), [0, 1, 2, 3])
circuit.append(hash_operator(), [0, 1, 2, 3])
circuit.append(oracle(), [0, 1, 2, 3])
circuit.append(dehash_operator(), [0, 1, 2, 3])
circuit.append(diffuser(n_qubits), [0, 1, 2, 3])
circuit.append(hash_operator(), [0, 1, 2, 3])
circuit.append(oracle(), [0, 1, 2, 3])
circuit.append(dehash_operator(), [0, 1, 2, 3])
circuit.append(diffuser(n_qubits), [0, 1, 2, 3])
circuit.measure_all()
circuit.draw()
sim = Aer.get_backend('aer_simulator')
# We run the simulator with sim.run(QUANTUM CIRCUIT),
# And we get the resulting values with .result()
transpiled_grover_circuit = transpile(circuit, sim)
qobj = assemble(transpiled_grover_circuit)
result = sim.run(qobj).result()
# We then collect the results using .get_counts()
counts = result.get_counts()
# Visualization
plot_histogram(counts)
|
https://github.com/rebajram/quantumteleportation
|
rebajram
|
from qiskit import *
import numpy as np
class teleprotocol:
def __init__(self,nq,ne0,ne1,input):
self.n=n
self.input=input
self.qubit = QuantumRegister(nq, "Q")
self.ebit0 = QuantumRegister(ne0, "Alice")
self.ebit1 = QuantumRegister(ne1, "Bob")
self.a = ClassicalRegister(nq, "Alice Q")
self.b = ClassicalRegister(ne0, "Alice A")
self.c = ClassicalRegister(ne1, "Bob B")
self.d = ClassicalRegister(ne1, "Spion")
def Qcirc(self):
qc = QuantumCircuit(self.qubit,self.ebit0,self.ebit1)
for i in range(0, self.n):
if self.input[i]==1:
qc.x(self.qubit[i])
qc.h(self.qubit[i])
if self.input[i]==0:
qc.h(self.qubit[i])
# qc.u(np.pi/2,np.pi/4,np.pi/8,self.qubit[i])
return qc
def Acirc(self):
qc = QuantumCircuit(self.qubit,self.ebit0,self.ebit1)
qc.h(self.ebit0)
qc.cx(self.ebit0, self.ebit1)
qc.barrier()
return qc
def QAcirc(self):
qc = QuantumCircuit(self.qubit,self.ebit0,self.ebit1)
qc.cx(self.qubit,self.ebit0)
qc.h(self.qubit)
qc.barrier()
return qc
def M0circ(self):
qc = QuantumCircuit(self.qubit,self.ebit0,self.ebit1,self.a,self.b,self.c,self.d)
qc.measure(self.ebit0, self.a)
qc.measure(self.qubit, self.b)
qc.barrier()
return qc
def M1circ(self):
qc = QuantumCircuit(self.qubit,self.ebit0,self.ebit1,self.a,self.b,self.c,self.d)
for i in range(0, self.n):
with qc.if_test((self.a[i], 1)):
qc.x(self.ebit1[i])
with qc.if_test((self.b[i], 1)):
qc.z(self.ebit1[i])
qc.barrier()
return qc,self.a,self.b
def SPcirc(self):
qc = QuantumCircuit(self.qubit,self.ebit0,self.ebit1,self.a,self.b,self.c,self.d)
qc.measure(self.ebit1, self.d)
qc.barrier()
return qc,self.d
def Bobmeasure(self):
qc = QuantumCircuit(self.qubit,self.ebit0,self.ebit1,self.a,self.b,self.c,self.d)
qc.h(self.ebit1)
qc.measure(self.ebit1, self.c)
qc.barrier()
return qc,self.c
n=6
input=[1,0,0,1,1,1]
qc=teleprotocol(n,0,0,input).Qcirc()
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = backend.run(qc)
result = job.result()
qubitstate = result.get_statevector(qc, decimals=3)
qubitstate.draw('latex')
qc=teleprotocol(0,n,n,input).Acirc()
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = backend.run(qc)
result = job.result()
qcstate = result.get_statevector(qc, decimals=3)
qcstate.draw('latex')
qc1=teleprotocol(n,n,n,input).Qcirc()
qc2=teleprotocol(n,n,n,input).Acirc()
qc3=teleprotocol(n,n,n,input).QAcirc()
qcSpion,c=teleprotocol(n,n,n,input).SPcirc()
qcnew = qc1.compose(qc2)
#qcnew = qcnew.compose(qc3)
#qcnew = qcnew.compose(qcSpion)
qcnew.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = backend.run(qcnew)
result = job.result()
qcstate = result.get_statevector(qcnew, decimals=3)
qcstate.draw('latex')
qc1=teleprotocol(n,n,n,input).Qcirc()
qc2=teleprotocol(n,n,n,input).Acirc()
qc3=teleprotocol(n,n,n,input).QAcirc()
qc4=teleprotocol(n,n,n,input).M0circ()
qc5,a,b=teleprotocol(n,n,n,input).M1circ()
qcSpion,c=teleprotocol(n,n,n,input).SPcirc()
qc6,d=teleprotocol(n,n,n,input).Bobmeasure()
#qcnew = qc1
qcnew = qc1.compose(qc2)
qcnew = qcnew.compose(qc3)
qcnew = qcnew.compose(qc4)
qcnew.draw('mpl')
job=backend.run(qcnew,shots=1)
result=job.result()
qcstate = result.get_statevector(qcnew, decimals=3)
qcstate.draw('latex')
counts=result.get_counts(qcnew)
print(counts)
qc1=teleprotocol(n,n,n,input).Qcirc()
qc2=teleprotocol(n,n,n,input).Acirc()
qc3=teleprotocol(n,n,n,input).QAcirc()
qc4=teleprotocol(n,n,n,input).M0circ()
qc5,a,b=teleprotocol(n,n,n,input).M1circ()
qcSpion,c=teleprotocol(n,n,n,input).SPcirc()
qc6,d=teleprotocol(n,n,n,input).Bobmeasure()
#qcnew = qc1
qcnew = qc1.compose(qc2)
spion = qcnew.compose(qcSpion)
#qcnew = qcnew.compose(qcSpion)
qcnew = qcnew.compose(qc3)
qcnew = qcnew.compose(qc4)
qcnew = qcnew.compose(qc5)
qcnew.draw('mpl')
job=backend.run(qcnew,shots=1)
result=job.result()
qcstate = result.get_statevector(qcnew, decimals=3)
qcstate.draw('latex')
qc1=teleprotocol(n,n,n,input).Qcirc()
qc2=teleprotocol(n,n,n,input).Acirc()
qc3=teleprotocol(n,n,n,input).QAcirc()
qc4=teleprotocol(n,n,n,input).M0circ()
qc5,a,b=teleprotocol(n,n,n,input).M1circ()
qcSpion,c=teleprotocol(n,n,n,input).SPcirc()
qc6,d=teleprotocol(n,n,n,input).Bobmeasure()
#qcnew = qc1
qcnew = qc1.compose(qc2)
spion = qcnew.compose(qcSpion)
#qcnew = qcnew.compose(qcSpion)
qcnew = qcnew.compose(qc3)
qcnew = qcnew.compose(qc4)
qcnew = qcnew.compose(qc5)
qcnew = qcnew.compose(qc6)
qcnew.draw('mpl')
job=backend.run(qcnew,shots=1)
result=job.result()
qcstate = result.get_statevector(qcnew, decimals=3)
qcstate.draw('latex')
counts=result.get_counts(qcnew)
print(counts)
|
https://github.com/oscarhiggott/pewpew-qube
|
oscarhiggott
|
%matplotlib notebook
# import pygame to run the PewPew emulator from a notebook
import pygame
# add the src directory to the search path to load modules
import sys
sys.path.insert(0, "../src/")
qiskit_images = (
(
(0, 3, 3, 3, 3, 3, 3, 0),
(3, 2, 0, 1, 1, 0, 0, 3),
(3, 0, 2, 0, 0, 1, 0, 3),
(3, 1, 0, 2, 0, 0, 1, 3),
(3, 3, 0, 0, 2, 0, 3, 3),
(3, 0, 3, 3, 3, 3, 0, 3),
(3, 0, 0, 0, 0, 0, 2, 3),
(0, 3, 3, 3, 3, 3, 3, 0)
),
(
(0, 3, 3, 3, 3, 3, 3, 0),
(3, 0, 0, 2, 1, 0, 0, 3),
(3, 0, 1, 2, 0, 1, 0, 3),
(3, 1, 0, 0, 2, 0, 1, 3),
(3, 3, 0, 0, 2, 0, 3, 3),
(3, 0, 3, 3, 3, 3, 0, 3),
(3, 0, 0, 0, 0, 2, 0, 3),
(0, 3, 3, 3, 3, 3, 3, 0)
),
(
(0, 3, 3, 3, 3, 3, 3, 0),
(3, 0, 0, 1, 2, 0, 0, 3),
(3, 0, 1, 0, 2, 1, 0, 3),
(3, 1, 0, 2, 0, 0, 1, 3),
(3, 3, 0, 2, 0, 0, 3, 3),
(3, 0, 3, 3, 3, 3, 0, 3),
(3, 0, 2, 0, 0, 0, 0, 3),
(0, 3, 3, 3, 3, 3, 3, 0)
),
(
(0, 3, 3, 3, 3, 3, 3, 0),
(3, 0, 0, 1, 1, 0, 2, 3),
(3, 0, 1, 0, 0, 2, 0, 3),
(3, 1, 0, 0, 2, 0, 1, 3),
(3, 3, 0, 2, 0, 0, 3, 3),
(3, 0, 3, 3, 3, 3, 0, 3),
(3, 2, 0, 0, 0, 0, 0, 3),
(0, 3, 3, 3, 3, 3, 3, 0)
)
)
import pew
i = 0 # frame counter
value = 0 # selected level
pew.init() # initialize the PewPew console
# main loop
while not value:
# check for pressed keys
keys = pew.keys()
if keys & pew.K_UP:
value = 1
elif keys & pew.K_RIGHT:
value = 2
elif keys & pew.K_DOWN:
value = 3
elif keys & pew.K_LEFT:
value = 4
# display the next frame
animation = (0,0,1,1,2,2,3,3,2,2,1,1)
i = (i + 1) % len(animation)
screen = qiskit_images[animation[i]]
pew.show(pew.Pix.from_iter(screen))
# wait 0.1 seconds
pew.tick(0.1)
# freeze the screen while a button is pressed
while pew.keys():
pew.tick(0.1)
# the following is just necessary in a jupyter notebook:
pygame.display.quit()
pygame.quit()
import random
import time
# initialize the random-number generator
random.seed(int(time.monotonic()*1000))
# unload unnecessary objects to save RAM
del qiskit_images
# load the new main loop
from loop import main_loop
# execute the new main loop passing to it the seleced level
if value == 1:
from rotations import instruction_set_XYZ
main_loop(instruction_set_XYZ())
else:
from instruction_sets import InstructionSet
from displays import IBMQ
main_loop(InstructionSet(level=value-2, goal=IBMQ))
# the following is just necessary in a jupyter notebook:
pygame.display.quit()
pygame.quit()
def main_loop(ins):
# initialize PewPew console
pew.init()
# Load start screens
for start_screen in start_screens:
pew.show(pew.Pix.from_iter(start_screen))
pew.tick(0.2)
pew.show(pew.Pix.from_iter(blank_screen))
pew.tick(0.5)
# display the first frame of the level
pew.show(ins.get_current_screen())
# flags used throughout the loop
bool_loop = True
old_keys = 0
# new main loop
while bool_loop:
keys = pew.keys()
if keys != 0 and keys != old_keys:
# old_keys is necessary to debounce the buttons
old_keys = keys
# dispatch the pushed buttons
if keys & pew.K_X:
value = pew.K_X
elif keys & pew.K_DOWN:
value = pew.K_DOWN
elif keys & pew.K_LEFT:
value = pew.K_LEFT
elif keys & pew.K_RIGHT:
value = pew.K_RIGHT
elif keys & pew.K_UP:
value = pew.K_UP
elif keys & pew.K_O:
# the key "O" ("Z" in the emulator) will terminate the game
value = pew.K_O
bool_loop = False
else:
value = 0
# send the pressed key to the instruction set
ins.key_pressed(value)
elif keys == 0:
# this is necessary to be able to push
# a button twice in a row
old_keys = keys
# update the screen and wait for 20ms
pew.show(ins.get_current_screen())
pew.tick(0.02)
# the program has been terminated.
# display the final sequence
for final_screen in final_screens:
pew.show(pew.Pix.from_iter(final_screen))
pew.tick(0.2)
pew.show(pew.Pix.from_iter(blank_screen))
pew.tick(0.2)
class instruction_set_XYZ:
def __init__(self):
# history of pushed keys
self.key_hist = []
# current state vector
self.state = random_state()
def key_pressed(self, key):
if key == pew.K_UP:
# forget all pushed buttons
self.key_hist = []
elif key == pew.K_LEFT or key == pew.K_DOWN or key == pew.K_RIGHT:
# append button to history
self.key_hist.append(key)
# if two buttons have been pressed, determine the corresponding transformation
if len(self.key_hist) == 2:
if self.key_hist[0] == pew.K_LEFT:
gate = 'x'
elif self.key_hist[0] == pew.K_DOWN:
gate = 'y'
else:
gate = 'z'
if self.key_hist[1] == pew.K_LEFT:
gate = gate + 'x'
elif self.key_hist[1] == pew.K_DOWN:
gate = gate + 'y'
else:
gate = gate + 'z'
# update the state vector
self.state = propagate_statevector(self.state, make_circuit(gate))
# clear the history of pushed buttons
self.key_hist = []
elif key == pew.K_X:
# restart the level
self.__init__()
def get_current_screen(self):
return make_image(self.state)
from aether import QuantumCircuit
pi4 = 0.785398
pi2 = 1.570796
def make_circuit(gate):
qc = QuantumCircuit(2)
if gate[0] == 'x':
qc.h(0)
elif gate[0] == 'y':
qc.rx(pi2,0)
if gate[1] == 'x':
qc.h(1)
elif gate[1] == 'y':
qc.rx(pi2,1)
qc.cx(0,1)
qc.h(1)
qc.rx(pi2,1)
qc.h(1)
qc.cx(0,1)
if gate[0] == 'x':
qc.h(0)
elif gate[0] == 'y':
qc.rx(-pi2,0)
if gate[1] == 'x':
qc.h(1)
elif gate[1] == 'y':
qc.rx(-pi2,1)
return qc
from aether import QuantumCircuit, simulate
def propagate_statevector(vec,qc):
qc_i = QuantumCircuit(2,0)
qc_i.initialize(vec)
return simulate(qc_i + qc, get='statevector')
def random_state():
state = [[1.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0]]
for i in range(5):
gate = ['xx','xy','xz','yx','yz','yy','zx','zy','zz'][randint(0,8)]
qc = make_circuit(gate)
state = propagate_statevector(state, qc)
return state
def make_image(state):
blocks = []
for num in state:
blocks.append(make_block(num))
image = pew.Pix()
for i in range(2):
for j in range(4):
tmp = blocks[2*i][j] + blocks[2*i+1][j]
for x in range(8):
image.pixel(x,4*i+j,tmp[x])
return image
def make_block(c_num):
amp = sqrt(c_num[0]*c_num[0] + c_num[1]*c_num[1])
phi = atan2(c_num[1], c_num[0])
if amp < 0.01:
phi = 0
scenario = 0
phases = [0.0, pi4, -pi4, 2.0*pi4, -2.0*pi4, 3.0*pi4, -3.0*pi4, 4.0*pi4, -4.0*pi4]
scenarios = [1, -1, -2, 4, 2, -4, -3, 3, 3 ]
for i in range(9):
if (phi - phases[i])*(phi - phases[i]) < 0.001:
scenario = scenarios[i]
continue
if amp < 0.25:
block = [[0,0,0,0],[0,2,2,0],[0,2,2,0],[0,0,0,0]]
elif amp < 0.6:
if scenario > 0:
block = [[0,0,2,0],[0,0,0,2],[0,0,0,2],[0,0,2,0]]
else:
block = [[0,0,0,0],[0,2,2,0],[0,0,2,0],[0,0,0,0]]
elif amp < 0.9:
if scenario > 0:
block = [[0,0,0,2],[0,0,2,0],[0,0,2,0],[0,0,0,2]]
else:
block = [[0,0,2,0],[0,0,2,2],[0,0,0,0],[0,0,0,0]]
else:
if scenario > 0:
block = [[0,0,0,2],[0,0,0,2],[0,0,0,2],[0,0,0,2]]
else:
block = [[0,0,2,2],[0,0,0,2],[0,0,0,0],[0,0,0,0]]
if scenario != 1 and scenario != -1:
for r in range(abs(scenario) - 1):
block = rot90(block)
return block
def rot90(block):
res = []
for i in range(len(block)):
transposed = []
for col in block:
transposed.append(col[i])
transposed.reverse()
res.append(transposed)
return res
|
https://github.com/v0lta/Quantum-init
|
v0lta
|
# based on https://github.com/pytorch/examples/blob/master/mnist/main.py
import math
import numpy as np
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from qrandom import get_quantum_uniform, get_backend
from qiskit import Aer
import matplotlib.pyplot as plt
import pickle
def _calculate_fan_in_and_fan_out(tensor):
# from torch.nn
dimensions = tensor.dim()
if dimensions < 2:
raise ValueError("Fan in and fan out can not be computed for \
tensor with fewer than 2 dimensions")
num_input_fmaps = tensor.size(1)
num_output_fmaps = tensor.size(0)
receptive_field_size = 1
if tensor.dim() > 2:
receptive_field_size = tensor[0][0].numel()
fan_in = num_input_fmaps * receptive_field_size
fan_out = num_output_fmaps * receptive_field_size
return fan_in, fan_out
def kaiming_normal_(tensor, a=0, fan=None, nonlinearity='relu',
quantum=False, backend=Aer.get_backend('qasm_simulator'),
qbits=5):
if not fan:
fan, _ = _calculate_fan_in_and_fan_out(tensor)
gain = torch.nn.init.calculate_gain(nonlinearity, a)
std = gain / math.sqrt(fan)
bound = math.sqrt(3.0) * std
if not quantum:
with torch.no_grad():
tensor.uniform_(-bound, bound)
else:
quantum_random = get_quantum_uniform(tensor.shape,
-bound, bound,
backend=backend,
n_qbits=qbits)
with torch.no_grad():
tensor.data.copy_(
torch.from_numpy(quantum_random.astype(np.float16)))
class Net(nn.Module):
""" Fully connected parameters have been reduced
to reduce the number of random numbers required.
"""
def __init__(self, quantum_init=True, qbits=5):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, stride=2)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(1600, 64)
self.fc2 = nn.Linear(64, 10)
self.quantum_init = quantum_init
if self.quantum_init:
self.qbits = qbits
self.qbackend = get_backend(self.qbits)
# self.qbackend = Aer.get_backend('qasm_simulator')
else:
self.qbackend = None
self.qbits = None
# initialize weights
# loop over the parameters
previous_tensor = None
for param in self.parameters():
if param.dim() < 2:
# use kernel fan for bias terms.
fan, _ = _calculate_fan_in_and_fan_out(previous_tensor)
else:
fan = None
kaiming_normal_(param, fan=fan,
quantum=self.quantum_init,
backend=self.qbackend,
qbits=self.qbits)
previous_tensor = param
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
def train(args, model, device, train_loader, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
if args.dry_run:
break
def test(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
test_loss += F.nll_loss(output, target, reduction='sum').item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
test_acc = 100. * correct / len(test_loader.dataset)
return test_loss, test_acc
def main():
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=14, metavar='N',
help='number of epochs to train (default: 14)')
parser.add_argument('--lr', type=float, default=1.0, metavar='LR',
help='learning rate (default: 1.0)')
parser.add_argument('--gamma', type=float, default=0.7, metavar='M',
help='Learning rate step gamma (default: 0.7)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--dry-run', action='store_true', default=False,
help='quickly check a single pass')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
help='how many batches to wait before logging training status')
parser.add_argument('--save-model', action='store_true', default=False,
help='For Saving the current Model')
parser.add_argument('--pseudo-init', action='store_true', default=False,
help='If True initialize using real qseudo randomnes')
parser.add_argument('--pickle-stats', action='store_true', default=False,
help='If True stores test loss and acc in pickle file.')
parser.add_argument('--qbits', type=int, default=5, metavar='N',
help='The number of qbits to use. Defaults to 5.')
args = parser.parse_args()
print('args', args)
use_cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
device = torch.device("cuda" if use_cuda else "cpu")
train_kwargs = {'batch_size': args.batch_size}
test_kwargs = {'batch_size': args.test_batch_size}
if use_cuda:
cuda_kwargs = {'num_workers': 1,
'pin_memory': True,
'shuffle': True}
train_kwargs.update(cuda_kwargs)
test_kwargs.update(cuda_kwargs)
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
dataset1 = datasets.MNIST('../data', train=True, download=True,
transform=transform)
dataset2 = datasets.MNIST('../data', train=False,
transform=transform)
train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs)
test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)
if args.pseudo_init:
print('initializing using pseudorandom numbers.')
model = Net(quantum_init=False).to(device)
else:
print('initializing using quantum randomness.')
model = Net(quantum_init=True, qbits=args.qbits).to(device)
optimizer = optim.Adadelta(model.parameters(), lr=args.lr)
scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
test_loss_lst = []
test_acc_lst = []
for epoch in range(1, args.epochs + 1):
train(args, model, device, train_loader, optimizer, epoch)
epoch_test_loss, epoch_acc_loss = test(model, device, test_loader)
test_loss_lst.append(epoch_test_loss)
test_acc_lst.append(epoch_acc_loss)
scheduler.step()
if args.save_model:
torch.save(model.state_dict(), "mnist_cnn.pt")
plt.plot(test_loss_lst)
plt.xlabel('epochs')
plt.ylabel('test loss')
if args.pseudo_init:
plt.title('pseudo-random-init')
plt.savefig('pseudornd.png')
else:
plt.title('quantum-random-init')
plt.savefig('qrnd.png')
if args.pickle_stats:
try:
res = pickle.load(open("stats.pickle", "rb"))
except (OSError, IOError) as e:
res = []
print(e,
'stats.pickle does not exist, creating a new file.')
res.append({'args': args,
'test_loss_lst': test_loss_lst,
'test_acc_lst': test_acc_lst})
pickle.dump(res, open("stats.pickle", "wb"))
print('stats.pickle saved.')
if __name__ == '__main__':
main()
|
https://github.com/v0lta/Quantum-init
|
v0lta
|
# written by moritz (wolter@cs.uni-bonn.de) at 20/01/2021
import numpy as np
from qiskit import(
QuantumCircuit,
execute,
Aer)
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
def get_backend(nqubits=5):
""" Returns a quantum computation backend.
Args:
nqubits (int, optional): The number of desired qbits.
Defaults to 5.
Returns:
backend (qiskit.providers.ibmq.IBMQBackend): The device to run on.
"""
provider = IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(
provider.backends(
filters=lambda x: x.configuration().n_qubits >= nqubits
and not x.configuration().simulator
and x.status().operational is True))
# backend = provider.backends.ibmq_armonk
# backend = Aer.get_backend('qasm_simulator')
print("least busy backend: ", backend)
return backend
def get_qrandom(shots, backend, n_qbits):
""" Get a list of quantum random bits.
Args:
shots (int): The number of required circuit measurements.
backend (IBMQBackend): The device to run on.
n_qbits (int, optional): Number of available qbits. Defaults to 5.
Returns:
[list]: A list with uniformly distributed bits.
"""
# Create a Quantum Circuit
circuit = QuantumCircuit(n_qbits)
# Add a H gate on qubit 0
for q in range(n_qbits):
circuit.h(q)
# Map the quantum measurement to the classical bits
# circuit.measure([0,1], [0,1])
circuit.measure_all()
max_shots = backend.configuration().max_shots
if shots < max_shots:
# Execute the circuit on the qasm simulator
print('qrnd_job', ' ', 'shots', shots, 'missing', 0)
job = execute(circuit, backend, shots=shots,
memory=True)
# Grab results from the job
result = job.result()
# Return Memory
mem = result.get_memory(circuit)
else:
mem = []
# split shots over multiple runs.
runs = int(np.ceil(shots/max_shots))
total_shots = 0
for jobno in range(runs):
shots_missing = int(shots - total_shots)
if shots_missing > max_shots:
run_shots = max_shots
else:
run_shots = shots_missing
print('qrnd_job', jobno, 'shots', run_shots, 'missing',
shots_missing)
job = execute(circuit, backend, shots=run_shots,
memory=True)
result = job.result()
partial_mem = result.get_memory(circuit)
mem.extend(partial_mem)
total_shots += run_shots
return mem
def get_array(shape, n_qbits, backend=Aer.get_backend('qasm_simulator')):
"""Generates an array populated with uniformly distributed
numbers in [0, 1].
Args:
shape (tuple): The desired shape of the array.
n_qbits: The number of qbits per machine. Defaults to 5.
backend: The Qiskit backend used the generate the
random numbers.
Defaults to Aer.get_backend('qasm_simulator').
Returns:
[np.array]: An array filled with uniformly distributed numbers.
"""
int_total = np.prod(shape)
shot_total = np.ceil((16./n_qbits)*int_total)
mem = get_qrandom(shots=shot_total, backend=backend,
n_qbits=n_qbits)
bits_total = ''
for m in mem:
bits_total += m
int_lst = []
cint = ''
for b in bits_total:
cint += b
if len(cint) == 16:
int_lst.append(int(cint, 2))
cint = ''
array = np.array(int_lst[:int_total])
# move to [0, 1]
array = array / np.power(2, 16)
array = np.reshape(array, shape)
return array
def get_quantum_uniform(shape, a, b,
n_qbits=5,
backend=Aer.get_backend('qasm_simulator')):
""" Get a numpy array with quantum uniformly initialized numbers
Args:
shape (touple): Desired output array shape
a (float): The lower bound of the uniform distribution
b (float): The upper bound of the uniform distribution
n_qbits (int): The number of qbits to utilize.
backend (optional): Quiskit backend for number generation.
Defaults to Aer.get_backend('qasm_simulator').
Returns:
uniform (nparray): Array initialized to U(a, b).
"""
zero_one = get_array(shape, backend=backend, n_qbits=n_qbits)
spread = np.abs(a) + np.abs(b)
pos_array = zero_one * spread
uniform = pos_array + a
return uniform
if __name__ == '__main__':
import matplotlib.pyplot as plt
rnd_array = get_quantum_uniform([128, 128], a=-1., b=1.,
n_qbits=1)
print(rnd_array.shape)
print('done')
|
https://github.com/SamperQuinto/QisKit
|
SamperQuinto
|
import os
from qiskit import *
import qiskit.tools.visualization as qt
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
from numpy import pi
import matplotlib.pyplot as plt
%matplotlib inline
qreg_q = QuantumRegister(2, 'q')
creg_c = ClassicalRegister(2, 'c')
circuits = []
for i in range(0, 4):
circuits.append(QuantumCircuit(qreg_q, creg_c))
def entlanging(circuit, qreg_q):
circuit.barrier()
circuit.h(qreg_q[0])
circuit.cnot(qreg_q[0], qreg_q[1])
circuit.barrier()
# 00 state
circuits[0].reset(qreg_q[0])
circuits[0].reset(qreg_q[1])
entlanging(circuits[0], qreg_q)
# 01 state
circuits[1].reset(qreg_q[0])
circuits[1].x(qreg_q[1])
entlanging(circuits[1], qreg_q)
# 10 state
circuits[2].x(qreg_q[0])
circuits[2].reset(qreg_q[1])
entlanging(circuits[2], qreg_q)
# 11 state
circuits[3].x(qreg_q[0])
circuits[3].x(qreg_q[1])
entlanging(circuits[3], qreg_q)
simulator = Aer.get_backend('qasm_simulator')
circuits[0].measure(qreg_q[0], creg_c[0])
circuits[0].measure(qreg_q[1], creg_c[1])
result0 = execute(circuits[0], backend=simulator, shots=1024).result()
counts0 = result0.get_counts()
qt.plot_histogram(counts0, color="#5C9DFF", title="Entangled qubits values for input |00>")
circuits[0].draw(output='mpl')
circuits[1].measure(qreg_q[0], creg_c[0])
circuits[1].measure(qreg_q[1], creg_c[1])
result1 = execute(circuits[1], backend=simulator, shots=1024).result()
counts1 = result1.get_counts()
qt.plot_histogram(counts1, color="#5C9DFF", title="Entangled qubits values for input |01>")
circuits[1].draw(output='mpl')
circuits[2].measure(qreg_q[0], creg_c[0])
circuits[2].measure(qreg_q[1], creg_c[1])
result2 = execute(circuits[2], backend=simulator, shots=1024).result()
counts2 = result2.get_counts()
qt.plot_histogram(counts2, color="#5C9DFF", title="Entangled qubits values for input |10>")
circuits[2].draw(output='mpl')
circuits[3].measure(qreg_q[0], creg_c[0])
circuits[3].measure(qreg_q[1], creg_c[1])
result3 = execute(circuits[3], backend=simulator, shots=1024).result()
counts3 = result3.get_counts()
qt.plot_histogram(counts3, color="#5C9DFF", title="Entangled qubits values for input |11>")
circuits[3].draw(output='mpl')
|
https://github.com/SamperQuinto/QisKit
|
SamperQuinto
|
import numpy as np
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister
from qiskit.quantum_info import *
# Creamos los registros del circuito de corrección de errores
qreg_state = QuantumRegister(1,'state')
qreg_sup = QuantumRegister(2,'ancila_sup')
qreg_inf = QuantumRegister(2,'ancila_inf')
creg= ClassicalRegister(4,'sindrome')
# Creamos el circuito cuántico para la codificación y decodificación
circ = QuantumCircuit(qreg_sup,qreg_state,qreg_inf,creg)
circ_state = QuantumCircuit(qreg_sup,qreg_state,qreg_inf,creg)
state = [1/np.sqrt(3), np.sqrt(2/3)]
#state = random_statevector(2)
# Inicializamos el circuito
circ_state.initialize(state, 2)
circ_state.barrier()
circ_state.draw()
from qiskit.circuit.library.standard_gates.z import ZGate
# Procedemos con la construcción del circuito cuántico asociado:
circ.h(0)
circ.h(1)
circ.h(3)
circ.cz(1,4)
circ.cz(2,4)
circ.cz(3,4)
circ.cz(1,4, ctrl_state=0)
circ.cz(2,4)
circ.cz(3,4, ctrl_state=0)
circ.cx(2,4)
circ.cx(0,2)
circ.cx(0,4)
circ.cx(3,2)
circ.cx(1,4)
circ.cz(2,3)
circ.cz(2,4)
# Introducimos el error
qreg_error = QuantumRegister(5)
circ_error = QuantumCircuit(qreg_error)
circ_error.barrier()
#circ_error.x(2)
circ_error.z(2)
#Fin del error
circ_error.barrier()
circ_con_state = circ_state.compose(circ)
circ_con_error = circ_con_state.compose(circ_error)
circ_inverse = circ.inverse()
circ = circ_con_error.compose(circ_inverse)
circ.barrier()
state_con_error = Statevector.from_instruction(circ)
circ.measure([0,1,3,4],[0,1,2,3])
circ.barrier()
circ.z(qreg_state[0]).c_if(creg,12)
circ.z(qreg_state[0]).c_if(creg,10)
circ.z(qreg_state[0]).c_if(creg,1)
circ.z(qreg_state[0]).c_if(creg,5)
circ.z(qreg_state[0]).c_if(creg,15)
circ.z(qreg_state[0]).c_if(creg,6)
circ.x(qreg_state[0]).c_if(creg,6)
circ.z(qreg_state[0]).c_if(creg,14)
circ.x(qreg_state[0]).c_if(creg,14)
circ.z(qreg_state[0]).c_if(creg,9)
circ.x(qreg_state[0]).c_if(creg,9)
circ.z(qreg_state[0]).c_if(creg,13)
circ.x(qreg_state[0]).c_if(creg,13)
circ.z(qreg_state[0]).c_if(creg,11)
circ.x(qreg_state[0]).c_if(creg,11)
circ.z(qreg_state[0]).c_if(creg,7)
circ.x(qreg_state[0]).c_if(creg,7)
circ.draw()
from qiskit import Aer, execute
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator
from qiskit_textbook.tools import array_to_latex
from qiskit.visualization import *
import warnings
warnings.filterwarnings("ignore")
backend = Aer.get_backend('statevector_simulator')
job = execute(circ,backend ,shots = 1000)
resultado = job.result()
counts = resultado.get_counts(circ)
plot_histogram(counts, title = 'sindrome')
psi_error=list(filter(lambda x: x != 0, state_con_error))
resultado_sv = job.result().get_statevector()
resultado_psi=list(filter(lambda x: x != 0, resultado_sv))
psi_error=list(filter(lambda x: x != 0, state_con_error))
display(array_to_latex(state, prefix= 'Estado \; original \; |\\Psi \\rangle='))
display(array_to_latex(psi_error, prefix= 'Estado \; con \; error \; |\\Psi \\rangle='))
display(array_to_latex(resultado_psi, prefix = 'Estado \; corregido \; |\\Psi \\rangle='))
|
https://github.com/SamperQuinto/QisKit
|
SamperQuinto
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
import math
# importing Qiskit
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
# import basic plot tools
from qiskit.visualization import plot_histogram
qpe = QuantumCircuit(4, 3)
qpe.x(3)
#Apply Hadamard gate
for qubit in range(3):
qpe.h(qubit)
qpe.draw()
repetitions = 1
for counting_qubit in range(3):
for i in range(repetitions):
qpe.cp(math.pi/4, counting_qubit, 3); # This is CU # we use 2*pi*(1/theta)
repetitions *= 2
qpe.draw()
def qft_dagger(qc, n):
"""n-qubit QFTdagger the first n qubits in circ"""
# Don't forget the Swaps!
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-math.pi/float(2**(j-m)), m, j)
qc.h(j)
qpe.barrier()
# Apply inverse QFT
qft_dagger(qpe, 3)
# Measure
qpe.barrier()
for n in range(3):
qpe.measure(n,n)
qpe.draw()
aer_sim = Aer.get_backend('aer_simulator')
shots = 2048
t_qpe = transpile(qpe, aer_sim)
qobj = assemble(t_qpe, shots=shots)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
# Create and set up circuit
qpe2 = QuantumCircuit(4, 3)
# Apply H-Gates to counting qubits:
for qubit in range(3):
qpe2.h(qubit)
# Prepare our eigenstate |psi>:
qpe2.x(3)
# Do the controlled-U operations:
angle = 2*math.pi/3
repetitions = 1
for counting_qubit in range(3):
for i in range(repetitions):
qpe2.cp(angle, counting_qubit, 3);
repetitions *= 2
# Do the inverse QFT:
qft_dagger(qpe2, 3)
# Measure of course!
for n in range(3):
qpe2.measure(n,n)
qpe2.draw()
# Let's see the results!
aer_sim = Aer.get_backend('aer_simulator')
shots = 4096
t_qpe2 = transpile(qpe2, aer_sim)
qobj = assemble(t_qpe2, shots=shots)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
# Create and set up circuit
qpe3 = QuantumCircuit(6, 5)
# Apply H-Gates to counting qubits:
for qubit in range(5):
qpe3.h(qubit)
# Prepare our eigenstate |psi>:
qpe3.x(5)
# Do the controlled-U operations:
angle = 2*math.pi/3
repetitions = 1
for counting_qubit in range(5):
for i in range(repetitions):
qpe3.cp(angle, counting_qubit, 5);
repetitions *= 2
# Do the inverse QFT:
qft_dagger(qpe3, 5)
# Measure of course!
qpe3.barrier()
for n in range(5):
qpe3.measure(n,n)
qpe3.draw()
# Let's see the results!
aer_sim = Aer.get_backend('aer_simulator')
shots = 4096
t_qpe3 = transpile(qpe3, aer_sim)
qobj = assemble(t_qpe3, shots=shots)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
from ipywidgets import interact, interactive, fixed, interact_manual, FloatSlider, Layout
import ipywidgets as widgets
sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]})
plt.rcParams['figure.figsize'] = [12, 8]
# load dataframe
filepath = "../datasets/AllErrors/U3_5.csv"
df = pd.read_csv(filepath)
# reorder columns
df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'population', 'p0_0', 'p0_1', 'p1_0', 'p1_1']]
# filters
labels = ['theta', 'phi', 'lam', 'E']
depol_columns = ['depol_prob']
thermal_columns = ['t1', 't2', 'population']
readout_columns = ['p0_0', 'p0_1', 'p1_0', 'p1_1']
# filtered dataframes
ideal_only = df.query('depol_prob == 0 & t1 == inf & t2 == inf & p0_0 == 1 & p1_1 == 1')
df
# Explore Features
@interact
def show_gates_more_than(theta_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%')),
lam_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%')),
phi_values=widgets.SelectMultiple(options=df['phi'].unique(), value=tuple(df['phi'].unique()))):
filtered = df.loc[(df['theta'].between(theta_range[0],theta_range[1])) & (df['lam'].between(lam_range[0],lam_range[1])) & (df['phi'].isin(phi_values))]
sns.scatterplot(x='theta', y='E', hue="lam", data=filtered);
@interact
def show_gates_more_than(theta_range=widgets.FloatRangeSlider(value=[2.2, 2.6], min = 0.0, max=2*np.pi, layout=Layout(width='80%')),
lam_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%')),
phi_values=widgets.SelectMultiple(options=df['phi'].unique(), value=tuple(df['phi'].unique()))):
filtered = df.loc[(df['theta'].between(theta_range[0],theta_range[1])) & (df['lam'].between(lam_range[0],lam_range[1])) & (df['phi'].isin(phi_values))]
sns.scatterplot(x='theta', y='E', hue="lam", data=filtered);
@interact
def show_gates_more_than(theta_range=widgets.FloatRangeSlider(value=[2.2, 2.6], min = 0.0, max=2*np.pi, layout=Layout(width='80%')),
lam_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%')),
phi_values=widgets.SelectMultiple(options=df['phi'].unique(), value=tuple(df['phi'].unique()))):
filtered = df.loc[(df['theta'].between(theta_range[0],theta_range[1])) & (df['lam'].between(lam_range[0],lam_range[1])) & (df['phi'].isin(phi_values))]
sns.scatterplot(x='theta', y='E', hue="lam", data=filtered);
@interact
def show_gates_more_than(
theta_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%'), description='theta_range'),
lam_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%'), description='lam_range'),
phi_values=widgets.SelectMultiple(options=df['phi'].unique(), value=tuple(df['phi'].unique()), description='phi_values')):
filtered = df.loc[(df['p1_1'] == 1.0) & (df['theta'].between(theta_range[0],theta_range[1])) & (df['lam'].between(lam_range[0],lam_range[1])) & (df['phi'].isin(phi_values))]
display(theta_range, lam_range, phi_values);
return sns.scatterplot(x='theta', y='E', hue='p0_0', data=filtered);
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
# %load imports.py
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
import ipywidgets as widgets
widgets.IntSlider()
widgets.FloatSlider()
widgets.FloatLogSlider()
widgets.IntRangeSlider()
widgets.FloatRangeSlider()
widgets.IntProgress(75)
widgets.FloatProgress(98)
widgets.BoundedIntText(7)
widgets.BoundedFloatText(7, step=0.1)
widgets.IntText(7)
widgets.FileUpload(
accept='', # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf'
multiple=False # True to accept multiple files upload else False
)
widgets.Controller(
index=0,
)
out = widgets.Output(layout={'border': '1px solid black'})
from IPython.display import YouTubeVideo
with out:
display(YouTubeVideo('eWzY2nGfkXk'))
out
from ipywidgets import Layout, Button, Box
items_layout = Layout( width='auto') # override the default width of the button to 'auto' to let the button grow
box_layout = Layout(display='flex',
flex_flow='column',
align_items='stretch',
border='solid',
width='50%')
words = ['correct', 'horse', 'battery', 'staple']
items = [Button(description=word, layout=items_layout, button_style='danger') for word in words]
box = Box(children=items, layout=box_layout)
box
from ipywidgets import Layout, Button, Box, VBox
# Items flex proportionally to the weight and the left over space around the text
items_auto = [
Button(description='weight=1; auto', layout=Layout(flex='1 1 auto', width='auto'), button_style='danger'),
Button(description='weight=3; auto', layout=Layout(flex='3 1 auto', width='auto'), button_style='danger'),
Button(description='weight=1; auto', layout=Layout(flex='1 1 auto', width='auto'), button_style='danger'),
]
# Items flex proportionally to the weight
items_0 = [
Button(description='weight=1; 0%', layout=Layout(flex='1 1 0%', width='auto'), button_style='danger'),
Button(description='weight=3; 0%', layout=Layout(flex='3 1 0%', width='auto'), button_style='danger'),
Button(description='weight=1; 0%', layout=Layout(flex='1 1 0%', width='auto'), button_style='danger'),
]
box_layout = Layout(display='flex',
flex_flow='row',
align_items='stretch',
width='70%')
box_auto = Box(children=items_auto, layout=box_layout)
box_0 = Box(children=items_0, layout=box_layout)
VBox([box_auto, box_0])
from ipywidgets import Layout, Button, Box, FloatText, Textarea, Dropdown, Label, IntSlider
form_item_layout = Layout(
display='flex',
flex_flow='row',
justify_content='space-between'
)
form_items = [
Box([Label(value='Age of the captain'), IntSlider(min=40, max=60)], layout=form_item_layout),
Box([Label(value='Egg style'),
Dropdown(options=['Scrambled', 'Sunny side up', 'Over easy'])], layout=form_item_layout),
Box([Label(value='Ship size'),
FloatText()], layout=form_item_layout),
Box([Label(value='Information'),
Textarea()], layout=form_item_layout)
]
form = Box(form_items, layout=Layout(
display='flex',
flex_flow='column',
border='solid 2px',
align_items='stretch',
width='50%'
))
form
from ipywidgets import Layout, Button, VBox, Label, Box
item_layout = Layout(height='100px', min_width='40px')
items = [Button(layout=item_layout, description=str(i), button_style='warning') for i in range(40)]
box_layout = Layout(overflow='scroll hidden',
border='3px solid black',
width='500px',
height='',
flex_flow='row',
display='flex')
carousel = Box(children=items, layout=box_layout)
VBox([Label('Scroll horizontally:'), carousel])
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from ipywidgets import interact, interactive, fixed, interact_manual, FloatSlider
import ipywidgets as widgets
sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]})
filepath = "../datasets/universal_error/AllErrors/U3_5.csv"
df = pd.read_csv(filepath)
# reorder columns
df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'population', 'p0_0', 'p0_1', 'p1_0', 'p1_1']]
df.info()
df.head()
sns.distplot(df['E'], norm_hist=False, kde=False, bins=20, hist_kws={'alpha': 1}).set(xlabel="'Expected Value", ylabel='Count')
df.hist(bins=50, figsize=(20,15), layout=(3,4));
sns.scatterplot(x=df['theta'], y=df['E']);
sns.scatterplot(x=df['phi'], y=df['E']);
sns.scatterplot(x=df['lam'], y=df['E']);
sns.scatterplot(x=df['theta'], y=df['phi']);
sns.pairplot(data=df.sample(1000));
sns.pairplot(data=df.sample(10000));
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
filepath = "../datasets/universal_error/DepolOnly/U3_19.csv"
df = pd.read_csv(filepath)
# reorder columns
df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'p0_0', 'p0_1', 'p1_0', 'p1_1']]
# filter out inf values
df = df[np.isfinite]
df.info()
df.head()
sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]})
sns.distplot(df['E'], norm_hist=False, kde=False, bins=50, hist_kws={'alpha': 1}).set(xlabel="'Expected Value", ylabel='Count')
df.hist(bins=100, figsize=(20,15), layout=(3,4));
sns.scatterplot(x=df['theta'], y=df['E']);
sns.jointplot(x=df['theta'], y=df['E']);
sns.scatterplot(x=df['phi'], y=df['E']);
sns.scatterplot(x=df['lam'], y=df['E']);
sns.scatterplot(x=df['theta'], y=df['phi']);
sns.scatterplot(x=df['depol_prob'], y=df['E']);
sns.jointplot(x=df['t1'], y=df['E']);
sns.jointplot(x=df['t2'], y=df['E']);
sns.scatterplot(x=df['t1'], y=df['E']);
sns.scatterplot(x=df['t2'], y=df['E']);
sns.pairplot(data=df);
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
filepath = "../datasets/universal_error/ReadoutOnly/U3_7.csv"
df = pd.read_csv(filepath)
# reorder columns
df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'p0_0', 'p0_1', 'p1_0', 'p1_1']]
# filter out inf values
df = df[np.isfinite]
df.info()
df.head()
sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]})
sns.distplot(df['E'], norm_hist=False, kde=False, bins=50, hist_kws={'alpha': 1}).set(xlabel="'Expected Value", ylabel='Count')
df.hist(bins=100, figsize=(20,15), layout=(3,4));
sns.scatterplot(x=df['theta'], y=df['E']);
sns.scatterplot(x=df['phi'], y=df['E']);
sns.scatterplot(x=df['lam'], y=df['E']);
sns.scatterplot(x=df['depol_prob'], y=df['E']);
sns.jointplot(x=df['t1'], y=df['E']);
sns.jointplot(x=df['t2'], y=df['E']);
sns.pairplot(data=df);
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
filepath = "../datasets/universal_error/ThermalOnly/U3_14.csv"
df = pd.read_csv(filepath)
# reorder columns
df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'p0_0', 'p0_1', 'p1_0', 'p1_1']]
# filter out inf values
df = df[np.isfinite]
df.info()
df.head()
sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]})
sns.distplot(df['E'], norm_hist=False, kde=False, bins=50, hist_kws={'alpha': 1}).set(xlabel="'Expected Value", ylabel='Count')
df.hist(bins=100, figsize=(20,15), layout=(3,4));
sns.scatterplot(x=df['theta'], y=df['E']);
sns.jointplot(x=df['theta'], y=df['E']);
sns.scatterplot(x=df['phi'], y=df['E']);
sns.scatterplot(x=df['lam'], y=df['E']);
sns.scatterplot(x=df['theta'], y=df['phi']);
sns.scatterplot(x=df['depol_prob'], y=df['E']);
sns.jointplot(x=df['t1'], y=df['E']);
sns.jointplot(x=df['t2'], y=df['E']);
sns.scatterplot(x=df['t1'], y=df['E']);
sns.scatterplot(x=df['t2'], y=df['E']);
sns.pairplot(data=df);
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
filepath = "../datasets/universal_error/AllErrors/U3_4.csv"
df = pd.read_csv(filepath)
# reorder columns
df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'p0_0', 'p0_1', 'p1_0', 'p1_1']]
# filter out inf values
df = df[np.isfinite]
df.info()
df.head()
sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]})
sns.distplot(df['E'], norm_hist=False, kde=False, bins=50, hist_kws={'alpha': 1}).set(xlabel="'Expected Value", ylabel='Count')
df.hist(bins=100, figsize=(20,15), layout=(3,4));
sns.scatterplot(x=df['theta'], y=df['E']);
sns.jointplot(x=df['theta'], y=df['E']);
sns.scatterplot(x=df['phi'], y=df['E']);
sns.scatterplot(x=df['lam'], y=df['E']);
sns.scatterplot(x=df['theta'], y=df['phi']);
sns.scatterplot(x=df['depol_prob'], y=df['E']);
sns.jointplot(x=df['t1'], y=df['E']);
sns.jointplot(x=df['t2'], y=df['E']);
sns.scatterplot(x=df['t1'], y=df['E']);
sns.scatterplot(x=df['t2'], y=df['E']);
### Pair Plots
sns.scatterplot(x=df['t2'], y=df['E']);
sns.pairplot(data=df);
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
from ipywidgets import interact, interactive, fixed, interact_manual, FloatSlider, Layout
import ipywidgets as widgets
sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]})
plt.rcParams['figure.figsize'] = [12, 8]
# load dataframe
filepath = "../datasets/universal_error/DepolOnly/U3_19.csv"
df = pd.read_csv(filepath)
# reorder columns
df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'population', 'p0_0', 'p0_1', 'p1_0', 'p1_1']]
# filters
labels = ['theta', 'phi', 'lam', 'E']
depol_columns = ['depol_prob']
thermal_columns = ['t1', 't2', 'population']
readout_columns = ['p0_0', 'p0_1', 'p1_0', 'p1_1']
# filtered dataframes
ideal_only = df.query('depol_prob == 0 & t1 == inf & t2 == inf & p0_0 == 1 & p1_1 == 1')
@interact
def show_gates_more_than(theta_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%')),
lam_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%')),
phi_values=widgets.SelectMultiple(options=ideal_only['phi'].unique(), value=tuple(ideal_only['phi'].unique()))):
filtered = ideal_only.loc[(ideal_only['theta'].between(theta_range[0],theta_range[1])) & (ideal_only['lam'].between(lam_range[0],lam_range[1])) & (ideal_only['phi'].isin(phi_values))]
# filtered = filtered.loc[filtered[]]
sns.scatterplot(x='theta', y='E', hue="lam", data=filtered);
depol_only = df.query('p0_0 == 1 & p1_1 == 1 & t1 == inf & t2 == inf')[labels + depol_columns]
sns.scatterplot(x=depol_only['theta'], y=depol_only['E']);
sns.regplot(x=depol_only['lam'], y=depol_only['E'])
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
filepath = "../datasets/universal_error/ThermalOnly/U3_12.csv"
df = pd.read_csv(filepath)
# reorder columns
df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'p0_0', 'p0_1', 'p1_0', 'p1_1']]
# filter out inf values
df = df[np.isfinite]
df.info()
df.head()
sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]})
sns.distplot(df['E'], norm_hist=False, kde=False, bins=20, hist_kws={'alpha': 1}).set(xlabel="'Expected Value", ylabel='Count')
df.hist(bins=15, figsize=(20,15), layout=(3,4));
sns.scatterplot(x=df['theta'], y=df['E']);
sns.scatterplot(x=df['phi'], y=df['E']);
sns.scatterplot(x=df['lam'], y=df['E']);
sns.scatterplot(x=df['theta'], y=df['phi']);
sns.scatterplot(x=df['depol_prob'], y=df['E']);
### Pair Plots
sns.pairplot(data=df);
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import logging
import sys
import time
from itertools import product
import numpy as np
import pandas as pd
from qiskit import QuantumCircuit, execute
from qiskit.circuit.library import U3Gate
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel, depolarizing_error, ReadoutError, thermal_relaxation_error
def get_data_point(circ, theta, phi, lam, readout_params, depol_param, thermal_params, shots):
"""Generate a dict datapoint with the given circuit and noise parameters"""
U3_gate_length = 7.111111111111112e-08
# extract parameters
(p0_0, p1_0), (p0_1, p1_1) = readout_params
depol_prob = depol_param
t1, t2, population = thermal_params
# Add Readout and Quantum Errors
noise_model = NoiseModel()
noise_model.add_all_qubit_readout_error(ReadoutError(readout_params))
noise_model.add_all_qubit_quantum_error(depolarizing_error(depol_param, 1), 'u3', warnings=False)
noise_model.add_all_qubit_quantum_error(
thermal_relaxation_error(t1, t2, U3_gate_length, excited_state_population=population), 'u3',
warnings=False)
job = execute(circ, QasmSimulator(), shots=shots, noise_model=noise_model)
result = job.result()
# add data point to DataFrame
data_point = {'theta': theta,
'phi': phi,
'lam': lam,
'p0_0': p0_0,
'p1_0': p1_0,
'p0_1': p0_1,
'p1_1': p1_1,
'depol_prob': depol_prob,
't1': t1,
't2': t2,
'population': population,
'E': result.get_counts(0).get('1', 0) / shots}
return data_point
def get_noise_model_params(K=10, readout=True, thermal=True, depol=True):
"""generate a list of tuples for all noise params (readout_params, depol_param, thermal_params) """
# Simple implementation. Use this...
noise_model_params = []
# Readout Error
for p0_0 in np.linspace(0.94, 1.0, K, endpoint=True):
for p1_1 in np.linspace(0.94, 1.0, K, endpoint=True):
p1_0 = 1 - p0_0
p0_1 = 1 - p1_1
readout_params = (p0_0, p1_0), (p0_1, p1_1)
# Thermal Error
# for t1 in np.itertools.chain(np.linspace(34000, 190000, K, endpoint=True), np.inf):
# for t2 in np.linspace(t1 / 5.6, t1 / 0.65, K, endpoint=True):
# for population in np.linspace(0, 1, K, endpoint=True):
# thermal_params = (t1, t2, population)
t1 = np.inf
t2 = np.inf
population = 0
thermal_params = (t1, t2, population)
# Depolarizing Error
for depol_param in np.linspace(0, 0.001, K, endpoint=True):
noise_model_params.append((readout_params, depol_param, thermal_params))
return noise_model_params
# Inefficient implementation. Don't Use...
"""if readout:
p0_0_iter = np.linspace(0.94, 1.0, K, endpoint=True)
p1_1_iter = np.linspace(0.94, 1.0, K, endpoint=True)
else:
p0_0_iter = [1]
p1_1_iter = [1]
if depol:
depol_iter = np.linspace(0, 0.001, K, endpoint=True)
else:
depol_iter = [0]
if thermal:
t1_iter = np.linspace(34000, 190000, K, endpoint=True)
# thermal_iter = map(lambda t1: (t1, np.linspace(t1/5.6, t1/0.65, 10, endpoint=True)), t1_iter)
thermal_iter = chain.from_iterable(
map(lambda t1: product([t1], np.linspace(t1 / 5.6, t1 / 0.65, K, endpoint=True)), t1_iter))
else:
thermal_iter = [(np.inf, np.inf)]
iterator = product(p0_0_iter, p1_1_iter, depol_iter, thermal_iter)
noise_model_params = [(((p0_0, 1 - p0_0), (1 - p1_1, p1_1)), depol, (t1, t2)) for p0_0, p1_1, depol, (t1, t2) in
tqdm(iterator)]
return noise_model_params"""
def U3Dataset(angle_step=10, other_steps=10, shots=2048, readout=True, thermal=True, depol=True, save_dir=None):
a_logger = logging.getLogger(__name__)
# the dictionary to pass to pandas dataframe
data = {}
# a counter to use to add entries to "data"
i = 0
# a counter to use to log circuit number
j = 0
# Iterate over all U3 gates
for theta, phi, lam in product(np.linspace(0, 2 * np.pi, angle_step, endpoint=True), repeat=3):
j = j + 1
# Generate sample data
circ = QuantumCircuit(1, 1)
circ.append(U3Gate(theta, phi, lam), [0])
circ.measure(0, 0)
a_logger.info("Generating data points for circuit: {}/{}\n".format(j, angle_step ** 3) + str(circ))
start_time = time.time()
for readout_params, depol_param, thermal_params in get_noise_model_params(other_steps, readout, thermal, depol):
data_point = get_data_point(circ, theta, phi, lam, readout_params, depol_param, thermal_params, shots)
data[i] = {'theta': data_point['theta'],
'phi': data_point['phi'],
'lam': data_point['lam'],
'p0_0': data_point['p0_0'],
'p1_0': data_point['p1_0'],
'p0_1': data_point['p0_1'],
'p1_1': data_point['p1_1'],
'depol_prob': data_point['depol_prob'],
't1': data_point['t1'],
't2': data_point['t2'],
'population': data_point['population'],
'E': data_point['E']}
i = i + 1
a_logger.info("Last circuit took: {:.2f} seconds.".format(time.time() - start_time))
# set the 'orient' parameter to "index" to make the keys as rows
df = pd.DataFrame.from_dict(data, "index")
# Save to CSV
if save_dir is not None:
df.to_csv(save_dir)
return df
# start main script
if __name__ == '__main__':
# create formatter
formatter = logging.Formatter("%(asctime)s; %(message)s", "%y-%m-%d %H:%M:%S")
# initialize logger
a_logger = logging.getLogger(__name__)
a_logger.setLevel(logging.INFO)
# log to output file
log_file_path = "../logs/output_{}.log".format(time.strftime("%Y%m%d-%H%M%S"))
output_file_handler = logging.FileHandler(log_file_path, mode='w', encoding='utf-8')
output_file_handler.setFormatter(formatter)
a_logger.addHandler(output_file_handler)
# log to stdout
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(formatter)
a_logger.addHandler(stdout_handler)
for n, m in [(5, 5)]:
save_dir = '../datasets/universal_error/AllErrors/U3_{}_{}_no_thermal.csv'.format(n, m)
a_logger.info("Starting dataset generation with resolution n = {}, m = {}.".format(n, m))
angle_step = n
other_steps = m
U3Dataset(angle_step=angle_step, other_steps=other_steps, readout=True, thermal=True, depol=True,
save_dir=save_dir)
a_logger.info("Finished dataset generation with resolution n = {}, m = {}.".format(n, m))
a_logger.info("Dataset saved to {}".format(save_dir))
a_logger.info("Exiting Gracefully")
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import logging
import sys
import time
from itertools import product
import numpy as np
import pandas as pd
from qiskit import QuantumCircuit, execute
from qiskit.circuit.library import U3Gate
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel, depolarizing_error, ReadoutError, thermal_relaxation_error
def get_data_point(circ, theta, phi, lam, readout_params, depol_param, thermal_params, shots):
"""Generate a dict datapoint with the given circuit and noise parameters"""
U3_gate_length = 7.111111111111112e-08
# extract parameters
(p0_0, p1_0), (p0_1, p1_1) = readout_params
depol_prob = depol_param
t1, t2, population = thermal_params
# Add Readout and Quantum Errors
noise_model = NoiseModel()
noise_model.add_all_qubit_readout_error(ReadoutError(readout_params))
noise_model.add_all_qubit_quantum_error(depolarizing_error(depol_param, 1), 'u3', warnings=False)
noise_model.add_all_qubit_quantum_error(
thermal_relaxation_error(t1, t2, U3_gate_length, excited_state_population=population), 'u3',
warnings=False)
job = execute(circ, QasmSimulator(), shots=shots, noise_model=noise_model)
result = job.result()
# add data point to DataFrame
data_point = {'theta': theta,
'phi': phi,
'lam': lam,
'p0_0': p0_0,
'p1_0': p1_0,
'p0_1': p0_1,
'p1_1': p1_1,
'depol_prob': depol_prob,
't1': t1,
't2': t2,
'population': population,
'E': result.get_counts(0).get('1', 0) / shots}
return data_point
def get_noise_model_params(K=10, readout=True, thermal=True, depol=True):
"""generate a list of tuples for all noise params (readout_params, depol_param, thermal_params) """
# Simple implementation. Use this...
noise_model_params = []
# Readout Error
for p0_0 in np.linspace(0.94, 1.0, K, endpoint=True):
for p1_1 in np.linspace(0.94, 1.0, K, endpoint=True):
p1_0 = 1 - p0_0
p0_1 = 1 - p1_1
readout_params = (p0_0, p1_0), (p0_1, p1_1)
# Thermal Error
for t1 in np.linspace(34000, 190000, K, endpoint=True):
for t2 in np.linspace(t1 / 5.6, t1 / 0.65, K, endpoint=True):
for population in np.linspace(0, 1, K, endpoint=True):
thermal_params = (t1, t2, population)
# Depolarizing Error
for depol_param in np.linspace(0, 0.001, K, endpoint=True):
noise_model_params.append((readout_params, depol_param, thermal_params))
return noise_model_params
# Inefficient implementation. Don't Use...
"""if readout:
p0_0_iter = np.linspace(0.94, 1.0, K, endpoint=True)
p1_1_iter = np.linspace(0.94, 1.0, K, endpoint=True)
else:
p0_0_iter = [1]
p1_1_iter = [1]
if depol:
depol_iter = np.linspace(0, 0.001, K, endpoint=True)
else:
depol_iter = [0]
if thermal:
t1_iter = np.linspace(34000, 190000, K, endpoint=True)
# thermal_iter = map(lambda t1: (t1, np.linspace(t1/5.6, t1/0.65, 10, endpoint=True)), t1_iter)
thermal_iter = chain.from_iterable(
map(lambda t1: product([t1], np.linspace(t1 / 5.6, t1 / 0.65, K, endpoint=True)), t1_iter))
else:
thermal_iter = [(np.inf, np.inf)]
iterator = product(p0_0_iter, p1_1_iter, depol_iter, thermal_iter)
noise_model_params = [(((p0_0, 1 - p0_0), (1 - p1_1, p1_1)), depol, (t1, t2)) for p0_0, p1_1, depol, (t1, t2) in
tqdm(iterator)]
return noise_model_params"""
def U3Dataset(angle_step=10, other_steps=10, shots=2048, readout=True, thermal=True, depol=True, save_dir=None):
a_logger = logging.getLogger(__name__)
# the array to hold dataset
array = np.empty()
# the dictionary to pass to pandas dataframe
data = {}
# a counter to use to add entries to "data"
i = 0
# a counter to use to log circuit number
j = 0
# Iterate over all U3 gates
for theta, phi, lam in product(np.linspace(0, 2 * np.pi, angle_step, endpoint=True), repeat=3):
j = j + 1
# Generate sample data
circ = QuantumCircuit(1, 1)
circ.append(U3Gate(theta, phi, lam), [0])
circ.measure(0, 0)
a_logger.info("Generating data points for circuit: {}/{}\n".format(j, angle_step ** 3) + str(circ))
start_time = time.time()
for readout_params, depol_param, thermal_params in get_noise_model_params(other_steps, readout, thermal, depol):
data_point = get_data_point(circ, theta, phi, lam, readout_params, depol_param, thermal_params, shots)
data[i] = {'thet a': data_point['theta'],
'phi': data_point['phi'],
'lam': data_point['lam'],
'p0_0': data_point['p0_0'],
'p1_0': data_point['p1_0'],
'p0_1': data_point['p0_1'],
'p1_1': data_point['p1_1'],
'depol_prob': data_point['depol_prob'],
't1': data_point['t1'],
't2': data_point['t2'],
'population': data_point['population'],
'E': data_point['E']}
i = i + 1
a_logger.info("Last circuit took: {:.2f} seconds.".format(time.time() - start_time))
# set the 'orient' parameter to "index" to make the keys as rows
df = pd.DataFrame.from_dict(data, "index")
# Save to CSV
if save_dir is not None:
df.to_csv(save_dir)
return df
# start main script
if __name__ == '__main__':
# create formatter
formatter = logging.Formatter("%(asctime)s; %(message)s", "%y-%m-%d %H:%M:%S")
# initialize logger
a_logger = logging.getLogger(__name__)
a_logger.setLevel(logging.INFO)
# log to output file
log_file_path = "../logs/output_{}.log".format(time.strftime("%Y%m%d-%H%M%S"))
output_file_handler = logging.FileHandler(log_file_path, mode='w', encoding='utf-8')
output_file_handler.setFormatter(formatter)
a_logger.addHandler(output_file_handler)
# log to stdout
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(formatter)
a_logger.addHandler(stdout_handler)
for n, m in [(12, 6)]:
save_dir = '../datasets/universal_error/AllErrors/U3_{}_{}.csv'.format(n, m)
a_logger.info("Starting dataset generation with resolution n = {}, m = {}.".format(n, m))
angle_step = n
other_steps = m
U3Dataset(angle_step=angle_step, other_steps=other_steps, readout=True, thermal=True, depol=True,
save_dir=save_dir)
a_logger.info("Finished dataset generation with resolution n = {}, m = {}.".format(n, m))
a_logger.info("Dataset saved to {}".format(save_dir))
a_logger.info("Exiting Gracefully")
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import csv
import datetime
import os
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-education', group='technion-Weinste')
log_time = datetime.datetime.now()
def write_log_to_file(csv_writer):
for backend in provider.backends():
try:
for qubit_idx, qubit_prop in enumerate(backend.properties().qubits):
for prop in qubit_prop:
csv_writer.writerow(
[backend.name(), qubit_idx, prop.date.isoformat(), prop.name, prop.unit, prop.value,
log_time.isoformat()])
id_gate = [i for i in backend.properties().gates if i.gate == 'id' and qubit_idx in i.qubits][0]
id_gate_length = [p for p in id_gate.parameters if p.name == 'gate_length'][0]
csv_writer.writerow([backend.name(), qubit_idx, id_gate_length.date.isoformat(), 'id_length',
id_gate_length.unit, id_gate_length.value, log_time.isoformat()])
except Exception as e:
print("Cannot add backend", backend.name(), e)
path = '../docs/backend_properties/backend_properties_log.csv'
if not os.path.isfile(path):
with open(path, "w", newline='') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(["backend", "qubit", "datetime", "name", "units", "value", "log_datetime"])
write_log_to_file(csv_writer)
else:
with open(path, "a", newline='') as f:
write_log_to_file(csv.writer(f))
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
from qiskit import IBMQ
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.device import thermal_relaxation_values, gate_param_values
from qiskit.providers.aer.noise.noiseerror import NoiseError
provider = IBMQ.load_account()
print("Available Backends: ", provider.backends())
for be in provider.backends():
try:
print()
print("*" * 20 + be.name() + "*" * 20)
noise_model = NoiseModel.from_backend(be)
# readout
print("Readout Error on q_0:", noise_model._local_readout_errors['0'])
# thermal and depol
properties = be.properties()
relax_params = thermal_relaxation_values(properties) # T1, T2 (microS) and frequency values (GHz)
t1, t2, freq = relax_params[0]
u3_length = properties.gate_length('u3', 0)
print("t1: " + str(t1))
print("t2: " + str(t2))
print("freq: " + str(freq))
print("universal_error gate length: " + str(u3_length))
# depol
device_gate_params = gate_param_values(properties)
except NoiseError:
pass
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
%%capture
%pip install qiskit
%pip install qiskit_ibm_provider
%pip install qiskit-aer
# Importing standard Qiskit libraries
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer
from qiskit_ibm_provider import IBMProvider
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.circuit.library import C3XGate
# Importing matplotlib
import matplotlib.pyplot as plt
# Importing Numpy, Cmath and math
import numpy as np
import os, math, cmath
from numpy import pi
# Other imports
from IPython.display import display, Math, Latex
# Specify the path to your env file
env_file_path = 'config.env'
# Load environment variables from the file
os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#'))
# Load IBM Provider API KEY
IBMP_API_KEY = os.environ.get('IBMP_API_KEY')
# Loading your IBM Quantum account(s)
IBMProvider.save_account(IBMP_API_KEY, overwrite=True)
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
qc_b1 = QuantumCircuit(2, 2)
qc_b1.h(0)
qc_b1.cx(0, 1)
qc_b1.draw(output='mpl', style="iqp")
sv = backend.run(qc_b1).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.x(0)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.z(0)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.x(1)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.x(0)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.x(0)
qc_b4.h(0)
qc_b4.x(1)
qc_b4.cx(0, 1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.h(0)
qc_b4.cx(0, 1)
qc_b4.x(0)
qc_b4.z(1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
def sv_latex_from_qc(qc, backend):
sv = backend.run(qc).result().get_statevector()
return sv.draw(output='latex')
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(3)
sv_latex_from_qc(qc_ej2, backend)
def circuit_adder (num):
if num<1 or num>8:
raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricción sería directo.
# Definición del circuito base que vamos a construir
qreg_q = QuantumRegister(4, 'q')
creg_c = ClassicalRegister(1, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
qbit_position = 0
for element in reversed(np.binary_repr(num)):
if (element=='1'):
circuit.barrier()
match qbit_position:
case 0: # +1
circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]])
circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
circuit.x(qreg_q[0])
case 1: # +2
circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.x(qreg_q[1])
case 2: # +4
circuit.cx(qreg_q[2], qreg_q[3])
circuit.x(qreg_q[2])
case 3: # +8
circuit.x(qreg_q[3])
qbit_position+=1
return circuit
add_3 = circuit_adder(3)
add_3.draw(output='mpl', style="iqp")
qc_test_2 = QuantumCircuit(4, 4)
qc_test_2.x(1)
qc_test_2_plus_3 = qc_test_2.compose(add_3)
qc_test_2_plus_3.draw(output='mpl', style="iqp")
sv_latex_from_qc(qc_test_2_plus_3, backend)
qc_test_7 = QuantumCircuit(4, 4)
qc_test_7.x(0)
qc_test_7.x(1)
qc_test_7.x(2)
qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8))
sv_latex_from_qc(qc_test_7_plus_8, backend)
#qc_test_7_plus_8.draw()
theta = 6.544985
phi = 2.338741
lmbda = 0
alice_1 = 0
alice_2 = 1
bob_1 = 2
qr_alice = QuantumRegister(2, 'Alice')
qr_bob = QuantumRegister(1, 'Bob')
cr = ClassicalRegister(3, 'c')
qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr)
qc_ej3.barrier(label='1')
qc_ej3.u(theta, phi, lmbda, alice_1);
qc_ej3.barrier(label='2')
qc_ej3.h(alice_2)
qc_ej3.cx(alice_2, bob_1);
qc_ej3.barrier(label='3')
qc_ej3.cx(alice_1, alice_2)
qc_ej3.h(alice_1);
qc_ej3.barrier(label='4')
qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]);
qc_ej3.barrier(label='5')
qc_ej3.x(bob_1).c_if(alice_2, 1)
qc_ej3.z(bob_1).c_if(alice_1, 1)
qc_ej3.measure(bob_1, bob_1);
qc_ej3.draw(output='mpl', style="iqp")
result = backend.run(qc_ej3, shots=1024).result()
counts = result.get_counts()
plot_histogram(counts)
sv_0 = np.array([1, 0])
sv_1 = np.array([0, 1])
def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/√2'}, tolerance=1e-10):
"""
Check if the given numerical value corresponds to a symbolic constant within a specified tolerance.
Parameters:
- value (float): The numerical value to check.
- symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations.
Defaults to {1/np.sqrt(2): '1/√2'}.
- tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10.
Returns:
str or float: If a match is found, returns the symbolic representation as a string
(prefixed with '-' if the value is negative); otherwise, returns the original value.
"""
for constant, symbol in symbolic_constants.items():
if np.isclose(abs(value), constant, atol=tolerance):
return symbol if value >= 0 else '-' + symbol
return value
def array_to_dirac_notation(array, tolerance=1e-10):
"""
Convert a complex-valued array representing a quantum state in superposition
to Dirac notation.
Parameters:
- array (numpy.ndarray): The complex-valued array representing
the quantum state in superposition.
- tolerance (float): Tolerance for considering amplitudes as negligible.
Returns:
str: The Dirac notation representation of the quantum state.
"""
# Ensure the statevector is normalized
array = array / np.linalg.norm(array)
# Get the number of qubits
num_qubits = int(np.log2(len(array)))
# Find indices where amplitude is not negligible
non_zero_indices = np.where(np.abs(array) > tolerance)[0]
# Generate Dirac notation terms
terms = [
(find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b"))
for i in non_zero_indices
]
# Format Dirac notation
dirac_notation = " + ".join([f"{amplitude}|{binary_rep}⟩" for amplitude, binary_rep in terms])
return dirac_notation
def array_to_matrix_representation(array):
"""
Convert a one-dimensional array to a column matrix representation.
Parameters:
- array (numpy.ndarray): The one-dimensional array to be converted.
Returns:
numpy.ndarray: The column matrix representation of the input array.
"""
# Replace symbolic constants with their representations
matrix_representation = np.array([find_symbolic_representation(value) or value for value in array])
# Return the column matrix representation
return matrix_representation.reshape((len(matrix_representation), 1))
def array_to_dirac_and_matrix_latex(array):
"""
Generate LaTeX code for displaying both the matrix representation and Dirac notation
of a quantum state.
Parameters:
- array (numpy.ndarray): The complex-valued array representing the quantum state.
Returns:
Latex: A Latex object containing LaTeX code for displaying both representations.
"""
matrix_representation = array_to_matrix_representation(array)
latex = "Matrix representation\n\\begin{bmatrix}\n" + \
"\\\\\n".join(map(str, matrix_representation.flatten())) + \
"\n\\end{bmatrix}\n"
latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}'
return Latex(latex)
sv_b1 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b2 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b3 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b4 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
from qiskit import Aer
from qiskit import execute
from qiskit.test.mock import FakeVigo
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
class QuantumNoiseEstimator:
def __init__(self, dataset=None, classifier=RandomForestClassifier()):
"""
Initialize the class
:param dataset: the dataset (QuantumNoiseDataset)
:param classifier: the classifier to use
todo: generalize classifier to an estimator (regression etc.)
"""
self.dataset = dataset
assert self.dataset is not None, "dataset is empty"
self.classifier = classifier
self.encoder_decoder = QuantumDatasetEncoder(classifier)
encoded_features = self.encoder_decoder.encode_features(self.dataset)
encoded_labels = self.encoder_decoder.encode_labels(self.dataset)
self.X_train, self.X_test, self.Y_train, self.Y_test = train_test_split(encoded_features, encoded_labels,
test_size=0.33)
def fit(self):
"""
Fit the model to the dataset
:return:
"""
self.classifier.fit(self.X_train, self.Y_train)
def predict(self, feature):
encoded_feature = self.encoder_decoder.encode_feature(feature)
encoded_label = self.classifier.predict(encoded_feature)
decoded_label = self.encoder_decoder.decode_label(encoded_label)
return decoded_label
def __repr__(self):
return "I am a Quantum Noise Estimator"
class DatasetGenerator:
def __init__(self, shots=1000):
"""
Initialize this class
:param shots: number of times to measure each circuit
"""
self.shots = shots
self.observations = []
self.features = []
self.labels = []
self.dataset = QuantumNoiseDataset()
# Device Model
self.device_backend = FakeVigo()
self.coupling_map = self.device_backend.configuration().coupling_map
self.simulator = Aer.get_backend('qasm simulator')
def add_observation(self, circuit, noise_model):
"""
Add a new data point - (feature, label) -to the dataset. Blocking method (until counts are calculated)
:param circuit:
:param noise_model:
:return: none
"""
feature = (circuit, noise_model)
label = self.get_counts(circuit, noise_model)
self.dataset.add_data_point(feature, label)
def get_counts(self, circuit, noise_model):
"""
Simulate a circuit with a noise_model and return measurement counts
:param circuit:
:param noise_model:
:return: measurement counts (dict)
"""
result = execute(circuit, self.simulator, noise_model=noise_model, coupling_map=self.coupling_map,
basis_gates=noise_model.basis_gates, shots=self.shots).result()
counts = result.get_counts()
return counts
def get_dataset(self):
"""
:return: the dataset (QuantumNoiseDataset)
"""
return self.dataset
def __repr__(self):
return "I am a dataset generator for quantum noise estimation"
def mock_dataset(self):
"""
Generate a mock dataset
:return: the dataset (QuantumNoiseDataset)
"""
raise NotImplementedError
class QuantumNoiseDataset:
def __init__(self):
self.data_points = []
def add_data_point(self, feature, label):
dp = (feature, label)
self.data_points.append(dp)
class QuantumDatasetEncoder:
def __init__(self, classifier):
"""
Initialize the class
:param classifier: the classifier (might be useful later)
Encodes and Decodes dataset for sklearn classifier
"""
self.classifier = classifier
self.features_encoder = OneHotEncoder()
self.labels_encoder = None
def encode_features(self, dataset):
raise NotImplementedError
def encode_labels(self, dataset):
raise NotImplementedError
def decode_labels(self, labels):
raise NotImplementedError
def decode_label(self, encoded_label):
raise NotImplementedError
def encode_feature(self, feature):
raise NotImplementedError
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import pandas as pd
from qiskit import Aer
from qiskit import execute
from qiskit.test.mock import FakeVigo
class DatasetGenerator:
def __init__(self, shots=1000, L=3):
"""
Initialize a new DatasetGenerator.
This object provides an interface to generate synthetic quantum-noisy datasets.
The user must prescribe the circuits and noise models.
Some presets are available.
:param shots: number of times to measure each circuit, default: 1000
:param L: maximum circuit length
"""
# Simulator Variables
self.device_backend = FakeVigo()
self.coupling_map = self.device_backend.configuration().coupling_map
self.simulator = Aer.get_backend('qasm_simulator')
self.shots = shots
self.L = L
self.dataset = self.emptyDataset()
"""self.observations = []
self.features = []
self.labels = []"""
def add_observation(self, circuit, noise_model):
"""
Add a new data point - (feature, label) - to the dataset.
:param circuit: circuit, len(circuit) <= self.L
:param noise_model:
:return: none
"""
assert len(circuit) <= self.L
feature = (circuit, noise_model)
label = self.get_counts(circuit, noise_model)
self.dataset.add_data_point(feature, label)
def get_dataset(self):
"""
:return: the dataset (DataFrame)
"""
return self.dataset
def get_counts(self, circuit, noise_model):
"""
Simulate a circuit with a noise_model and return measurement counts
:param circuit:
:param noise_model:
:return: measurement counts (dict {'0':C0, '1':C1})
"""
result = execute(circuit, self.simulator, noise_model=noise_model, coupling_map=self.coupling_map,
basis_gates=noise_model.basis_gates, shots=self.shots).result()
counts = result.get_counts()
return counts
def emptyDataset(self):
"""
Generate an empty Dataset.
Column format:
Gate_1
NM_1
...
...
Expected Value
:return: df: DataFrame
"""
column_names = []
for i in range(self.L):
column_names.append("Gate_{}_theta".format(i))
column_names.append("Gate_{}_phi".format(i))
column_names.append("Gate_{}_lambda".format(i))
column_names.append("NM_{}".format(i))
column_names.append("ExpectedValue")
df = pd.DataFrame(dtype='float64', columns=column_names)
df.loc[0] = pd.Series(dtype='float64')
df.loc[1] = pd.Series(dtype='float64')
df.loc[2] = pd.Series(dtype='float64')
return df
def __repr__(self):
return "I am a dataset generator for quantum noise estimation"
dgen = DatasetGenerator()
ds = dgen.dataset
print("ds.info()")
print(ds.info())
"""
Questions
1. how to encode noise model
2. how to generate data samples
"""
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.circuit.library import RXGate
import numpy as np
basis_gates = ['u3']
circ = QuantumCircuit(1, 1)
RX = RXGate(0)
# circ.append(RX, [0])
circ.h(0)
circ.measure(0, 0)
print("Before Transpiling:")
print(circ)
new_circ = qiskit.compiler.transpile(circ, basis_gates=basis_gates, optimization_level=0)
print("After Transpiling:")
print(new_circ)
|
https://github.com/dcavar/q
|
dcavar
|
import numpy as np
A = np.array([[1, 3, 2], [0, 2, 6]])
print("Matrix A:\n", A)
B = np.array([[2, 0, 1, 4], [3, 1, 3, 1], [1, 2, 2, 6]])
print("Matrix B:\n", B)
print("Matrix product:")
A @ B
A = np.array([[0, 1], [1, 0]])
print("Matrix A:\n", A)
B = np.array([[1], [0]])
print("Matrix B:\n", B)
A @ B
C = 2 * A
print("Matrix C:\n", C)
from qiskit.quantum_info import Statevector
ASV = Statevector([0, 1])
ASV.draw(output="latex")
ASV.draw(output="qsphere")
BSV = Statevector([1, 0])
BSV.draw(output="latex")
BSV.draw(output="qsphere")
CSV = BSV.tensor(ASV.tensor(BSV))
CSV.draw(output="latex")
A = np.array([ 1, 2 ])
B = np.array([ 1, 2 ])
np.tensordot(A, B, axes=0)
A = np.array([[1,3], [4,2]])
B = np.array([[2,1], [5,4]])
np.tensordot(A, B, axes=0)
x = 2
y = 1
z = complex(x, y)
z
print(np.real(z))
print(np.imag(z))
r = complex(2, 3)
r
r * z
x = complex((z.real * r.real) - (z.imag * r.imag), (z.real * r.imag) + (z.imag * r.real))
x
from qiskit.visualization import plot_bloch_vector
x = plot_bloch_vector([0,1,0], title="New Bloch Sphere")
|
https://github.com/dcavar/q
|
dcavar
|
import numpy as np
X = np.array([[0, 1], [1, 0]])
print("Matrix X:\n", X)
B = np.array([[1], [0]])
print("Matrix B:\n", B)
X @ B
|
https://github.com/dcavar/q
|
dcavar
|
!pip install -U qiskit
!pip install -U qiskit_ibm_provider
from qiskit import transpile
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime.fake_provider import FakeManilaV2
q = QuantumRegister(2,'q')
c = ClassicalRegister(2,'c')
circuit = QuantumCircuit(q,c)
circuit.h(q)
circuit.cx(q[0], q[1])
circuit.measure(q,c)
fake_manila = FakeManilaV2()
pm = generate_preset_pass_manager(backend=fake_manila, optimization_level=1)
isa_qc = pm.run(circuit)
print(isa_qc)
new_circuit = transpile(circuit, fake_manila)
job = fake_manila.run(new_circuit, shots=100)
res = job.result()
print('Result:', res)
|
https://github.com/dcavar/q
|
dcavar
|
!pip install -U --user qiskit
!pip install -U --user qiskit_ibm_runtime
!pip install -U --user matplotlib
!pip install -U --user pylatexenc
import qiskit
import secret
qiskit.__version__
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum", # or ibm_cloud
token=secret.api_key_ibm_q)
QiskitRuntimeService.save_account(channel="ibm_quantum",
token=secret.api_key_ibm_q)
backend = service.backend(name="ibm_brisbane")
backend.num_qubits
|
https://github.com/dcavar/q
|
dcavar
|
!pip install -U --user qiskit
!pip install -U --user qiskit_ibm_runtime
!pip install -U --user qiskit_aer
!pip install -U --user matplotlib
!pip install -U --user pylatexenc
import qiskit
import secret
qc = qiskit.QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
x = qc.draw(output='mpl')
x
from qiskit.quantum_info import Pauli
ZZ = Pauli('ZZ')
ZI = Pauli('ZI')
IZ = Pauli('IZ')
XX = Pauli('XX')
XI = Pauli('XI')
IX = Pauli('IX')
observables = [ZZ, ZI, IZ, XX, XI, IX]
from qiskit_aer.primitives import Estimator
estimator = Estimator()
job = estimator.run([qc] * len(observables), observables)
job.result()
import matplotlib.pyplot as plt
data = ["ZZ", "ZI", "IZ", "XX", "XI", "IX"]
values = job.result().values
plt.plot(data, values, '-o')
plt.xlabel('Observables')
plt.ylabel('Expectation value')
plt.show()
|
https://github.com/dcavar/q
|
dcavar
|
!pip install -U qiskit
!pip install -U qiskit_ibm_provider
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile
from qiskit_ibm_provider import IBMProvider
from secret import api_key_ibm_q
provider = IBMProvider(token=api_key_ibm_q)
backends = provider.backends()
print(backends)
backend = provider.get_backend('ibm_brisbane')
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
circuit = QuantumCircuit(q,c)
circuit.h(q)
circuit.measure(q,c)
new_circuit = transpile(circuit, backend)
job = backend.run(new_circuit, shots=1, memory=True)
status = backend.status()
print(status.operational)
print(status.pending_jobs)
res = job.result()
print('Result:', res)
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram, circuit_drawer
q = QuantumRegister(2)
c = ClassicalRegister(2)
#quantum circuit is used to perform operations on qubits
qc = QuantumCircuit(q, c)
#hadamard gate (ususally used to create superposition)
qc.h(q[0])
#controllled not gate
qc.cx(q[0], q[1])
#measures the qubits
qc.measure(q, c)
#run simulation (default backend: "local_qasm_simulator")
job_sim = execute(qc, "local_qasm_simulator")
#Simulation Results
sim_result = job_sim.result()
#qubit probability results
print(sim_result.get_counts(qc))
#visualize simulation results in histogram
plot_histogram(sim_result.get_counts(qc))
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
import getpass, time
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import available_backends, execute, register, least_busy, get_backend
import Qconfig
# import basic plot tools
from qiskit.tools.visualization import plot_histogram, circuit_drawer
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c)
register(Qconfig.APItoken)
backend = get_backend('ibmqx4')
job_exp = execute(qc, backend=backend, shots=1024, max_credits=3)
lapse = 0
interval = 30
while not job_exp.done:
print('Status @ {} seconds'.format(interval * lapse))
print(job_exp.status)
time.sleep(interval)
lapse += 1
print(job_exp.status)
plot_histogram(job_exp.result().get_counts(qc))
print('You have made entanglement!')
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError
from qiskit import available_backends, execute, register, get_backend
# import state tomography functions
from qiskit.tools.visualization import plot_histogram, plot_state
# useful additional packages
import matplotlib.pyplot as plt
#%matplotlib inline
import numpy as np
from pprint import pprint
from scipy import linalg as la
def ghz_state(q, c, n):
# Create a GHZ state
qc = QuantumCircuit(q, c)
qc.h(q[0])
for i in range(n-1):
qc.cx(q[i], q[i+1])
return qc
def superposition_state(q, c):
# Create a Superposition state
qc = QuantumCircuit(q, c)
qc.h(q)
return qc
def overlap(state1, state2):
return round(np.dot(state1.conj(), state2))
def expectation_value(state, Operator):
return round(np.dot(state.conj(), np.dot(Operator, state)).real)
def state_2_rho(state):
return np.outer(state, state.conj())
# Build the quantum cirucit. We are going to build two circuits a GHZ over 3 qubits and a
# superpositon over all 3 qubits
n = 3 # number of qubits
q = QuantumRegister(n)
c = ClassicalRegister(n)
'''
# quantum circuit to make a GHZ state
ghz = ghz_state(q, c, n)
# quantum circuit to make a superposition state
superposition = superposition_state(q, c)
measure_circuit = QuantumCircuit(q,c)
measure_circuit.measure(q, c)
# execute the quantum circuit
backend = 'local_qasm_simulator' # the device to run on
circuits = [ghz+measure_circuit, superposition+measure_circuit]
job = execute(circuits, backend=backend, shots=1000)
plot_histogram(job.result().get_counts(circuits[0]))
plot_histogram(job.result().get_counts(circuits[1]),15)
'''
qc = QuantumCircuit(q, c)
qc.h(q[1])
# execute the quantum circuit
job = execute(qc, backend='local_statevector_simulator')
state_superposition = job.result().get_statevector(qc)
#print(state_superposition)
#print(overlap(state_superposition, state_superposition))
rho_superposition = state_2_rho(state_superposition)
print(rho_superposition)
plot_state(rho_superposition, 'bloch') #'city', 'paulivec', 'qsphere', 'bloch'
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError
from qiskit import available_backends, execute, register, get_backend
from qiskit.tools.visualization import circuit_drawer
from qiskit.tools.qi.qi import state_fidelity
# Useful additional packages
import matplotlib.pyplot as plt
#matplotlib inline
import numpy as np
from math import pi
q = QuantumRegister(3)
qc = QuantumCircuit(q)
'''
#Controlled Pauli Gates
# 1. Controlled-X (or, controlled-NOT) gate
qc.cx(q[0], q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 2. Controlled Y gate
qc.cy(q[0], q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 3. Controlled Z (or, controlled phase) gate
qc.cz(q[0], q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 4. Controlled Hadamard gate
qc.ch(q[0], q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
#Controlled rotation gates
# 5. Controlled rotation around Z-axis
qc.crz(pi/2,q[0],q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 6. Controlled phase rotation
qc.cu1(pi/2,q[0], q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 7. Controlled u3 rotation
qc.cu3(pi/2, pi/2, pi/2, q[0], q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 8. Swap rotation
qc.swap(q[0], q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 9. Toffoli gate
qc.ccx(q[0], q[1], q[2])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
'''
# 10. Controlled swap gate (Fredkin Gate)
qc.cswap(q[0], q[1], q[2])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError
from qiskit import available_backends, execute, register, get_backend
from qiskit.tools.visualization import circuit_drawer
from qiskit.tools.qi.qi import state_fidelity
# Useful additional packages
import matplotlib.pyplot as plt
#matplotlib inline
import numpy as np
from math import pi
q = QuantumRegister(1)
qc = QuantumCircuit(q)
# 1. u/unitary gate
'''qc.u1(pi/2,q) #u0, u1, u2, u3
#circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
# 2. identity gate
qc.iden(q) #or u0(1)
job = execute(qc, backend='local_unitary_simulator')
print(np.round(job.result().get_data(qc)['unitary'], 3))
#Pauli Gates
# 3. X (bit-flip) gate
qc.x(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 4. Y (bit- and phase-flip) gate
qc.y(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 5. Z (phase-flip) gate
qc.z(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
#Clifford Gates
# 6. hadamard gate
qc.h(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 7. S (or sqrt(Z) phase) gate
qc.s(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 8. Sdg (or conjugate of sqrt(Z) phase) gate
qc.sdg(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
#C3 Gates
# 9. T (or sqrt(S) phase) gate
qc.t(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 10. Tdg (or sqrt(S) phase) gate
qc.tdg(q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
#Standard Rotations
# 11. Rotation around X-axis
qc.rx(pi/2,q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 12. Rotation around Y-axis
qc.ry(pi/2,q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
'''
# 13. Rotation around Z-axis
qc.rz(pi/2,q)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
# -*- coding: utf-8 -*-
# Copyright 2017, 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.
"""Demo basic optimization: Remove Zero Rotations and Remove Double CNOTs.
Note: if you have only cloned the Qiskit repository but not
used `pip install`, the examples only work from the root directory.
"""
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import CompositeGate
from qiskit.extensions.standard.cx import CnotGate
from qiskit.extensions.standard.rx import RXGate
quantum_r = QuantumRegister(4, "qr")
classical_r = ClassicalRegister(4, "cr")
circuit = QuantumCircuit(quantum_r, classical_r)
circuit.h(quantum_r[0])
circuit.rx(0, quantum_r[0])
circuit.cx(quantum_r[0], quantum_r[1])
circuit.cx(quantum_r[0], quantum_r[1])
circuit.h(quantum_r[0])
circuit.cx(quantum_r[0], quantum_r[1])
composite_gate_1 = CompositeGate("composite1", [],
[quantum_r[x] for x in range(4)])
composite_gate_1._attach(CnotGate(quantum_r[0], quantum_r[1]))
circuit._attach(composite_gate_1)
circuit.h(quantum_r[0])
composite_gate_2 = CompositeGate("composite2", [],
[quantum_r[x] for x in range(4)])
composite_gate_2._attach(CnotGate(quantum_r[0], quantum_r[1]))
circuit._attach(composite_gate_2)
circuit.cx(quantum_r[0], quantum_r[1])
circuit.h(quantum_r[0])
composite_gate_3 = CompositeGate("composite3", [],
[quantum_r[x] for x in range(4)])
composite_gate_3._attach(CnotGate(quantum_r[0], quantum_r[1]))
composite_gate_3._attach(CnotGate(quantum_r[0], quantum_r[2]))
circuit._attach(composite_gate_3)
circuit.h(quantum_r[0])
composite_gate_4 = CompositeGate("composite4", [],
[quantum_r[x] for x in range(4)])
composite_gate_4._attach(CnotGate(quantum_r[0], quantum_r[1]))
composite_gate_4._attach(RXGate(0, quantum_r[0]))
composite_gate_4._attach(CnotGate(quantum_r[0], quantum_r[1]))
circuit._attach(composite_gate_4)
print("Removed Zero Rotations: " + str(circuit.remove_zero_rotations()))
print("Removed Double CNOTs: " + str(circuit.remove_double_cnots_once()))
QASM_source = circuit.qasm()
print(QASM_source)
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
# useful additional packages
import matplotlib.pyplot as plt
#%matplotlib inline
import numpy as np
from pprint import pprint
# importing QISKit
from qiskit import QuantumProgram, QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import available_backends, execute, register, least_busy
# import basic plot tools
from qiskit.tools.visualization import plot_histogram, circuit_drawer
qx_config = {
"APItoken": 'dcdb2d9414a625c1f57373c544add3711c78c3d7faf39397fe2c41887110e8b59caf81bcb2bc32714d936da41a261fea510f96df379afcbdfa9df6cc6bfe3829',
"url": 'https://quantumexperience.ng.bluemix.net/api'
}
backend = 'local_qasm_simulator' # run on local simulator by default
'''register(qx_config['APItoken'], qx_config['url'])
backend = least_busy(available_backends({'simulator': False, 'local': False}))
print("the best backend is " + backend)
'''
# Creating registers
q2 = QuantumRegister(2)
c2 = ClassicalRegister(2)
# quantum circuit to make an entangled bell state
bell = QuantumCircuit(q2, c2)
bell.h(q2[0])
bell.cx(q2[0], q2[1])
# quantum circuit to measure q0 in the standard basis
measureIZ = QuantumCircuit(q2, c2)
measureIZ.measure(q2[0], c2[0])
bellIZ = bell+measureIZ
# quantum circuit to measure q0 in the superposition basis
measureIX = QuantumCircuit(q2, c2)
measureIX.h(q2[0])
measureIX.measure(q2[0], c2[0])
bellIX = bell+measureIX
# quantum circuit to measure q1 in the standard basis
measureZI = QuantumCircuit(q2, c2)
measureZI.measure(q2[1], c2[1])
bellZI = bell+measureZI
# quantum circuit to measure q1 in the superposition basis
measureXI = QuantumCircuit(q2, c2)
measureXI.h(q2[1])
measureXI.measure(q2[1], c2[1])
bellXI = bell+measureXI
# quantum circuit to measure q in the standard basis
measureZZ = QuantumCircuit(q2, c2)
measureZZ.measure(q2[0], c2[0])
measureZZ.measure(q2[1], c2[1])
bellZZ = bell+measureZZ
# quantum circuit to measure q in the superposition basis
measureXX = QuantumCircuit(q2, c2)
measureXX.h(q2[0])
measureXX.h(q2[1])
measureXX.measure(q2[0], c2[0])
measureXX.measure(q2[1], c2[1])
bellXX = bell+measureXX
# quantum circuit to make a mixed state
mixed1 = QuantumCircuit(q2, c2)
mixed2 = QuantumCircuit(q2, c2)
mixed2.x(q2)
mixed1.h(q2[0])
mixed1.h(q2[1])
mixed1.measure(q2[0], c2[0])
mixed1.measure(q2[1], c2[1])
mixed2.h(q2[0])
mixed2.h(q2[1])
mixed2.measure(q2[0], c2[0])
mixed2.measure(q2[1], c2[1])
'''circuits = [bellIZ,bellIX,bellZI,bellXI,bellZZ,bellXX]
job = execute(circuits, backend)
result = job.result()
print(result.get_counts(bellXX))
plot_histogram(result.get_counts(bellXX))'''
mixed_state = [mixed1,mixed2]
job = execute(mixed_state, backend)
result = job.result()
counts1 = result.get_counts(mixed_state[0])
counts2 = result.get_counts(mixed_state[1])
from collections import Counter
ground = Counter(counts1)
excited = Counter(counts2)
plot_histogram(ground+excited)
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
# Imports
import matplotlib.pyplot as plt
#%matplotlib inline
import numpy as np
from qiskit import QuantumProgram, QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import available_backends, get_backend, execute, register, least_busy
from qiskit.tools.visualization import plot_histogram, circuit_drawer
# Connecting to the IBM Quantum Experience
qx_config = {
"APItoken": 'dcdb2d9414a625c1f57373c544add3711c78c3d7faf39397fe2c41887110e8b59caf81bcb2bc32714d936da41a261fea510f96df379afcbdfa9df6cc6bfe3829',
"url": 'https://quantumexperience.ng.bluemix.net/api'
}
register(qx_config['APItoken'], qx_config['url'])
device_shots = 1024
device_name = least_busy(available_backends({'simulator': False, 'local': False}))
device = get_backend(device_name)
device_coupling = device.configuration['coupling_map']
print("the best backend is " + device_name + " with coupling " + str(device_coupling))
# Creating registers
q = QuantumRegister(2)
c = ClassicalRegister(2)
# quantum circuit to make an entangled bell state
bell = QuantumCircuit(q, c)
bell.h(q[0])
bell.cx(q[0], q[1])
# quantum circuit to measure q in the standard basis
measureZZ = QuantumCircuit(q, c)
measureZZ.measure(q[0], c[0])
measureZZ.measure(q[1], c[1])
bellZZ = bell+measureZZ
# quantum circuit to measure q in the superposition basis
measureXX = QuantumCircuit(q, c)
measureXX.h(q[0])
measureXX.h(q[1])
measureXX.measure(q[0], c[0])
measureXX.measure(q[1], c[1])
bellXX = bell+measureXX
# quantum circuit to measure ZX
measureZX = QuantumCircuit(q, c)
measureZX.h(q[0])
measureZX.measure(q[0], c[0])
measureZX.measure(q[1], c[1])
bellZX = bell+measureZX
# quantum circuit to measure XZ
measureXZ = QuantumCircuit(q, c)
measureXZ.h(q[1])
measureXZ.measure(q[0], c[0])
measureXZ.measure(q[1], c[1])
bellXZ = bell+measureXZ
circuits = [bellZZ,bellXX,bellZX,bellXZ]
job = execute(circuits, backend=device_name, coupling_map=device_coupling, shots=device_shots)
result = job.result()
observable_first ={'00': 1, '01': -1, '10': 1, '11': -1}
observable_second ={'00': 1, '01': 1, '10': -1, '11': -1}
observable_correlated ={'00': 1, '01': -1, '10': -1, '11': 1}
print('IZ = ' + str(result.average_data(bellZZ,observable_first)))
print('ZI = ' + str(result.average_data(bellZZ,observable_second)))
print('ZZ = ' + str(result.average_data(bellZZ,observable_correlated)))
print('IX = ' + str(result.average_data(bellXX,observable_first)))
print('XI = ' + str(result.average_data(bellXX,observable_second)))
print('XX = ' + str(result.average_data(bellXX,observable_correlated)))
print('ZX = ' + str(result.average_data(bellZX,observable_correlated)))
print('XZ = ' + str(result.average_data(bellXZ,observable_correlated)))
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
# useful additional packages
import matplotlib.pyplot as plt
#%matplotlib inline
import numpy as np
from pprint import pprint
# importing QISKit
from qiskit import QuantumProgram, QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import available_backends, execute, register, least_busy
# import basic plot tools
from qiskit.tools.visualization import plot_histogram, circuit_drawer
qx_config = {
"APItoken": 'dcdb2d9414a625c1f57373c544add3711c78c3d7faf39397fe2c41887110e8b59caf81bcb2bc32714d936da41a261fea510f96df379afcbdfa9df6cc6bfe3829',
"url": 'https://quantumexperience.ng.bluemix.net/api'
}
backend = 'local_qasm_simulator' # run on local simulator by default
# register(qx_config['APItoken'], qx_config['url'])
# backend = least_busy(available_backends({'simulator': False, 'local': False}))
# print("the best backend is " + backend)
# Creating registers
sdq = QuantumRegister(2)
sdc = ClassicalRegister(2)
# Quantum circuit to make the shared entangled state
superdense = QuantumCircuit(sdq, sdc)
superdense.h(sdq[0])
superdense.cx(sdq[0], sdq[1])
# For 00, do nothing
# For 01, apply $X$
#shared.x(q[0])
# For 01, apply $Z$
#shared.z(q[0])
# For 11, apply $XZ$
superdense.z(sdq[0])
superdense.x(sdq[0])
superdense.barrier()
superdense.cx(sdq[0], sdq[1])
superdense.h(sdq[0])
superdense.measure(sdq[0], sdc[0])
superdense.measure(sdq[1], sdc[1])
superdense_job = execute(superdense, backend)
superdense_result = superdense_job.result()
plot_histogram(superdense_result.get_counts(superdense))
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
# useful additional packages
import matplotlib.pyplot as plt
#%matplotlib inline
import numpy as np
from pprint import pprint
# importing QISKit
from qiskit import QuantumProgram, QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import available_backends, execute, register, least_busy
# import basic plot tools
from qiskit.tools.visualization import plot_histogram, circuit_drawer
qx_config = {
"APItoken": 'dcdb2d9414a625c1f57373c544add3711c78c3d7faf39397fe2c41887110e8b59caf81bcb2bc32714d936da41a261fea510f96df379afcbdfa9df6cc6bfe3829',
"url": 'https://quantumexperience.ng.bluemix.net/api'
}
backend = 'local_qasm_simulator' # run on local simulator by default
'''register(qx_config['APItoken'], qx_config['url'])
backend = least_busy(available_backends({'simulator': False, 'local': False}))
print("the best backend is " + backend)
'''
# Creating registers
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
# Quantum circuit ground
qc_ground = QuantumCircuit(qr, cr)
qc_ground.measure(qr[0], cr[0])
# Quantum circuit excited
qc_excited = QuantumCircuit(qr, cr)
qc_excited.x(qr)
qc_excited.measure(qr[0], cr[0])
# Quantum circuit superposition
qc_superposition = QuantumCircuit(qr, cr)
qc_superposition.h(qr)
qc_superposition.barrier()
qc_superposition.h(qr)
qc_superposition.measure(qr[0], cr[0])
circuits = [qc_ground, qc_excited, qc_superposition]
job = execute(circuits, backend)
result = job.result()
plot_histogram(result.get_counts(qc_superposition))
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer
from qiskit.extensions import Initialize
from qiskit.quantum_info import random_statevector, Statevector,partial_trace
def trace01(out_vector):
return Statevector([sum([out_vector[i] for i in range(0,4)]), sum([out_vector[i] for i in range(4,8)])])
def teleportation():
# Create random 1-qubit state
psi = random_statevector(2)
print(psi)
init_gate = Initialize(psi)
init_gate.label = "init"
## SETUP
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical registers
crx = ClassicalRegister(1, name="crx")
qc = QuantumCircuit(qr, crz, crx)
# Don't modify the code above
## Put your code below
# ----------------------------
qc.initialize(psi, qr[0])
qc.h(qr[1])
qc.cx(qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.h(qr[0])
qc.measure(qr[0],crz[0])
qc.measure(qr[1],crx[0])
qc.x(qr[2]).c_if(crx[0], 1)
qc.z(qr[2]).c_if(crz[0], 1)
# ----------------------------
# Don't modify the code below
sim = Aer.get_backend('aer_simulator')
qc.save_statevector()
out_vector = sim.run(qc).result().get_statevector()
result = trace01(out_vector)
return psi, result
# (psi,res) = teleportation()
# print(psi)
# print(res)
# if psi == res:
# print('1')
# else:
# print('0')
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
import qiskit as qk
from qiskit import available_backends, get_backend, execute, register, least_busy
import numpy as np
from scipy.optimize import curve_fit
from qiskit.tools.qcvv.fitters import exp_fit_fun, osc_fit_fun, plot_coherence
qx_config = {
"APItoken": 'dcdb2d9414a625c1f57373c544add3711c78c3d7faf39397fe2c41887110e8b59caf81bcb2bc32714d936da41a261fea510f96df379afcbdfa9df6cc6bfe3829',
"url": 'https://quantumexperience.ng.bluemix.net/api'
}
#backend = 'local_qasm_simulator' # run on local simulator by default
register(qx_config['APItoken'], qx_config['url'])
backend = qk.get_backend('ibmqx4') # the device to run on
#backend = least_busy(available_backends({'simulator': False, 'local': False}))
#print("the best backend is " + backend)
# function for padding with QId gates
def pad_QId(circuit,N,qr):
# circuit to add to, N = number of QId gates to add, qr = qubit reg
for ii in range(N):
circuit.barrier(qr)
circuit.iden(qr)
return circuit
shots = 1024 # the number of shots in the experiment
# Select qubit whose T1 is to be measured
qubit=1
# Creating registers
qr = qk.QuantumRegister(5)
cr = qk.ClassicalRegister(5)
# the delay times are all set in terms of single-qubit gates
# so we need to calculate the time from these parameters
params = backend.parameters['qubits'][qubit]
pulse_length=params['gateTime']['value'] # single-qubit gate time
buffer_length=params['buffer']['value'] # spacing between pulses
unit = params['gateTime']['unit']
steps=10
gates_per_step=120
max_gates=(steps-1)*gates_per_step+1
tot_length=buffer_length+pulse_length
time_per_step=gates_per_step*tot_length
qc_dict={}
for ii in range(steps):
step_num='step_%s'%(str(ii))
qc_dict.update({step_num:qk.QuantumCircuit(qr, cr)})
qc_dict[step_num].x(qr[qubit])
qc_dict[step_num]=pad_QId(qc_dict[step_num],gates_per_step*ii,qr[qubit])
qc_dict[step_num].barrier(qr[qubit])
qc_dict[step_num].measure(qr[qubit], cr[qubit])
circuits=list(qc_dict.values())
# run the program
status = backend.status
if status['operational'] == False or status['pending_jobs'] > 10:
print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible')
t1_job=qk.execute(circuits, backend, shots=shots)
# arrange the data from the run
result_t1 = t1_job.result()
keys_0_1=list(result_t1.get_counts(qc_dict['step_0']).keys())# get the key of the excited state '00001'
data=np.zeros(len(qc_dict.keys())) # numpy array for data
sigma_data = np.zeros(len(qc_dict.keys()))
# change unit from ns to microseconds
plot_factor=1
if unit.find('ns')>-1:
plot_factor=1000
punit='$\mu$s'
xvals=time_per_step*np.linspace(0,len(qc_dict.keys()),len(qc_dict.keys()))/plot_factor # calculate the time steps in microseconds
for ii,key in enumerate(qc_dict.keys()):
# get the data in terms of counts for the excited state normalized to the total number of counts
data[ii]=float(result_t1.get_counts(qc_dict[key])[keys_0_1[1]])/shots
sigma_data[ii] = np.sqrt(data[ii]*(1-data[ii]))/np.sqrt(shots)
# fit the data to an exponential
fitT1, fcov = curve_fit(exp_fit_fun, xvals, data, bounds=([-1,2,0], [1., 500, 1]))
ferr = np.sqrt(np.diag(fcov))
plot_coherence(xvals, data, sigma_data, fitT1, exp_fit_fun, punit, 'T$_1$ ', qubit)
print("a: " + str(round(fitT1[0],2)) + u" \u00B1 " + str(round(ferr[0],2)))
print("T1: " + str(round(fitT1[1],2))+ " µs" + u" \u00B1 " + str(round(ferr[1],2)) + ' µs')
print("c: " + str(round(fitT1[2],2)) + u" \u00B1 " + str(round(ferr[2],2)))
|
https://github.com/Hayatto9217/Qiskit8
|
Hayatto9217
|
from qiskit import pulse
with pulse.build(name='my_example') as my_program:
pass
my_program
from qiskit.pulse import DriveChannel
channel = DriveChannel(0)
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend=backend, name='backend_aware') as backend_aware_program:
channel = pulse.drive_channel(0)
print(pulse.num_qubits())
with pulse.build(backend) as delay_5dt:
pulse.delay(5, channel)
#with pulse.build() as sched:
#pulse.play(pulse, channel)
from qiskit.pulse import library
amp = 1
sigma = 10
num_samples = 128
gaus = pulse.library.Gaussian(num_samples, amp, sigma, name="Parametric Gaus")
gaus.draw()
import numpy as np
times = np.arange(num_samples)
gaussian_samples = np.exp(-1/2 *((times - num_samples / 2) ** 2 / sigma**2))
gaus = library.Waveform(gaussian_samples, name="WF Gaus")
gaus.draw()
gaus = library.gaussian(duration=num_samples, amp=amp, sigma=sigma, name="Lib Gaus")
gaus.draw()
with pulse.build() as schedule:
pulse.play(gaus, channel)
schedule.draw()
with pulse.build() as schedule:
pulse.play([0.001*i for i in range(160)], channel)
schedule.draw()
with pulse.build(backend) as schedule:
pulse.set_frequency(4.5e9, channel)
with pulse.build(backend) as schedule:
pulse.shift_phase(np.pi, channel)
from qiskit.pulse import Acquire, AcquireChannel, MemorySlot
with pulse.build(backend) as schedule:
pulse.acquire(1200, pulse.acquire_channel(0), MemorySlot(0))
with pulse.build(backend, name='Left align example') as program:
with pulse.align_left():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
# 上のパルスにはスケジューリングの自由度がないことに注意してください。2 番目の波形は最初の波形の直後に始まります。
with pulse.build(backend, name='example') as program:
gaussian_pulse = library.gaussian(100, 0.5, 20)
with pulse.align_equispaced(2*gaussian_pulse.duration):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='example') as program:
with pulse.align_sequential():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='Offset example') as program:
with pulse.phase.offset(3.14, pulse.drive_channel(0)):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
with pulse.frequency_offset(10e6, pulse.drive_channel(0)):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
program.draw(9)
|
https://github.com/Hayatto9217/Qiskit4
|
Hayatto9217
|
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer
from qiskit.compiler import transpile
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit.quantum_info import process_fidelity
from qiskit.extensions import RXGate, XGate, CXGate
#Operator create
XX = Operator([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])
XX
# Operater propaty
XX.data
input_dim, output_dim = XX.dim
input_dim, output_dim
#InputとOutputの関数でサブシステムの追跡可能
op = Operator(np.random.rand(2 ** 1, 2 ** 2))
print('Input dimensions:', op.input_dims())
print('Output dimesions:', op.output_dims())
#6*6の行列場合
op = Operator(np.random.rand(6, 6))
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
#初期化時に手動でして可能
op = Operator(np.random.rand(2 ** 1, 2 ** 3), input_dims=[8])
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
# Specify system is a qubit and qutrit
op = Operator(np.random.rand(6, 6),
input_dims=[2, 3], output_dims=[2, 3])
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
print('Dimension of input system 0:', op.input_dims([0]))
print('Dimension of iutput system 1:', op.input_dims([1]))
#Pauliオブジェクトからオペレーターに変換
pauliXX = Pauli('XX')
Operator(pauliXX)
#Gateオブジェクトからオペレータに変換
Operator(CXGate())
#parameterized gateオブジェクトからオペレータに変換
Operator(RXGate(np.pi / 2))
#QuantumCircuitオブジェクトからオペレータに変換
circ = QuantumCircuit(10)
circ.h(0)
for j in range(1, 10):
circ.cx(j-1, j)
Operator(circ)
#回路にオペレータ利用
XX = Operator(Pauli('XX'))
circ = QuantumCircuit(2,2)
circ.append(XX, [0,1])
circ.measure([0,1],[0,1])
circ.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
circ =transpile(circ, backend, basis_gates=['u1', 'u2', 'u3', 'cx'])
job =backend.run(circ)
job.result().get_counts(0)
circ2 = QuantumCircuit(2,2)
circ2.append(Pauli('YY'),[0, 1])
circ2.measure([0,1], [0,1])
circ2.draw()
#単一量子ビットオペレータの場合
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.tensor(B)
#順序が逆になるテンソル積
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.expand(B)
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.compose(B)
#順番を逆にする役割
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.compose(B, front= True)
#Compose XZと3-qubit indetity
op = Operator(np.eye(2 ** 3))
XZ = Operator(Pauli('XZ'))
op.compose(XZ, qargs=[0,2])
op.is_unitary()
#Compose YXと前のオペレータ
op = Operator(np.eye(2 ** 4))
YX = Operator(Pauli('YX'))
op.compose(XZ, qargs= [0,2], front=True)
op.is_unitary()
#標準な線形オペレータ(非ユニタリー性)
XX = Operator(Pauli('XX'))
YY = Operator(Pauli('YY'))
ZZ = Operator(Pauli('ZZ'))
op = 0.5 * (XX + YY -6 * ZZ)
op
op.is_unitary()
Operator(np.eye(2)).compose([[0,1],[1,0]])
#Operatorの近似的チェック法
Operator(Pauli('X'))!= Operator(XGate())
Operator(XGate()) != np.exp(1j * 0.5) * Operator(XGate())
op_a = Operator(XGate())
op_b = np.exp(1j * 1) * Operator(XGate())
F = process_fidelity(op_a, op_b)
print('Process fidelity =', F)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/JamesTheZhang/Qiskit2023
|
JamesTheZhang
|
########################################
# ENTER YOUR NAME AND WISC EMAIL HERE: #
########################################
# Name: Rochelle Li
# Email: rli484@wisc.edu
event = "Qiskit Fall Fest"
## Write your code below here. Delete the current information and replace it with your own ##
## Make sure to write your information between the quotation marks!
name = "Rochelle Li"
age = "19"
school = "University of Wisconsin Madison"
## Now press the "Run" button in the toolbar above, or press Shift + Enter while you're active in this cell
## You do not need to write any code in this cell. Simply run this cell to see your information in a sentence. ##
print(f'My name is {name}, I am {age} years old, and I attend {school}.')
## Run this cell to make sure your grader is setup correctly
%set_env QC_GRADE_ONLY=true
%set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com
from qiskit import QuantumCircuit
# Create quantum circuit with 3 qubits and 3 classical bits
# (we'll explain why we need the classical bits later)
qc = QuantumCircuit(3,3)
# return a drawing of the circuit
qc.draw()
## You don't need to write any new code in this cell, just run it
from qiskit import QuantumCircuit
qc = QuantumCircuit(3,3)
# measure all the qubits
qc.measure([0,1,2], [0,1,2])
qc.draw(output="mpl")
from qiskit.providers.aer import AerSimulator
# make a new simulator object
sim = AerSimulator()
job = sim.run(qc) # run the experiment
result = job.result() # get the results
result.get_counts() # interpret the results as a "counts" dictionary
from qiskit import QuantumCircuit
from qiskit.providers.aer import AerSimulator
## Write your code below here ##
qc = QuantumCircuit(4,4)
qc.measure([0,1,2,3], [0,1,2,3])
## Do not modify the code under this line ##
qc.draw()
sim = AerSimulator() # make a new simulator object
job = sim.run(qc) # run the experiment
result = job.result() # get the results
answer1 = result.get_counts()
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex1a
grade_ex1a(answer1)
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
# We start by flipping the first qubit, which is qubit 0, using an X gate
qc.x(0)
# Next we add an H gate on qubit 0, putting this qubit in superposition.
qc.h(0)
# Finally we add a CX (CNOT) gate on qubit 0 and qubit 1
# This entangles the two qubits together
qc.cx(0, 1)
qc.draw(output="mpl")
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 2)
## Write your code below here ##
qc.h(0)
qc.cx(0,1)
## Do not modify the code under this line ##
answer2 = qc
qc.draw(output="mpl")
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex1b
grade_ex1b(answer2)
|
https://github.com/JamesTheZhang/Qiskit2023
|
JamesTheZhang
|
########################################
# ENTER YOUR NAME AND WISC EMAIL HERE: #
########################################
# Name: Rochelle Li
# Email: rli484@wisc.edu
## Run this cell to make sure your grader is setup correctly
%set_env QC_GRADE_ONLY=true
%set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, 3)
## Write your code below this line ##
qc.h(0)
qc.h(2)
qc.cx(0,1)
## Do not change the code below here ##
answer1 = qc
qc.draw()
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2a
grade_ex2a(answer1)
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, 3)
qc.barrier(0, 1, 2)
## Write your code below this line ##
qc.cx(1,2)
qc.x(2)
qc.cx(2,0)
qc.x(2)
## Do not change the code below this line ##
answer2 = qc
qc.draw()
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2b
grade_ex2b(answer2)
answer3: bool
## Quiz: evaluate the results and decide if the following statement is True or False
q0 = 1
q1 = 0
q2 = 1
## Based on this, is it TRUE or FALSE that the Guard on the left is a liar?
## Assign your answer, either True or False, to answer3 below
answer3 = True
from qc_grader.challenges.fall_fest23 import grade_ex2c
grade_ex2c(answer3)
## Quiz: Fill in the correct numbers to make the following statement true:
## The treasure is on the right, and the Guard on the left is the liar
q0 = 0
q1 = 1
q2 = 1
## HINT - Remember that Qiskit uses little-endian ordering
answer4 = [q0, q1, q2]
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2d
grade_ex2d(answer4)
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
## in the code below, fill in the missing gates. Run the cell to see a drawing of the current circuit ##
qc.h(0)
qc.h(2)
qc.cx(0,1)
qc.barrier(0, 1, 2)
qc.cx(2, 1)
qc.x(2)
qc.cx(2, 0)
qc.x(2)
qc.barrier(0, 1, 2)
qc.swap(0,1)
qc.x(0)
qc.x(1)
qc.cx(2,1)
qc.x(2)
qc.cx(2,0)
qc.x(2)
## Do not change any of the code below this line ##
answer5 = qc
qc.draw(output="mpl")
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2e
grade_ex2e(answer5)
from qiskit import QuantumCircuit, Aer, transpile
from qiskit.visualization import plot_histogram
## This is the full version of the circuit. Run it to see the results ##
quantCirc = QuantumCircuit(3)
quantCirc.h(0), quantCirc.h(2), quantCirc.cx(0, 1), quantCirc.barrier(0, 1, 2), quantCirc.cx(2, 1), quantCirc.x(2), quantCirc.cx(2, 0), quantCirc.x(2)
quantCirc.barrier(0, 1, 2), quantCirc.swap(0, 1), quantCirc.x(1), quantCirc.cx(2, 1), quantCirc.x(0), quantCirc.x(2), quantCirc.cx(2, 0), quantCirc.x(2)
# Execute the circuit and draw the histogram
measured_qc = quantCirc.measure_all(inplace=False)
backend = Aer.get_backend('qasm_simulator') # the device to run on
result = backend.run(transpile(measured_qc, backend), shots=1000).result()
counts = result.get_counts(measured_qc)
plot_histogram(counts)
from qiskit.primitives import Sampler
from qiskit.visualization import plot_distribution
sampler = Sampler()
result = sampler.run(measured_qc, shots=1000).result()
probs = result.quasi_dists[0].binary_probabilities()
plot_distribution(probs)
|
https://github.com/JamesTheZhang/Qiskit2023
|
JamesTheZhang
|
########################################
# ENTER YOUR NAME AND WISC EMAIL HERE: #
########################################
# Name: Rochelle Li
# Email: rli484@wisc.edu
## Run this cell to make sure your grader is setup correctly
%set_env QC_GRADE_ONLY=true
%set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com
from qiskit import QuantumCircuit
from qiskit.circuit import QuantumRegister, ClassicalRegister
qr = QuantumRegister(1)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
# unpack the qubit and classical bits from the registers
(q0,) = qr
b0, b1 = cr
# apply Hadamard
qc.h(q0)
# measure
qc.measure(q0, b0)
# begin if test block. the contents of the block are executed if b0 == 1
with qc.if_test((b0, 1)):
# if the condition is satisfied (b0 == 1), then flip the bit back to 0
qc.x(q0)
# finally, measure q0 again
qc.measure(q0, b1)
qc.draw(output="mpl", idle_wires=False)
from qiskit_aer import AerSimulator
# initialize the simulator
backend_sim = AerSimulator()
# run the circuit
reset_sim_job = backend_sim.run(qc)
# get the results
reset_sim_result = reset_sim_job.result()
# retrieve the bitstring counts
reset_sim_counts = reset_sim_result.get_counts()
print(f"Counts: {reset_sim_counts}")
from qiskit.visualization import *
# plot histogram
plot_histogram(reset_sim_counts)
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
q0, q1 = qr
b0, b1 = cr
qc.h(q0)
qc.measure(q0, b0)
## Write your code below this line ##
with qc.if_test((b0, 0)) as else_:
qc.x(1)
with else_:
qc.h(1)
## Do not change the code below this line ##
qc.measure(q1, b1)
qc.draw(output="mpl", idle_wires=False)
backend_sim = AerSimulator()
job_1 = backend_sim.run(qc)
result_1 = job_1.result()
counts_1 = result_1.get_counts()
print(f"Counts: {counts_1}")
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3b
grade_ex3b(qc)
controls = QuantumRegister(2, name="control")
target = QuantumRegister(1, name="target")
mid_measure = ClassicalRegister(2, name="mid")
final_measure = ClassicalRegister(1, name="final")
base = QuantumCircuit(controls, target, mid_measure, final_measure)
def trial(
circuit: QuantumCircuit,
target: QuantumRegister,
controls: QuantumRegister,
measures: ClassicalRegister,
):
"""Probabilistically perform Rx(theta) on the target, where cos(theta) = 3/5."""
## Write your code below this line, making sure it's indented to where this comment begins from ##
c0,c1 = controls
(t0,) = target
b0, b1 = mid_measure
circuit.h(c0)
circuit.h(c1)
circuit.h(t0)
circuit.ccx(c0, c1, t0)
circuit.s(t0)
circuit.ccx(c0, c1, t0)
circuit.h(c0)
circuit.h(c1)
circuit.h(t0)
circuit.measure(c0, b0)
circuit.measure(c1, b1)
## Do not change the code below this line ##
qc = base.copy_empty_like()
trial(qc, target, controls, mid_measure)
qc.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3c
grade_ex3c(qc)
def reset_controls(
circuit: QuantumCircuit, controls: QuantumRegister, measures: ClassicalRegister
):
"""Reset the control qubits if they are in |1>."""
## Write your code below this line, making sure it's indented to where this comment begins from ##
c0, c1 = controls
r0, r1 = measures
# circuit.h(c0)
# circuit.h(c1)
# circuit.measure(c0, r0)
# circuit.measure(c1, r1)
with circuit.if_test((r0, 1)):
circuit.x(c0)
with circuit.if_test((r1, 1)):
circuit.x(c1)
## Do not change the code below this line ##
qc = base.copy_empty_like()
trial(qc, target, controls, mid_measure)
reset_controls(qc, controls, mid_measure)
qc.measure(controls, mid_measure)
qc.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3d
grade_ex3d(qc)
# Set the maximum number of trials
max_trials = 2
# Create a clean circuit with the same structure (bits, registers, etc) as the initial base we set up.
circuit = base.copy_empty_like()
# The first trial does not need to reset its inputs, since the controls are guaranteed to start in the |0> state.
trial(circuit, target, controls, mid_measure)
# Manually add the rest of the trials. In the future, we will be able to use a dynamic `while` loop to do this, but for now,
# we statically add each loop iteration with a manual condition check on each one.
# This involves more classical synchronizations than the while loop, but will suffice for now.
for _ in range(max_trials - 1):
reset_controls(circuit, controls, mid_measure)
with circuit.if_test((mid_measure, 0b00)) as else_:
# This is the success path, but Qiskit can't directly
# represent a negative condition yet, so we have an
# empty `true` block in order to use the `else` branch.
pass
with else_:
## Write your code below this line, making sure it's indented to where this comment begins from ##
# (t0,) = target
circuit.x(2)
trial(circuit, target, controls, mid_measure)
## Do not change the code below this line ##
# We need to measure the control qubits again to ensure we get their final results; this is a hardware limitation.
circuit.measure(controls, mid_measure)
# Finally, let's measure our target, to check that we're getting the rotation we desired.
circuit.measure(target, final_measure)
circuit.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3e
grade_ex3e(circuit)
sim = AerSimulator()
job = sim.run(circuit, shots=1000)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
|
https://github.com/JamesTheZhang/Qiskit2023
|
JamesTheZhang
|
from qiskit.circuit import ClassicalRegister, QuantumRegister, QuantumCircuit, Parameter
theta = Parameter('θ')
qr = QuantumRegister(1, 'q')
qc = QuantumCircuit(qr)
qc.ry(theta, 0)
qc.draw('mpl')
tele_qc = qc.copy()
bell = QuantumRegister(2, 'Bell')
alice = ClassicalRegister(2, 'Alice')
bob = ClassicalRegister(1, 'Bob')
tele_qc.add_register(bell, alice, bob)
tele_qc.draw('mpl')
# create Bell state with other two qubits
tele_qc.barrier()
tele_qc.h(1)
tele_qc.cx(1, 2)
tele_qc.barrier()
tele_qc.draw('mpl')
# alice operates on her qubits
tele_qc.cx(0, 1)
tele_qc.h(0)
tele_qc.barrier()
tele_qc.draw('mpl')
tele_qc.measure([qr[0], bell[0]], alice)
tele_qc.draw('mpl')
full_qc = tele_qc.copy()
#### ANSWER
# Bob's conditional operations
with full_qc.if_test((alice[1], 1)):
full_qc.x(bell[1])
with full_qc.if_test((alice[0], 1)):
full_qc.z(bell[1])
#### END ANSWER
full_qc.draw('mpl')
full_qc.barrier()
full_qc.measure(bell[1], bob)
full_qc.draw('mpl')
from qiskit_aer.primitives import Sampler
import numpy as np
angle = 5*np.pi/7
sampler = Sampler()
qc.measure_all()
job_static = sampler.run(qc.bind_parameters({theta: angle}))
job_dynamic = sampler.run(full_qc.bind_parameters({theta: angle}))
print(f"Original Dists: {job_static.result().quasi_dists[0].binary_probabilities()}")
print(f"Teleported Dists: {job_dynamic.result().quasi_dists[0].binary_probabilities()}")
from qiskit.result import marginal_counts
from qiskit.visualization import *
# FILL IN CODE HERE
# noticed that the ratio between the teleported states with bob = 0 and bob = 1 is roughly what we expect for the original distribution, so we extracted it and passed in as a dictionary to marginalize counts
bob0 = job_dynamic.result().quasi_dists[0][0] + job_dynamic.result().quasi_dists[0][1] + job_dynamic.result().quasi_dists[0][2] + job_dynamic.result().quasi_dists[0][3]
bob1 = job_dynamic.result().quasi_dists[0][4] + job_dynamic.result().quasi_dists[0][5] + job_dynamic.result().quasi_dists[0][6] + job_dynamic.result().quasi_dists[0][7]
dictionary = {'0':bob0, '1':bob1}
tele_counts = marginal_counts(dictionary)
#### ANSWER
#### END ANSWER
legend = ['Original State', 'Teleported State']
plot_histogram([job_static.result().quasi_dists[0].binary_probabilities(), tele_counts], legend=legend)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/lkcoredo/qiskitWorkshop
|
lkcoredo
|
import qiskit
qiskit.__qiskit_version__
from qiskit import IBMQ
IBMQ.save_account('86ae6d9e149ed5f78869fe4c6ba5b9b42419053fed9e1c0f731d63d6c7b416c9812292cc69fd2cf108e4096a6c3e20f5d7366d48de2ac650fc599d86acaa526c')
IBMQ.load_account()
from qiskit import *
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit = QuantumCircuit(qr, cr)
circuit.draw()
circuit.h(qr[0])
circuit.draw(output= 'mpl')
circuit.cx(qr[0], qr[1])
circuit.draw(output= 'mpl')
circuit.measure(qr, cr)
circuit.draw(output= 'mpl')
simulator = Aer.get_backend("qasm_simulator")
execute(circuit, backend = simulator)
result = execute(circuit, backend = simulator).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider.backends()
qcomp = provider.get_backend('ibmq_santiago')
job = execute(circuit, backend=qcomp)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
plot_histogram(result.get_count(circuit))
|
https://github.com/lkcoredo/qiskitWorkshop
|
lkcoredo
|
from qiskit import *
from qiskit.tools.visualization import plot_bloch_multivector
circuit = QuantumCircuit(1,1)
circuit.x(0)
simulator = Aer.get_backend('statevector_simulator')
execute(circuit, backend = simulator).result()
circuit.draw(output='mpl')
circuit.measure([0], [0])
backend = Aer.get_backend('qasm_simulator')
execute(circuit, backend = backend, shots = 1024).result()
result = execute(circuit, backend = simulator).result()
counts = result.get_counts()
statevector = result.get_statevector()
print(statevector)
%matplotlib inline
circuit.draw(output='mpl')
plot_bloch_multivector(statevector)
circuit.measure([0], [0])
backend = Aer.get_backend('qasm_simulator')
execute(circuit, backend = backend, shots = 1024).result()
counts = result.get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
circuit.draw(output='mpl')
circuit.draw(output='mpl')
|
https://github.com/lkcoredo/qiskitWorkshop
|
lkcoredo
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, assemble, transpile
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.providers.ibmq import least_busy
# import basic plot tools
from qiskit.visualization import plot_histogram
n = 2
grover_circuit = QuantumCircuit(n)
def initialize_s(qc, qubits):
"""Apply a H-gate to 'qubits' in qc"""
for q in qubits:
qc.h(q)
return qc
def diffuser(nqubits):
qc = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qc.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qc.x(qubit)
# Do multi-controlled-Z gate
qc.h(nqubits-1)
qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qc.h(nqubits-1)
# Apply transformation |11..1> -> |00..0>
for qubit in range(nqubits):
qc.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qc.h(qubit)
# We will return the diffuser as a gate
U_s = qc.to_gate()
U_s.name = "U$_s$"
return U_s
grover_circuit = initialize_s(grover_circuit, [0,1])
grover_circuit.draw(output="mpl")
grover_circuit.cz(0,1) # Oracle
grover_circuit.draw(output="mpl")
# Diffusion operator (U_s)
grover_circuit.append(diffuser(n),[0,1])
grover_circuit.draw(output="mpl")
sim = Aer.get_backend('aer_simulator')
# we need to make a copy of the circuit with the 'save_statevector'
# instruction to run on the Aer simulator
grover_circuit_sim = grover_circuit.copy()
grover_circuit_sim.save_statevector()
qobj = assemble(grover_circuit_sim)
result = sim.run(qobj).result()
statevec = result.get_statevector()
from qiskit_textbook.tools import vector2latex
vector2latex(statevec, pretext="|\\psi\\rangle =")
grover_circuit.measure_all()
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(grover_circuit)
result = aer_sim.run(qobj).result()
counts = result.get_counts()
plot_histogram(counts)
nqubits = 4
qc = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qc.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qc.x(qubit)
qc.barrier()
# Do multi-controlled-Z gate
qc.h(nqubits-1)
qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qc.h(nqubits-1)
qc.barrier()
# Apply transformation |11..1> -> |00..0>
for qubit in range(nqubits):
qc.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qc.h(qubit)
qc.draw(output="mpl")
from qiskit.circuit import classical_function, Int1
# define a classical function f(x): this returns 1 for the solutions of the problem
# in this case, the solutions are 1010 and 1100
@classical_function
def f(x1: Int1, x2: Int1, x3: Int1, x4: Int1) -> Int1:
return (x1 and not x2 and x3 and not x4) or (x1 and x2 and not x3 and not x4)
nqubits = 4
Uf = f.synth() # turn it into a circuit
oracle = QuantumCircuit(nqubits+1)
oracle.compose(Uf, inplace=True)
oracle.draw(output="mpl")
# We will return the diffuser as a gate
#U_f = oracle.to_gate()
# U_f.name = "U$_f$"
# return U_f
|
https://github.com/sjana01/QiskitNotebooks
|
sjana01
|
import sys
sys.path.append('../')
from circuits import sampleCircuitA, sampleCircuitB1, sampleCircuitB2,\
sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE,\
sampleCircuitF
from entanglement import Ent
import warnings
warnings.filterwarnings('ignore')
labels = [
'Circuit A', 'Circuit B1', 'Circuit B2', 'Circuit B3',
'Circuit C', 'Circuit D', 'Circuit E', 'Circuit F'
]
samplers = [
sampleCircuitA,
sampleCircuitB1,
sampleCircuitB2,
sampleCircuitB3,
sampleCircuitC,
sampleCircuitD,
sampleCircuitE,
sampleCircuitF
]
q = 4
for layer in range(1, 4):
print(f'qubtis: {q}')
print('-' * 25)
for (label, sampler) in zip(labels, samplers):
expr = Ent(sampler, layer=layer, epoch=3000)
print(f'{label}(layer={layer}): {expr}')
print()
|
https://github.com/sjana01/QiskitNotebooks
|
sjana01
|
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Set a seed for the random number generator so we get the same random numbers each time
np.random.seed(42)
# Create fake x-data
x = np.arange(10)
# Create fake y-data
a = 4.5
b = 0.5
c = 20
y = a * np.exp(-b * x) + c
y = y + np.random.normal(loc=0, scale=0.3, size=len(x)) # Add noise
def plot_sc(x,y):
fig, ax = plt.subplots()
ax.scatter(x, y, c="green")
ax.set_xlabel("X")
ax.set_ylabel("y")
#ax.legend()
plt.show()
plot_sc(x,y)
# Set a seed for the random number generator so we get the same random numbers each time
np.random.seed(6354)
# Create fake x-data
x1 = np.arange(10)
# Create fake y-data
a = 4.5
b = 0.5
c = 0 #set c=0
y1 = a * np.exp(b * x)
y1 = y1 + np.random.normal(loc=0, scale=10, size=len(x)) # Add noise
plot_sc(x1,y1)
# Fit a polynomial of degree 1 (a linear function) to the data
p = np.polyfit(x1, np.log(y1), 1)
# Convert the polynomial back into an exponential
a = np.exp(p[1])
b = p[0]
x1_fit = np.linspace(np.min(x1), np.max(x1), 100)
y1_fit = a*np.exp(b * x1_fit)
ax = plt.axes()
ax.scatter(x1, y1, label='Raw data')
ax.plot(x1_fit, y1_fit, 'k', label='Fitted curve')
ax.set_title('Using polyfit() to fit an exponential function')
ax.set_ylabel('y')
ax.set_ylim(0, 500)
ax.set_xlabel('X')
ax.legend()
# Fit a weighted polynomial of degree 1 (a linear function) to the data
p = np.polyfit(x1, np.log(y1), 1, w=np.sqrt(y1))
# Convert the polynomial back into an exponential
a = np.exp(p[1])
b = p[0]
x1_fit_wt = np.linspace(np.min(x1), np.max(x1), 100)
y1_fit_wt = a * np.exp(b * x1_fit_wt)
# Plot
ax = plt.axes()
ax.scatter(x1, y1, label='Raw data')
ax.plot(x1_fit, y1_fit, 'k', label='Fitted curve, unweighted')
ax.plot(x1_fit_wt, y1_fit_wt, 'k--', label='Fitted curve, weighted')
ax.set_title('Using polyfit() to fit an exponential function')
ax.set_ylabel('y')
ax.set_ylim(0, 500)
ax.set_xlabel('X')
ax.legend()
# Set a seed for the random number generator so we get the same random numbers each time
np.random.seed(6354)
# Create fake x-data
x2 = np.arange(10)
# Create fake y-data
a = 4.5
b = 0.5
c = 50
y2 = a * np.exp(b * x) + c
y2 = y2 + np.random.normal(loc=0, scale=10, size=len(x)) # Add noise
plot_sc(x2,y2)
# Have an initial guess as to what the values of the parameters are
a0 = 5
b0 = 0.6
c0 = 40
from scipy.optimize import curve_fit
# Fit the function a * np.exp(b * t) + c to x and y
popt, pcov = curve_fit(lambda t, a, b, c: a * np.exp(b * t) + c, x2, y2, p0=(a0,b0,c0), maxfev=5000)
# Create the fitted curve
x2_fit = np.linspace(np.min(x2), np.max(x2), 100)
y2_fit = popt[0] * np.exp(popt[1] * x2_fit) + popt[2]
ax = plt.axes()
ax.scatter(x2, y2, label='Raw data')
ax.plot(x2_fit, y2_fit, 'k', label='Fitted curve')
ax.set_title('Using curve_fit() to fit an exponential function')
ax.set_ylabel('y')
ax.set_ylim(0, 500)
ax.set_xlabel('X')
ax.legend()
print(popt)
# Set a seed for the random number generator so we get the same random numbers each time
np.random.seed(64)
# Create fake x-data
x3 = np.arange(10)
# Create fake y-data
a = 4.5
b = - 0.5
c = 10
y3 = a * np.exp(b * x) + c
y3 = y3 + np.random.normal(loc=0, scale=0.1, size=len(x3)) # Add noise
plot_sc(x3,y3)
# Have an initial guess as to what the values of the parameters are
a0 = 5
b0 = - 0.6
c0 = 12
# Fit the function a * np.exp(b * t) + c to x and y
popt, pcov = curve_fit(lambda t, a, b, c: a * np.exp(b * t) + c, x3, y3, p0=(a0,b0,c0), maxfev=5000)
# Create the fitted curve
x3_fit = np.linspace(np.min(x3), np.max(x3), 100)
y3_fit = popt[0] * np.exp(popt[1] * x3_fit) + popt[2]
ax = plt.axes()
ax.scatter(x3, y3, label='Raw data')
ax.plot(x3_fit, y3_fit, 'k', label='Fitted curve')
ax.set_title('Fitting an negative exponential function')
ax.set_ylabel('y')
ax.set_ylim(9.5, 15.5)
ax.set_xlabel('X')
ax.legend()
popt
def func(x,a,b,c):
return a * np.exp(b * x) + c
from lmfit import Model
model = Model(func)
model.independent_vars
model.param_names
params = model.make_params(a=5.0, b=-0.6, c=12)
result = model.fit(y3, params, x=x3)
print(result.fit_report())
y4 = np.array([146., 94., 79.,62., 41.])
x4 = np.array([375, 470, 528, 625,880])
def fun(x, alpha1, alpha2, A, B):
return A*x**(-alpha1)
uncertainty = abs(0.16 + np.random.normal(size=x.size, scale=0.05))
uncertainty
from lmfit import minimize, Parameters
def residual(params, x, data):
alpha1 = params['alpha1']
A = params['A']
model = A*x**(-alpha1)
return (data-model)
params = Parameters()
params.add('alpha1', value=1.0, min=0.8, max=10.0)
params.add('A', value=100.0, min=100.0, max=1.0e10)
out = minimize(residual, params, args=(x4, y4))
out.params
x4_fit = np.linspace(np.min(x4), np.max(x4), 100)
y4_fit = 15423.092*x4_fit**(-1.40000000) + 1.0000e+29*x4_fit**(-13.0000000)
ax = plt.axes()
ax.scatter(x4, y4, label='Raw data')
ax.plot(x4_fit, y4_fit, 'k', label='Fitted curve')
ax.set_title('Fitting an power curve')
ax.set_ylabel('y')
ax.set_xlabel('X')
ax.legend()
y4_B = 1.0000e+10*x4_fit**(-10.0000000)
ax = plt.axes()
ax.scatter(x4, y4, label='Raw data')
ax.plot(x4_fit, y4_fit, 'k', label='Fitted curve')
ax.plot(x4_fit, y4_B, 'k--', label='Fit 2nd Component')
ax.set_title('Fitting an power curve')
ax.set_ylabel('y')
ax.set_xlabel('X')
ax.legend()
y4 = np.array([146., 94., 79.,62., 41.])
x4 = np.array([375., 470., 528., 625.,880.])
from scipy.optimize import differential_evolution
def func(parameters, *data):
#we have 3 parameters which will be passed as parameters and
#"experimental" x,y which will be passed as data
a1,a2,A1,A2 = parameters
x,y = data
result = 0
for i in range(len(x)):
result += (A1*x[i]**(-a1) + A2*x[i]**(-a2) - y[i])**2
return result**0.5
bounds = [(0.8, 1.4), (1.5,15.0), (1000.0, 1.0e10), (1000.0, 1.0e30)]
#packing "experimental" data into args
args = (x4,y4)
result = differential_evolution(func, bounds, args=args)
result.x
def func1(parameters, *data):
#we have 3 parameters which will be passed as parameters and
#"experimental" x,y which will be passed as data
a1,A1= parameters
x,y = data
result = 0
for i in range(len(x)):
result += (A1*x[i]**(-a1) -y4[i])**2
return result
bounds = [(0.5, 10), (100.0, 1.0e10)]
#packing "experimental" data into args
args = (x4,y4)
result = differential_evolution(func1, bounds, args=args)
result.x
alpha1 = [optimizer(bounds)[0] for i in range(20)]
alpha2 = [optimizer(bounds)[1] for i in range(20)]
min(alpha2), max(alpha2)
x4_fit = np.linspace(np.min(x4), np.max(x4), 100)
alpha1 = result.x[0]
alpha2 = result.x[1]
A = result.x[2]
B = result.x[3]
y4_A = A*x4_fit**(-alpha1)
y4_B = B*x4_fit**(-alpha2)
ax = plt.axes()
# ax.scatter(x4, y4, label='Raw data')
ax.plot(x4_fit, y4_A, 'k', label='Fit curve 1st Component')
ax.plot(x4_fit, y4_B, 'k--', label='Fit curve 2nd Component')
ax.set_title('Fitting an power curve')
ax.set_ylabel('y')
ax.set_xlabel('X')
ax.legend()
y4_fit = result.x[1]*x4_fit**(-result.x[0])
ax = plt.axes()
ax.scatter(x4, y4, label='Raw data')
ax.plot(x4_fit, y4_fit, 'k', label='Fit curve 1st Component')
#ax.plot(x4_fit, y4_B, 'k--', label='Fit curve 2nd Component')
ax.set_title('Fitting an power curve')
ax.set_ylabel('y')
ax.set_xlabel('X')
ax.legend()
|
https://github.com/sjana01/QiskitNotebooks
|
sjana01
|
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumRegister, ClassicalRegister, execute
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import plot_state_city
def real_map(value, leftMin, leftMax, rightMin, rightMax):
# Maps one range to another
# Figure out how 'wide' each range is
leftSpan = leftMax - leftMin
rightSpan = rightMax - rightMin
# Convert the left range into a 0-1 range (float)
valueScaled = float(value - leftMin) / float(leftSpan)
# Convert the 0-1 range into a value in the right range.
return rightMin + (valueScaled * rightSpan)
def QRandNum(lb, ub):
# Quantum Random Number generator
# Select the number of qubits
qubits = int(np.log2(ub-lb))
q = QuantumRegister(qubits, 'q')
circ = QuantumCircuit(q)
c0 = ClassicalRegister(2, 'c0')
circ.add_register(c0)
for i in range(qubits):
circ.h(q[i])
for i in range(qubits):
circ.measure(q[i], c0)
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
#print(job.status())
result = job.result()
output = np.asarray(result.get_statevector(circ))
num = 0
for i in range(len(output)):
if output[i] != 0:
num = i
y = real_map(num + 1 , 1, 2**qubits, lb, ub)
return y
x = []
for i in range(100):
x.append(QRandNum(1, 100))
plt.scatter(range(0, 100), x)
from qiskit.extensions import UnitaryGate
from qiskit.circuit.library import GroverOperator
from qiskit.visualization import plot_histogram
def grover_search(marked_elt: str):
index = int(marked_elt, 2)
arr = np.identity(2**(len(marked_elt)))
arr[index, index] = -1
unitary_gate = UnitaryGate(arr)
oracle = QuantumCircuit(5)
oracle.compose(unitary_gate, qubits=range(5), inplace=True)
#oracle.draw(output='mpl')
grover_op = GroverOperator(oracle)
init = QuantumCircuit(5, 5)
init.h(range(5))
qc = init.compose(grover_op)
qc.compose(grover_op, inplace=True)
qc.compose(grover_op, inplace=True)
qc.compose(grover_op, inplace=True)
qc.measure(range(5),range(5))
#qc.draw(output='mpl')
sim = Aer.get_backend('aer_simulator')
t_qc = transpile(qc, sim)
counts = sim.run(t_qc).result().get_counts()
return counts
counts = grover_search('01101')
plot_histogram(counts)
def grover_circuit(marked_elts: list):
n = len(marked_elts[0])
indices = [int(marked_elt, 2) for marked_elt in marked_elts]
arr = np.identity(2**n)
for index in indices:
arr[index, index] = -1
unitary_gate = UnitaryGate(arr)
oracle = QuantumCircuit(n)
oracle.compose(unitary_gate, qubits=range(n), inplace=True)
# grover operator
grover_op = GroverOperator(oracle)
init = QuantumCircuit(n, n)
init.h(range(n))
r = int(np.pi/4*np.sqrt(2**n/len(indices)))
print(f'{n} qubits, basis states {indices} marked, {r} rounds')
qc = init.compose(grover_op)
for _ in range(1, r):
qc.compose(grover_op, inplace=True)
qc.measure(range(n),range(n))
return qc
q_circuit = grover_circuit(['001101', '101010'])
q_circuit.draw('mpl')
sim = Aer.get_backend('aer_simulator')
t_qc = transpile(q_circuit, sim)
counts = sim.run(t_qc).result().get_counts()
plot_histogram(counts)
# Implementation both with constant and balanced oracles
def build_oracle(size, type='constant'):
''' size (int): n for an n-bit the function
type (str): "constant" or "balanced". default value = constant
output: an oracle
'''
oracle = QuantumCircuit(size+1)
if type == 'constant':
r = np.random.randint(2)
if r == 1:
oracle.x(size)
elif type == 'balanced':
r = np.random.randint(2**size)
b_str = (bin(r)[2:]).zfill(size)
# place X gates determined by b_str
for qubit in range(size):
if b_str[qubit] == '1':
oracle.x(qubit)
oracle.barrier()
# controlled not gate
for qubit in range(size):
oracle.cx(qubit, size)
oracle.barrier()
# place X gates again
for qubit in range(size):
if b_str[qubit] == '1':
oracle.x(qubit)
else:
print("Give valid inputs")
return None
return oracle
balanced_oracle = build_oracle(5, 'balanced')
balanced_oracle.draw('mpl')
constant_oracle = build_oracle(5)
constant_oracle.draw('mpl')
# Let's built the dj circuit now
def build_dj_circuit(size, oracle):
''' size: size of the oracle
oracle: oracle representing the given function
'''
qc = QuantumCircuit(size+1, size)
# Apply H gates to the input qubits
for qubit in range(size):
qc.h(qubit)
# Initialize the output qubit in the |-> state
qc.x(size)
qc.h(size)
# Add oracle
qc = qc.compose(oracle)
# Add the H gate on the input qubits again
for qubit in range(size):
qc.h(qubit)
# Measure
for qubit in range(size):
qc.measure(qubit, qubit)
return qc
dj_circuit = build_dj_circuit(5, balanced_oracle)
dj_circuit.draw('mpl')
# Output using the Aer simulator
sim = Aer.get_backend('aer_simulator')
t_qc = transpile(dj_circuit, sim)
counts = sim.run(dj_circuit).result().get_counts()
#the output should be anything other than '00000'
plot_histogram(counts)
# with the constant oracle the output should always be '00000'
dj_circuit_const = build_dj_circuit(5, constant_oracle)
#dj_circuit_const.draw('mpl')
sim = Aer.get_backend('aer_simulator')
t_qc = transpile(dj_circuit_const, sim)
counts = sim.run(dj_circuit_const).result().get_counts()
plot_histogram(counts)
|
https://github.com/sjana01/QiskitNotebooks
|
sjana01
|
import numpy as np
ket0 = np.array([1,0])
ket1 = np.array([0,1])
ket0/2 + ket1/2
M1 = np.array([ [1, 1], [0, 0] ])
M2 = np.array([ [1, 1], [1, 0] ])
M1/2 + M2/2
print("product of M1 with ket0: ", np.matmul(M1,ket0))
print("product of M1 and M2: \n",np.matmul(M1,M2))
from qiskit.quantum_info import Statevector
u = Statevector([1/np.sqrt(2), 1/np.sqrt(2)])
v = Statevector([(1+2.j)/3, -2/3])
display(u.draw('latex'))
display(u.draw('text'))
display(v.draw('latex'))
w = Statevector([1/3,2/3])
display(v.is_valid())
display(w.is_valid())
v = Statevector([(1+2.j)/3, -2/3])
v.measure()
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt
stat = v.sample_counts(10000)
display(stat)
plot_histogram(stat)
from qiskit.quantum_info import Operator
t = np.sqrt(2)
X = Operator([[0,1],[1,0]])
Y = Operator([[0,-1.j],[1.j,0]])
Z = Operator([[1,0],[0,-1]])
H = Operator([[1/t, 1/t],[1/t, -1/t]])
S = Operator([[1,0],[0,1.j]])
T = Operator([[1,0],[0,(1+1.j)/t]])
v = Statevector([1,0])
display(v.evolve(X).draw('latex'))
display(v.evolve(Y).draw('latex'))
display(v.evolve(H).draw('latex'))
display(v.evolve(S).draw('latex'))
from qiskit import QuantumCircuit
# initiate an instance of the class
qc = QuantumCircuit(1) ## A QuantumCircuit with 1 qubits
qc.h(0)
qc.t(0)
qc.h(0)
qc.t(0)
qc.z(0)
qc.draw()
ket0 = Statevector([1,0])
v = ket0.evolve(qc)
v.draw('latex')
stat = v.sample_counts(5000)
plot_histogram(stat)
ket0 = Statevector([1,0])
ket1 = Statevector([0,1])
ket01 = ket0.tensor(ket1)
display(ket01.draw('latex'))
# Another quick way to define the common states
zero = Statevector.from_label('0')
one = Statevector.from_label('1')
plus = Statevector.from_label('+')
minus = Statevector.from_label('-')
i_state = 1/np.sqrt(2) * (zero + 1.j * one)
psi = minus.tensor(i_state)
psi.draw('latex')
X.tensor(Z)
psi_1 = psi.evolve(T^X)
display(psi_1.draw('latex'))
CNOT = Operator([ [1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0] ])
psi_2 = psi.evolve(CNOT)
display(psi_2.draw('latex'))
# SOLUTION
phi_plus = plus.tensor(zero).evolve(CNOT)
phi_minus = minus.tensor(zero).evolve(CNOT)
psi_plus = plus.tensor(one).evolve(CNOT)
psi_minus = minus.tensor(one).evolve(CNOT)
display(phi_plus.draw('latex'))
display(phi_minus.draw('latex'))
display(psi_plus.draw('latex'))
display(psi_minus.draw('latex'))
W = Statevector([0,1,1,0,1,0,0,0]/np.sqrt(3))
display(W.draw('latex'))
result, new_statevector = W.measure([0])
print(f"Measured: {result} \n New Statevector:")
display(new_statevector.draw('latex'))
result, new_statevector = W.measure([1])
print(f"Measured: {result} \n New Statevector:")
display(new_statevector.draw('latex'))
I = Operator([[1,0],[0,1]])
W1 = W.evolve(I^I^H)
display(W1.draw('latex'))
result, new_statevector = W1.measure([0])
print(f"Measured: {result} \n New Statevector:")
display(new_statevector.draw('latex'))
W1.probabilities([0])
import qiskit.tools.jupyter
%qiskit_version_table
from qiskit import QuantumCircuit
qc = QuantumCircuit(1)
qc.h(0)
qc.s(0)
qc.h(0)
qc.t(0)
qc.draw()
from qiskit import QuantumRegister
u = QuantumRegister(1, "u")
qc = QuantumCircuit(u)
qc.y(0)
qc.s(0)
qc.h(0)
qc.t(0)
qc.x(0)
qc.draw()
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
X = QuantumRegister(1, "x")
Y = QuantumRegister(1, "y")
A = ClassicalRegister(1, "a")
B = ClassicalRegister(1, "b")
qc = QuantumCircuit(Y,X,B,A)
qc.h(Y)
qc.cx(Y,X)
qc.measure(Y,B)
qc.measure(X,A)
qc.draw()
from qiskit import transpile
from qiskit_aer import AerSimulator
simulator = AerSimulator()
qc_simulator = simulator.run(transpile(qc,simulator), shots=1000)
statistics = qc_simulator.result().get_counts()
plot_histogram(statistics)
# Circuit
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.measure_all()
from qiskit import Aer
# 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)
memory
Aer.backends()
|
https://github.com/sjana01/QiskitNotebooks
|
sjana01
|
import numpy as np
# importing Qiskit
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram, plot_bloch_multivector
# 3 qubit example
qc = QuantumCircuit(3)
qc.h(2)
qc.cp(np.pi/2, 1, 2) # CROT from qubit 1 to qubit 2
qc.cp(np.pi/4, 0, 2) # CROT from qubit 0 to qubit 2
qc.h(1)
qc.cp(np.pi/2, 0, 1) # CROT from qubit 0 to qubit 1
qc.h(0)
qc.swap(0, 2) #swaps qubit 0 and 2
qc.draw('mpl')
# General QFT function
def qft_rot(circuit, n):
'''
circuit: given quantum circuit
n: number of qubit
'''
if n==0:
return circuit
n -= 1 # we want the qubit indexing to go from 0 to n-2
circuit.h(n)
for qubit in range(n):
circuit.cp(np.pi/2**(n-qubit), qubit, n)
qft_rot(circuit, n) # recursively call the function to repeat the process for next n-1 qubits
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-1-qubit)
return circuit
def qft(circuit, n):
''' QFT on the n qubits
'''
qft_rot(circuit, n)
swap_registers(circuit, n)
return circuit
# Draw the circuit with n=4
qc = QuantumCircuit(4)
qft(qc, 4)
qc.draw('mpl')
bin(13)
# Checking the circuit with 13='1101'
#quantum circuit that encodes '1101'
qc = QuantumCircuit(4)
qc.x([0,2,3])
qc.draw('mpl')
sim = Aer.get_backend("aer_simulator")
qc_init = qc.copy()
qc_init.save_statevector()
statevector = sim.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
qft(qc, 4)
qc.draw('mpl')
qc.save_statevector()
statevector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(statevector)
# Inverse QFT
def inv_qft(circuit, n):
"""Does the inverse QFT on the first n qubits in circuit"""
# First we create a QFT circuit of the correct size:
qft_circ = qft(QuantumCircuit(n), n)
# Then we take the inverse of this circuit
invqft_circ = qft_circ.inverse()
# And add it to the first n qubits in our existing circuit
circuit.append(invqft_circ, circuit.qubits[:n])
return circuit.decompose() # .decompose() allows us to see the individual gates
# Create the state |13>
state = 13
qc1 = QuantumCircuit(4)
for qubit in range(4):
qc1.h(qubit)
qc1.p(state*np.pi/8, 0)
qc1.p(state*np.pi/4, 1)
qc1.p(state*np.pi/2, 2)
qc1.p(state*np.pi, 3)
qc1.draw('mpl')
# Check this creates the state |13>
qc1_init = qc1.copy()
qc1_init.save_statevector()
sim = Aer.get_backend("aer_simulator")
statevector = sim.run(qc1_init).result().get_statevector()
plot_bloch_multivector(statevector)
# Apply inverse QFT
inv_qc = inv_qft(qc1, 4)
inv_qc.measure_all()
inv_qc.draw('mpl')
# check on simulator
counts = sim.run(qc_init).result().get_counts()
plot_histogram(counts)
# initialize
qpe = QuantumCircuit(4, 3)
qpe.x(3)
# apply the hadamard gates
for qubit in range(3):
qpe.h(qubit)
j = 1
for qubit in range(3):
for i in range(j):
qpe.cp(np.pi/4, qubit, 3)
j *= 2
qpe.barrier()
# apply inverse QFT, we use the in built QFT function
from qiskit.circuit.library import QFT
qpe = qpe.compose(QFT(3, inverse=True), [0,1,2])
# Measure
qpe.barrier()
for n in range(3):
qpe.measure(n,n)
qpe.draw('mpl')
aer_sim = Aer.get_backend('aer_simulator')
shots = 2048
t_qpe = transpile(qpe, aer_sim)
results = aer_sim.run(t_qpe, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Create and set up circuit
qpe2 = QuantumCircuit(4, 3)
# Apply H-Gates to counting qubits:
for qubit in range(3):
qpe2.h(qubit)
# Prepare our eigenstate |psi>:
qpe2.x(3)
# Do the controlled-U operations:
angle = 2*np.pi/3
repetitions = 1
for counting_qubit in range(3):
for i in range(repetitions):
qpe2.cp(angle, counting_qubit, 3);
repetitions *= 2
# Do the inverse QFT:
qpe2 = qpe2.compose(QFT(3, inverse=True), [0,1,2])
# Measure of course!
for n in range(3):
qpe2.measure(n,n)
qpe2.draw('mpl')
# Let's see the results!
shots = 4096
t_qpe2 = transpile(qpe2, aer_sim)
results = aer_sim.run(t_qpe2, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Examples of periods
N = 35
a = 3
import matplotlib.pyplot as plt
# Calculate the plotting data
xvals = np.arange(N)
yvals = [np.mod(a**x, N) for x in xvals]
# Use matplotlib to display it nicely
fig, ax = plt.subplots()
ax.plot(xvals, yvals, linewidth=1, linestyle='dotted', marker='x')
ax.set(xlabel='$x$', ylabel=f'${a}^x$ mod ${N}$',
title="Example of Periodic Function in Shor's Algorithm")
try: # plot r on the graph
r = yvals[1:].index(1) + 1
plt.annotate('', xy=(0,1), xytext=(r,1),
arrowprops=dict(arrowstyle='<->'))
plt.annotate(f'$r={r}$', xy=(r/3,1.5))
except ValueError:
print('Could not find period, check a < N and have no common factors.')
# We solve period finding problem for N=15
# The function c_amod15 returns the controlled-U gate for a, repeated power times.
def c_amod15(a, power):
"""Controlled multiplication by a mod 15"""
if a not in [2,4,7,8,11,13]:
raise ValueError("'a' must be 2,4,7,8,11 or 13")
U = QuantumCircuit(4)
for _iteration in range(power):
if a in [2,13]:
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
if a in [7,8]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
if a in [4, 11]:
U.swap(1,3)
U.swap(0,2)
if a in [7,11,13]:
for q in range(4):
U.x(q)
U = U.to_gate()
U.name = f"{a}^{power} mod 15"
c_U = U.control()
return c_U
# Specify variables
N_COUNT = 8 # number of counting qubits
a = 8
# Create QuantumCircuit with N_COUNT counting qubits
# plus 4 qubits for U to act on
qc = QuantumCircuit(N_COUNT + 4, N_COUNT)
# Initialize counting qubits
# in state |+>
for qubit in range(N_COUNT):
qc.h(qubit)
# And auxiliary register in state |1>
qc.x(N_COUNT)
# Do controlled-U operations
for qubit in range(N_COUNT):
qc.append(c_amod15(a, 2**qubit), [qubit] + [i+N_COUNT for i in range(4)])
# Do inverse-QFT
qc.append(QFT(N_COUNT, inverse=True), range(N_COUNT))
# Measure circuit
qc.measure(range(N_COUNT), range(N_COUNT))
qc.draw('mpl', fold=-1)
# measurement results
t_qc = transpile(qc, aer_sim)
counts = aer_sim.run(t_qc).result().get_counts()
plot_histogram(counts)
import pandas as pd
rows, measured_phases = [], []
for output in counts:
decimal = int(output, 2) # Convert (base 2) string to decimal
phase = decimal/(2**N_COUNT) # Find corresponding eigenvalue
measured_phases.append(phase)
# Add these values to the rows in our table:
rows.append([f"{output}(bin) = {decimal:>3}(dec)",
f"{decimal}/{2**N_COUNT} = {phase:.2f}"])
# Print the rows in a table
headers=["Register Output", "Phase"]
df = pd.DataFrame(rows, columns=headers)
df
from fractions import Fraction
rows = []
for phase in measured_phases:
frac = Fraction(phase).limit_denominator(15)
rows.append([phase,
f"{frac.numerator}/{frac.denominator}",
frac.denominator])
# Print as a table
headers=["Phase", "Fraction", "Guess for r"]
df = pd.DataFrame(rows, columns=headers)
print(df)
def a_2jmodN(a, j, N):
''' Computes a^{2^j} mod N '''
for _ in range(j):
a = np.mod(a**2 , N)
return a
# Factoring 15 using period finding
def qpe_amod15(a):
"""Performs quantum phase estimation on the operation a*r mod 15.
Args:
a (int): This is 'a' in a*r mod 15
Returns:
float: Estimate of the phase
"""
N_COUNT = 8
qc = QuantumCircuit(4+N_COUNT, N_COUNT)
for q in range(N_COUNT):
qc.h(q) # Initialize counting qubits in state |+>
qc.x(3+N_COUNT) # And auxiliary register in state |1>
for q in range(N_COUNT): # Do controlled-U operations
qc.append(c_amod15(a, 2**q), [q] + [i+N_COUNT for i in range(4)])
qc.append(QFT(N_COUNT, inverse=True), range(N_COUNT)) # Do inverse-QFT
qc.measure(range(N_COUNT), range(N_COUNT))
# Simulate Results
aer_sim = Aer.get_backend('aer_simulator')
# `memory=True` tells the backend to save each measurement in a list
job = aer_sim.run(transpile(qc, aer_sim), shots=1, memory=True)
readings = job.result().get_memory()
print("Register Reading: " + readings[0])
phase = int(readings[0],2)/(2**N_COUNT)
print(f"Corresponding Phase: {phase}")
return phase
phase = qpe_amod15(a) # Phase = s/r
Fraction(phase).limit_denominator(15)
frac = Fraction(phase).limit_denominator(15)
s, r = frac.numerator, frac.denominator
print(r)
from math import gcd
# repeats the algorithm until at least one factor of 15 is found
a = 7
FACTOR_FOUND = False
ATTEMPT = 0
while not FACTOR_FOUND:
ATTEMPT += 1
print(f"\nATTEMPT {ATTEMPT}:")
phase = qpe_amod15(a) # Phase = s/r
frac = Fraction(phase).limit_denominator(N)
r = frac.denominator
print(f"Result: r = {r}")
if phase != 0:
# Guesses for factors are gcd(x^{r/2} ±1 , 15)
guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)]
print(f"Guessed Factors: {guesses[0]} and {guesses[1]}")
for guess in guesses:
if guess not in [1,N] and (N % guess) == 0:
# Guess is a factor!
print("*** Non-trivial factor found: {guess} ***")
FACTOR_FOUND = True
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from sympy import *
init_printing(use_unicode=True)
%matplotlib inline
p00,p01,p10,p11 = symbols('p_{00} p_{01} p_{10} p_{11}')
th,ph = symbols('theta phi')
Psi00 = Matrix([[cos(th)],[0],[0],[sin(th)]])
Psi01 = Matrix([[0],[sin(ph)],[cos(ph)],[0]])
Psi11 = Matrix([[0],[cos(ph)],[-sin(ph)],[0]])
Psi10 = Matrix([[-sin(th)],[0],[0],[cos(th)]])
#Psi00, Psi00.T, Psi00*Psi00.T
rhoX = p00*Psi00*Psi00.T + p01*Psi01*Psi01.T + p10*Psi10*Psi10.T + p11*Psi11*Psi11.T
simplify(rhoX)
def kp(x,y):
return KroneckerProduct(x,y)
I = Matrix([[1,0],[0,1]])
Y = Matrix([[0,-1j],[1j,0]])
Y = Matrix([[0,1],[1,0]])
Z = Matrix([[1,0],[0,-1]])
cxx,cyy,czz,az,bz = symbols('c_{xx} c_{yy} c_{zz} a_{z} b_{z}')
rhoX = (1/4)*(kp(I,I) + cxx*kp(X,X) + cyy*kp(Y,Y) + czz*kp(Z,Z) + az*kp(Z,I) + bz*kp(I,Z))
simplify(rhoX)
th,be,ga = symbols('theta beta gamma')
c00 = cos(th/2)*cos(be/2)*cos(ga/2) + sin(th/2)*sin(be/2)*sin(ga/2)
c01 = cos(th/2)*cos(be/2)*sin(ga/2) - sin(th/2)*sin(be/2)*cos(ga/2)
c10 = cos(th/2)*sin(be/2)*cos(ga/2) - sin(th/2)*cos(be/2)*sin(ga/2)
c11 = cos(th/2)*sin(be/2)*sin(ga/2) + sin(th/2)*cos(be/2)*cos(ga/2)
simplify(c00**2 + c01**2 + c10**2 + c11**2) # ok!
P0 = Matrix([[1,0],[0,0]])
P1 = Matrix([[0,0],[0,1]])
def Ry(th):
return cos(th/2)*I - 1j*sin(th/2)*Y
def Cx_ab():
return KroneckerProduct(P0,I) + KroneckerProduct(P1,X)
def Cx_ba():
return KroneckerProduct(I,P0) + KroneckerProduct(X,P1)
MB = Cx_ab()*KroneckerProduct(Ry(th-ph),I)*Cx_ba()*KroneckerProduct(Ry(th+ph),I) # mudanca de base
simplify(MB)
from qiskit import *
import numpy as np
import math
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# retorna o circuito quantico que prepara um certo estado real de 1 qubit
# coef = array com os 2 coeficientes reais do estado na base computacional
def qc_psi_1qb_real(coef):
qr = QuantumRegister(1)
qc = QuantumCircuit(qr, name='psir_1qb')
th = 2*math.acos(np.abs(coef[0]))
qc.ry(th, qr[0])
return qc
eigvals = [0.1,0.9]
coef = np.sqrt(eigvals)
print(coef)
qc_psi_1qb_real_ = qc_psi_1qb_real(coef)
qc_psi_1qb_real_.draw('mpl')
from qiskit.quantum_info import Statevector
sv = Statevector.from_label('0')
sv
sv = sv.evolve(qc_psi_1qb_real_)
sv
# retorna o circuito quantico que prepara um certo estado real de 2 qubits
# coef = array com os 4 coeficientes reais do estado na base computacional
def qc_psi_2qb_real(coef):
qr = QuantumRegister(2)
qc = QuantumCircuit(qr, name = 'psir_2qb')
xi = 2*math.acos(math.sqrt(coef[0]**2+coef[1]**2))
coef1 = [math.sqrt(coef[0]**2+coef[1]**2),math.sqrt(1-coef[0]**2-coef[1]**2)]
c_psi_1qb_real_ = qc_psi_1qb_real(coef1)
qc.append(c_psi_1qb_real_, [qr[0]])
th0 = 2*math.atan(np.abs(coef[1])/np.abs(coef[0]))
th1 = 2*math.atan(np.abs(coef[3])/np.abs(coef[2]))
qc.x(0)
qc.cry(th0, 0, 1)
qc.x(0)
qc.cry(th1, 0, 1)
return qc
eigvals = [0.1, 0.2, 0.3, 0.4]
coef = np.sqrt(eigvals)
print(coef)
qc_psi_2qb_real_ = qc_psi_2qb_real(coef)
qc_psi_2qb_real_.draw('mpl')
sv = Statevector.from_label('00')
sv
sv = sv.evolve(qc_psi_2qb_real_)
sv # note o ordenamento, o 2º qb é o 1º e o 1º é o 2º (00,10,01,11)
def qc_ry(th):
qr = QuantumRegister(1)
qc = QuantumCircuit(qr, name = 'RY')
qc.ry(th, 0)
return qc
# retorna o circuito quantico que prepara um certo estado real de 3 qubits
# coef = array com os 8 coeficientes reais do estado na base computacional
def qc_psi_3qb_real(coef):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr, name = 'psir_3qb')
d = len(coef)
coef2 = np.zeros(d//2)
th = np.zeros(d//2)
for j in range(0,2):
for k in range(0,2):
coef2[int(str(j)+str(k),2)] = math.sqrt(coef[int(str(j)+str(k)+str(0),2)]**2+coef[int(str(j)+str(k)+str(1),2)]**2)
c_psi_2qb_real_ = qc_psi_2qb_real(coef2)
qc.append(c_psi_2qb_real_, [qr[0],qr[1]])
for j in range(0,2):
for k in range(0,2):
th[int(str(j)+str(k),2)] = 2*math.atan(np.abs(coef[int(str(j)+str(k)+str(1),2)])/np.abs(coef[int(str(j)+str(k)+str(0),2)]))
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
qc_ry_ = qc_ry(th[int(str(j)+str(k),2)])
ccry = qc_ry_.to_gate().control(2)
qc.append(ccry, [0,1,2])
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
return qc
list_bin = []
for j in range(0,2**3):
b = "{:03b}".format(j)
list_bin.append(b)
print(list_bin)
eigvals = [0.01,0.1,0.04,0.2,0.05,0.3,0.18,0.12]
coef = np.sqrt(eigvals)
print(coef)
qc_psi_3qb_real_ = qc_psi_3qb_real(coef)
qc_psi_3qb_real_.draw('mpl') # odernamento: '000', '001', '010', '011', '100', '101', '110', '111'
sv = Statevector.from_label('000')
sv
sv = sv.evolve(qc_psi_3qb_real_)
sv # ordenamento aqui: 000 100 010 110 001 101 011 111
# retorna o circuito quantico que prepara um certo estado real de 4 qubits
# coef = array com os 16 coeficientes reais do estado na base computacional
def qc_psi_4qb_real(coef):
qr = QuantumRegister(4)
qc = QuantumCircuit(qr, name = 'psir_4qb')
d = len(coef)
coef3 = np.zeros(d//2)
th = np.zeros(d//2)
for j in range(0,2):
for k in range(0,2):
for l in range(0,2):
coef3[int(str(j)+str(k)+str(l),2)] = math.sqrt(coef[int(str(j)+str(k)+str(l)+str(0),2)]**2+coef[int(str(j)+str(k)+str(l)+str(1),2)]**2)
c_psi_3qb_real_ = qc_psi_3qb_real(coef3)
qc.append(c_psi_3qb_real_, [qr[0],qr[1],qr[2]])
for j in range(0,2):
for k in range(0,2):
for l in range(0,2):
th[int(str(j)+str(k)+str(l),2)] = 2*math.atan(np.abs(coef[int(str(j)+str(k)+str(l)+str(1),2)])/np.abs(coef[int(str(j)+str(k)+str(l)+str(0),2)]))
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
if l == 0:
qc.x(2)
qc_ry_ = qc_ry(th[int(str(j)+str(k)+str(l),2)])
ccry = qc_ry_.to_gate().control(3)
qc.append(ccry, [0,1,2,3])
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
if l == 0:
qc.x(2)
return qc
list_bin = []
for j in range(0,2**4):
b = "{:04b}".format(j)
list_bin.append(b)
print(list_bin)
eigvals = np.zeros(2**4)
eigvals[0] = 0.008
for j in range(1,len(eigvals)-1):
eigvals[j] = eigvals[j-1]+0.005
#print(np.sum(eigvals))
eigvals[j+1] = 1 - np.sum(eigvals)
#print(eigvals)
#print(np.sum(eigvals))
coef = np.sqrt(eigvals)
print(coef)
qc_psi_4qb_real_ = qc_psi_4qb_real(coef)
qc_psi_4qb_real_.draw('mpl')
# '0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111'
sv = Statevector.from_label('0000')
sv
sv = sv.evolve(qc_psi_4qb_real_)
sv # ordenamento aqui: 0000 1000 0100 1100 0010 1010 0110 1110 0001 1001 0101 1101 0011 1011 0111 1111
sv[1]
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from sympy import *
init_printing(use_unicode=True)
mu_u = Matrix([[-1],[+1],[+1]]); mu_u
A_R = Matrix([[1,1,-1,-1],[1,-1,1,-1],[1,-1,-1,1]]); A_R
p1,p2,p3,p4 = symbols('p_1 p_2 p_3 p_4')
p4 = 1-p1-p2-p3
cl = A_R[:,0]*p1 + A_R[:,1]*p2 + A_R[:,2]*p3 + A_R[:,3]*p4
mu_u - cl
s1 = Matrix([[0,1],[1,0]])
s2 = Matrix([[0,-1j],[1j,0]])
s1*s2
import numpy as np
a = [] # gera uma lista com com todos os 512 estados ônticos
for j in range(-1,2,2):
for k in range(-1,2,2):
for l in range(-1,2,2):
for m in range(-1,2,2):
for n in range(-1,2,2):
for o in range(-1,2,2):
for p in range(-1,2,2):
for q in range(-1,2,2):
for r in range(-1,2,2):
a.append(np.array([j,k,l,m,n,o,p,q,r]))
a[10], a[10][5], len(a)
mu = [] # gera, a partir dos estados ônticos, uma lista com os 512 vetores de medida, muitos dos quais são iguais
for j in range(0,2**9):
r1 = a[j][0]*a[j][1]*a[j][2]
r2 = a[j][3]*a[j][4]*a[j][5]
r3 = a[j][6]*a[j][7]*a[j][8]
c1 = a[j][0]*a[j][3]*a[j][6]
c2 = a[j][1]*a[j][4]*a[j][7]
c3 = a[j][2]*a[j][5]*a[j][8]
mu.append([r1,r2,r3,c1,c2,c3])
mu[0], len(mu)
mu_ = [] # remove as repeticoes do vetor de medida
for j in range(0,2**6):
if mu[j] not in mu_:
mu_.append(mu[j])
mu_, len(mu_), mu_[1]
A_R = np.zeros((6,16))#; A_R
for j in range(0,16):
A_R[:,j] = mu_[j]
print(A_R)
print(A_R.shape)
def rpv_zhsl(d): # vetor de probabilidades aleatório
rn = np.zeros(d-1)
for j in range(0,d-1):
rn[j] = np.random.random()
rpv = np.zeros(d)
rpv[0] = 1.0 - rn[0]**(1.0/(d-1.0))
norm = rpv[0]
if d > 2:
for j in range(1,d-1):
rpv[j] = (1.0 - rn[j]**(1.0/(d-j-1)))*(1.0-norm)
norm = norm + rpv[j]
rpv[d-1] = 1.0 - norm
return rpv
rpv = rpv_zhsl(16)
print(rpv)
print(np.linalg.norm(rpv))
mu_Q = np.zeros((6,1)); mu_Q = np.array([1,1,1,1,1,-1]); print(mu_Q.shape)
p = np.zeros((16,1)); p = rpv_zhsl(16); print(p.shape)
vec = mu_Q - A_R@p
print(vec)
def objective(x):
mu_Q = np.array([1,1,1,1,1,-1])
vec = mu_Q - A_R@x
return np.linalg.norm(vec)
from scipy.optimize import minimize
# define o vinculo como sendo uma distribuicao de probabilidades
constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x)-1},
{'type':'ineq', 'fun': lambda x: x},
{'type':'ineq', 'fun': lambda x: 1-x}]
# 'eq' quer dizer = 0 e 'ineq' quer dizer >=0
np.random.seed(130000)
x0 = rpv_zhsl(16)
print(x0)
result = minimize(objective, x0, constraints=constraints, method='trust-constr')
print('melhor distribuicao de probabilidades', result.x)
print(objective(result.x))
from qiskit import *
import numpy as np
import math
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_manila')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
#from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
#from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.visualization import plot_histogram
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier() # mede XI
qc.h(0)
qc.cx(0,2)
qc.barrier() # mede IX
qc.h(1)
qc.cx(1,2)
qc.barrier() # mede XX
qc.cx(0,2)
qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier() # mede YI
qc.sdg(0)
qc.h(0)
qc.cx(0,2)
qc.barrier() # mede IY
qc.sdg(1)
qc.h(1)
qc.cx(1,2)
qc.barrier() # mede YY
qc.cx(0,2)
qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier()
qc.h(0)
qc.cx(0,2) # mede XI
qc.barrier()
qc.sdg(1)
qc.h(1)
qc.cx(1,2) # mede IX
qc.barrier()
qc.cx(0,2); qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier()
qc.sdg(0)
qc.h(0)
qc.cx(0,2) # mede XI
qc.barrier()
qc.h(1)
qc.cx(1,2) # mede IX
qc.barrier()
qc.cx(0,2); qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
I = Matrix([[1,0],[0,1]]); X = Matrix([[0,1],[1,0]]);
Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]])
I,X,Y,Z
XX = kronecker_product(X,X); XX.eigenvects()
YY = kronecker_product(Y,Y); YY.eigenvects()
ZZ = kronecker_product(Z,Z); ZZ.eigenvects()
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier() # mede ZZ
qc.cx(0,2)
qc.cx(1,2)
qc.barrier() # mede XX
qc.h([0,1])
qc.cx(0,2)
qc.cx(1,2)
qc.barrier() # mede YY
qc.h([0,1])
qc.sdg([0,1])
qc.h([0,1])
qc.cx(0,2)
qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
XY = kronecker_product(X,Y); XY.eigenvects()
YX = kronecker_product(Y,X); YX.eigenvects()
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier() # mede ZZ
qc.cx(0,2)
qc.cx(1,2)
qc.barrier() # mede XX
qc.sdg(1)
qc.h([0,1])
qc.cx(0,2)
qc.cx(1,2)
qc.barrier() # mede YY
qc.h([0,1])
qc.sdg(0)
qc.s(1)
qc.h([0,1])
qc.cx(0,2)
qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
cr1 = {'0': 7921, '1': 271}
cr2 = {'0': 7944, '1': 248}
cr3 = {'0': 7754, '1': 438}
cc1 = {'0': 7913, '1': 279}
cc2 = {'0': 7940, '1': 252}
cc3 = {'0': 610, '1': 7582}
r1a = (cr1['0']-cr1['1'])/(cr1['0']+cr1['1'])
r2a = (cr2['0']-cr2['1'])/(cr2['0']+cr2['1'])
r3a = (cr3['0']-cr3['1'])/(cr3['0']+cr3['1'])
c1a = (cc1['0']-cc1['1'])/(cc1['0']+cc1['1'])
c2a = (cc2['0']-cc2['1'])/(cc2['0']+cc2['1'])
c3a = (cc3['0']-cc3['1'])/(cc3['0']+cc3['1'])
print(r1a,r2a,r3a,c1a,c2a,c3a)
def objective(x):
mu_Q = np.array([0.93,0.94,0.89,0.93,0.94,-0.85])
vec = mu_Q - A_R@x
return np.linalg.norm(vec)
constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x)-1},
{'type':'ineq', 'fun': lambda x: x},
{'type':'ineq', 'fun': lambda x: 1-x}]
np.random.seed(130000)
x0 = rpv_zhsl(16)
result = minimize(objective, x0, constraints=constraints, method='trust-constr')
print('melhor distribuicao de probabilidades', result.x)
print(objective(result.x))
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from sympy import *
init_printing(use_unicode=True)
r1,r2,r3,s1,s2,s3 = symbols('r_1 r_2 r_3 s_1 s_2 s_3')
I = Matrix([[1,0],[0,1]]); X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]])
rho = (1/2)*(I+r1*X+r2*Y+r3*Z); sigma = (1/2)*(I+s1*X+s2*Y+s3*Z)
#rho, sigma
def frho(r1,r2,r3):
return (1/2)*(I+r1*X+r2*Y+r3*Z)
def fsigma(s1,s2,s3):
return (1/2)*(I+s1*X+s2*Y+s3*Z)
A = frho(r1,0,r2)*fsigma(0,s2,0)
simplify(A.eigenvals())
A = frho(0,0,r3); B = fsigma(s1,s2,0)
simplify(A*(B**2)*A - B*(A**2)*B)
M = A*B; simplify(M)
simplify(M.eigenvals()) # parecem ser positivos o que esta na raiz e o autovalores
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from qiskit import *
import numpy as np
import math
import qiskit
nshots = 8192
IBMQ.load_account()
#provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
dth = math.pi/10
th = np.arange(0,math.pi+dth,dth)
ph = 0; lb = 0
N = len(th)
F_the = np.zeros(N); F_sim = np.zeros(N); F_exp = np.zeros(N)
for j in range(0,N):
F_the[j] = math.cos(th[j]/2)**2
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.u(th[j],ph,lb,qr[2])
qc.h(qr[0])
qc.cswap(qr[0],qr[1],qr[2])
qc.h(qr[0])
qc.measure(qr[0],cr[0])
job_sim = execute(qc, backend=simulator, shots=nshots)
counts = job_sim.result().get_counts(qc)
if '0' in counts:
F_sim[j] = 2*counts['0']/nshots - 1
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts = job_exp.result().get_counts(qc)
if '0' in counts:
F_exp[j] = 2*counts['0']/nshots - 1
qc.draw('mpl')
qc.decompose().decompose().draw('mpl') # o circuito é "profundo" por causa da swap controlada
F_the, F_sim, F_exp
from matplotlib import pyplot as plt
plt.plot(th, F_the, label=r'$F_{the}$')
plt.plot(th, F_sim, '*', label=r'$F_{sim}$')
plt.plot(th, F_exp, 'o', label=r'$F_{exp}$')
plt.xlabel(r'$\theta$')
plt.legend()
plt.show()
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from qiskit import *
import numpy as np
import math
from matplotlib import pyplot as plt
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
#from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.visualization import plot_histogram
def qc_dqc1(ph):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr, name='DQC1')
qc.h(0)
qc.h(1) # cria o estado de Bell dos qubits 1 e 2, que equivale ao estado de 1 sendo maximamente misto
qc.cx(1,2)
#qc.barrier()
qc.cp(ph, 0, 1)
return qc
ph = math.pi/2
qc_dqc1_ = qc_dqc1(ph)
qc_dqc1_.draw('mpl')
qc_dqc1_.decompose().draw('mpl')
def pTraceL_num(dl, dr, rhoLR): # Retorna traco parcial sobre L de rhoLR
rhoR = np.zeros((dr, dr), dtype=complex)
for j in range(0, dr):
for k in range(j, dr):
for l in range(0, dl):
rhoR[j,k] += rhoLR[l*dr+j,l*dr+k]
if j != k:
rhoR[k,j] = np.conj(rhoR[j,k])
return rhoR
def pTraceR_num(dl, dr, rhoLR): # Retorna traco parcial sobre R de rhoLR
rhoL = np.zeros((dl, dl), dtype=complex)
for j in range(0, dl):
for k in range(j, dl):
for l in range(0, dr):
rhoL[j,k] += rhoLR[j*dr+l,k*dr+l]
if j != k:
rhoL[k,j] = np.conj(rhoL[j,k])
return rhoL
# simulation
phmax = 2*math.pi
dph = phmax/20
ph = np.arange(0,phmax+dph,dph)
d = len(ph);
xm = np.zeros(d)
ym = np.zeros(d)
for j in range(0,d):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
qc_dqc1_ = qc_dqc1(ph[j])
qc.append(qc_dqc1_, [0,1,2])
qstc = state_tomography_circuits(qc, [1,0])
job = execute(qstc, backend=simulator, shots=nshots)
qstf = StateTomographyFitter(job.result(), qstc)
rho_01 = qstf.fit(method='lstsq')
rho_0 = pTraceR_num(2, 2, rho_01)
xm[j] = 2*rho_0[1,0].real
ym[j] = 2*rho_0[1,0].imag
qc.draw('mpl')
# experiment
phmax = 2*math.pi
dph = phmax/10
ph_exp = np.arange(0,phmax+dph,dph)
d = len(ph_exp);
xm_exp = np.zeros(d)
ym_exp = np.zeros(d)
for j in range(0,d):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
qc_dqc1_ = qc_dqc1(ph_exp[j])
qc.append(qc_dqc1_, [0,1,2])
qstc = state_tomography_circuits(qc, [1,0])
job = execute(qstc, backend=device, shots=nshots)
print(job.job_id())
job_monitor(job)
qstf = StateTomographyFitter(job.result(), qstc)
rho_01 = qstf.fit(method='lstsq')
rho_0 = pTraceR_num(2, 2, rho_01)
xm_exp[j] = 2*rho_0[1,0].real
ym_exp[j] = 2*rho_0[1,0].imag
plt.plot(ph, xm, label = r'$\langle X\rangle_{sim}$')#, marker='*')
plt.plot(ph, ym, label = r'$\langle Y\rangle_{sim}$')#, marker='o')
plt.scatter(ph_exp, xm_exp, label = r'$\langle X\rangle_{exp}$', marker='*', color='r')
plt.scatter(ph_exp, ym_exp, label = r'$\langle Y\rangle_{exp}$', marker='o', color='g')
plt.legend(bbox_to_anchor=(1, 1))#,loc='center right')
#plt.xlim(0,2*math.pi)
#plt.ylim(-1,1)
plt.xlabel(r'$\phi$')
plt.show()
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from qiskit import *
import numpy as np
import math
from matplotlib import pyplot as plt
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
#from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.visualization import plot_histogram
qr = QuantumRegister(4)
cr = ClassicalRegister(3)
qc = QuantumCircuit(qr, cr)
qc.x(3)
qc.h([0,1,2])
qc.draw('mpl')
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi/2, np.pi/2, 1000) # generate 1000 evenly spaced points between -pi and pi
y_sin = np.abs(np.sin(x/2)) # compute sin(x) for each x
y_x = np.abs(x/2) # set y=x for each x
plt.plot(x, y_sin, label='sin(x)') # plot sin(x) as a blue line
plt.plot(x, y_x, label='x', color='orange') # plot x as an orange line
plt.legend() # display the legend
plt.show() # show the plot
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
%run init.ipynb
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from qiskit import *
import numpy as np
import math
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_manila')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
#from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
#from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.visualization import plot_histogram
def qc_bb84():
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr,cr)
qc.h([1,2])
qc.measure([1,2],[1,2])
qc.x(0).c_if(cr[1],1)
qc.h(0).c_if(cr[2],1)
qc.barrier()
qc.barrier()
qc.h(3)
qc.measure(qr[3],cr[3])
qc.h(0).c_if(cr[3],1)
qc.measure(0,0)
return qc
qc_bb84_ = qc_bb84(); qc_bb84_.draw('mpl')
nshots = 1
N = 100
counts = []
for j in range(0,N):
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
counts.append(counts_sim)
counts[0:5]
counts_keys = [j for j in counts]
counts_keys
k=0;l=1;m=0;n=0
s= str(k)+str(l)+str(m)+str(n)
s
eo = [] # observavel escolhido por Alice e Bob (mesmo = 0, diferente=1)
for j in range(0,N):
for k in range(0,2):
for l in range(0,2):
for m in range(0,2):
for n in range(0,2):
s = str(n) + str(m) + str(l) + str(k)
if counts[j][s] in counts and counts[j][s] == 1:
if l==0 and m==0:
eo.append(0)
else:
eo.append(1)
eo
qr = QuantumRegister(4)
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
%run init.ipynb
((10+9.8+9.5)/3+10)/2
(9.77+10)/2
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from qiskit.circuit import Parameter
from qiskit import QuantumCircuit
theta = Parameter('$\\theta$')
chsh_circuits_no_meas = QuantumCircuit(2)
chsh_circuits_no_meas.h(0)
chsh_circuits_no_meas.cx(0, 1)
chsh_circuits_no_meas.ry(theta, 0)
chsh_circuits_no_meas.draw('mpl')
import numpy as np
number_of_phases = 21
phases = np.linspace(0, 2*np.pi, number_of_phases)
# Phases need to be expressed as list of lists in order to work
individual_phases = [[ph] for ph in phases]
individual_phases
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator"
from qiskit_ibm_runtime import Estimator, Session
from qiskit.quantum_info import SparsePauliOp
ZZ = SparsePauliOp.from_list([("ZZ", 1)])
ZX = SparsePauliOp.from_list([("ZX", 1)])
XZ = SparsePauliOp.from_list([("XZ", 1)])
XX = SparsePauliOp.from_list([("XX", 1)])
ops = [ZZ, ZX, XZ, XX]
chsh_est_sim = []
# Simulator
with Session(service=service, backend=backend):
estimator = Estimator()
for op in ops:
job = estimator.run(
circuits=[chsh_circuits_no_meas]*len(individual_phases),
observables=[op]*len(individual_phases),
parameter_values=individual_phases)
est_result = job.result()
chsh_est_sim.append(est_result)
# <CHSH1> = <AB> - <Ab> + <aB> + <ab>
chsh1_est_sim = chsh_est_sim[0].values - chsh_est_sim[1].values + chsh_est_sim[2].values + chsh_est_sim[3].values
# <CHSH2> = <AB> + <Ab> - <aB> + <ab>
chsh2_est_sim = chsh_est_sim[0].values + chsh_est_sim[1].values - chsh_est_sim[2].values + chsh_est_sim[3].values
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
fig, ax = plt.subplots(figsize=(10, 6))
# results from a simulator
ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Simulation')
ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Simulation')
# classical bound +-2
ax.axhline(y=2, color='r', linestyle='--')
ax.axhline(y=-2, color='r', linestyle='--')
# quantum bound, +-2√2
ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.')
ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.')
# set x tick labels to the unit of pi
ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5))
# set title, labels, and legend
plt.title('Violation of CHSH Inequality')
plt.xlabel('Theta')
plt.ylabel('CHSH witness')
plt.legend()
from qiskit_ibm_runtime import Estimator, Session
from qiskit.quantum_info import SparsePauliOp
backend = service.get_backend("ibmq_belem")
ZZ = SparsePauliOp.from_list([("ZZ", 1)])
ZX = SparsePauliOp.from_list([("ZX", 1)])
XZ = SparsePauliOp.from_list([("XZ", 1)])
XX = SparsePauliOp.from_list([("XX", 1)])
ops = [ZZ, ZX, XZ, XX]
chsh_est_sim = []
with Session(service=service, backend=backend):
estimator = Estimator()
for op in ops:
job = estimator.run(
circuits=[chsh_circuits_no_meas]*len(individual_phases),
observables=[op]*len(individual_phases),
parameter_values=individual_phases)
print(job.job_id())
est_result = job.result()
chsh_est_sim.append(est_result)
# <CHSH1> = <AB> - <Ab> + <aB> + <ab>
chsh1_est_sim = chsh_est_sim[0].values - chsh_est_sim[1].values + chsh_est_sim[2].values + chsh_est_sim[3].values
# <CHSH2> = <AB> + <Ab> - <aB> + <ab>
chsh2_est_sim = chsh_est_sim[0].values + chsh_est_sim[1].values - chsh_est_sim[2].values + chsh_est_sim[3].values
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
fig, ax = plt.subplots(figsize=(10, 6))
# results from a simulator
ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Experiment')
ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Experiment')
# classical bound +-2
ax.axhline(y=2, color='r', linestyle='--')
ax.axhline(y=-2, color='r', linestyle='--')
# quantum bound, +-2√2
ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.')
ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.')
# set x tick labels to the unit of pi
ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5))
# set title, labels, and legend
plt.title('Violation of CHSH Inequality')
plt.xlabel('Theta')
plt.ylabel('CHSH witness')
plt.legend()
(250/4)*3
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
%run init.ipynb
def plot_Pr0(R1, R2):
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100)
ph_max = 2*math.pi; dph = ph_max/20; ph = np.arange(0, ph_max+dph, dph)
dimph = ph.shape[0]; P0 = np.zeros(dimph)
T1 = math.sqrt(1 - R1**2); T2 = math.sqrt(1 - R2**2)
P0 = T1**2*R2**2 + R1**2*T2**2 + 2*T1*R1*T2*R2*np.cos(ph)
plt.plot(ph, P0); plt.xlabel(r'$\phi$'); plt.ylabel(r'$Pr(0)$')
plt.xlim(0, 2*math.pi); plt.ylim(0, 1)
plt.annotate(r'$R_{1}=$'+str(R1), xy=(0.5,0.5), xytext=(0.5,0.5), fontsize=12)
plt.annotate(r'$R_{2}=$'+str(R1), xy=(0.5,0.4), xytext=(0.5,0.4), fontsize=12)
plt.show()
interactive(plot_Pr0, R1 = (0, 1, 0.05), R2 = (0, 1, 0.05))
def V1(T1, T2):
return (2*T1*T2*np.sqrt(1-T1**2)*np.sqrt(1-T2**2))/((T1**2)*(T2**2) + (1-T1**2)*(1-T2**2))
def V_3d(th, ph):
x = np.linspace(0.00001, 0.99999, 20); y = np.linspace(0.00001, 0.99999, 20); X, Y = np.meshgrid(x, y)
Z = V1(X, Y); fig = plt.figure();
ax = plt.axes(projection = "3d"); ax.plot_wireframe(X, Y, Z, color = 'blue')
ax.set_xlabel(r'$T_{1}$'); ax.set_ylabel(r'$T_{2}$'); ax.set_zlabel(r'$V_{0}$')
ax.view_init(th, ph); fig.tight_layout(); plt.show()
interactive(V_3d, th = (0,90,10), ph = (0,360,10))
from mpl_toolkits import mplot3d
def V0(T1, T2):
return (2*T1*T2*np.sqrt(1-T1**2)*np.sqrt(1-T2**2))/((T1**2)*(1-T2**2) + (1-T1**2)*T2**2)
def V_3d(th, ph):
x = np.linspace(0.00001, 0.99999, 20); y = np.linspace(0.00001, 0.99999, 20); X, Y = np.meshgrid(x, y)
Z = V0(X, Y); fig = plt.figure();
ax = plt.axes(projection = "3d"); ax.plot_wireframe(X, Y, Z, color = 'blue')
ax.set_xlabel(r'$T_{1}$'); ax.set_ylabel(r'$T_{2}$'); ax.set_zlabel(r'$V_{0}$')
ax.view_init(th, ph); fig.tight_layout(); plt.show()
interactive(V_3d, th = (0,90,10), ph = (0,360,10))
def V_3d(th, ph):
x = np.linspace(0.00001, 0.99999, 20); y = np.linspace(0.00001, 0.99999, 20); X, Y = np.meshgrid(x, y)
Z = V0(X, Y)-V1(X, Y); fig = plt.figure();
ax = plt.axes(projection = "3d"); ax.plot_wireframe(X, Y, Z, color = 'blue')
ax.set_xlabel(r'$T_{1}$'); ax.set_ylabel(r'$T_{2}$'); ax.set_zlabel(r'$V_{0}-V_{1}$')
ax.view_init(th, ph); fig.tight_layout(); plt.show()
interactive(V_3d, th = (0,90,10), ph = (0,360,10))
import math
import qiskit
def shannon_num(pv):
d = pv.shape[0]; SE = 0.0; j = -1
while (j < d-1):
j = j + 1
if pv[j] > 10**-15 and pv[j] < (1.0-10**-15):
SE -= pv[j]*math.log2(pv[j])
return SE
import scipy.linalg.lapack as lapak
def von_neumann_num(rho):
d = rho.shape[0]; b = lapak.zheevd(rho)
return shannon_num(b[0])
def coh_re_num(rho):
d = rho.shape[0]; pv = np.zeros(d)
for j in range(0,d):
pv[j] = rho[j,j].real
return shannon_num(pv) - von_neumann_num(rho)
def P_vn_num(rho):
d = rho.shape[0]; P = 0
for j in range(0, d):
if rho[j,j] > 10**-15 and rho[j,j] < (1.0-10**-15):
P += np.absolute(rho[j,j])*math.log2(np.absolute(rho[j,j]))
return math.log2(d) + P
def qc_gmzi(th, ph, ga):
qc = qiskit.QuantumCircuit(1)
qc.rx(-2*th, 0); qc.z(0); qc.y(0); qc.p(ph, 0); qc.rx(-2*ga, 0)
return qc
th, ph, ga = math.pi/3, math.pi/2, math.pi; qcgmzi = qc_gmzi(th, ph, ga); qcgmzi.draw(output = 'mpl')
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_armonk')
simulator = qiskit.Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
# for error mitigation
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
qr = qiskit.QuantumRegister(1)
qubit_list = [0] # os qubits para os quais aplicaremos calibracao de medidas
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr)
job = qiskit.execute(meas_calibs, backend = device, shots = nshots); job_monitor(job)
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels)
# for computing coherence and predictability
th_max = math.pi/2; dth = th_max/10; th = np.arange(0, th_max+dth, dth); dimth = th.shape[0]
Csim = np.zeros(dimth); Psim = np.zeros(dimth); Cexp = np.zeros(dimth); Pexp = np.zeros(dimth)
for j in range(0, dimth):
qr = qiskit.QuantumRegister(1); qc = qiskit.QuantumCircuit(qr); qc.rx(-2*th[j], qr[0])
qstc = state_tomography_circuits(qc, qr[0])
job = qiskit.execute(qstc, simulator, shots = nshots) # simulation
qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method = 'lstsq')
Csim[j] = coh_re_num(rho); Psim[j] = P_vn_num(rho)
jobE = qiskit.execute(qstc, backend = device, shots = nshots); job_monitor(jobE)
mitigated_results = meas_fitter.filter.apply(jobE.result())
qstfE = StateTomographyFitter(mitigated_results, qstc)
#qstfE = StateTomographyFitter(jobE.result(), qstc)
rhoE = qstfE.fit(method = 'lstsq')
Cexp[j] = coh_re_num(rhoE); Pexp[j] = P_vn_num(rhoE)
Cexp
Pexp
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100)
plt.plot(th, Csim, label = r'$C_{re}^{sim}$')
plt.plot(th, Psim, label = r'$P_{vn}^{sim}$')
plt.plot(th, Cexp, 'o', label = r'$C_{re}^{exp}$')
plt.plot(th, Pexp, '*', label = r'$P_{vn}^{exp}$')
plt.legend(); plt.xlabel(r'$\theta$')
plt.savefig('coh_vs_ivi_armonk_mit.pdf', format = 'pdf', dpi = 200)
plt.show()
# for computing the visibility
ph_max = 2*math.pi; dph = ph_max/10; ph = np.arange(0, ph_max+dph, dph); dimph = ph.shape[0]
P0sim = np.zeros(dimph); P0exp = np.zeros(dimph)
th[j] = math.pi/2
for k in range(0, dimph):
qr = qiskit.QuantumRegister(1); cr = qiskit.ClassicalRegister(1); qc = qiskit.QuantumCircuit(qr, cr)
qc.rx(-2*th[j], qr[0]); qc.z(qr[0]); qc.y(qr[0])
qc.p(ph[k], qr[0]); ga = th[j]; qc.rx(-2*ga, qr[0]); qc.measure(qr[0], cr[0])
job = qiskit.execute(qc, backend = simulator, shots = nshots) # simulation
counts = job.result().get_counts(qc)
if '0' in counts:
P0sim[k] = counts['0']
jobE = qiskit.execute(qc, backend = device, shots = nshots); job_monitor(jobE)
mitigated_results = meas_fitter.filter.apply(jobE.result())
countsE = mitigated_results.get_counts(qc)
#countsE = jobE.result().get_counts(qc)
if '0' in countsE:
P0exp[k] = countsE['0']
P0sim = P0sim/nshots; P0exp = P0exp/nshots
P0exp
P0sim
P0expthpi2 = np.array([0.0267666 , 0.02431936, 0.02646069, 0.03701438, 0.02340165,
0.02997859, 0.02095442, 0.02049556, 0.02156623, 0.01957785,
0.03242582])
P0simthpi2 = np.array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
P0expthpi4 = np.array([1. , 0.90838173, 0.66274091, 0.37488527, 0.11976134,
0.01881309, 0.12251453, 0.36310798, 0.65050474, 0.90455797,
1. ])
P0simthpi4 = np.array([1. , 0.90612793, 0.65258789, 0.34069824, 0.09924316,
0. , 0.09228516, 0.34741211, 0.64331055, 0.90209961,
1. ])
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100)
plt.plot(ph, P0simthpi4, label = r'$P_{0}^{sim}(\theta=\pi/4)$')
plt.plot(ph, P0expthpi4, 'o', label = r'$P_{0}^{exp}(\theta=\pi/4)$')
plt.plot(ph, P0simthpi2, '.-', label = r'$P_{0}^{sim}(\theta=\pi/2)$')
plt.plot(ph, P0expthpi2, '*', label = r'$P_{0}^{exp}(\theta=\pi/2)$')
plt.ylim(0, 2*math.pi); plt.ylim(-0.01, 1.01)
plt.legend(); plt.xlabel(r'$\phi$')
plt.savefig('P0_thpi4_armonk_mit.pdf', format = 'pdf', dpi = 200)
plt.show()
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
%run init.ipynb
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
|
hub=qc-spring-22-2, group=group-5 and project=recPrYILNAOsYMWIV
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.