repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
### replaced x gate ###
qc.z(qubit)
if msg[0] == "1":
### replaced z gate ###
qc.x(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/tuf65651/quantum-research
|
tuf65651
|
# %matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from datetime import datetime
# import math
# Loading your IBM Q account(s)
# IBMQ.load_account()
backend = Aer.get_backend("qasm_simulator")
# global n_reg
# global m_reg
# global scratch_a
# global class_reg
# global backend
# global qc
# global test_timestamp
# def before_tests():
n_reg = QuantumRegister(3, 'n')
m_reg = QuantumRegister(2, 'm')
scratch_a = QuantumRegister(3, 'sca')
class_reg = ClassicalRegister(3, 'y')
qc = QuantumCircuit(n_reg, m_reg, scratch_a, class_reg)
backend = Aer.get_backend('qasm_simulator')
from ArithmaticFunctions import ripple_carry_bits
test_timestamp = str(datetime.now())
def before_each_ripple_borrow_test():
n_reg = QuantumRegister(3, 'n')
m_reg = QuantumRegister(2, 'm')
scratch_a = QuantumRegister(3, 'sca')
qc = QuantumCircuit(n_reg, m_reg, scratch_a, class_reg)
# Set control bits
qc.x(m_reg[1])
return {'n_reg': n_reg, 'm_reg': m_reg, 'scratch_a': scratch_a, 'class_reg': class_reg, 'qc': qc }
def get_results_of_last_test():
for bit in range(len(n_reg)):
qc.measure(n_reg[bit], class_reg[bit])
simulate = execute(qc, backend=backend, shots=1024).result()
return simulate.get_counts()
def verify_results(expected):
time_stamp = str(datetime.now())
if [expected] == list(results.keys()):
print("PASSING - ", test_timestamp)
else:
print("FAILING - ", test_timestamp)
print(f'Got - {results}')
# 0 + 1 = 1
test_components = before_each_ripple_borrow_test()
qc = test_components['qc']
qc.barrier()
ripple_carry_bits(circuit=qc, acc_reg=n_reg, control_bit=m_reg[1], scratch_reg=scratch_a, start_shifting_at=0)
results = get_results_of_last_test()
# qc.draw()
verify_results(expected='001')
# NO-OP(1)
test_components = before_each_ripple_borrow_test()
qc = test_components['qc']
qc.x(n_reg[0])
# qc.barrier()
ripple_carry_bits(circuit=qc, acc_reg=n_reg, control_bit=m_reg[False], scratch_reg=scratch_a, start_shifting_at=0)
results = get_results_of_last_test()
qc.draw()
verify_results(expected='001')
# 1 + 1 = 2
test_components = before_each_ripple_borrow_test()
qc = test_components['qc']
qc.x(n_reg[0])
ripple_carry_bits(circuit=qc, acc_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=0)
results = get_results_of_last_test()
# qc.draw()
verify_results(expected='010')
# 2 + 1 = 3
test_components = before_each_ripple_borrow_test()
qc = test_components['qc']
qc.x(n_reg[1])
# qc.barrier()
ripple_carry_bits(circuit=qc, acc_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=0)
results = get_results_of_last_test()
qc.draw()
verify_results(expected='011')
# 1 + 2 = 3
test_components = before_each_ripple_borrow_test()
qc = test_components['qc']
qc.x(n_reg[0])
ripple_carry_bits(circuit=qc, acc_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=1)
results = get_results_of_last_test()
# qc.draw()
verify_results(expected='011')
# 2 + 2 = 4
test_components = before_each_ripple_borrow_test()
qc = test_components['qc']
qc.x(n_reg[1])
ripple_carry_bits(circuit=qc, acc_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=1)
results = get_results_of_last_test()
qc.draw()
verify_results(expected='100')
# 7 - 2 = 5
test_components = before_each_ripple_borrow_test()
qc = test_components['qc']
qc.x(n_reg[0])
qc.x(n_reg[1])
qc.x(n_reg[2])
c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=1)
results = get_results_of_last_test()
# qc.draw()
verify_results(expected='101')
# NO-OP(7) = 7
test_components = before_each_ripple_borrow_test()
qc = test_components['qc']
qc.x(n_reg[0])
qc.x(n_reg[1])
qc.x(n_reg[2])
qc.barrier()
ripple_carry_bits(circuit=qc, acc_reg=n_reg, control_bit=m_reg[False], scratch_reg=scratch_a, start_shifting_at=1)
results = get_results_of_last_test()
# qc.draw()
verify_results(expected='111')
# 7 + 2 = ?
test_components = before_each_ripple_borrow_test()
qc = test_components['qc']
qc.x(n_reg[0])
qc.x(n_reg[1])
qc.x(n_reg[2])
# c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=2)
ripple_carry_bits(circuit=qc, acc_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=1)
results = get_results_of_last_test()
qc.draw()
# print(results)
print(results)
execute(qc, backend=backend, shots=1024).result().get_counts().keys()
|
https://github.com/tstopa/Qiskit_for_high_schools
|
tstopa
|
import qiskit
from qiskit import Aer
from qiskit.aqua.algorithms import Shor
N=15
shor = Shor(N)
backend = Aer.get_backend('qasm_simulator')
result = shor.run(backend)
print("The factors of {} computed by the Shor's algorithm: {}.".format(N, result['factors'][0]))
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import TruthTableOracle, LogicalExpressionOracle
truthTable = '0010100101000001'
oracle = TruthTableOracle(truthTable)
grover = Grover(oracle)
result = grover.run(backend)
from qiskit.visualization import plot_histogram
plot_histogram(result['measurement'])
secondOracle = LogicalExpressionOracle('(a & ~b) & (c ^ d)')
grover = Grover(secondOracle)
result = grover.run(backend)
plot_histogram(result['measurement'])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import *
from qiskit.visualization import plot_histogram
# quantum circuit to make a Bell state
bell = QuantumCircuit(2, 2)
bell.h(0)
bell.cx(0, 1)
meas = QuantumCircuit(2, 2)
meas.measure([0,1], [0,1])
# execute the quantum circuit
backend = BasicAer.get_backend('qasm_simulator') # the device to run on
circ = bell.compose(meas)
result = backend.run(transpile(circ, backend), shots=1000).result()
counts = result.get_counts(circ)
print(counts)
plot_histogram(counts)
# Execute 2-qubit Bell state again
second_result = backend.run(transpile(circ, backend), shots=1000).result()
second_counts = second_result.get_counts(circ)
# Plot results with legend
legend = ['First execution', 'Second execution']
plot_histogram([counts, second_counts], legend=legend)
plot_histogram([counts, second_counts], legend=legend, sort='desc', figsize=(15,12),
color=['orange', 'black'], bar_labels=False)
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_state_paulivec, plot_state_hinton
from qiskit.visualization import plot_state_qsphere
# execute the quantum circuit
backend = BasicAer.get_backend('statevector_simulator') # the device to run on
result = backend.run(transpile(bell, backend)).result()
psi = result.get_statevector(bell)
plot_state_city(psi)
plot_state_hinton(psi)
plot_state_qsphere(psi)
plot_state_paulivec(psi)
plot_bloch_multivector(psi)
plot_state_city(psi, title="My City", color=['black', 'orange'])
plot_state_hinton(psi, title="My Hinton")
plot_state_paulivec(psi, title="My Paulivec", color=['purple', 'orange', 'green'])
plot_bloch_multivector(psi, title="My Bloch Spheres")
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([0,1,0])
plot_bloch_vector([0,1,0], title='My Bloch Sphere')
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit.circuit.library import CCXGate
toffoli = CCXGate()
print(toffoli.num_ctrl_qubits)
toffoli = CCXGate()
toffoli.ctrl_state = 2
toffoli.definition.draw()
from qiskit import QuantumCircuit
import math
p16_qc = QuantumCircuit(1)
p16_qc.p(math.pi/16, 0)
p16_gate = p16_qc.to_gate()
p16_gate.definition.draw()
ctrl_p16 = p16_gate.control(2)
ctrl_p16.definition.draw()
qc = QuantumCircuit(4)
qc.h([0,1,2,3])
qc.append(ctrl_p16,[0,1,3])
qc.decompose().draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
state = Statevector(qc)
plot_bloch_multivector(state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(3, 'q')
anc = QuantumRegister(1, 'ancilla')
cr = ClassicalRegister(3, 'c')
qc = QuantumCircuit(qr, anc, cr)
qc.x(anc[0])
qc.h(anc[0])
qc.h(qr[0:3])
qc.cx(qr[0:3], anc[0])
qc.h(qr[0:3])
qc.barrier(qr)
qc.measure(qr, cr)
qc.draw('mpl')
|
https://github.com/LeanderThiessen/antisymmetrization-circuit
|
LeanderThiessen
|
#General Imports
import numpy as np
import matplotlib.pyplot as plt
import time
from itertools import product,permutations
from string import ascii_lowercase as asc
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
#Qiskit Imports
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile
from qiskit.circuit.library.standard_gates import MCXGate, CXGate, XGate, CSwapGate
from qiskit.circuit.library import Diagonal
from qiskit.quantum_info import partial_trace,purity
#############FUNCTIONS###########################################################################################################
#wrapper for measuring time taken by function 'func'
def timeis(func):
def wrap(*args,**kwargs):
start = time.time()
result = func(*args,**kwargs)
end = time.time()
if measure_time:
print("{} took {:.2f}s".format(func.__name__,end-start))
return result
return wrap
#check if inputs are valid
def check_inputs(n,m):
if n == 1:
print("Case n=1 currently not supported")
correct = 1
if m>2**n:
correct == 0
if correct == 1:
print("Inputs valid")
return 0
#initialize quantum circuit with electron register, swap_ancillas, record_ancillas, collision_ancillas
def initialize_circuit(n,m,L):
circuit = QuantumCircuit()
#add main electron register (seed/target)
for e in range(m):
r_q = QuantumRegister(n,'{}'.format(asc[e]))#asc[i]=ith letter of the alphabe
c = QuantumCircuit(r_q)
circuit = circuit.combine(c)
#add ancillas for comparator_swaps
for k in range(int(np.ceil(m/2))):
anc_q = QuantumRegister(n-1,'anc_{}'.format(k))
c = QuantumCircuit(anc_q)
circuit = circuit.combine(c)
#add 'record' register for storing outcomes of comparators
for l in range(L):
anc_q = QuantumRegister(1,'record_{}'.format(l))
c = QuantumCircuit(anc_q)
circuit = circuit.combine(c)
#add ancillas to store the occurence of collisions between pairs of electrons
for c in range(m-1):
anc_q = QuantumRegister(1,'coll_record_{}'.format(c))
c = QuantumCircuit(anc_q)
circuit = circuit.combine(c)
#add one ancilla to store if all other collision ancillas are '1'
anc_q = QuantumRegister(1,'collision_test')
c = QuantumCircuit(anc_q)
circuit = circuit.combine(c)
return circuit
#returns x in binary format as string of length n, incl leading zeros
def binary_n(x,n):
return bin(x)[2:].zfill(n)
#initializes j-th electron register with number x
def binary_init(circuit,n,m,input):
for k,e in enumerate(input):
e_bin = binary_n(e,n)
for i in range(n):
if e_bin[i]=='1':
circuit.append(XGate(),[i+k*n])
return circuit
#Apply a Hadamard gate to each qubit in the electron register
def Hadamard(circuit,n,m):
for q in range(n*m):
circuit.h(q)
return circuit
#Compare bits at positions x and y, only output=(x<y) to position anc
def bit_compare(circuit,cbits,control,debug=True):
x = cbits[0]
y = cbits[1]
anc = cbits[2]
if debug:
circuit.barrier()
#control='01' for initial sorting and '10' for collision detection
circuit.append(MCXGate(2,ctrl_state=control),[x,y,anc])
if debug:
circuit.barrier()
return circuit
#split the array 'index' into array of pairs of adjacent indices; first entry is (e.g.) [0] if number of entries of index is odd
def get_subsets(index):
#index = [0,1,2,3] -> result = [[0,1],[2,3]]
#index = [0,1,2,3,4] -> result = [[0],[1,2],[3,4]]
M = len(index)
result = []
if M % 2 != 0:
result.append(np.array([0]))
n_split = int((M-1)/2)
for s in np.split(index[1:M],n_split):
result.append(s)
else:
result = np.split(index,M/2)
return result
#get position of first qubit in swap_control ancilla register
def get_first_swap_ctrl(n,m):
#n_comp_parallel is the number of comparators that are applied in each layer
#n*m = main register for storing electron registers;
#(n_comp_parallel)*(n-1) = fixed ancilla register needed for compare_n
n_comp_parallel = int(np.ceil(m/2))
ctrl_0 = n*m + (n-1)*n_comp_parallel
return ctrl_0
#get position of first qubit in collision_control ancilla register
def get_first_coll_ctrl(n,m,L):
coll_0 = get_first_swap_ctrl(n,m) + L
return coll_0
#return pairs of electron indices that need to be compared in collision-detection step
def get_coll_sets(m):
ind = np.arange(m)
if m == 2:
sets_a = [np.array([0,1])]
sets_b = []
return sets_a,sets_b
if m % 2 == 0:
sets_a = np.split(ind,m/2)
sets_b = np.split(ind[1:-1],(m-2)/2)
else:
sets_a = np.split(ind[:-1],(m-1)/2)
sets_b = np.split(ind[1:],(m-1)/2)
#all gates in sets_a can be applied in parallel
#all gates in sets_b can be applied in parallel
return sets_a,sets_b
#returns the first qubit position of the ancilla register used for swap of i and j (only really tested for m<6)
def get_anc(n,m,i,j):
if abs(j-i) == 1:
anc_reg = int( np.min([i,j])/2 )
elif abs(j-i) == 2:
anc_reg = int( np.ceil( np.min([i,j])/2 ))
else:
anc_reg = int( np.min([i,j]) )
anc = n*m + anc_reg*(n-1)
return anc
#Implement 'Compare2' function (Fig 3); input: two 2bit numbers, output: two 1bit numbers with same ordering
def compare_2(circuit,x_0,x_1,y_0,y_1,anc):
#Notation: x = 2^1*x_0 + x_1 (reverse from paper!!)
#compares numbers x,y and outputs two bits x',y' (at positions x_1 and y_1) with the same ordering
circuit.append(XGate(),[anc])
circuit.append(CXGate(),[y_0,x_0])
circuit.append(CXGate(),[y_1,x_1])
circuit.append(CSwapGate(),[x_0,x_1,anc])
circuit.append(CSwapGate(),[x_0,y_0,y_1])
circuit.append(CXGate(),[y_1,x_1])
return circuit
#Generalisation of 'compare2' two nbit numbers, output: two 1bit numbers with same ordering at positions x1,y1
def compare_n(circuit,n,m,i,j,l,L,debug):
index = np.arange(n)
subsets = get_subsets(index)
M = len(subsets)
anc = get_anc(n,m,i,j)
for s in subsets:
if len(s)==2:
if debug:
circuit.barrier()
x_0 = s[0] + i*n
x_1 = s[1] + i*n
y_0 = s[0] + j*n
y_1 = s[1] + j*n
circuit = compare_2(circuit,x_0,x_1,y_0,y_1,anc)
anc += 1
while (len(subsets)>1):
index = np.array([subsets[k][-1] for k in range(M)])
subsets = get_subsets(index)
M = len(subsets)
for s in subsets:
if len(s)==2:
if debug:
circuit.barrier()
x_0 = s[0] + i*n
x_1 = s[1] + i*n
y_0 = s[0] + j*n
y_1 = s[1] + j*n
circuit = compare_2(circuit,x_0,x_1,y_0,y_1,anc)
anc += 1
########################################################################################################################################
#at this point the bits x_1 and y_1 have the same ordering as numbers stored in registers i and j
#e(i)<e(j) -> x_1=0 and y_1=1
#e(i)>e(j) -> x_1=1 and y_1=0
#e(i)=e(j) -> x_1=0 y_1=0 if e(i) even or x_1=1 y_1=1 if e(i) odd
#prepare output for bit_compare function; anc iterates through the second ancilla register (+1 for each comparator)
#l = current swap; each new swap gets a new ancilla for storing the outcome
anc = get_first_swap_ctrl(n,m) + l
cbits = x_1,y_1,anc
return circuit,cbits
#apply diagonal phase shift to qubit i, conditioned on qubit 'ctrl'
def cphase_shift(circuit,ctrl,i):
target = i*n
CDiag = Diagonal([-1,-1]).control(1)
CDiag = CDiag.to_gate()
CDiag.label = "D" #doesn't work currently
circuit.append(CDiag,[ctrl,target])
return circuit
#performs swap of registers i and j conditioned on ancilla qubit 'ctrl'
def swap_registers(circuit,n,i,j,ctrl,debug):
for g in range(n):
circuit.append(CSwapGate(),[ctrl,i*n+g,j*n+g])
if debug:
circuit.barrier()
return circuit
#compare electron registers i and j; swap registers iff e(i)<(j); l=current swap (0 to L)
def comparator_swap(n,m,i,j,l,L,phase,debug):
#Perform comparison to generate output qubits "cbits"
circuit_compute = initialize_circuit(n,m,L)
circuit_compute,cbits = compare_n(circuit_compute,n,m,i,j,l,L,debug)
#Add bit_compare between the two output qubits and store in ancilla
circuit_bit_compare = initialize_circuit(n,m,L)
circuit_bit_compare = bit_compare(circuit_bit_compare,cbits,'10',debug)
#add uncomputing step only of the comparison circuit
circuit_uncompute = circuit_compute.inverse()
#Swap registers based on control ancilla
circuit_swap = initialize_circuit(n,m,L)
#apply a conditioned phase shift to the first qubit of the register pair; is only called when sn is applied backwards, that's why it's (phase,swap) and not (swap,phase)
if phase:
circuit_swap = cphase_shift(circuit_swap,cbits[2],i)
circuit_swap = swap_registers(circuit_swap,n,i,j,cbits[2],debug)
#Combine circuits
circuit_comparator = circuit_compute + circuit_bit_compare + circuit_uncompute + circuit_swap
return circuit_comparator
#Apply the sorting network sn, where each comparator stores the outcome in ctrl_register
def apply_sorting_network(circuit,n,m,sn,L,phase,debug):
for l,swap in enumerate(sn):
#swap = [i, j, direction]; dir = 0 : descending (from the top); dir = 1 : ascending (from the top)
if swap[2]==0:
i = swap[0]
j = swap[1]
if swap[2]==1:
i = swap[1]
j = swap[0]
circuit_comparator = comparator_swap(n,m,i,j,l,L,phase,debug)
circuit = circuit + circuit_comparator
return circuit
#Apply the reverse of the sorting networkl sn for antisymmetrizing the input state
def apply_reverse_sorting_network(circuit,n,m,sn,L,phase,debug):
circuit_sn = initialize_circuit(n,m,L)
circuit_sn = apply_sorting_network(circuit_sn,n,m,sn,L,phase,debug)
#reverse all gates in the circuit
circuit_reverse_sn = circuit_sn.inverse()
circuit = circuit + circuit_reverse_sn
return circuit
#reset first register to [|0>,|0>,|0>,...] (all zeros)
def reset_electrons(circuit,n,m):
circuit.barrier()
for g in range(m):
g_indices = np.arange(g*n,(g+1)*n) #classical register positions for electron g
for g_i in g_indices:
circuit.reset(g_i)
return circuit
#reset all registers except for the main electron register
def reset_ancillas(circuit,n,m,L):
circuit.barrier()
start = n*m
end = get_first_coll_ctrl(n,m,L) + m
for q in range(start,end):
circuit.reset(q)
return circuit
#Perform comparisons between all adjacent electron registers, with ctrl ancilla in the coll_register
def collision_compare(circuit,n,m,L,debug):
#all sets in sets_a can be applied simultaneously (same for sets_b); both for loops are otherwise identical and could be combined
sets_a,sets_b = get_coll_sets(m)
c = 0
for s in sets_a:
circuit_coll_test = initialize_circuit(n,m,L)
i = s[0]
j = s[1]
circuit_coll_test,cbits = compare_n(circuit_coll_test,n,m,i,j,0,L,debug)
x_1 = cbits[0]
y_1 = cbits[1]
coll_anc = get_first_coll_ctrl(n,m,L) + c
cbits = [x_1,y_1,coll_anc]
circuit_coll_test_reverse = circuit_coll_test.inverse()
circuit = circuit + circuit_coll_test
circuit = bit_compare(circuit,cbits,'01',debug)
circuit = circuit + circuit_coll_test_reverse
c+=1
for s in sets_b:
circuit_coll_test = initialize_circuit(n,m,L)
i = s[0]
j = s[1]
circuit_coll_test,cbits = compare_n(circuit_coll_test,n,m,i,j,0,L,debug)
x_1 = cbits[0]
y_1 = cbits[1]
coll_anc = get_first_coll_ctrl(n,m,L) + c
cbits = [x_1,y_1,coll_anc]
circuit_coll_test_reverse = circuit_coll_test.inverse()
circuit = circuit + circuit_coll_test
circuit = bit_compare(circuit,cbits,'01',debug)
circuit = circuit + circuit_coll_test_reverse
c+=1
return circuit
#apply X gate on last qubit, conditioned on all other coll_ancillas being 1 (which means that all elctron registers are different)
def collision_test(circuit,n,m,L,debug):
coll_ctrl_0 = get_first_coll_ctrl(n,m,L)
control = ''
qubits = []
for i in range(m-1):
control = control + '1'
qubits.append(coll_ctrl_0+i)
qubits.append(coll_ctrl_0+m-1)
circuit.append(MCXGate(m-1,ctrl_state=control),qubits)
return circuit
#not necessary
#returns True if output contains only unique elements; returns False otherwise (if two or more elements are the same)
def collision_check_old(output):
if len(output) == len(set(output)):
return True
else:
return False
#Perform measurement on last qubit in coll_register
def measure_collisions(circuit,n,m,L):
#add classical register to store measurement result
c_q = QuantumRegister(0)
c_reg = ClassicalRegister(1,'collision_check')
c = QuantumCircuit(c_q,c_reg)
circuit = circuit.combine(c)
#perform measurements on each electron register and store in separate memorey
circuit.measure(get_first_coll_ctrl(n,m,L) + m - 1, 0)
return circuit
#Add classical registers and apply measurements on the main electron register
def measure_electrons(circuit,n,m):
circuit.barrier()
for g in range(m):
#Add classicla register to store measurement outcomes
c_q = QuantumRegister(0)
c_reg = ClassicalRegister(n,'mem_{}'.format(asc[g]))
c = QuantumCircuit(c_q,c_reg)
circuit = circuit.combine(c)
#perform measurements on each electron register and store in separate memorey
circuit.measure(np.arange(g*n,(g+1)*n),np.arange(g*n + 1,(g+1)*n + 1))
return circuit
#Build the circuit with all gates and measurements
@timeis
def build_circuit(n,m,input,sn,L,debug=True):
#Initialize the circuit with the right number of qubits and ancillas
circuit = initialize_circuit(n,m,L)
#Apply Hadamard gates to each qubit in the first register
circuit = Hadamard(circuit,n,m)
#Apply the sorting network sn
phase = False
circuit = apply_sorting_network(circuit,n,m,sn,L,phase,debug)
#apply comparisons between all adjacent electron registers and store outcome in coll_register
circuit = collision_compare(circuit,n,m,L,debug)
#check if outcome of all comparisons is "not_equal"; flip last qubit in coll_register if this is the case
circuit = collision_test(circuit,n,m,L,debug)
#measure last qubit in coll_register, which stores (no collisions = 1) or (collisions = 0); result is kept until the end of the simulation and result accepted if (no collisions == True)
circuit = measure_collisions(circuit,n,m,L)
#Measurements: classical register 0 stores the random sorted array that can still include collisions
#circuit = measure_electrons(circuit,n,m)
#Reset main electron register
circuit = reset_electrons(circuit,n,m)
#Initialize main electron register in given input product state
circuit = binary_init(circuit,n,m,input)
#Apply the reverse of 'apply_sorting_network' and add a conditioned phase shift after each swap (this antisymmetrizes the input state)
phase = True
circuit = apply_reverse_sorting_network(circuit,n,m,sn,L,phase,debug)
#Reset all ancilla qubits and only keep the main electron register (disable for testing final state for antisymmetry)
#circuit = reset_ancillas(circuit,n,m,L)
#Measure electron register (for testing)
#circuit = measure_electrons(circuit,n,m)
return circuit
#Simulate circuit using specified backend and return simulation result
@timeis
def simulate(circuit,backend,shots):
simulator = Aer.get_backend(backend)
#transpile the circuit into the supported set of gates
circuit = transpile(circuit,backend=simulator)
result = simulator.run(circuit,shots=shots).result()
return result
#turns simulation result 'counts' into list of decimal numbers corresponding to the electron registers; only use if shots=1 or all outcomes are the same
def convert_output_to_decimal(counts,n,m):
output_list = list(counts.keys())[0][::-1]
coll_test = output_list[0]
output_list = output_list[2:]
output = []
offset = 0
for g in range(m):
start = g*n + offset
end = (g+1)*n + offset
g_out = int(output_list[start:end],2)
output.append(g_out)
offset += 1
output_0 = output[0:m]
return coll_test,output_0
#draw the circuit using size,name as input if plot==True
@timeis
def draw_circuit(circuit,plot_scale,fname):
circuit.draw(output='mpl',fold=-1,scale=plot_scale,plot_barriers=True)
plt.savefig(fname,dpi=700)
return 0
def plot_circuit(circuit,plot_scale,fname,plot=True):
if plot:
draw_circuit(circuit,plot_scale,fname)
plt.show()
return 0
print("Plot disabled")
return 0
#plot sorting network by itself, using cnot as directed comparator (only for visualizationo)
def plot_sorting_network(sn,m):
circuit_sn = QuantumCircuit(m)
for s in sn:
if s[2] == 0:
i,j = s[0],s[1]
else:
i,j = s[1],s[0]
circuit_sn.cz(i,j)
circuit_sn.draw(output='mpl')
plt.show()
return 0
#Generate a bitonic sorting network for m electrons; dir=0 (descending), dir=1 (ascending)
def sorting_network_bitonic(m,dir):
sn = []
def compAndSwap(i,j,dir):
sn.append([i,j,dir])
def bitonic_sort(low, cnt, dir):
if cnt>1:
k = cnt//2
dir_n = (dir + 1) % 2
bitonic_sort(low, k, dir_n)#n_dir
bitonic_sort(low + k, cnt-k, dir)#dir
bitonic_merge(low, cnt, dir)
def bitonic_merge(low, cnt, dir):
if cnt>1:
k = greatestPowerOfTwoLessThan(cnt)
i = low
while i < low+cnt-k:
compAndSwap(i, i+k, dir)
i+=1
bitonic_merge(low,k,dir)
bitonic_merge(low+k,cnt-k,dir)
def greatestPowerOfTwoLessThan(cnt):
i=1
while (2**i)<cnt:
i+=1
return 2**(i-1)
bitonic_sort(0,m,dir)
L = len(sn)
return sn,L
#Test if sorting network correctly sorts all possible inputs
def test_sn(sn,n,m):
all_inputs = list(product(range(2**n),repeat=m))
fail = 0
count = 0
for input in all_inputs:
input = np.array(input)
temp = np.copy(input)
for s in sn:
if s[2]==0:
i = s[0]
j = s[1]
if s[2]==1:
i = s[1]
j = s[0]
if input[i]<input[j]:
input[i],input[j] = input[j],input[i]
should_be = np.sort(temp)[::-1]
if (input == should_be).all():
fail += 0
else:
fail += 1
print(f"Testing sorting network {count}/{len(all_inputs)}",end="\r")
count+=1
print(" ", end = "\r")
if fail == 0:
print("Sorting network correct\n")
return 1
else:
print("Error in sorting network\n")
return 0
#Returns all steps of sorting network with corresponding ancilla registers (for testing)
def test_sn_anc(sn,n,m):
for s in sn:
i = s[0]
j = s[1]
anc = get_anc(n,m,i,j)
anc_reg = int((anc-n*m)/(n-1))
print(f"[{i},{j}] anc_reg={anc_reg}")
return 0
#Output density matrix of electron register (target) and compute purity, doesnt actually test antisymmetry yet!
def test_antisymmetry(result,n,m,L):
sv = result.get_statevector()
trace_out = list(np.arange(n*m,get_first_coll_ctrl(n,m,L)+m))
#print(f"Tracing out qubits: {trace_out}")
rho_e = partial_trace(sv,trace_out)
if rho_e.is_valid():
print("Target state is valid density matrix\n")
else:
print("Target state is not valid density matrix")
#print(rho_e)
p = purity(rho_e)
print(f"Purity of target state = {p}\n")
return p
###################MAINPART############################################################################################################
#Parameters
#n: number of qubits per electron; N = 2^n orbitals
n=3
#m: number of electrons
m=4
#input: list of orbitals the electrons are initialized in; needs to be in descending order, without repetitions
input = [5,4,3,2]
#dir: ordering descending (dir=0) or ascending (dir=1)
dir = 0
#plot and save the circuit
plot = True
#include barriers between comparators in the circuit for visualization
debug = False
#measure time of functions: {build_circuit, simulate, draw_circuit}
measure_time = True
#size of the plot
plot_scale = 0.2
#simulation method
backend = 'statevector_simulator'#'aer_simulator'
#number of circuit repetitions in 'simulate'
shots = 1
#check valid inputs
check_inputs(n,m)
#Generate sorting network
sn,L = sorting_network_bitonic(m,dir)
#Test sorting network
test_sn(sn,n,m)
#Plot sorting network
plot_sorting_network(sn,m)
#Build circuit
circuit = build_circuit(n,m,input,sn,L,debug)
#Simulate
result = simulate(circuit,backend,shots)
counts = result.get_counts(circuit)
print(f"Counts: {counts}\n")
#Test if final state is antisymmetric
test_antisymmetry(result,n,m,L)
output_list = list(counts.keys())[0][::-1]
coll_test = output_list[0]
if coll_test == '1':
print("No collisions detected - continue\n")
else:
print("Collisions detected - repeat\n")
#plot circuit
plot_circuit(circuit,plot_scale,f"Plots/Circuit_m{m}_n{n}_debug{debug}",plot)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeManilaV2
from qiskit import transpile
from qiskit.tools.visualization import plot_histogram
# Get a fake backend from the fake provider
backend = FakeManilaV2()
# Create a simple circuit
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(0,2)
circuit.measure_all()
circuit.draw('mpl')
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(circuit, backend)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated fake backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/a24l/IBM_Qiskit_QGSS
|
a24l
|
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# Import qubit states Zero (|0>) and One (|1>), Pauli operators (X, Y, Z), and the identity operator (I)
from qiskit.opflow import Zero, One, X, Y, Z, I
# Returns the XXX Heisenberg model for 3 spin-1/2 particles in a line
def ex1_compute_H_heis3():
# FILL YOUR CODE IN HERE
xspin = (I^X^X)+(X^X^I)
yspin = (I^Y^Y)+(Y^Y^I)
zspin = (I^Z^Z)+(Z^Z^I)
H = xspin + yspin + zspin
# Return Hamiltonian
return H
from qc_grader.challenges.qgss_2022 import grade_lab4_ex1
# The grading function is expecting a PauliSumOp operator
grade_lab4_ex1(ex1_compute_H_heis3())
# Returns the time evolution operator U_heis3(t) for a given time t assuming an XXX Heisenberg Hamiltonian for 3 spins-1/2 particles in a line
def ex2_compute_U_heis3(t):
# FILL YOUR CODE IN HERE
U=(ex1_compute_H_heis3()*t).exp_i()
return U
from qc_grader.challenges.qgss_2022 import grade_lab4_ex2
# The grading function is expecting a funtion that returns PauliSumOp operator
grade_lab4_ex2(ex2_compute_U_heis3)
# Define array of time points
ts = np.linspace(0, np.pi, 100)
# Define initial state |110>
initial_state = One^One^Zero
# Compute probability of remaining in |110> state over the array of time points
# ~initial_state gives the bra of the initial state (<110|)
# @ is short hand for matrix multiplication
# ex2_compute_U_heis3(t) is the unitary time evolution at time t
# t needs to be wrapped with float(t) to avoid a bug
# (...).eval() returns the inner product <110|ex2_compute_U_heis3(t)|110>
# np.abs(...)**2 is the modulus squared of the innner product which is the expectation value, or probability, of remaining in |110>
probs_110 = [np.abs((~initial_state @ ex2_compute_U_heis3(float(t)) @ initial_state).eval())**2 for t in ts]
# Plot evolution of |110>
plt.figure(facecolor='white')
plt.plot(ts, probs_110, linewidth=2)
plt.xlabel('time')
plt.ylabel(r'probability of state $|110\rangle$')
plt.title(r'Evolution of state $|110\rangle$ under $H_{Heis3}$')
plt.ylim([-0.05,1.05])
plt.grid()
plt.show()
import qiskit
qiskit.__version__
pip install qiskit-ignis
# Importing standard Qiskit modules
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# load IBMQ Account data
# IBMQ.save_account(TOKEN) # replace TOKEN with your API token string (https://quantum-computing.ibm.com/lab/docs/iql/manage/account/ibmq)
provider = IBMQ.load_account()
# Get backend for experiment
provider = IBMQ.get_provider(hub='ibm-q')
manila = provider.get_backend('ibmq_manila')
# properties = manila.properties()
# Simulated backend based on ibmq_manila's device noise profile
sim_noisy_manila = QasmSimulator.from_backend(provider.get_backend('ibmq_manila'))
# Noiseless simulated backend
sim = QasmSimulator()
# Parameterize variable t to be evaluated at t=pi later
t = Parameter('t')
# Build a subcircuit for XX(t) two-qubit gate
def compute_XX_gate(t):
XX_qr = QuantumRegister(2)
XX_qc = QuantumCircuit(XX_qr, name='XX')
XX_qc.ry(np.pi/2,[0,1])
XX_qc.cnot(0,1)
XX_qc.rz(2 * t, 1)
XX_qc.cnot(0,1)
XX_qc.ry(-np.pi/2,[0,1])
# Convert custom quantum circuit into a gate
XX = XX_qc.to_instruction()
return XX
# Build a subcircuit for YY(t) two-qubit gate
def ex3_compute_YY_gate(t):
# FILL YOUR CODE IN HERE
YY_qr = QuantumRegister(2)
YY_qc = QuantumCircuit(YY_qr, name='YY')
YY_qc.rx(np.pi/2,[0,1])
YY_qc.cnot(0,1)
YY_qc.rz(2 * t, 1)
YY_qc.cnot(0,1)
YY_qc.rx(-np.pi/2,[0,1])
# Convert custom quantum circuit into a gate
YY = YY_qc.to_instruction()
return YY
from qc_grader.challenges.qgss_2022 import grade_lab4_ex3
# The grading function is expecting an Instruction
grade_lab4_ex3(ex3_compute_YY_gate(t))
# Build a subcircuit for ZZ(t) two-qubit gate
def ex4_compute_ZZ_gate(t):
# FILL YOUR CODE IN HERE
ZZ_qr = QuantumRegister(2)
ZZ_qc = QuantumCircuit(ZZ_qr, name='ZZ')
ZZ_qc.cnot(0,1)
ZZ_qc.rz(2 * t, 1)
ZZ_qc.cnot(0,1)
# Convert custom quantum circuit into a gate
ZZ = ZZ_qc.to_instruction()
return ZZ
from qc_grader.challenges.qgss_2022 import grade_lab4_ex4
# The grading function is expecting an Instruction
grade_lab4_ex4(ex4_compute_ZZ_gate(t))
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# Define two-qubit interactions Parameterized by t
XX = compute_XX_gate(t)
YY = ex3_compute_YY_gate(t)
ZZ = ex4_compute_ZZ_gate(t)
Trot_qr = QuantumRegister(num_qubits)
Trot_qc = QuantumCircuit(Trot_qr, name='Trot')
for i in range(0, num_qubits - 1):
Trot_qc.append(ZZ, [Trot_qr[i], Trot_qr[i+1]])
Trot_qc.append(YY, [Trot_qr[i], Trot_qr[i+1]])
Trot_qc.append(XX, [Trot_qr[i], Trot_qr[i+1]])
# Convert custom quantum circuit into a gate
Trot_gate = Trot_qc.to_instruction()
# Setup experiment parameters
# The final time of the state evolution
target_time = np.pi # DO NOT MODIFY
# Number of trotter steps
trotter_steps = 4 ### CAN BE >= 4
# Select which qubits to use for the simulation
q_regs = [0,1,2]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(5)
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on manila qubits (q_5, q_3, q_1) corresponding to the state |110>)
qc.x([q_regs[2], q_regs[1]]) # For example this could be (q_regs=[2, 1, 0] which corresponds to => |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, q_regs)
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({t: target_time/trotter_steps})
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, q_regs)
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw() # only view trotter gates
shots = 8192
reps = 4
# Pick the simulated or real backend for manila
backend = sim # Noiseless simulator
# backend = sim_noisy_manila # Simulator that mimics ibmq_manila
# backend = manila # The real manila backend
jobs = []
for _ in range(reps):
# Execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
for job in jobs:
job_monitor(job)
try:
if job.error_message() is not None:
print(job.error_message())
except:
pass
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Compute tomography fidelities for each repetition
fids = []
for job in jobs:
fid = state_tomo(job.result(), st_qcs)
fids.append(fid)
# Share tomography fidelity of discord to compete and collaborate with other students
print('state tomography fidelity on ' + str(backend) + ' = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
# Share what lectures and techniques were useful in optimizing your results
print('Inspiration: Measurement error mitigation, Olivia Lanes\'s 2nd lecture')
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
"""Tests for qiskit.quantum_info.analysis"""
import unittest
import qiskit
from qiskit import BasicAer
from qiskit.quantum_info.analysis.average import average_data
from qiskit.quantum_info.analysis.make_observable import make_dict_observable
from qiskit.quantum_info.analysis import hellinger_fidelity
from qiskit.test import QiskitTestCase
class TestAnalyzation(QiskitTestCase):
"""Test qiskit.Result API"""
def test_average_data_dict_observable(self):
"""Test average_data for dictionary observable input"""
qr = qiskit.QuantumRegister(2)
cr = qiskit.ClassicalRegister(2)
qc = qiskit.QuantumCircuit(qr, cr, name="qc")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
shots = 10000
backend = BasicAer.get_backend("qasm_simulator")
result = qiskit.execute(qc, backend, shots=shots).result()
counts = result.get_counts(qc)
observable = {"00": 1, "11": 1, "01": -1, "10": -1}
mean_zz = average_data(counts=counts, observable=observable)
observable = {"00": 1, "11": -1, "01": 1, "10": -1}
mean_zi = average_data(counts, observable)
observable = {"00": 1, "11": -1, "01": -1, "10": 1}
mean_iz = average_data(counts, observable)
self.assertAlmostEqual(mean_zz, 1, places=1)
self.assertAlmostEqual(mean_zi, 0, places=1)
self.assertAlmostEqual(mean_iz, 0, places=1)
def test_average_data_list_observable(self):
"""Test average_data for list observable input."""
qr = qiskit.QuantumRegister(3)
cr = qiskit.ClassicalRegister(3)
qc = qiskit.QuantumCircuit(qr, cr, name="qc")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.cx(qr[0], qr[2])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
shots = 10000
backend = BasicAer.get_backend("qasm_simulator")
result = qiskit.execute(qc, backend, shots=shots).result()
counts = result.get_counts(qc)
observable = [1, -1, -1, 1, -1, 1, 1, -1]
mean_zzz = average_data(counts=counts, observable=observable)
observable = [1, 1, 1, 1, -1, -1, -1, -1]
mean_zii = average_data(counts, observable)
observable = [1, 1, -1, -1, 1, 1, -1, -1]
mean_izi = average_data(counts, observable)
observable = [1, 1, -1, -1, -1, -1, 1, 1]
mean_zzi = average_data(counts, observable)
self.assertAlmostEqual(mean_zzz, 0, places=1)
self.assertAlmostEqual(mean_zii, 0, places=1)
self.assertAlmostEqual(mean_izi, 0, places=1)
self.assertAlmostEqual(mean_zzi, 1, places=1)
def test_average_data_matrix_observable(self):
"""Test average_data for matrix observable input."""
qr = qiskit.QuantumRegister(2)
cr = qiskit.ClassicalRegister(2)
qc = qiskit.QuantumCircuit(qr, cr, name="qc")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
shots = 10000
backend = BasicAer.get_backend("qasm_simulator")
result = qiskit.execute(qc, backend, shots=shots).result()
counts = result.get_counts(qc)
observable = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]
mean_zz = average_data(counts=counts, observable=observable)
observable = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]
mean_zi = average_data(counts, observable)
observable = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]
mean_iz = average_data(counts, observable)
self.assertAlmostEqual(mean_zz, 1, places=1)
self.assertAlmostEqual(mean_zi, 0, places=1)
self.assertAlmostEqual(mean_iz, 0, places=1)
def test_make_dict_observable(self):
"""Test make_dict_observable."""
list_in = [1, 1, -1, -1]
list_out = make_dict_observable(list_in)
list_expected = {"00": 1, "01": 1, "10": -1, "11": -1}
matrix_in = [[4, 0, 0, 0], [0, -3, 0, 0], [0, 0, 2, 0], [0, 0, 0, -1]]
matrix_out = make_dict_observable(matrix_in)
matrix_expected = {"00": 4, "01": -3, "10": 2, "11": -1}
long_list_in = [1, 1, -1, -1, -1, -1, 1, 1]
long_list_out = make_dict_observable(long_list_in)
long_list_expected = {
"000": 1,
"001": 1,
"010": -1,
"011": -1,
"100": -1,
"101": -1,
"110": 1,
"111": 1,
}
self.assertEqual(list_out, list_expected)
self.assertEqual(matrix_out, matrix_expected)
self.assertEqual(long_list_out, long_list_expected)
def test_hellinger_fidelity_same(self):
"""Test hellinger fidelity is one for same dist."""
qc = qiskit.QuantumCircuit(5, 5)
qc.h(2)
qc.cx(2, 1)
qc.cx(2, 3)
qc.cx(3, 4)
qc.cx(1, 0)
qc.measure(range(5), range(5))
sim = BasicAer.get_backend("qasm_simulator")
res = qiskit.execute(qc, sim).result()
ans = hellinger_fidelity(res.get_counts(), res.get_counts())
self.assertEqual(ans, 1.0)
def test_hellinger_fidelity_no_overlap(self):
"""Test hellinger fidelity is zero for no overlap."""
# ┌───┐ ┌─┐
# q_0: ──────────┤ X ├─────┤M├────────────
# ┌───┐└─┬─┘ └╥┘┌─┐
# q_1: ─────┤ X ├──■────────╫─┤M├─────────
# ┌───┐└─┬─┘ ║ └╥┘┌─┐
# q_2: ┤ H ├──■────■────────╫──╫─┤M├──────
# └───┘ ┌─┴─┐ ║ ║ └╥┘┌─┐
# q_3: ──────────┤ X ├──■───╫──╫──╫─┤M├───
# └───┘┌─┴─┐ ║ ║ ║ └╥┘┌─┐
# q_4: ───────────────┤ X ├─╫──╫──╫──╫─┤M├
# └───┘ ║ ║ ║ ║ └╥┘
# c: 5/═════════════════════╩══╩══╩══╩══╩═
# 0 1 2 3 4
qc = qiskit.QuantumCircuit(5, 5)
qc.h(2)
qc.cx(2, 1)
qc.cx(2, 3)
qc.cx(3, 4)
qc.cx(1, 0)
qc.measure(range(5), range(5))
# ┌───┐ ┌─┐
# q_0: ──────────┤ X ├─────┤M├─────────
# ┌───┐└─┬─┘ └╥┘┌─┐
# q_1: ─────┤ X ├──■────────╫─┤M├──────
# ┌───┐└─┬─┘┌───┐ ║ └╥┘┌─┐
# q_2: ┤ H ├──■──┤ Y ├──■───╫──╫─┤M├───
# └───┘ └───┘┌─┴─┐ ║ ║ └╥┘┌─┐
# q_3: ───────────────┤ X ├─╫──╫──╫─┤M├
# ┌─┐ └───┘ ║ ║ ║ └╥┘
# q_4: ─┤M├─────────────────╫──╫──╫──╫─
# └╥┘ ║ ║ ║ ║
# c: 5/══╩══════════════════╩══╩══╩══╩═
# 4 0 1 2 3
qc2 = qiskit.QuantumCircuit(5, 5)
qc2.h(2)
qc2.cx(2, 1)
qc2.y(2)
qc2.cx(2, 3)
qc2.cx(1, 0)
qc2.measure(range(5), range(5))
sim = BasicAer.get_backend("qasm_simulator")
res1 = qiskit.execute(qc, sim).result()
res2 = qiskit.execute(qc2, sim).result()
ans = hellinger_fidelity(res1.get_counts(), res2.get_counts())
self.assertEqual(ans, 0.0)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
qrx = QuantumRegister(3, 'x')
qry = QuantumRegister(1, 'y')
cr = ClassicalRegister(3, 'c')
qc = QuantumCircuit(qrx, qry, cr)
qc.h(qrx)
qc.x(qry)
qc.h(qry)
qc.barrier()
qc.x(qry)
qc.barrier()
qc.h(qrx)
qc.h(qry)
qc.measure(qrx, cr)
qc.draw("mpl")
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
state = Statevector(qc)
plot_bloch_multivector(state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
pip install qiskit
import qiskit
qiskit.__qiskit_version__
pip install qiskit-ibm-runtime
from qiskit_ibm_runtime import QiskitRuntimeService
QiskitRuntimeService.save_account(channel="ibm_quantum", token="463bc61b55d82149a7ec719c9e89eeb8bc80a916eac5331f2d98fc35be2b4650af627d457593b0050910aa0bd4a0f1e3a8361ff25874d214f01640e55e571d27")
from qiskit.test.reference_circuits import ReferenceCircuits
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler
service = QiskitRuntimeService()
backend = service.backend("ibmq_qasm_simulator")
job = Sampler(backend).run(ReferenceCircuits.bell())
print(f"job id: {job.job_id()}")
result = job.result()
print(result)
# General
import numpy as np
# Qiskit imports
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.quantum_info import SparsePauliOp
# Runtime imports
from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session
# Plotting routines
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
# Add your token below
service = QiskitRuntimeService(channel="ibm_quantum")
# Select the system with the fewest number of jobs in the queue
backend = service.least_busy(simulator=False, operational=True)
# Initialize your session
session = Session(backend=backend)
backend.name
theta = Parameter("$\\theta$")
chsh_circuit_no_meas = QuantumCircuit(2)
chsh_circuit_no_meas.h(0)
chsh_circuit_no_meas.cx(0, 1)
chsh_circuit_no_meas.ry(theta, 0)
chsh_circuit_no_meas.draw()
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]
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]
num_ops = len(ops)
batch_circuits = [chsh_circuit_no_meas] * number_of_phases * num_ops
batch_ops = [op for op in ops for _ in individual_phases]
estimator = Estimator(session=session)
batch_expvals = (
estimator.run(
batch_circuits, batch_ops, parameter_values=individual_phases * num_ops, shots=int(1e4)
)
.result()
.values
)
ZZ_expval, ZX_expval, XZ_expval, XX_expval = [
batch_expvals[kk * number_of_phases : (kk + 1) * number_of_phases] for kk in range(num_ops)
]
# <CHSH1> = <AB> - <Ab> + <aB> + <ab>
chsh1_est = ZZ_expval - ZX_expval + XZ_expval + XX_expval
# <CHSH2> = <AB> + <Ab> - <aB> + <ab>
chsh2_est = ZZ_expval + ZX_expval - XZ_expval + XX_expval
fig, ax = plt.subplots(figsize=(10, 6))
# results from hardware
ax.plot(phases / np.pi, chsh1_est, "o-", label="CHSH1", zorder=3)
ax.plot(phases / np.pi, chsh2_est, "o-", label="CHSH2", zorder=3)
# classical bound +-2
ax.axhline(y=2, color="0.9", linestyle="--")
ax.axhline(y=-2, color="0.9", linestyle="--")
# quantum bound, +-2√2
ax.axhline(y=np.sqrt(2) * 2, color="0.9", linestyle="-.")
ax.axhline(y=-np.sqrt(2) * 2, color="0.9", linestyle="-.")
ax.fill_between(phases / np.pi, 2, 2 * np.sqrt(2), color="0.6", alpha=0.7)
ax.fill_between(phases / np.pi, -2, -2 * np.sqrt(2), color="0.6", alpha=0.7)
# 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(f"Violation of CHSH Inequality")
plt.xlabel("Theta")
plt.ylabel("CHSH witness")
plt.legend()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from initialize import *
my_algorithm = initialize(circuit_name = 'demo', qubit_number=2, bit_number=2, backend = 'local_qasm_simulator', shots = 1024)
#Append sequence of gates to the quantum circuit.
#For each gate, the qubits on which it is acting must be specified along with other gate-dependent parameters
my_algorithm.q_circuit.x(my_algorithm.q_reg[0]) # apply the X gate to the first qubit
my_algorithm.q_circuit.x(my_algorithm.q_reg[1]) # apply the X gate to the second qubit
my_algorithm.q_circuit.h(my_algorithm.q_reg[0]) # apply the Hadamard gate to the first qubit
my_algorithm.q_circuit.cx(my_algorithm.q_reg[0],my_algorithm.q_reg[1]) # apply the CNOT gate using the first qubit as control and second qubit as target
my_algorithm.q_circuit.measure(my_algorithm.q_reg[0], my_algorithm.c_reg[0]) # measures the first qubit and store the result in the first bit
my_algorithm.q_circuit.measure(my_algorithm.q_reg[1], my_algorithm.c_reg[1]) # measures the second qubit and store the result in the second bit
print('List of gates:')
for circuit in my_algorithm.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_algorithm.Q_program.execute(my_algorithm.circ_name, backend=my_algorithm.backend, shots= my_algorithm.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_algorithm.circ_name) ## you can declare/initiate q_name first at the time you initialize circuit,
print('\nThe measured outcomes of the circuits are:',counts)
from initialize import *
#initialize quantum program
my_alg = initialize(circuit_name = 'multi', qubit_number=7, bit_number=7, backend = 'local_qasm_simulator', shots = 1024)
#add gates to the circuit
my_alg.q_circuit.x(my_alg.q_reg[1]) # applies X gate to second qubit
my_alg.q_circuit.x(my_alg.q_reg[3]) # applies X gate to fourth qubit
my_alg.q_circuit.x(my_alg.q_reg[5]) # applies X gate to sixth qubit
my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit
my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures the second qubit and store the result in the second bit
my_alg.q_circuit.measure(my_alg.q_reg[2], my_alg.c_reg[2]) # measures the third qubit and store the result in the third bit
my_alg.q_circuit.measure(my_alg.q_reg[3], my_alg.c_reg[3]) # measures the fourth qubit and store the result in the fourth bit
my_alg.q_circuit.measure(my_alg.q_reg[4], my_alg.c_reg[4]) # measures the fifth qubit and store the result in the fifth bit
my_alg.q_circuit.measure(my_alg.q_reg[5], my_alg.c_reg[5]) # measures the sixth qubit and store the result in the sixth bit
my_alg.q_circuit.measure(my_alg.q_reg[6], my_alg.c_reg[6]) # measures the seventh qubit and store the result in the seventh bit
print('List of gates:')
for circuit in my_alg.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_alg.circ_name)
print('\nThe measured outcomes of the circuits are:',counts)
from initialize import *
#initialize quantum program
my_alg = initialize(circuit_name = 'multi_super', qubit_number=2, bit_number=2, backend = 'local_qasm_simulator', shots = 1024)
#add gates to the circuit
my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit
my_alg.q_circuit.h(my_alg.q_reg[1]) # applies X gate to second qubit
my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit
my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures the second qubit and store the result in the second bit
print('List of gates:')
for circuit in my_alg.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_alg.circ_name)
print('\nThe measured outcomes of the circuits are:',counts)
from initialize import *
#initialize quantum program
my_alg = initialize(circuit_name = 'bell', qubit_number=2, bit_number=2, backend = 'local_qasm_simulator', shots = 1024)
#add gates to the circuit
my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit
my_alg.q_circuit.cx(my_alg.q_reg[0],my_alg.q_reg[1]) # applies CX gate using the first qubit as control and the second qubit as target
my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit
my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures the second qubit and store the result in the second bit
print('List of gates:')
for circuit in my_alg.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_alg.circ_name)
print('\nThe measured outcomes of the circuits are:',counts)
from initialize import *
#initialize quantum program
my_alg = initialize(circuit_name = 'x_gate', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1024)
#add gates to the circuit
my_alg.q_circuit.x(my_alg.q_reg[0]) # applies X gate to first qubit
my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit
print('List of gates:')
for circuit in my_alg.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_alg.circ_name)
print('\nThe measured outcomes of the circuits are:',counts)
from initialize import *
#initialize quantum program
my_alg = initialize(circuit_name = 'y_gate', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1024)
#add gates to the circuit
my_alg.q_circuit.y(my_alg.q_reg[0]) # applies Y gate to first qubit
my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit
print('List of gates:')
for circuit in my_alg.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_alg.circ_name)
print('\nThe measured outcomes of the circuits are:',counts)
from initialize import *
#initialize quantum program
my_alg = initialize(circuit_name = 'h_gate', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1024)
#add gates to the circuit
my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit
my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit
print('List of gates:')
for circuit in my_alg.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_alg.circ_name)
print('\nThe measured outcomes of the circuits are:',counts)
from initialize import *
#initialize quantum program
my_alg = initialize(circuit_name = 'rx_gate', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1024)
theta = 0.79 # angle of rotation pi/4
#add gates to the circuit
my_alg.q_circuit.rx(theta, my_alg.q_reg[0]) # applies x-rotation of angle theta to first qubit
my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit
print('List of gates:')
for circuit in my_alg.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_alg.circ_name)
print('\nThe measured outcomes of the circuits are:',counts)
from initialize import *
for _ in range(4): # run over all possible initial states of two qubits
#initialize quantum program
my_alg = initialize(circuit_name = 'cx_gate', qubit_number=2, bit_number=2, backend = 'local_qasm_simulator', shots = 1024)
#add gates to the circuit
if _ == 1:
my_alg.q_circuit.x(my_alg.q_reg[0]) # applies X gate to first qubit (prepares state 10)
if _ == 2:
my_alg.q_circuit.x(my_alg.q_reg[1]) # applies X gate to second qubit (prepares state 01)
if _ == 3:
my_alg.q_circuit.x(my_alg.q_reg[0]) # applies X gate to first qubit
my_alg.q_circuit.x(my_alg.q_reg[1]) # applies X gate to second qubit (prepares state 11)
my_alg.q_circuit.cx(my_alg.q_reg[0],my_alg.q_reg[1]) ## applies CX gate using the first qubit as control and the second qubit as target
my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit
my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures the second qubit and store the result in the second bit
print('List of gates:')
for circuit in my_alg.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_alg.circ_name)
print('\nThe measured outcomes of the circuits are:',counts)
from initialize import *
#initialize quantum program
my_alg = initialize(circuit_name = 'evo_1', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1024)
#add gates to the circuit
my_alg.q_circuit.iden(my_alg.q_reg[0]) # applies U1
my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit
print('List of gates:')
for circuit in my_alg.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_alg.circ_name)
print('\nThe measured outcomes of the circuits are:',counts)
from initialize import *
#initialize quantum program
my_alg = initialize(circuit_name = 'evo_2', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1024)
#add gates to the circuit
my_alg.q_circuit.iden(my_alg.q_reg[0])
my_alg.q_circuit.x(my_alg.q_reg[0]) # applies U2
my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit
print('List of gates:')
for circuit in my_alg.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_alg.circ_name)
print('\nThe measured outcomes of the circuits are:',counts)
from initialize import *
#initialize quantum program
my_alg = initialize(circuit_name = 'evo_3', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1024)
#add gates to the circuit
my_alg.q_circuit.iden(my_alg.q_reg[0])
my_alg.q_circuit.x(my_alg.q_reg[0])
my_alg.q_circuit.x(my_alg.q_reg[0]) # applies U3
my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit
print('List of gates:')
for circuit in my_alg.q_circuit:
print(circuit.name)
#Execute the quantum algorithm
result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots)
#Show the results obtained from the quantum algorithm
counts = result.get_counts(my_alg.circ_name)
print('\nThe measured outcomes of the circuits are:',counts)
|
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/Simultonian/hamilutor-qiskit
|
Simultonian
|
from qiskit import QuantumCircuit
from ..grouping.bitwise import Bitwise
from .group_trotter import generic
from ..ordering import lexico
def bitwise_simple(
h: dict[str, float], t: float = 1.0, reps: int = 1
) -> QuantumCircuit:
"""
Takes in a Hamiltonian and constructs the simple Trotterization circuit
after grouping the terms using bitwise Pauli grouping.
Inputs:
- h: Hamiltonian in dictionary form.
- t: Float representing time of evolution.
- reps: Repetitions for Trotterization.
Returns: QuantumCircuit that will simulate the Hamiltonian
"""
return generic(Bitwise, lexico, h, t, reps)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
# with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
# with open(filename, "wb") as f:
# pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
# with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump(backend.properties(), f)
retrieved_jobs = jobs
retrieved_cal_job = cal_job
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/bagmk/qiskit-quantum-state-classifier
|
bagmk
| |
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
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/IceKhan13/QiskitFlow
|
IceKhan13
|
'''
This is a implementation of the quantum teleportation algorithm
'''
from qiskit import *
from qiskit.visualization import plot_histogram
import os, shutil, numpy
from matplotlib.pyplot import plot, draw, show
LaTex_folder_Quantum_Teleportation = str(os.getcwd())+'/Latex_quantum_gates/Quantum_Teleportation/'
if not os.path.exists(LaTex_folder_Quantum_Teleportation):
os.makedirs(LaTex_folder_Quantum_Teleportation)
else:
shutil.rmtree(LaTex_folder_Quantum_Teleportation)
os.makedirs(LaTex_folder_Quantum_Teleportation)
qc = QuantumCircuit(3,3)
## prepare the state to be teleported
phi = 0*numpy.pi
theta= 0.5*numpy.pi
lam = 0*numpy.pi
qc.u(phi=phi, theta=theta,lam=lam,qubit=0)
## teleport the state
qc.barrier()
qc.h(1)
qc.cx(1,2)
qc.cz(0,1)
qc.h(0)
qc.h(1)
qc.barrier()
qc.measure([0,1],[0,1])
qc.barrier()
qc.x(2).c_if(0,1)
qc.z(2).c_if(1,1)
qc.h(2)
qc.measure(2,2)
LaTex_code = qc.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'quantum_teleportation.tex'
with open(LaTex_folder_Quantum_Teleportation+f_name, 'w') as f:
f.write(LaTex_code)
# simulation
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend=simulator, shots=100000).result()
counts = {'0':0,
'1': 0}
print(result.get_counts().keys())
for key, value in result.get_counts().items():
if(key[0] == '0'):
counts['0'] += value
else:
counts['1'] += value
print(counts)
plt = plot_histogram(counts)
draw()
show(block=True)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/mgg39/qiskit-networks
|
mgg39
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(3, 'q')
anc = QuantumRegister(1, 'ancilla')
cr = ClassicalRegister(3, 'c')
qc = QuantumCircuit(qr, anc, cr)
qc.x(anc[0])
qc.h(anc[0])
qc.h(qr[0:3])
qc.cx(qr[0:3], anc[0])
qc.h(qr[0:3])
qc.barrier(qr)
qc.measure(qr, cr)
qc.draw('mpl')
|
https://github.com/baronefr/perceptron-dqa
|
baronefr
|
# ====================================================
# Quantum Information and Computing exam project
#
# UNIPD Project | AY 2022/23 | QIC
# group : Barone, Coppi, Zinesi
# ----------------------------------------------------
# > description |
#
# class setup of dQA execution
# ----------------------------------------------------
# coder : Zinesi Paolo
# dated : 27 March 2023
# ver : 1.0.0
# ====================================================
from qiskit import QuantumCircuit, QuantumRegister, AncillaRegister
from qiskit.circuit.library import QFT, IntegerComparator
import numpy as np
class HammingEvolution:
"""
Class to generate all the modules of Heaviside evolution circuit consistently.
"""
def __init__(self, num_data_qubits : int) -> None:
# infer number ancillas used to count, number of ancillas used to compare Hamming distance
self._num_data_qubits = num_data_qubits
self._num_count_ancillas = int(np.ceil(np.log2(self._num_data_qubits+1)))
# in this situation the comparison is really simple
self._simple_compare = (self._num_data_qubits + 1 == 2**self._num_count_ancillas)
# circuit initializer
self._data_qubits = QuantumRegister(self._num_data_qubits)
self._count_ancillas = AncillaRegister(self._num_count_ancillas)
self._qc = QuantumCircuit(self._data_qubits, self._count_ancillas)
# intialize comparison ancillas if necessary
if not self._simple_compare:
self._num_comp_ancillas = self._num_count_ancillas
self._comp_ancillas = AncillaRegister(self._num_count_ancillas)
self._qc.add_register(self._comp_ancillas)
# ancilla in which the Heaviside control will be stored
if self._simple_compare:
self._control_ancilla = self._count_ancillas[-1]
else:
self._control_ancilla = self._comp_ancillas[0]
@property
def num_data_qubits(self):
return self._num_data_qubits
@property
def num_count_ancillas(self):
return self._num_count_ancillas
@property
def simple_compare(self):
return self._simple_compare
@property
def data_qubits(self):
return self._data_qubits
@property
def count_ancillas(self):
return self._count_ancillas
@property
def qc(self):
return self._qc.copy()
@property
def num_comp_ancillas(self):
if self._simple_compare:
return 0
else:
return self._num_comp_ancillas
@property
def comp_ancillas(self):
if self._simple_compare:
return []
else:
return self._comp_ancillas
@property
def num_ancillas(self):
return self.num_count_ancillas + self.num_comp_ancillas
@property
def ancillas(self):
return list(self.count_ancillas) + list(self.comp_ancillas)
@property
def qubits(self):
return list(self.data_qubits) + list(self.count_ancillas) + list(self.comp_ancillas)
@property
def control_ancilla(self):
return self._control_ancilla
def init_state_plus(self):
"""
Generate a circuit where all the qubits are initialized at |+> = H|0> intead of simply |0>.
"""
# return a new copy of the circuit, but with the same number of qubits for consistency
circ = self.qc.copy()
for iq in range(self.num_data_qubits):
circ.h(self.data_qubits[iq])
return circ
def Hamming_count(self, train_data):
"""
Generate circuit of `self.num_data_qubits` qubits that counts the Hamming distance from the training data.
The count is stored in the `self.count_ancillas` qubits.
- train_data: vector of training data.
Conventions:
- (1,-1) <--> (|0>,|1>)
- little endians: least significant bit is the last one of the string
"""
assert len(train_data) == self.num_data_qubits, "Wrong dimension of training data"
# return a new copy of the circuit, but with the same number of qubits for consistency
circ = self.qc.copy()
# flip only when the training data is -1: in this way the circuit can simply count the number
# of states that are |1>
# little endians convention is applied !!! train_data[::-1] !!!
for iq, train_data_i in enumerate(train_data[::-1]):
if train_data_i == -1:
circ.x(self.data_qubits[iq])
# initial Hadamards to create superposition in the counter register
for ia in range(self.num_count_ancillas):
circ.h(self.count_ancillas[ia])
# Phase estimation
for ia in range(self.num_count_ancillas):
# the order is from the lowest index of the ancilla to the highest
n_reps = 2**ia
# repeat n_reps times the application of the unitary gate controlled on the ancillary qubit
for rep_idx in range(n_reps):
for iq in range(self.num_data_qubits):
circ.cp(2*np.pi/2**self.num_count_ancillas, self.count_ancillas[ia], self.data_qubits[iq])
# invert flip applied previously to count the number of |1>
# little endians convention is applied !!! train_data[::-1] !!!
for iq, train_data_i in enumerate(train_data[::-1]):
if train_data_i == -1:
circ.x(self.data_qubits[iq])
circ.barrier()
qft_circ = QFT(self.num_count_ancillas, inverse=True).decompose(reps=1)
circ = circ.compose(qft_circ, self.count_ancillas)
# add an additional comparison circuit if needed
if not self.simple_compare:
circ = circ.compose(IntegerComparator(self.num_count_ancillas, int(np.ceil(self.num_data_qubits/2.0)), geq=True).decompose(reps=1),
qubits=self.ancillas)
return circ
def U_z(self, train_data, gamma):
"""
Generate circuit for Uz evolution according to the training data and the value of gamma.
- train_data: vector of training data.
- gamma: multiplicative float in the time evolution definition.
Conventions:
- (1,-1) <--> (|0>,|1>)
- little endians: least significant bit is the last one of the string
"""
assert len(train_data) == self.num_data_qubits, "Wrong dimension of training data"
# return a new copy of the circuit, but with the same number of qubits for consistency
circ = self.qc.copy()
circ.barrier()
# define controlled operation on the 'ancilla_index'
# little endians convention is applied !!! iq and idata goes on opposite directions !!!
for iq, idata in zip(range(self.num_data_qubits),range(len(train_data)-1,-1,-1)):
circ.crz(-2*gamma*train_data[idata]/np.sqrt(self.num_data_qubits), self.control_ancilla, self.data_qubits[iq])
circ.barrier()
return circ
def U_x(self, beta):
"""
Generate circuit for Ux evolution according to the value of beta.
- beta: multiplicative float in the time evolution definition.
"""
# return a new copy of the circuit, but with the same number of qubits for consistency
circ = self.qc.copy()
circ.barrier()
for iq in range(self.num_data_qubits):
circ.rx(-2*beta, self.data_qubits[iq])
return circ
def single_step_composer(self, qc, dataset, beta_p : float, gamma_p : float, tracking_function = None):
"""Define how a circuit is composed for each step in dQA."""
if qc is None: qc = self.qc.copy()
for mu in range( dataset.shape[0] ):
# create Hamming error counter circuit based on the given pattern
qc_counter = self.Hamming_count(train_data = dataset[mu,:])
qc_counter_inverse = qc_counter.inverse()
# create Uz evolution circuit
qc_Uz = self.U_z(train_data = dataset[mu,:], gamma=gamma_p)
# compose all circuits to evolve according to Uz
qc.compose(qc_counter, inplace=True)
qc.compose(qc_Uz, inplace=True)
qc.compose(qc_counter_inverse, inplace=True)
# create and apply Ux evolution circuit
qc_Ux = self.U_x(beta_p)
qc.compose(qc_Ux, inplace=True)
if tracking_function is not None:
tracking_function( [qc_counter, qc_Uz, qc_counter_inverse, qc_Ux], compose=True)
return qc
|
https://github.com/usamisaori/quantum-expressibility-entangling-capability
|
usamisaori
|
import numpy as np
import qiskit
from qiskit import QuantumCircuit
import matplotlib.pyplot as plt
from qiskit.circuit import QuantumCircuit, Parameter
import warnings
warnings.filterwarnings('ignore')
theta = Parameter("θ")
phi = Parameter("φ")
lamb = Parameter("λ")
def sampleCircuitA(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for i in range(qubits - 1):
circuit.cx(i, i + 1)
circuit.cx(qubits - 1, 0)
for i in range(qubits - 1):
circuit.cx(i, i + 1)
circuit.cx(qubits - 1, 0)
circuit.barrier()
for i in range(qubits):
circuit.u3(theta, phi, lamb, i)
return circuit
circuitA = sampleCircuitA(qubits=4)
circuitA.draw(output='mpl')
def sampleCircuitB1(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u1(theta, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u1(theta, j)
return circuit
def sampleCircuitB2(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u2(phi, lamb, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u2(phi, lamb, j)
return circuit
def sampleCircuitB3(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u3(theta, phi, lamb, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u3(theta, phi, lamb, j)
return circuit
circuitB1 = sampleCircuitB1(qubits=4)
circuitB1.draw(output='mpl')
circuitB2 = sampleCircuitB2(qubits=4)
circuitB2.draw(output='mpl')
circuitB3 = sampleCircuitB3(qubits=4)
circuitB3.draw(output='mpl')
def sampleCircuitC(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.ry(theta, j)
circuit.crx(theta, qubits - 1, 0)
for j in range(qubits - 1, 0, -1):
circuit.crx(theta, j - 1, j)
circuit.barrier()
for j in range(qubits):
circuit.ry(theta, j)
circuit.crx(theta, 3, 2)
circuit.crx(theta, 0, 3)
circuit.crx(theta, 1, 0)
circuit.crx(theta, 2, 1)
return circuit
circuitC = sampleCircuitC(qubits=4)
circuitC.draw(output='mpl')
def sampleCircuitD(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(qubits - 1, -1, -1):
for k in range(qubits - 1, -1, -1):
if j != k:
circuit.crx(theta, j, k)
circuit.barrier()
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
return circuit
circuitD = sampleCircuitD(qubits=4)
circuitD.draw(output='mpl')
def sampleCircuitE(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(1, qubits, 2):
circuit.crx(theta, j, j - 1)
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(2, qubits, 2):
circuit.crx(theta, j, j - 1)
return circuit
circuitE = sampleCircuitE(qubits=4)
circuitE.draw(output='mpl')
def sampleCircuitF(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
circuit.crx(theta, qubits - 1, 0)
for j in range(qubits - 1, 0, -1):
circuit.crx(theta, j - 1, j)
return circuit
circuitF = sampleCircuitF(qubits=4)
circuitF.draw(output='mpl')
def sampleEncoding(qubits):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.h(i)
circuit.ry(theta, i)
return circuit
circuit = sampleEncoding(4)
circuit.draw(output='mpl')
# demo:
circuit = sampleEncoding(5).compose(sampleCircuitB3(layer=2, qubits=5))
circuit.draw(output='mpl')
|
https://github.com/hritiksauw199/Qiskit-textbook-solutions
|
hritiksauw199
|
#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
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)
# 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/2
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
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/4
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
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 = 7*2*math.pi/8
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
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/2
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)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the legacy Scheduling passes"""
import unittest
from ddt import ddt, data, unpack
from qiskit import QuantumCircuit
from qiskit.circuit import Delay, Parameter
from qiskit.circuit.library.standard_gates import XGate, YGate, CXGate
from qiskit.test import QiskitTestCase
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.instruction_durations import InstructionDurations
from qiskit.transpiler.passes import ASAPSchedule, ALAPSchedule, DynamicalDecoupling
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.target import Target, InstructionProperties
@ddt
class TestSchedulingPass(QiskitTestCase):
"""Tests the Scheduling passes"""
def test_alap_agree_with_reverse_asap_reverse(self):
"""Test if ALAP schedule agrees with doubly-reversed ASAP schedule."""
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500, 1)
qc.cx(0, 1)
qc.measure_all()
durations = InstructionDurations(
[("h", 0, 200), ("cx", [0, 1], 700), ("measure", None, 1000)]
)
pm = PassManager(ALAPSchedule(durations))
alap_qc = pm.run(qc)
pm = PassManager(ASAPSchedule(durations))
new_qc = pm.run(qc.reverse_ops())
new_qc = new_qc.reverse_ops()
new_qc.name = new_qc.name
self.assertEqual(alap_qc, new_qc)
@data(ALAPSchedule, ASAPSchedule)
def test_classically_controlled_gate_after_measure(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit.
See: https://github.com/Qiskit/qiskit-terra/issues/7654
(input)
┌─┐
q_0: ┤M├───────────
└╥┘ ┌───┐
q_1: ─╫────┤ X ├───
║ └─╥─┘
║ ┌────╨────┐
c: 1/═╩═╡ c_0 = T ╞
0 └─────────┘
(scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(200[dt]) ├
┌─────────────────┐└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├───────
└─────────────────┘ ║ └─╥─┘
║ ┌────╨────┐
c: 1/════════════════════╩════╡ c_0=0x1 ╞════
0 └─────────┘
"""
qc = QuantumCircuit(2, 1)
qc.measure(0, 0)
qc.x(1).c_if(0, True)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
pm = PassManager(schedule_pass(durations))
scheduled = pm.run(qc)
expected = QuantumCircuit(2, 1)
expected.measure(0, 0)
expected.delay(1000, 1) # x.c_if starts after measure
expected.x(1).c_if(0, True)
expected.delay(200, 0)
self.assertEqual(expected, scheduled)
@data(ALAPSchedule, ASAPSchedule)
def test_measure_after_measure(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with measure after measure with a common clbit.
See: https://github.com/Qiskit/qiskit-terra/issues/7654
(input)
┌───┐┌─┐
q_0: ┤ X ├┤M├───
└───┘└╥┘┌─┐
q_1: ──────╫─┤M├
║ └╥┘
c: 1/══════╩══╩═
0 0
(scheduled)
┌───┐ ┌─┐┌─────────────────┐
q_0: ───────┤ X ├───────┤M├┤ Delay(1000[dt]) ├
┌──────┴───┴──────┐└╥┘└───────┬─┬───────┘
q_1: ┤ Delay(1200[dt]) ├─╫─────────┤M├────────
└─────────────────┘ ║ └╥┘
c: 1/════════════════════╩══════════╩═════════
0 0
"""
qc = QuantumCircuit(2, 1)
qc.x(0)
qc.measure(0, 0)
qc.measure(1, 0)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
pm = PassManager(schedule_pass(durations))
scheduled = pm.run(qc)
expected = QuantumCircuit(2, 1)
expected.x(0)
expected.measure(0, 0)
expected.delay(1200, 1)
expected.measure(1, 0)
expected.delay(1000, 0)
self.assertEqual(expected, scheduled)
@data(ALAPSchedule, ASAPSchedule)
def test_c_if_on_different_qubits(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with `c_if`s on different qubits.
(input)
┌─┐
q_0: ┤M├──────────────────────
└╥┘ ┌───┐
q_1: ─╫────┤ X ├──────────────
║ └─╥─┘ ┌───┐
q_2: ─╫──────╫────────┤ X ├───
║ ║ └─╥─┘
║ ┌────╨────┐┌────╨────┐
c: 1/═╩═╡ c_0 = T ╞╡ c_0 = T ╞
0 └─────────┘└─────────┘
(scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(200[dt]) ├───────────
┌─────────────────┐└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├──────────────────
├─────────────────┤ ║ └─╥─┘ ┌───┐
q_2: ┤ Delay(1000[dt]) ├─╫─────────╫────────────┤ X ├───
└─────────────────┘ ║ ║ └─╥─┘
║ ┌────╨────┐ ┌────╨────┐
c: 1/════════════════════╩════╡ c_0=0x1 ╞════╡ c_0=0x1 ╞
0 └─────────┘ └─────────┘
"""
qc = QuantumCircuit(3, 1)
qc.measure(0, 0)
qc.x(1).c_if(0, True)
qc.x(2).c_if(0, True)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
pm = PassManager(schedule_pass(durations))
scheduled = pm.run(qc)
expected = QuantumCircuit(3, 1)
expected.measure(0, 0)
expected.delay(1000, 1)
expected.delay(1000, 2)
expected.x(1).c_if(0, True)
expected.x(2).c_if(0, True)
expected.delay(200, 0)
self.assertEqual(expected, scheduled)
@data(ALAPSchedule, ASAPSchedule)
def test_shorter_measure_after_measure(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with shorter measure after measure with a common clbit.
(input)
┌─┐
q_0: ┤M├───
└╥┘┌─┐
q_1: ─╫─┤M├
║ └╥┘
c: 1/═╩══╩═
0 0
(scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(700[dt]) ├
┌─────────────────┐└╥┘└──────┬─┬───────┘
q_1: ┤ Delay(1000[dt]) ├─╫────────┤M├────────
└─────────────────┘ ║ └╥┘
c: 1/════════════════════╩═════════╩═════════
0 0
"""
qc = QuantumCircuit(2, 1)
qc.measure(0, 0)
qc.measure(1, 0)
durations = InstructionDurations([("measure", [0], 1000), ("measure", [1], 700)])
pm = PassManager(schedule_pass(durations))
scheduled = pm.run(qc)
expected = QuantumCircuit(2, 1)
expected.measure(0, 0)
expected.delay(1000, 1)
expected.measure(1, 0)
expected.delay(700, 0)
self.assertEqual(expected, scheduled)
@data(ALAPSchedule, ASAPSchedule)
def test_measure_after_c_if(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit.
(input)
┌─┐
q_0: ┤M├──────────────
└╥┘ ┌───┐
q_1: ─╫────┤ X ├──────
║ └─╥─┘ ┌─┐
q_2: ─╫──────╫─────┤M├
║ ┌────╨────┐└╥┘
c: 1/═╩═╡ c_0 = T ╞═╩═
0 └─────────┘ 0
(scheduled)
┌─┐┌─────────────────┐
q_0: ───────────────────┤M├┤ Delay(1000[dt]) ├──────────────────
┌─────────────────┐└╥┘└──────┬───┬──────┘┌────────────────┐
q_1: ┤ Delay(1000[dt]) ├─╫────────┤ X ├───────┤ Delay(800[dt]) ├
├─────────────────┤ ║ └─╥─┘ └──────┬─┬───────┘
q_2: ┤ Delay(1000[dt]) ├─╫──────────╫────────────────┤M├────────
└─────────────────┘ ║ ┌────╨────┐ └╥┘
c: 1/════════════════════╩═════╡ c_0=0x1 ╞════════════╩═════════
0 └─────────┘ 0
"""
qc = QuantumCircuit(3, 1)
qc.measure(0, 0)
qc.x(1).c_if(0, 1)
qc.measure(2, 0)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
pm = PassManager(schedule_pass(durations))
scheduled = pm.run(qc)
expected = QuantumCircuit(3, 1)
expected.delay(1000, 1)
expected.delay(1000, 2)
expected.measure(0, 0)
expected.x(1).c_if(0, 1)
expected.measure(2, 0)
expected.delay(1000, 0)
expected.delay(800, 1)
self.assertEqual(expected, scheduled)
def test_parallel_gate_different_length(self):
"""Test circuit having two parallel instruction with different length.
(input)
┌───┐┌─┐
q_0: ┤ X ├┤M├───
├───┤└╥┘┌─┐
q_1: ┤ X ├─╫─┤M├
└───┘ ║ └╥┘
c: 2/══════╩══╩═
0 1
(expected, ALAP)
┌────────────────┐┌───┐┌─┐
q_0: ┤ Delay(200[dt]) ├┤ X ├┤M├
└─────┬───┬──────┘└┬─┬┘└╥┘
q_1: ──────┤ X ├────────┤M├──╫─
└───┘ └╥┘ ║
c: 2/════════════════════╩═══╩═
1 0
(expected, ASAP)
┌───┐┌─┐┌────────────────┐
q_0: ┤ X ├┤M├┤ Delay(200[dt]) ├
├───┤└╥┘└──────┬─┬───────┘
q_1: ┤ X ├─╫────────┤M├────────
└───┘ ║ └╥┘
c: 2/══════╩═════════╩═════════
0 1
"""
qc = QuantumCircuit(2, 2)
qc.x(0)
qc.x(1)
qc.measure(0, 0)
qc.measure(1, 1)
durations = InstructionDurations(
[("x", [0], 200), ("x", [1], 400), ("measure", None, 1000)]
)
pm = PassManager(ALAPSchedule(durations))
qc_alap = pm.run(qc)
alap_expected = QuantumCircuit(2, 2)
alap_expected.delay(200, 0)
alap_expected.x(0)
alap_expected.x(1)
alap_expected.measure(0, 0)
alap_expected.measure(1, 1)
self.assertEqual(qc_alap, alap_expected)
pm = PassManager(ASAPSchedule(durations))
qc_asap = pm.run(qc)
asap_expected = QuantumCircuit(2, 2)
asap_expected.x(0)
asap_expected.x(1)
asap_expected.measure(0, 0) # immediately start after X gate
asap_expected.measure(1, 1)
asap_expected.delay(200, 0)
self.assertEqual(qc_asap, asap_expected)
def test_parallel_gate_different_length_with_barrier(self):
"""Test circuit having two parallel instruction with different length with barrier.
(input)
┌───┐┌─┐
q_0: ┤ X ├┤M├───
├───┤└╥┘┌─┐
q_1: ┤ X ├─╫─┤M├
└───┘ ║ └╥┘
c: 2/══════╩══╩═
0 1
(expected, ALAP)
┌────────────────┐┌───┐ ░ ┌─┐
q_0: ┤ Delay(200[dt]) ├┤ X ├─░─┤M├───
└─────┬───┬──────┘└───┘ ░ └╥┘┌─┐
q_1: ──────┤ X ├─────────────░──╫─┤M├
└───┘ ░ ║ └╥┘
c: 2/═══════════════════════════╩══╩═
0 1
(expected, ASAP)
┌───┐┌────────────────┐ ░ ┌─┐
q_0: ┤ X ├┤ Delay(200[dt]) ├─░─┤M├───
├───┤└────────────────┘ ░ └╥┘┌─┐
q_1: ┤ X ├───────────────────░──╫─┤M├
└───┘ ░ ║ └╥┘
c: 2/═══════════════════════════╩══╩═
0 1
"""
qc = QuantumCircuit(2, 2)
qc.x(0)
qc.x(1)
qc.barrier()
qc.measure(0, 0)
qc.measure(1, 1)
durations = InstructionDurations(
[("x", [0], 200), ("x", [1], 400), ("measure", None, 1000)]
)
pm = PassManager(ALAPSchedule(durations))
qc_alap = pm.run(qc)
alap_expected = QuantumCircuit(2, 2)
alap_expected.delay(200, 0)
alap_expected.x(0)
alap_expected.x(1)
alap_expected.barrier()
alap_expected.measure(0, 0)
alap_expected.measure(1, 1)
self.assertEqual(qc_alap, alap_expected)
pm = PassManager(ASAPSchedule(durations))
qc_asap = pm.run(qc)
asap_expected = QuantumCircuit(2, 2)
asap_expected.x(0)
asap_expected.delay(200, 0)
asap_expected.x(1)
asap_expected.barrier()
asap_expected.measure(0, 0)
asap_expected.measure(1, 1)
self.assertEqual(qc_asap, asap_expected)
def test_measure_after_c_if_on_edge_locking(self):
"""Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit.
The scheduler is configured to reproduce behavior of the 0.20.0,
in which clbit lock is applied to the end-edge of measure instruction.
See https://github.com/Qiskit/qiskit-terra/pull/7655
(input)
┌─┐
q_0: ┤M├──────────────
└╥┘ ┌───┐
q_1: ─╫────┤ X ├──────
║ └─╥─┘ ┌─┐
q_2: ─╫──────╫─────┤M├
║ ┌────╨────┐└╥┘
c: 1/═╩═╡ c_0 = T ╞═╩═
0 └─────────┘ 0
(ASAP scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(200[dt]) ├─────────────────────
┌─────────────────┐└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├────────────────────────────
└─────────────────┘ ║ └─╥─┘ ┌─┐┌────────────────┐
q_2: ────────────────────╫─────────╫─────────┤M├┤ Delay(200[dt]) ├
║ ┌────╨────┐ └╥┘└────────────────┘
c: 1/════════════════════╩════╡ c_0=0x1 ╞═════╩═══════════════════
0 └─────────┘ 0
(ALAP scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(200[dt]) ├───
┌─────────────────┐└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├──────────
└┬────────────────┤ ║ └─╥─┘ ┌─┐
q_2: ─┤ Delay(200[dt]) ├─╫─────────╫─────────┤M├
└────────────────┘ ║ ┌────╨────┐ └╥┘
c: 1/════════════════════╩════╡ c_0=0x1 ╞═════╩═
0 └─────────┘ 0
"""
qc = QuantumCircuit(3, 1)
qc.measure(0, 0)
qc.x(1).c_if(0, 1)
qc.measure(2, 0)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
# lock at the end edge
actual_asap = PassManager(ASAPSchedule(durations, clbit_write_latency=1000)).run(qc)
actual_alap = PassManager(ALAPSchedule(durations, clbit_write_latency=1000)).run(qc)
# start times of 2nd measure depends on ASAP/ALAP
expected_asap = QuantumCircuit(3, 1)
expected_asap.measure(0, 0)
expected_asap.delay(1000, 1)
expected_asap.x(1).c_if(0, 1)
expected_asap.measure(2, 0)
expected_asap.delay(200, 0)
expected_asap.delay(200, 2)
self.assertEqual(expected_asap, actual_asap)
expected_alap = QuantumCircuit(3, 1)
expected_alap.measure(0, 0)
expected_alap.delay(1000, 1)
expected_alap.x(1).c_if(0, 1)
expected_alap.delay(200, 2)
expected_alap.measure(2, 0)
expected_alap.delay(200, 0)
self.assertEqual(expected_alap, actual_alap)
@data([100, 200], [500, 0], [1000, 200])
@unpack
def test_active_reset_circuit(self, write_lat, cond_lat):
"""Test practical example of reset circuit.
Because of the stimulus pulse overlap with the previous XGate on the q register,
measure instruction is always triggered after XGate regardless of write latency.
Thus only conditional latency matters in the scheduling.
(input)
┌─┐ ┌───┐ ┌─┐ ┌───┐ ┌─┐ ┌───┐
q: ┤M├───┤ X ├───┤M├───┤ X ├───┤M├───┤ X ├───
└╥┘ └─╥─┘ └╥┘ └─╥─┘ └╥┘ └─╥─┘
║ ┌────╨────┐ ║ ┌────╨────┐ ║ ┌────╨────┐
c: 1/═╩═╡ c_0=0x1 ╞═╩═╡ c_0=0x1 ╞═╩═╡ c_0=0x1 ╞
0 └─────────┘ 0 └─────────┘ 0 └─────────┘
"""
qc = QuantumCircuit(1, 1)
qc.measure(0, 0)
qc.x(0).c_if(0, 1)
qc.measure(0, 0)
qc.x(0).c_if(0, 1)
qc.measure(0, 0)
qc.x(0).c_if(0, 1)
durations = InstructionDurations([("x", None, 100), ("measure", None, 1000)])
actual_asap = PassManager(
ASAPSchedule(durations, clbit_write_latency=write_lat, conditional_latency=cond_lat)
).run(qc)
actual_alap = PassManager(
ALAPSchedule(durations, clbit_write_latency=write_lat, conditional_latency=cond_lat)
).run(qc)
expected = QuantumCircuit(1, 1)
expected.measure(0, 0)
if cond_lat > 0:
expected.delay(cond_lat, 0)
expected.x(0).c_if(0, 1)
expected.measure(0, 0)
if cond_lat > 0:
expected.delay(cond_lat, 0)
expected.x(0).c_if(0, 1)
expected.measure(0, 0)
if cond_lat > 0:
expected.delay(cond_lat, 0)
expected.x(0).c_if(0, 1)
self.assertEqual(expected, actual_asap)
self.assertEqual(expected, actual_alap)
def test_random_complicated_circuit(self):
"""Test scheduling complicated circuit with control flow.
(input)
┌────────────────┐ ┌───┐ ░ ┌───┐ »
q_0: ┤ Delay(100[dt]) ├───┤ X ├────░──────────────────┤ X ├───»
└────────────────┘ └─╥─┘ ░ ┌───┐ └─╥─┘ »
q_1: ───────────────────────╫──────░───────┤ X ├────────╫─────»
║ ░ ┌─┐ └─╥─┘ ║ »
q_2: ───────────────────────╫──────░─┤M├─────╫──────────╫─────»
┌────╨────┐ ░ └╥┘┌────╨────┐┌────╨────┐»
c: 1/══════════════════╡ c_0=0x1 ╞════╩═╡ c_0=0x0 ╞╡ c_0=0x0 ╞»
└─────────┘ 0 └─────────┘└─────────┘»
« ┌────────────────┐┌───┐
«q_0: ┤ Delay(300[dt]) ├┤ X ├─────■─────
« └────────────────┘└───┘ ┌─┴─┐
«q_1: ────────■─────────────────┤ X ├───
« ┌─┴─┐ ┌─┐ └─╥─┘
«q_2: ──────┤ X ├────────┤M├──────╫─────
« └───┘ └╥┘ ┌────╨────┐
«c: 1/════════════════════╩══╡ c_0=0x0 ╞
« 0 └─────────┘
(ASAP scheduled) duration = 2800 dt
┌────────────────┐┌────────────────┐ ┌───┐ ░ ┌─────────────────┐»
q_0: ┤ Delay(100[dt]) ├┤ Delay(100[dt]) ├───┤ X ├────░─┤ Delay(1400[dt]) ├»
├────────────────┤└────────────────┘ └─╥─┘ ░ ├─────────────────┤»
q_1: ┤ Delay(300[dt]) ├───────────────────────╫──────░─┤ Delay(1200[dt]) ├»
├────────────────┤ ║ ░ └───────┬─┬───────┘»
q_2: ┤ Delay(300[dt]) ├───────────────────────╫──────░─────────┤M├────────»
└────────────────┘ ┌────╨────┐ ░ └╥┘ »
c: 1/════════════════════════════════════╡ c_0=0x1 ╞════════════╩═════════»
└─────────┘ 0 »
« ┌───┐ ┌────────────────┐»
«q_0: ────────────────────────────────┤ X ├───┤ Delay(300[dt]) ├»
« ┌───┐ └─╥─┘ └────────────────┘»
«q_1: ───┤ X ├──────────────────────────╫─────────────■─────────»
« └─╥─┘ ┌────────────────┐ ║ ┌─┴─┐ »
«q_2: ─────╫─────┤ Delay(300[dt]) ├─────╫───────────┤ X ├───────»
« ┌────╨────┐└────────────────┘┌────╨────┐ └───┘ »
«c: 1/╡ c_0=0x0 ╞══════════════════╡ c_0=0x0 ╞══════════════════»
« └─────────┘ └─────────┘ »
« ┌───┐ ┌────────────────┐
«q_0: ──────┤ X ├────────────■─────┤ Delay(700[dt]) ├
« ┌─────┴───┴──────┐ ┌─┴─┐ ├────────────────┤
«q_1: ┤ Delay(400[dt]) ├───┤ X ├───┤ Delay(700[dt]) ├
« ├────────────────┤ └─╥─┘ └──────┬─┬───────┘
«q_2: ┤ Delay(300[dt]) ├─────╫────────────┤M├────────
« └────────────────┘┌────╨────┐ └╥┘
«c: 1/══════════════════╡ c_0=0x0 ╞════════╩═════════
« └─────────┘ 0
(ALAP scheduled) duration = 3100
┌────────────────┐┌────────────────┐ ┌───┐ ░ ┌─────────────────┐»
q_0: ┤ Delay(100[dt]) ├┤ Delay(100[dt]) ├───┤ X ├────░─┤ Delay(1400[dt]) ├»
├────────────────┤└────────────────┘ └─╥─┘ ░ ├─────────────────┤»
q_1: ┤ Delay(300[dt]) ├───────────────────────╫──────░─┤ Delay(1200[dt]) ├»
├────────────────┤ ║ ░ └───────┬─┬───────┘»
q_2: ┤ Delay(300[dt]) ├───────────────────────╫──────░─────────┤M├────────»
└────────────────┘ ┌────╨────┐ ░ └╥┘ »
c: 1/════════════════════════════════════╡ c_0=0x1 ╞════════════╩═════════»
└─────────┘ 0 »
« ┌───┐ ┌────────────────┐»
«q_0: ────────────────────────────────┤ X ├───┤ Delay(300[dt]) ├»
« ┌───┐ ┌────────────────┐ └─╥─┘ └────────────────┘»
«q_1: ───┤ X ├───┤ Delay(300[dt]) ├─────╫─────────────■─────────»
« └─╥─┘ ├────────────────┤ ║ ┌─┴─┐ »
«q_2: ─────╫─────┤ Delay(600[dt]) ├─────╫───────────┤ X ├───────»
« ┌────╨────┐└────────────────┘┌────╨────┐ └───┘ »
«c: 1/╡ c_0=0x0 ╞══════════════════╡ c_0=0x0 ╞══════════════════»
« └─────────┘ └─────────┘ »
« ┌───┐ ┌────────────────┐
«q_0: ──────┤ X ├────────────■─────┤ Delay(700[dt]) ├
« ┌─────┴───┴──────┐ ┌─┴─┐ ├────────────────┤
«q_1: ┤ Delay(100[dt]) ├───┤ X ├───┤ Delay(700[dt]) ├
« └──────┬─┬───────┘ └─╥─┘ └────────────────┘
«q_2: ───────┤M├─────────────╫───────────────────────
« └╥┘ ┌────╨────┐
«c: 1/════════╩═════════╡ c_0=0x0 ╞══════════════════
« 0 └─────────┘
"""
qc = QuantumCircuit(3, 1)
qc.delay(100, 0)
qc.x(0).c_if(0, 1)
qc.barrier()
qc.measure(2, 0)
qc.x(1).c_if(0, 0)
qc.x(0).c_if(0, 0)
qc.delay(300, 0)
qc.cx(1, 2)
qc.x(0)
qc.cx(0, 1).c_if(0, 0)
qc.measure(2, 0)
durations = InstructionDurations(
[("x", None, 100), ("measure", None, 1000), ("cx", None, 200)]
)
actual_asap = PassManager(
ASAPSchedule(durations, clbit_write_latency=100, conditional_latency=200)
).run(qc)
actual_alap = PassManager(
ALAPSchedule(durations, clbit_write_latency=100, conditional_latency=200)
).run(qc)
expected_asap = QuantumCircuit(3, 1)
expected_asap.delay(100, 0)
expected_asap.delay(100, 0) # due to conditional latency of 200dt
expected_asap.delay(300, 1)
expected_asap.delay(300, 2)
expected_asap.x(0).c_if(0, 1)
expected_asap.barrier()
expected_asap.delay(1400, 0)
expected_asap.delay(1200, 1)
expected_asap.measure(2, 0)
expected_asap.x(1).c_if(0, 0)
expected_asap.x(0).c_if(0, 0)
expected_asap.delay(300, 0)
expected_asap.x(0)
expected_asap.delay(300, 2)
expected_asap.cx(1, 2)
expected_asap.delay(400, 1)
expected_asap.cx(0, 1).c_if(0, 0)
expected_asap.delay(700, 0) # creg is released at t0 of cx(0,1).c_if(0,0)
expected_asap.delay(
700, 1
) # no creg write until 100dt. thus measure can move left by 300dt.
expected_asap.delay(300, 2)
expected_asap.measure(2, 0)
self.assertEqual(expected_asap, actual_asap)
self.assertEqual(actual_asap.duration, 3100)
expected_alap = QuantumCircuit(3, 1)
expected_alap.delay(100, 0)
expected_alap.delay(100, 0) # due to conditional latency of 200dt
expected_alap.delay(300, 1)
expected_alap.delay(300, 2)
expected_alap.x(0).c_if(0, 1)
expected_alap.barrier()
expected_alap.delay(1400, 0)
expected_alap.delay(1200, 1)
expected_alap.measure(2, 0)
expected_alap.x(1).c_if(0, 0)
expected_alap.x(0).c_if(0, 0)
expected_alap.delay(300, 0)
expected_alap.x(0)
expected_alap.delay(300, 1)
expected_alap.delay(600, 2)
expected_alap.cx(1, 2)
expected_alap.delay(100, 1)
expected_alap.cx(0, 1).c_if(0, 0)
expected_alap.measure(2, 0)
expected_alap.delay(700, 0)
expected_alap.delay(700, 1)
self.assertEqual(expected_alap, actual_alap)
self.assertEqual(actual_alap.duration, 3100)
def test_dag_introduces_extra_dependency_between_conditionals(self):
"""Test dependency between conditional operations in the scheduling.
In the below example circuit, the conditional x on q1 could start at time 0,
however it must be scheduled after the conditional x on q0 in ASAP scheduling.
That is because circuit model used in the transpiler passes (DAGCircuit)
interprets instructions acting on common clbits must be run in the order
given by the original circuit (QuantumCircuit).
(input)
┌────────────────┐ ┌───┐
q_0: ┤ Delay(100[dt]) ├───┤ X ├───
└─────┬───┬──────┘ └─╥─┘
q_1: ──────┤ X ├────────────╫─────
└─╥─┘ ║
┌────╨────┐ ┌────╨────┐
c: 1/═══╡ c_0=0x1 ╞════╡ c_0=0x1 ╞
└─────────┘ └─────────┘
(ASAP scheduled)
┌────────────────┐ ┌───┐
q_0: ┤ Delay(100[dt]) ├───┤ X ├──────────────
├────────────────┤ └─╥─┘ ┌───┐
q_1: ┤ Delay(100[dt]) ├─────╫────────┤ X ├───
└────────────────┘ ║ └─╥─┘
┌────╨────┐┌────╨────┐
c: 1/══════════════════╡ c_0=0x1 ╞╡ c_0=0x1 ╞
└─────────┘└─────────┘
"""
qc = QuantumCircuit(2, 1)
qc.delay(100, 0)
qc.x(0).c_if(0, True)
qc.x(1).c_if(0, True)
durations = InstructionDurations([("x", None, 160)])
pm = PassManager(ASAPSchedule(durations))
scheduled = pm.run(qc)
expected = QuantumCircuit(2, 1)
expected.delay(100, 0)
expected.delay(100, 1) # due to extra dependency on clbits
expected.x(0).c_if(0, True)
expected.x(1).c_if(0, True)
self.assertEqual(expected, scheduled)
@data(ALAPSchedule, ASAPSchedule)
def test_respect_target_instruction_constraints(self, schedule_pass):
"""Test if ALAP/ASAP does not pad delays for qubits that do not support delay instructions.
See: https://github.com/Qiskit/qiskit-terra/issues/9993
"""
target = Target(dt=1)
target.add_instruction(XGate(), {(1,): InstructionProperties(duration=200)})
# delays are not supported
qc = QuantumCircuit(2)
qc.x(1)
pm = PassManager(schedule_pass(target=target))
scheduled = pm.run(qc)
expected = QuantumCircuit(2)
expected.x(1)
# no delay on qubit 0
self.assertEqual(expected, scheduled)
def test_dd_respect_target_instruction_constraints(self):
"""Test if DD pass does not pad delays for qubits that do not support delay instructions
and does not insert DD gates for qubits that do not support necessary gates.
See: https://github.com/Qiskit/qiskit-terra/issues/9993
"""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.cx(1, 2)
target = Target(dt=1)
# Y is partially supported (not supported on qubit 2)
target.add_instruction(
XGate(), {(q,): InstructionProperties(duration=100) for q in range(2)}
)
target.add_instruction(
CXGate(),
{
(0, 1): InstructionProperties(duration=1000),
(1, 2): InstructionProperties(duration=1000),
},
)
# delays are not supported
# No DD instructions nor delays are padded due to no delay support in the target
pm_xx = PassManager(
[
ALAPSchedule(target=target),
DynamicalDecoupling(durations=None, dd_sequence=[XGate(), XGate()], target=target),
]
)
scheduled = pm_xx.run(qc)
self.assertEqual(qc, scheduled)
# Fails since Y is not supported in the target
with self.assertRaises(TranspilerError):
PassManager(
[
ALAPSchedule(target=target),
DynamicalDecoupling(
durations=None,
dd_sequence=[XGate(), YGate(), XGate(), YGate()],
target=target,
),
]
)
# Add delay support to the target
target.add_instruction(Delay(Parameter("t")), {(q,): None for q in range(3)})
# No error but no DD on qubit 2 (just delay is padded) since X is not supported on it
scheduled = pm_xx.run(qc)
expected = QuantumCircuit(3)
expected.delay(1000, [2])
expected.cx(0, 1)
expected.cx(1, 2)
expected.delay(200, [0])
expected.x([0])
expected.delay(400, [0])
expected.x([0])
expected.delay(200, [0])
self.assertEqual(expected, scheduled)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
for idx in range(5):
qc.h(idx)
qc.cx(idx, idx+5)
qc.cx(1, 7)
qc.x(8)
qc.cx(1, 9)
qc.x(7)
qc.cx(1, 11)
qc.swap(6, 11)
qc.swap(6, 9)
qc.swap(6, 10)
qc.x(6)
qc.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.visualization import plot_error_map
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
plot_error_map(backend)
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test circuits with variable parameters."""
import unittest
import cmath
import math
import copy
import pickle
from operator import add, mul, sub, truediv
from test import combine
import numpy
from ddt import data, ddt, named_data
import qiskit
import qiskit.circuit.library as circlib
from qiskit.circuit.library.standard_gates.rz import RZGate
from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.circuit import Gate, Instruction, Parameter, ParameterExpression, ParameterVector
from qiskit.circuit.parametertable import ParameterReferences, ParameterTable, ParameterView
from qiskit.circuit.exceptions import CircuitError
from qiskit.compiler import assemble, transpile
from qiskit.execute_function import execute
from qiskit import pulse
from qiskit.quantum_info import Operator
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeOurense
from qiskit.tools import parallel_map
def raise_if_parameter_table_invalid(circuit):
"""Validates the internal consistency of a ParameterTable and its
containing QuantumCircuit. Intended for use in testing.
Raises:
CircuitError: if QuantumCircuit and ParameterTable are inconsistent.
"""
table = circuit._parameter_table
# Assert parameters present in circuit match those in table.
circuit_parameters = {
parameter
for instruction in circuit._data
for param in instruction.operation.params
for parameter in param.parameters
if isinstance(param, ParameterExpression)
}
table_parameters = set(table._table.keys())
if circuit_parameters != table_parameters:
raise CircuitError(
"Circuit/ParameterTable Parameter mismatch. "
"Circuit parameters: {}. "
"Table parameters: {}.".format(circuit_parameters, table_parameters)
)
# Assert parameter locations in table are present in circuit.
circuit_instructions = [instr.operation for instr in circuit._data]
for parameter, instr_list in table.items():
for instr, param_index in instr_list:
if instr not in circuit_instructions:
raise CircuitError(f"ParameterTable instruction not present in circuit: {instr}.")
if not isinstance(instr.params[param_index], ParameterExpression):
raise CircuitError(
"ParameterTable instruction does not have a "
"ParameterExpression at param_index {}: {}."
"".format(param_index, instr)
)
if parameter not in instr.params[param_index].parameters:
raise CircuitError(
"ParameterTable instruction parameters does "
"not match ParameterTable key. Instruction "
"parameters: {} ParameterTable key: {}."
"".format(instr.params[param_index].parameters, parameter)
)
# Assert circuit has no other parameter locations other than those in table.
for instruction in circuit._data:
for param_index, param in enumerate(instruction.operation.params):
if isinstance(param, ParameterExpression):
parameters = param.parameters
for parameter in parameters:
if (instruction.operation, param_index) not in table[parameter]:
raise CircuitError(
"Found parameterized instruction not "
"present in table. Instruction: {} "
"param_index: {}".format(instruction.operation, param_index)
)
@ddt
class TestParameters(QiskitTestCase):
"""Test Parameters."""
def test_gate(self):
"""Test instantiating gate with variable parameters"""
theta = Parameter("θ")
theta_gate = Gate("test", 1, params=[theta])
self.assertEqual(theta_gate.name, "test")
self.assertIsInstance(theta_gate.params[0], Parameter)
def test_compile_quantum_circuit(self):
"""Test instantiating gate with variable parameters"""
theta = Parameter("θ")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta, qr)
backend = BasicAer.get_backend("qasm_simulator")
qc_aer = transpile(qc, backend)
self.assertIn(theta, qc_aer.parameters)
def test_duplicate_name_on_append(self):
"""Test adding a second parameter object with the same name fails."""
param_a = Parameter("a")
param_a_again = Parameter("a")
qc = QuantumCircuit(1)
qc.rx(param_a, 0)
self.assertRaises(CircuitError, qc.rx, param_a_again, 0)
def test_get_parameters(self):
"""Test instantiating gate with variable parameters"""
from qiskit.circuit.library.standard_gates.rx import RXGate
theta = Parameter("θ")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
rxg = RXGate(theta)
qc.append(rxg, [qr[0]], [])
vparams = qc._parameter_table
self.assertEqual(len(vparams), 1)
self.assertIs(theta, next(iter(vparams)))
self.assertEqual(rxg, next(iter(vparams[theta]))[0])
def test_get_parameters_by_index(self):
"""Test getting parameters by index"""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
v = ParameterVector("v", 3)
qc = QuantumCircuit(1)
qc.rx(x, 0)
qc.rz(z, 0)
qc.ry(y, 0)
qc.u(*v, 0)
self.assertEqual(x, qc.parameters[3])
self.assertEqual(y, qc.parameters[4])
self.assertEqual(z, qc.parameters[5])
for i, vi in enumerate(v):
self.assertEqual(vi, qc.parameters[i])
def test_bind_parameters_anonymously(self):
"""Test setting parameters by insertion order anonymously"""
phase = Parameter("phase")
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
v = ParameterVector("v", 3)
qc = QuantumCircuit(1, global_phase=phase)
qc.rx(x, 0)
qc.rz(z, 0)
qc.ry(y, 0)
qc.u(*v, 0)
params = [0.1 * i for i in range(len(qc.parameters))]
order = [phase] + v[:] + [x, y, z]
param_dict = dict(zip(order, params))
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
bqc_anonymous = getattr(qc, assign_fun)(params)
bqc_list = getattr(qc, assign_fun)(param_dict)
self.assertEqual(bqc_anonymous, bqc_list)
def test_bind_parameters_allow_unknown(self):
"""Test binding parameters allowing unknown parameters."""
a = Parameter("a")
b = Parameter("b")
c = a.bind({a: 1, b: 1}, allow_unknown_parameters=True)
self.assertEqual(c, a.bind({a: 1}))
@data(QuantumCircuit.assign_parameters, QuantumCircuit.bind_parameters)
def test_bind_parameters_custom_definition_global_phase(self, assigner):
"""Test that a custom gate with a parametrised `global_phase` is assigned correctly."""
x = Parameter("x")
custom = QuantumCircuit(1, global_phase=x).to_gate()
base = QuantumCircuit(1)
base.append(custom, [0], [])
test = Operator(assigner(base, {x: math.pi}))
expected = Operator(numpy.array([[-1, 0], [0, -1]]))
self.assertEqual(test, expected)
def test_bind_half_single_precision(self):
"""Test binding with 16bit and 32bit floats."""
phase = Parameter("phase")
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
v = ParameterVector("v", 3)
for i in (numpy.float16, numpy.float32):
with self.subTest(float_type=i):
expr = (v[0] * (x + y + z) + phase) - (v[2] * v[1])
params = numpy.array([0.1 * j for j in range(8)], dtype=i)
order = [phase] + v[:] + [x, y, z]
param_dict = dict(zip(order, params))
bound_value = expr.bind(param_dict)
self.assertAlmostEqual(float(bound_value), 0.09, delta=1e-4)
def test_parameter_order(self):
"""Test the parameters are sorted by name but parameter vector order takes precedence.
This means that the following set of parameters
{a, z, x[0], x[1], x[2], x[3], x[10], x[11]}
will be sorted as
[a, x[0], x[1], x[2], x[3], x[10], x[11], z]
"""
a, b, some_name, z = (Parameter(name) for name in ["a", "b", "some_name", "z"])
x = ParameterVector("x", 12)
a_vector = ParameterVector("a_vector", 15)
qc = QuantumCircuit(2)
qc.p(z, 0)
for i, x_i in enumerate(reversed(x)):
qc.rx(x_i, i % 2)
qc.cry(a, 0, 1)
qc.crz(some_name, 1, 0)
for v_i in a_vector[::2]:
qc.p(v_i, 0)
for v_i in a_vector[1::2]:
qc.p(v_i, 1)
qc.p(b, 0)
expected_order = [a] + a_vector[:] + [b, some_name] + x[:] + [z]
actual_order = qc.parameters
self.assertListEqual(expected_order, list(actual_order))
@data(True, False)
def test_parameter_order_compose(self, front):
"""Test the parameter order is correctly maintained upon composing circuits."""
x = Parameter("x")
y = Parameter("y")
qc1 = QuantumCircuit(1)
qc1.p(x, 0)
qc2 = QuantumCircuit(1)
qc2.rz(y, 0)
order = [x, y]
composed = qc1.compose(qc2, front=front)
self.assertListEqual(list(composed.parameters), order)
def test_parameter_order_append(self):
"""Test the parameter order is correctly maintained upon appending circuits."""
x = Parameter("x")
y = Parameter("y")
qc1 = QuantumCircuit(1)
qc1.p(x, 0)
qc2 = QuantumCircuit(1)
qc2.rz(y, 0)
qc1.append(qc2, [0])
self.assertListEqual(list(qc1.parameters), [x, y])
def test_parameter_order_composing_nested_circuit(self):
"""Test the parameter order after nesting circuits and instructions."""
x = ParameterVector("x", 5)
inner = QuantumCircuit(1)
inner.rx(x[0], [0])
mid = QuantumCircuit(2)
mid.p(x[1], 1)
mid.append(inner, [0])
mid.p(x[2], 0)
mid.append(inner, [0])
outer = QuantumCircuit(2)
outer.compose(mid, inplace=True)
outer.ryy(x[3], 0, 1)
outer.compose(inner, inplace=True)
outer.rz(x[4], 0)
order = [x[0], x[1], x[2], x[3], x[4]]
self.assertListEqual(list(outer.parameters), order)
def test_is_parameterized(self):
"""Test checking if a gate is parameterized (bound/unbound)"""
from qiskit.circuit.library.standard_gates.h import HGate
from qiskit.circuit.library.standard_gates.rx import RXGate
theta = Parameter("θ")
rxg = RXGate(theta)
self.assertTrue(rxg.is_parameterized())
theta_bound = theta.bind({theta: 3.14})
rxg = RXGate(theta_bound)
self.assertFalse(rxg.is_parameterized())
h_gate = HGate()
self.assertFalse(h_gate.is_parameterized())
def test_fix_variable(self):
"""Test setting a variable to a constant value"""
theta = Parameter("θ")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta, qr)
qc.u(0, theta, 0, qr)
# test for both `bind_parameters` and `assign_parameters`
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
bqc = getattr(qc, assign_fun)({theta: 0.5})
self.assertEqual(float(bqc.data[0].operation.params[0]), 0.5)
self.assertEqual(float(bqc.data[1].operation.params[1]), 0.5)
bqc = getattr(qc, assign_fun)({theta: 0.6})
self.assertEqual(float(bqc.data[0].operation.params[0]), 0.6)
self.assertEqual(float(bqc.data[1].operation.params[1]), 0.6)
def test_multiple_parameters(self):
"""Test setting multiple parameters"""
theta = Parameter("θ")
x = Parameter("x")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta, qr)
qc.u(0, theta, x, qr)
self.assertEqual(qc.parameters, {theta, x})
def test_multiple_named_parameters(self):
"""Test setting multiple named/keyword argument based parameters"""
theta = Parameter(name="θ")
x = Parameter(name="x")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta, qr)
qc.u(0, theta, x, qr)
self.assertEqual(theta.name, "θ")
self.assertEqual(qc.parameters, {theta, x})
@named_data(
["int", 2, int],
["float", 2.5, float],
["float16", numpy.float16(2.5), float],
["float32", numpy.float32(2.5), float],
["float64", numpy.float64(2.5), float],
)
def test_circuit_assignment_to_numeric(self, value, type_):
"""Test binding a numeric value to a circuit instruction"""
x = Parameter("x")
qc = QuantumCircuit(1)
qc.append(Instruction("inst", 1, 0, [x]), (0,))
qc.assign_parameters({x: value}, inplace=True)
bound = qc.data[0].operation.params[0]
self.assertIsInstance(bound, type_)
self.assertEqual(bound, value)
def test_partial_binding(self):
"""Test that binding a subset of circuit parameters returns a new parameterized circuit."""
theta = Parameter("θ")
x = Parameter("x")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta, qr)
qc.u(0, theta, x, qr)
# test for both `bind_parameters` and `assign_parameters`
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
pqc = getattr(qc, assign_fun)({theta: 2})
self.assertEqual(pqc.parameters, {x})
self.assertEqual(float(pqc.data[0].operation.params[0]), 2)
self.assertEqual(float(pqc.data[1].operation.params[1]), 2)
@data(True, False)
def test_mixed_binding(self, inplace):
"""Test we can bind a mixed dict with Parameter objects and floats."""
theta = Parameter("θ")
x, new_x = Parameter("x"), Parameter("new_x")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta, qr)
qc.u(0, theta, x, qr)
pqc = qc.assign_parameters({theta: 2, x: new_x}, inplace=inplace)
if inplace:
self.assertEqual(qc.parameters, {new_x})
else:
self.assertEqual(pqc.parameters, {new_x})
def test_expression_partial_binding(self):
"""Test that binding a subset of expression parameters returns a new
parameterized circuit."""
theta = Parameter("θ")
phi = Parameter("phi")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta + phi, qr)
# test for both `bind_parameters` and `assign_parameters`
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
pqc = getattr(qc, assign_fun)({theta: 2})
self.assertEqual(pqc.parameters, {phi})
self.assertTrue(isinstance(pqc.data[0].operation.params[0], ParameterExpression))
self.assertEqual(str(pqc.data[0].operation.params[0]), "phi + 2")
fbqc = getattr(pqc, assign_fun)({phi: 1.0})
self.assertEqual(fbqc.parameters, set())
self.assertIsInstance(fbqc.data[0].operation.params[0], float)
self.assertEqual(float(fbqc.data[0].operation.params[0]), 3)
def test_two_parameter_expression_binding(self):
"""Verify that for a circuit with parameters theta and phi that
we can correctly assign theta to -phi.
"""
theta = Parameter("theta")
phi = Parameter("phi")
qc = QuantumCircuit(1)
qc.rx(theta, 0)
qc.ry(phi, 0)
self.assertEqual(len(qc._parameter_table[theta]), 1)
self.assertEqual(len(qc._parameter_table[phi]), 1)
qc.assign_parameters({theta: -phi}, inplace=True)
self.assertEqual(len(qc._parameter_table[phi]), 2)
def test_expression_partial_binding_zero(self):
"""Verify that binding remains possible even if a previous partial bind
would reduce the expression to zero.
"""
theta = Parameter("theta")
phi = Parameter("phi")
qc = QuantumCircuit(1)
qc.p(theta * phi, 0)
# test for both `bind_parameters` and `assign_parameters`
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
pqc = getattr(qc, assign_fun)({theta: 0})
self.assertEqual(pqc.parameters, {phi})
self.assertTrue(isinstance(pqc.data[0].operation.params[0], ParameterExpression))
self.assertEqual(str(pqc.data[0].operation.params[0]), "0")
fbqc = getattr(pqc, assign_fun)({phi: 1})
self.assertEqual(fbqc.parameters, set())
self.assertIsInstance(fbqc.data[0].operation.params[0], int)
self.assertEqual(float(fbqc.data[0].operation.params[0]), 0)
def test_raise_if_assigning_params_not_in_circuit(self):
"""Verify binding parameters which are not present in the circuit raises an error."""
x = Parameter("x")
y = Parameter("y")
z = ParameterVector("z", 3)
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
# test for both `bind_parameters` and `assign_parameters`
for assign_fun in ["bind_parameters", "assign_parameters"]:
qc = QuantumCircuit(qr)
with self.subTest(assign_fun=assign_fun):
qc.p(0.1, qr[0])
self.assertRaises(CircuitError, getattr(qc, assign_fun), {x: 1})
qc.p(x, qr[0])
self.assertRaises(CircuitError, getattr(qc, assign_fun), {x: 1, y: 2})
qc.p(z[1], qr[0])
self.assertRaises(CircuitError, getattr(qc, assign_fun), {z: [3, 4, 5]})
self.assertRaises(CircuitError, getattr(qc, assign_fun), {"a_str": 6})
self.assertRaises(CircuitError, getattr(qc, assign_fun), {None: 7})
def test_gate_multiplicity_binding(self):
"""Test binding when circuit contains multiple references to same gate"""
qc = QuantumCircuit(1)
theta = Parameter("theta")
gate = RZGate(theta)
qc.append(gate, [0], [])
qc.append(gate, [0], [])
# test for both `bind_parameters` and `assign_parameters`
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
qc2 = getattr(qc, assign_fun)({theta: 1.0})
self.assertEqual(len(qc2._parameter_table), 0)
for instruction in qc2.data:
self.assertEqual(float(instruction.operation.params[0]), 1.0)
def test_calibration_assignment(self):
"""That that calibration mapping and the schedules they map are assigned together."""
theta = Parameter("theta")
circ = QuantumCircuit(3, 3)
circ.append(Gate("rxt", 1, [theta]), [0])
circ.measure(0, 0)
rxt_q0 = pulse.Schedule(
pulse.Play(
pulse.library.Gaussian(duration=128, sigma=16, amp=0.2 * theta / 3.14),
pulse.DriveChannel(0),
)
)
circ.add_calibration("rxt", [0], rxt_q0, [theta])
circ = circ.assign_parameters({theta: 3.14})
instruction = circ.data[0]
cal_key = (
tuple(circ.find_bit(q).index for q in instruction.qubits),
tuple(instruction.operation.params),
)
self.assertEqual(cal_key, ((0,), (3.14,)))
# Make sure that key from instruction data matches the calibrations dictionary
self.assertIn(cal_key, circ.calibrations["rxt"])
sched = circ.calibrations["rxt"][cal_key]
self.assertEqual(sched.instructions[0][1].pulse.amp, 0.2)
def test_calibration_assignment_doesnt_mutate(self):
"""That that assignment doesn't mutate the original circuit."""
theta = Parameter("theta")
circ = QuantumCircuit(3, 3)
circ.append(Gate("rxt", 1, [theta]), [0])
circ.measure(0, 0)
rxt_q0 = pulse.Schedule(
pulse.Play(
pulse.library.Gaussian(duration=128, sigma=16, amp=0.2 * theta / 3.14),
pulse.DriveChannel(0),
)
)
circ.add_calibration("rxt", [0], rxt_q0, [theta])
circ_copy = copy.deepcopy(circ)
assigned_circ = circ.assign_parameters({theta: 3.14})
self.assertEqual(circ.calibrations, circ_copy.calibrations)
self.assertNotEqual(assigned_circ.calibrations, circ.calibrations)
def test_calibration_assignment_w_expressions(self):
"""That calibrations with multiple parameters are assigned correctly"""
theta = Parameter("theta")
sigma = Parameter("sigma")
circ = QuantumCircuit(3, 3)
circ.append(Gate("rxt", 1, [theta / 2, sigma]), [0])
circ.measure(0, 0)
rxt_q0 = pulse.Schedule(
pulse.Play(
pulse.library.Gaussian(duration=128, sigma=4 * sigma, amp=0.2 * theta / 3.14),
pulse.DriveChannel(0),
)
)
circ.add_calibration("rxt", [0], rxt_q0, [theta / 2, sigma])
circ = circ.assign_parameters({theta: 3.14, sigma: 4})
instruction = circ.data[0]
cal_key = (
tuple(circ.find_bit(q).index for q in instruction.qubits),
tuple(instruction.operation.params),
)
self.assertEqual(cal_key, ((0,), (3.14 / 2, 4)))
# Make sure that key from instruction data matches the calibrations dictionary
self.assertIn(cal_key, circ.calibrations["rxt"])
sched = circ.calibrations["rxt"][cal_key]
self.assertEqual(sched.instructions[0][1].pulse.amp, 0.2)
self.assertEqual(sched.instructions[0][1].pulse.sigma, 16)
def test_substitution(self):
"""Test Parameter substitution (vs bind)."""
alpha = Parameter("⍺")
beta = Parameter("beta")
schedule = pulse.Schedule(pulse.ShiftPhase(alpha, pulse.DriveChannel(0)))
circ = QuantumCircuit(3, 3)
circ.append(Gate("my_rz", 1, [alpha]), [0])
circ.add_calibration("my_rz", [0], schedule, [alpha])
circ = circ.assign_parameters({alpha: 2 * beta})
circ = circ.assign_parameters({beta: 1.57})
cal_sched = circ.calibrations["my_rz"][((0,), (3.14,))]
self.assertEqual(float(cal_sched.instructions[0][1].phase), 3.14)
def test_partial_assignment(self):
"""Expressions of parameters with partial assignment."""
alpha = Parameter("⍺")
beta = Parameter("beta")
gamma = Parameter("γ")
phi = Parameter("ϕ")
with pulse.build() as my_cal:
pulse.set_frequency(alpha + beta, pulse.DriveChannel(0))
pulse.shift_frequency(gamma + beta, pulse.DriveChannel(0))
pulse.set_phase(phi, pulse.DriveChannel(1))
circ = QuantumCircuit(2, 2)
circ.append(Gate("custom", 2, [alpha, beta, gamma, phi]), [0, 1])
circ.add_calibration("custom", [0, 1], my_cal, [alpha, beta, gamma, phi])
# Partial bind
delta = 1e9
freq = 4.5e9
shift = 0.5e9
phase = 3.14 / 4
circ = circ.assign_parameters({alpha: freq - delta})
cal_sched = list(circ.calibrations["custom"].values())[0]
self.assertEqual(cal_sched.instructions[0][1].frequency, freq - delta + beta)
circ = circ.assign_parameters({beta: delta})
cal_sched = list(circ.calibrations["custom"].values())[0]
self.assertEqual(float(cal_sched.instructions[0][1].frequency), freq)
self.assertEqual(cal_sched.instructions[1][1].frequency, gamma + delta)
circ = circ.assign_parameters({gamma: shift - delta})
cal_sched = list(circ.calibrations["custom"].values())[0]
self.assertEqual(float(cal_sched.instructions[1][1].frequency), shift)
self.assertEqual(cal_sched.instructions[2][1].phase, phi)
circ = circ.assign_parameters({phi: phase})
cal_sched = list(circ.calibrations["custom"].values())[0]
self.assertEqual(float(cal_sched.instructions[2][1].phase), phase)
def test_circuit_generation(self):
"""Test creating a series of circuits parametrically"""
theta = Parameter("θ")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta, qr)
backend = BasicAer.get_backend("qasm_simulator")
qc_aer = transpile(qc, backend)
# generate list of circuits
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
circs = []
theta_list = numpy.linspace(0, numpy.pi, 20)
for theta_i in theta_list:
circs.append(getattr(qc_aer, assign_fun)({theta: theta_i}))
qobj = assemble(circs)
for index, theta_i in enumerate(theta_list):
res = float(qobj.experiments[index].instructions[0].params[0])
self.assertTrue(math.isclose(res, theta_i), f"{res} != {theta_i}")
def test_circuit_composition(self):
"""Test preservation of parameters when combining circuits."""
theta = Parameter("θ")
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc1 = QuantumCircuit(qr, cr)
qc1.rx(theta, qr)
phi = Parameter("phi")
qc2 = QuantumCircuit(qr, cr)
qc2.ry(phi, qr)
qc2.h(qr)
qc2.measure(qr, cr)
qc3 = qc1.compose(qc2)
self.assertEqual(qc3.parameters, {theta, phi})
def test_composite_instruction(self):
"""Test preservation of parameters via parameterized instructions."""
theta = Parameter("θ")
qr1 = QuantumRegister(1, name="qr1")
qc1 = QuantumCircuit(qr1)
qc1.rx(theta, qr1)
qc1.rz(numpy.pi / 2, qr1)
qc1.ry(theta, qr1)
gate = qc1.to_instruction()
self.assertEqual(gate.params, [theta])
phi = Parameter("phi")
qr2 = QuantumRegister(3, name="qr2")
qc2 = QuantumCircuit(qr2)
qc2.ry(phi, qr2[0])
qc2.h(qr2)
qc2.append(gate, qargs=[qr2[1]])
self.assertEqual(qc2.parameters, {theta, phi})
def test_parameter_name_conflicts_raises(self):
"""Verify attempting to add different parameters with matching names raises an error."""
theta1 = Parameter("theta")
theta2 = Parameter("theta")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.p(theta1, 0)
self.assertRaises(CircuitError, qc.p, theta2, 0)
def test_bind_ryrz_vector(self):
"""Test binding a list of floats to a ParameterVector"""
qc = QuantumCircuit(4)
depth = 4
theta = ParameterVector("θ", length=len(qc.qubits) * depth * 2)
theta_iter = iter(theta)
for _ in range(depth):
for q in qc.qubits:
qc.ry(next(theta_iter), q)
qc.rz(next(theta_iter), q)
for i, q in enumerate(qc.qubits[:-1]):
qc.cx(qc.qubits[i], qc.qubits[i + 1])
qc.barrier()
theta_vals = numpy.linspace(0, 1, len(theta)) * numpy.pi
self.assertEqual(set(qc.parameters), set(theta.params))
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
bqc = getattr(qc, assign_fun)({theta: theta_vals})
for instruction in bqc.data:
if hasattr(instruction.operation, "params") and instruction.operation.params:
self.assertIn(float(instruction.operation.params[0]), theta_vals)
def test_compile_vector(self):
"""Test compiling a circuit with an unbound ParameterVector"""
qc = QuantumCircuit(4)
depth = 4
theta = ParameterVector("θ", length=len(qc.qubits) * depth * 2)
theta_iter = iter(theta)
for _ in range(depth):
for q in qc.qubits:
qc.ry(next(theta_iter), q)
qc.rz(next(theta_iter), q)
for i, q in enumerate(qc.qubits[:-1]):
qc.cx(qc.qubits[i], qc.qubits[i + 1])
qc.barrier()
backend = BasicAer.get_backend("qasm_simulator")
qc_aer = transpile(qc, backend)
for param in theta:
self.assertIn(param, qc_aer.parameters)
def test_instruction_ryrz_vector(self):
"""Test constructing a circuit from instructions with remapped ParameterVectors"""
qubits = 5
depth = 4
ryrz = QuantumCircuit(qubits, name="ryrz")
theta = ParameterVector("θ0", length=len(ryrz.qubits) * 2)
theta_iter = iter(theta)
for q in ryrz.qubits:
ryrz.ry(next(theta_iter), q)
ryrz.rz(next(theta_iter), q)
cxs = QuantumCircuit(qubits - 1, name="cxs")
for i, _ in enumerate(cxs.qubits[:-1:2]):
cxs.cx(cxs.qubits[2 * i], cxs.qubits[2 * i + 1])
paramvecs = []
qc = QuantumCircuit(qubits)
for i in range(depth):
theta_l = ParameterVector(f"θ{i + 1}", length=len(ryrz.qubits) * 2)
ryrz_inst = ryrz.to_instruction(parameter_map={theta: theta_l})
paramvecs += [theta_l]
qc.append(ryrz_inst, qargs=qc.qubits)
qc.append(cxs, qargs=qc.qubits[1:])
qc.append(cxs, qargs=qc.qubits[:-1])
qc.barrier()
backend = BasicAer.get_backend("qasm_simulator")
qc_aer = transpile(qc, backend)
for vec in paramvecs:
for param in vec:
self.assertIn(param, qc_aer.parameters)
@data("single", "vector")
def test_parameter_equality_through_serialization(self, ptype):
"""Verify parameters maintain their equality after serialization."""
if ptype == "single":
x1 = Parameter("x")
x2 = Parameter("x")
else:
x1 = ParameterVector("x", 2)[0]
x2 = ParameterVector("x", 2)[0]
x1_p = pickle.loads(pickle.dumps(x1))
x2_p = pickle.loads(pickle.dumps(x2))
self.assertEqual(x1, x1_p)
self.assertEqual(x2, x2_p)
self.assertNotEqual(x1, x2_p)
self.assertNotEqual(x2, x1_p)
def test_binding_parameterized_circuits_built_in_multiproc(self):
"""Verify subcircuits built in a subprocess can still be bound."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2429
num_processes = 4
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
parameters = [Parameter(f"x{i}") for i in range(num_processes)]
results = parallel_map(
_construct_circuit, parameters, task_args=(qr,), num_processes=num_processes
)
for qc in results:
circuit.compose(qc, inplace=True)
parameter_values = [{x: 1.0 for x in parameters}]
qobj = assemble(
circuit,
backend=BasicAer.get_backend("qasm_simulator"),
parameter_binds=parameter_values,
)
self.assertEqual(len(qobj.experiments), 1)
self.assertEqual(len(qobj.experiments[0].instructions), 4)
self.assertTrue(
all(
len(inst.params) == 1
and isinstance(inst.params[0], float)
and float(inst.params[0]) == 1
for inst in qobj.experiments[0].instructions
)
)
def test_transpiling_multiple_parameterized_circuits(self):
"""Verify several parameterized circuits can be transpiled at once."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2864
qr = QuantumRegister(1)
qc1 = QuantumCircuit(qr)
qc2 = QuantumCircuit(qr)
theta = Parameter("theta")
qc1.u(theta, 0, 0, qr[0])
qc2.u(theta, 3.14, 0, qr[0])
circuits = [qc1, qc2]
job = execute(
circuits,
BasicAer.get_backend("unitary_simulator"),
shots=512,
parameter_binds=[{theta: 1}],
)
self.assertTrue(len(job.result().results), 2)
@data(0, 1, 2, 3)
def test_transpile_across_optimization_levels(self, opt_level):
"""Verify parameterized circuits can be transpiled with all default pass managers."""
qc = QuantumCircuit(5, 5)
theta = Parameter("theta")
phi = Parameter("phi")
qc.rx(theta, 0)
qc.x(0)
for i in range(5 - 1):
qc.rxx(phi, i, i + 1)
qc.measure(range(5 - 1), range(5 - 1))
transpile(qc, FakeOurense(), optimization_level=opt_level)
def test_repeated_gates_to_dag_and_back(self):
"""Verify circuits with repeated parameterized gates can be converted
to DAG and back, maintaining consistency of circuit._parameter_table."""
from qiskit.converters import circuit_to_dag, dag_to_circuit
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.p(theta, qr[0])
double_qc = qc.compose(qc)
test_qc = dag_to_circuit(circuit_to_dag(double_qc))
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
bound_test_qc = getattr(test_qc, assign_fun)({theta: 1})
self.assertEqual(len(bound_test_qc.parameters), 0)
def test_rebinding_instruction_copy(self):
"""Test rebinding a copied instruction does not modify the original."""
theta = Parameter("th")
qc = QuantumCircuit(1)
qc.rx(theta, 0)
instr = qc.to_instruction()
qc1 = QuantumCircuit(1)
qc1.append(instr, [0])
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
output1 = getattr(qc1, assign_fun)({theta: 0.1}).decompose()
output2 = getattr(qc1, assign_fun)({theta: 0.2}).decompose()
expected1 = QuantumCircuit(1)
expected1.rx(0.1, 0)
expected2 = QuantumCircuit(1)
expected2.rx(0.2, 0)
self.assertEqual(expected1, output1)
self.assertEqual(expected2, output2)
@combine(target_type=["gate", "instruction"], parameter_type=["numbers", "parameters"])
def test_decompose_propagates_bound_parameters(self, target_type, parameter_type):
"""Verify bind-before-decompose preserves bound values."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2482
theta = Parameter("th")
qc = QuantumCircuit(1)
qc.rx(theta, 0)
if target_type == "gate":
inst = qc.to_gate()
elif target_type == "instruction":
inst = qc.to_instruction()
qc2 = QuantumCircuit(1)
qc2.append(inst, [0])
if parameter_type == "numbers":
bound_qc2 = qc2.assign_parameters({theta: 0.5})
expected_parameters = set()
expected_qc2 = QuantumCircuit(1)
expected_qc2.rx(0.5, 0)
else:
phi = Parameter("ph")
bound_qc2 = qc2.assign_parameters({theta: phi})
expected_parameters = {phi}
expected_qc2 = QuantumCircuit(1)
expected_qc2.rx(phi, 0)
decomposed_qc2 = bound_qc2.decompose()
with self.subTest(msg="testing parameters of initial circuit"):
self.assertEqual(qc2.parameters, {theta})
with self.subTest(msg="testing parameters of bound circuit"):
self.assertEqual(bound_qc2.parameters, expected_parameters)
with self.subTest(msg="testing parameters of deep decomposed bound circuit"):
self.assertEqual(decomposed_qc2.parameters, expected_parameters)
with self.subTest(msg="testing deep decomposed circuit"):
self.assertEqual(decomposed_qc2, expected_qc2)
@combine(target_type=["gate", "instruction"], parameter_type=["numbers", "parameters"])
def test_decompose_propagates_deeply_bound_parameters(self, target_type, parameter_type):
"""Verify bind-before-decompose preserves deeply bound values."""
theta = Parameter("th")
qc1 = QuantumCircuit(1)
qc1.rx(theta, 0)
if target_type == "gate":
inst = qc1.to_gate()
elif target_type == "instruction":
inst = qc1.to_instruction()
qc2 = QuantumCircuit(1)
qc2.append(inst, [0])
if target_type == "gate":
inst = qc2.to_gate()
elif target_type == "instruction":
inst = qc2.to_instruction()
qc3 = QuantumCircuit(1)
qc3.append(inst, [0])
if parameter_type == "numbers":
bound_qc3 = qc3.assign_parameters({theta: 0.5})
expected_parameters = set()
expected_qc3 = QuantumCircuit(1)
expected_qc3.rx(0.5, 0)
else:
phi = Parameter("ph")
bound_qc3 = qc3.assign_parameters({theta: phi})
expected_parameters = {phi}
expected_qc3 = QuantumCircuit(1)
expected_qc3.rx(phi, 0)
deep_decomposed_qc3 = bound_qc3.decompose().decompose()
with self.subTest(msg="testing parameters of initial circuit"):
self.assertEqual(qc3.parameters, {theta})
with self.subTest(msg="testing parameters of bound circuit"):
self.assertEqual(bound_qc3.parameters, expected_parameters)
with self.subTest(msg="testing parameters of deep decomposed bound circuit"):
self.assertEqual(deep_decomposed_qc3.parameters, expected_parameters)
with self.subTest(msg="testing deep decomposed circuit"):
self.assertEqual(deep_decomposed_qc3, expected_qc3)
@data("gate", "instruction")
def test_executing_parameterized_instruction_bound_early(self, target_type):
"""Verify bind-before-execute preserves bound values."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2482
theta = Parameter("theta")
sub_qc = QuantumCircuit(2)
sub_qc.h(0)
sub_qc.cx(0, 1)
sub_qc.rz(theta, [0, 1])
sub_qc.cx(0, 1)
sub_qc.h(0)
if target_type == "gate":
sub_inst = sub_qc.to_gate()
elif target_type == "instruction":
sub_inst = sub_qc.to_instruction()
unbound_qc = QuantumCircuit(2, 1)
unbound_qc.append(sub_inst, [0, 1], [])
unbound_qc.measure(0, 0)
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
bound_qc = getattr(unbound_qc, assign_fun)({theta: numpy.pi / 2})
shots = 1024
job = execute(bound_qc, backend=BasicAer.get_backend("qasm_simulator"), shots=shots)
self.assertDictAlmostEqual(job.result().get_counts(), {"1": shots}, 0.05 * shots)
def test_num_parameters(self):
"""Test the num_parameters property."""
with self.subTest(msg="standard case"):
theta = Parameter("θ")
x = Parameter("x")
qc = QuantumCircuit(1)
qc.rx(theta, 0)
qc.u(0, theta, x, 0)
self.assertEqual(qc.num_parameters, 2)
with self.subTest(msg="parameter vector"):
params = ParameterVector("x", length=3)
qc = QuantumCircuit(4)
qc.rx(params[0], 2)
qc.ry(params[1], 1)
qc.rz(params[2], 3)
self.assertEqual(qc.num_parameters, 3)
with self.subTest(msg="no params"):
qc = QuantumCircuit(1)
qc.x(0)
self.assertEqual(qc.num_parameters, 0)
def test_execute_result_names(self):
"""Test unique names for list of parameter binds."""
theta = Parameter("θ")
reps = 5
qc = QuantumCircuit(1, 1)
qc.rx(theta, 0)
qc.measure(0, 0)
plist = [{theta: i} for i in range(reps)]
simulator = BasicAer.get_backend("qasm_simulator")
result = execute(qc, backend=simulator, parameter_binds=plist).result()
result_names = {res.name for res in result.results}
self.assertEqual(reps, len(result_names))
def test_to_instruction_after_inverse(self):
"""Verify converting an inverse generates a valid ParameterTable"""
# ref: https://github.com/Qiskit/qiskit-terra/issues/4235
qc = QuantumCircuit(1)
theta = Parameter("theta")
qc.rz(theta, 0)
inv_instr = qc.inverse().to_instruction()
self.assertIsInstance(inv_instr, Instruction)
def test_repeated_circuit(self):
"""Test repeating a circuit maintains the parameters."""
qc = QuantumCircuit(1)
theta = Parameter("theta")
qc.rz(theta, 0)
rep = qc.repeat(3)
self.assertEqual(rep.parameters, {theta})
def test_copy_after_inverse(self):
"""Verify circuit.inverse generates a valid ParameterTable."""
qc = QuantumCircuit(1)
theta = Parameter("theta")
qc.rz(theta, 0)
inverse = qc.inverse()
self.assertIn(theta, inverse.parameters)
raise_if_parameter_table_invalid(inverse)
def test_copy_after_reverse(self):
"""Verify circuit.reverse generates a valid ParameterTable."""
qc = QuantumCircuit(1)
theta = Parameter("theta")
qc.rz(theta, 0)
reverse = qc.reverse_ops()
self.assertIn(theta, reverse.parameters)
raise_if_parameter_table_invalid(reverse)
def test_copy_after_dot_data_setter(self):
"""Verify setting circuit.data generates a valid ParameterTable."""
qc = QuantumCircuit(1)
theta = Parameter("theta")
qc.rz(theta, 0)
qc.data = []
self.assertEqual(qc.parameters, set())
raise_if_parameter_table_invalid(qc)
def test_circuit_with_ufunc(self):
"""Test construction of circuit and binding of parameters
after we apply universal functions."""
from math import pi
phi = Parameter(name="phi")
theta = Parameter(name="theta")
qc = QuantumCircuit(2)
qc.p(numpy.abs(-phi), 0)
qc.p(numpy.cos(phi), 0)
qc.p(numpy.sin(phi), 0)
qc.p(numpy.tan(phi), 0)
qc.rz(numpy.arccos(theta), 1)
qc.rz(numpy.arctan(theta), 1)
qc.rz(numpy.arcsin(theta), 1)
qc.assign_parameters({phi: pi, theta: 1}, inplace=True)
qc_ref = QuantumCircuit(2)
qc_ref.p(pi, 0)
qc_ref.p(-1, 0)
qc_ref.p(0, 0)
qc_ref.p(0, 0)
qc_ref.rz(0, 1)
qc_ref.rz(pi / 4, 1)
qc_ref.rz(pi / 2, 1)
self.assertEqual(qc, qc_ref)
def test_compile_with_ufunc(self):
"""Test compiling of circuit with unbound parameters
after we apply universal functions."""
from math import pi
theta = ParameterVector("theta", length=7)
qc = QuantumCircuit(7)
qc.rx(numpy.abs(theta[0]), 0)
qc.rx(numpy.cos(theta[1]), 1)
qc.rx(numpy.sin(theta[2]), 2)
qc.rx(numpy.tan(theta[3]), 3)
qc.rx(numpy.arccos(theta[4]), 4)
qc.rx(numpy.arctan(theta[5]), 5)
qc.rx(numpy.arcsin(theta[6]), 6)
# transpile to different basis
transpiled = transpile(qc, basis_gates=["rz", "sx", "x", "cx"], optimization_level=0)
for x in theta:
self.assertIn(x, transpiled.parameters)
bound = transpiled.bind_parameters({theta: [-1, pi, pi, pi, 1, 1, 1]})
expected = QuantumCircuit(7)
expected.rx(1.0, 0)
expected.rx(-1.0, 1)
expected.rx(0.0, 2)
expected.rx(0.0, 3)
expected.rx(0.0, 4)
expected.rx(pi / 4, 5)
expected.rx(pi / 2, 6)
expected = transpile(expected, basis_gates=["rz", "sx", "x", "cx"], optimization_level=0)
self.assertEqual(expected, bound)
def test_parametervector_resize(self):
"""Test the resize method of the parameter vector."""
vec = ParameterVector("x", 2)
element = vec[1] # store an entry for instancecheck later on
with self.subTest("shorten"):
vec.resize(1)
self.assertEqual(len(vec), 1)
self.assertListEqual([param.name for param in vec], _paramvec_names("x", 1))
with self.subTest("enlargen"):
vec.resize(3)
self.assertEqual(len(vec), 3)
# ensure we still have the same instance not a copy with the same name
# this is crucial for adding parameters to circuits since we cannot use the same
# name if the instance is not the same
self.assertIs(element, vec[1])
self.assertListEqual([param.name for param in vec], _paramvec_names("x", 3))
def test_raise_if_sub_unknown_parameters(self):
"""Verify we raise if asked to sub a parameter not in self."""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
with self.assertRaisesRegex(CircuitError, "not present"):
x.subs({y: z})
def test_sub_allow_unknown_parameters(self):
"""Verify we raise if asked to sub a parameter not in self."""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
subbed = x.subs({y: z}, allow_unknown_parameters=True)
self.assertEqual(subbed, x)
def _construct_circuit(param, qr):
qc = QuantumCircuit(qr)
qc.ry(param, qr[0])
return qc
def _paramvec_names(prefix, length):
return [f"{prefix}[{i}]" for i in range(length)]
@ddt
class TestParameterExpressions(QiskitTestCase):
"""Test expressions of Parameters."""
supported_operations = [add, sub, mul, truediv]
def test_compare_to_value_when_bound(self):
"""Verify expression can be compared to a fixed value
when fully bound."""
x = Parameter("x")
bound_expr = x.bind({x: 2.3})
self.assertEqual(bound_expr, 2.3)
def test_abs_function_when_bound(self):
"""Verify expression can be used with
abs functions when bound."""
x = Parameter("x")
xb_1 = x.bind({x: 2.0})
xb_2 = x.bind({x: 3.0 + 4.0j})
self.assertEqual(abs(xb_1), 2.0)
self.assertEqual(abs(-xb_1), 2.0)
self.assertEqual(abs(xb_2), 5.0)
def test_abs_function_when_not_bound(self):
"""Verify expression can be used with
abs functions when not bound."""
x = Parameter("x")
y = Parameter("y")
self.assertEqual(abs(x), abs(-x))
self.assertEqual(abs(x) * abs(y), abs(x * y))
self.assertEqual(abs(x) / abs(y), abs(x / y))
def test_cast_to_complex_when_bound(self):
"""Verify that the cast to complex works for bound objects."""
x = Parameter("x")
y = Parameter("y")
bound_expr = (x + y).bind({x: 1.0, y: 1j})
self.assertEqual(complex(bound_expr), 1 + 1j)
def test_raise_if_cast_to_complex_when_not_fully_bound(self):
"""Verify raises if casting to complex and not fully bound."""
x = Parameter("x")
y = Parameter("y")
bound_expr = (x + y).bind({x: 1j})
with self.assertRaisesRegex(TypeError, "unbound parameters"):
complex(bound_expr)
def test_cast_to_float_when_bound(self):
"""Verify expression can be cast to a float when fully bound."""
x = Parameter("x")
bound_expr = x.bind({x: 2.3})
self.assertEqual(float(bound_expr), 2.3)
def test_cast_to_float_when_underlying_expression_bound(self):
"""Verify expression can be cast to a float when it still contains unbound parameters, but
the underlying symbolic expression has a knowable value."""
x = Parameter("x")
expr = x - x + 2.3
self.assertEqual(float(expr), 2.3)
def test_cast_to_float_intermediate_complex_value(self):
"""Verify expression can be cast to a float when it is fully bound, but an intermediate part
of the expression evaluation involved complex types. Sympy is generally more permissive
than symengine here, and sympy's tends to be the expected behaviour for our users."""
x = Parameter("x")
bound_expr = (x + 1.0 + 1.0j).bind({x: -1.0j})
self.assertEqual(float(bound_expr), 1.0)
def test_cast_to_float_of_complex_fails(self):
"""Test that an attempt to produce a float from a complex value fails if there is an
imaginary part, with a sensible error message."""
x = Parameter("x")
bound_expr = (x + 1.0j).bind({x: 1.0})
with self.assertRaisesRegex(TypeError, "could not cast expression to float"):
float(bound_expr)
def test_raise_if_cast_to_float_when_not_fully_bound(self):
"""Verify raises if casting to float and not fully bound."""
x = Parameter("x")
y = Parameter("y")
bound_expr = (x + y).bind({x: 2.3})
with self.assertRaisesRegex(TypeError, "unbound parameters"):
float(bound_expr)
def test_cast_to_int_when_bound(self):
"""Verify expression can be cast to an int when fully bound."""
x = Parameter("x")
bound_expr = x.bind({x: 2.3})
self.assertEqual(int(bound_expr), 2)
def test_cast_to_int_when_bound_truncates_after_evaluation(self):
"""Verify expression can be cast to an int when fully bound, but
truncated only after evaluation."""
x = Parameter("x")
y = Parameter("y")
bound_expr = (x + y).bind({x: 2.3, y: 0.8})
self.assertEqual(int(bound_expr), 3)
def test_cast_to_int_when_underlying_expression_bound(self):
"""Verify expression can be cast to a int when it still contains unbound parameters, but the
underlying symbolic expression has a knowable value."""
x = Parameter("x")
expr = x - x + 2.3
self.assertEqual(int(expr), 2)
def test_raise_if_cast_to_int_when_not_fully_bound(self):
"""Verify raises if casting to int and not fully bound."""
x = Parameter("x")
y = Parameter("y")
bound_expr = (x + y).bind({x: 2.3})
with self.assertRaisesRegex(TypeError, "unbound parameters"):
int(bound_expr)
def test_raise_if_sub_unknown_parameters(self):
"""Verify we raise if asked to sub a parameter not in self."""
x = Parameter("x")
expr = x + 2
y = Parameter("y")
z = Parameter("z")
with self.assertRaisesRegex(CircuitError, "not present"):
expr.subs({y: z})
def test_sub_allow_unknown_parameters(self):
"""Verify we raise if asked to sub a parameter not in self."""
x = Parameter("x")
expr = x + 2
y = Parameter("y")
z = Parameter("z")
subbed = expr.subs({y: z}, allow_unknown_parameters=True)
self.assertEqual(subbed, expr)
def test_raise_if_subbing_in_parameter_name_conflict(self):
"""Verify we raise if substituting in conflicting parameter names."""
x = Parameter("x")
y_first = Parameter("y")
expr = x + y_first
y_second = Parameter("y")
# Replacing an existing name is okay.
expr.subs({y_first: y_second})
with self.assertRaisesRegex(CircuitError, "Name conflict"):
expr.subs({x: y_second})
def test_expressions_of_parameter_with_constant(self):
"""Verify operating on a Parameter with a constant."""
good_constants = [2, 1.3, 0, -1, -1.0, numpy.pi, 1j]
x = Parameter("x")
for op in self.supported_operations:
for const in good_constants:
expr = op(const, x)
bound_expr = expr.bind({x: 2.3})
self.assertEqual(complex(bound_expr), op(const, 2.3))
# Division by zero will raise. Tested elsewhere.
if const == 0 and op == truediv:
continue
# Repeat above, swapping position of Parameter and constant.
expr = op(x, const)
bound_expr = expr.bind({x: 2.3})
res = complex(bound_expr)
expected = op(2.3, const)
self.assertTrue(cmath.isclose(res, expected), f"{res} != {expected}")
def test_complex_parameter_bound_to_real(self):
"""Test a complex parameter expression can be real if bound correctly."""
x, y = Parameter("x"), Parameter("y")
with self.subTest("simple 1j * x"):
qc = QuantumCircuit(1)
qc.rx(1j * x, 0)
bound = qc.bind_parameters({x: 1j})
ref = QuantumCircuit(1)
ref.rx(-1, 0)
self.assertEqual(bound, ref)
with self.subTest("more complex expression"):
qc = QuantumCircuit(1)
qc.rx(0.5j * x - y * y + 2 * y, 0)
bound = qc.bind_parameters({x: -4, y: 1j})
ref = QuantumCircuit(1)
ref.rx(1, 0)
self.assertEqual(bound, ref)
def test_complex_angle_raises_when_not_supported(self):
"""Test parameters are validated when fully bound and errors are raised accordingly."""
x = Parameter("x")
qc = QuantumCircuit(1)
qc.r(x, 1j * x, 0)
with self.subTest("binding x to 0 yields real parameters"):
bound = qc.bind_parameters({x: 0})
ref = QuantumCircuit(1)
ref.r(0, 0, 0)
self.assertEqual(bound, ref)
with self.subTest("binding x to 1 yields complex parameters"):
# RGate does not support complex parameters
with self.assertRaises(CircuitError):
bound = qc.bind_parameters({x: 1})
def test_operating_on_a_parameter_with_a_non_float_will_raise(self):
"""Verify operations between a Parameter and a non-float will raise."""
bad_constants = ["1", numpy.Inf, numpy.NaN, None, {}, []]
x = Parameter("x")
for op in self.supported_operations:
for const in bad_constants:
with self.subTest(op=op, const=const):
with self.assertRaises(TypeError):
_ = op(const, x)
with self.assertRaises(TypeError):
_ = op(x, const)
def test_expressions_division_by_zero(self):
"""Verify dividing a Parameter by 0, or binding 0 as a denominator raises."""
x = Parameter("x")
with self.assertRaises(ZeroDivisionError):
_ = x / 0
with self.assertRaises(ZeroDivisionError):
_ = x / 0.0
expr = 2 / x
with self.assertRaises(ZeroDivisionError):
_ = expr.bind({x: 0})
with self.assertRaises(ZeroDivisionError):
_ = expr.bind({x: 0.0})
def test_expressions_of_parameter_with_parameter(self):
"""Verify operating on two Parameters."""
x = Parameter("x")
y = Parameter("y")
for op in self.supported_operations:
expr = op(x, y)
partially_bound_expr = expr.bind({x: 2.3})
self.assertEqual(partially_bound_expr.parameters, {y})
fully_bound_expr = partially_bound_expr.bind({y: -numpy.pi})
self.assertEqual(fully_bound_expr.parameters, set())
self.assertEqual(float(fully_bound_expr), op(2.3, -numpy.pi))
bound_expr = expr.bind({x: 2.3, y: -numpy.pi})
self.assertEqual(bound_expr.parameters, set())
self.assertEqual(float(bound_expr), op(2.3, -numpy.pi))
def test_expressions_operation_order(self):
"""Verify ParameterExpressions respect order of operations."""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
# Parenthesis before multiplication/division
expr = (x + y) * z
bound_expr = expr.bind({x: 1, y: 2, z: 3})
self.assertEqual(float(bound_expr), 9)
expr = x * (y + z)
bound_expr = expr.bind({x: 1, y: 2, z: 3})
self.assertEqual(float(bound_expr), 5)
# Multiplication/division before addition/subtraction
expr = x + y * z
bound_expr = expr.bind({x: 1, y: 2, z: 3})
self.assertEqual(float(bound_expr), 7)
expr = x * y + z
bound_expr = expr.bind({x: 1, y: 2, z: 3})
self.assertEqual(float(bound_expr), 5)
def test_nested_expressions(self):
"""Verify ParameterExpressions can also be the target of operations."""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
expr1 = x * y
expr2 = expr1 + z
bound_expr2 = expr2.bind({x: 1, y: 2, z: 3})
self.assertEqual(float(bound_expr2), 5)
def test_negated_expression(self):
"""Verify ParameterExpressions can be negated."""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
expr1 = -x + y
expr2 = -expr1 * (-z)
bound_expr2 = expr2.bind({x: 1, y: 2, z: 3})
self.assertEqual(float(bound_expr2), 3)
def test_standard_cu3(self):
"""This tests parameter negation in standard extension gate cu3."""
from qiskit.circuit.library import CU3Gate
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
qc = qiskit.QuantumCircuit(2)
qc.append(CU3Gate(x, y, z), [0, 1])
try:
qc.decompose()
except TypeError:
self.fail("failed to decompose cu3 gate with negated parameter expression")
def test_name_collision(self):
"""Verify Expressions of distinct Parameters of shared name raises."""
x = Parameter("p")
y = Parameter("p")
# Expression of the same Parameter are valid.
_ = x + x
_ = x - x
_ = x * x
_ = x / x
with self.assertRaises(CircuitError):
_ = x + y
with self.assertRaises(CircuitError):
_ = x - y
with self.assertRaises(CircuitError):
_ = x * y
with self.assertRaises(CircuitError):
_ = x / y
@combine(target_type=["gate", "instruction"], order=["bind-decompose", "decompose-bind"])
def test_to_instruction_with_expression(self, target_type, order):
"""Test preservation of expressions via parameterized instructions.
┌───────┐┌──────────┐┌───────────┐
qr1_0: |0>┤ Rx(θ) ├┤ Rz(pi/2) ├┤ Ry(phi*θ) ├
└───────┘└──────────┘└───────────┘
┌───────────┐
qr2_0: |0>───┤ Ry(delta) ├───
┌──┴───────────┴──┐
qr2_1: |0>┤ Circuit0(phi,θ) ├
└─────────────────┘
qr2_2: |0>───────────────────
"""
theta = Parameter("θ")
phi = Parameter("phi")
qr1 = QuantumRegister(1, name="qr1")
qc1 = QuantumCircuit(qr1)
qc1.rx(theta, qr1)
qc1.rz(numpy.pi / 2, qr1)
qc1.ry(theta * phi, qr1)
if target_type == "gate":
gate = qc1.to_gate()
elif target_type == "instruction":
gate = qc1.to_instruction()
self.assertEqual(gate.params, [phi, theta])
delta = Parameter("delta")
qr2 = QuantumRegister(3, name="qr2")
qc2 = QuantumCircuit(qr2)
qc2.ry(delta, qr2[0])
qc2.append(gate, qargs=[qr2[1]])
self.assertEqual(qc2.parameters, {delta, theta, phi})
binds = {delta: 1, theta: 2, phi: 3}
expected_qc = QuantumCircuit(qr2)
expected_qc.rx(2, 1)
expected_qc.rz(numpy.pi / 2, 1)
expected_qc.ry(3 * 2, 1)
expected_qc.r(1, numpy.pi / 2, 0)
if order == "bind-decompose":
decomp_bound_qc = qc2.assign_parameters(binds).decompose()
elif order == "decompose-bind":
decomp_bound_qc = qc2.decompose().assign_parameters(binds)
self.assertEqual(decomp_bound_qc.parameters, set())
self.assertEqual(decomp_bound_qc, expected_qc)
@combine(target_type=["gate", "instruction"], order=["bind-decompose", "decompose-bind"])
def test_to_instruction_expression_parameter_map(self, target_type, order):
"""Test preservation of expressions via instruction parameter_map."""
theta = Parameter("θ")
phi = Parameter("phi")
qr1 = QuantumRegister(1, name="qr1")
qc1 = QuantumCircuit(qr1)
qc1.rx(theta, qr1)
qc1.rz(numpy.pi / 2, qr1)
qc1.ry(theta * phi, qr1)
theta_p = Parameter("theta")
phi_p = Parameter("phi")
if target_type == "gate":
gate = qc1.to_gate(parameter_map={theta: theta_p, phi: phi_p})
elif target_type == "instruction":
gate = qc1.to_instruction(parameter_map={theta: theta_p, phi: phi_p})
self.assertListEqual(gate.params, [theta_p, phi_p])
delta = Parameter("delta")
qr2 = QuantumRegister(3, name="qr2")
qc2 = QuantumCircuit(qr2)
qc2.ry(delta, qr2[0])
qc2.append(gate, qargs=[qr2[1]])
self.assertListEqual(list(qc2.parameters), [delta, phi_p, theta_p])
binds = {delta: 1, theta_p: 2, phi_p: 3}
expected_qc = QuantumCircuit(qr2)
expected_qc.rx(2, 1)
expected_qc.rz(numpy.pi / 2, 1)
expected_qc.ry(3 * 2, 1)
expected_qc.r(1, numpy.pi / 2, 0)
if order == "bind-decompose":
decomp_bound_qc = qc2.assign_parameters(binds).decompose()
elif order == "decompose-bind":
decomp_bound_qc = qc2.decompose().assign_parameters(binds)
self.assertEqual(decomp_bound_qc.parameters, set())
self.assertEqual(decomp_bound_qc, expected_qc)
def test_binding_across_broadcast_instruction(self):
"""Bind a parameter which was included via a broadcast instruction."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/3008
theta = Parameter("θ")
n = 5
qc = QuantumCircuit(n, 1)
qc.h(0)
for i in range(n - 1):
qc.cx(i, i + 1)
qc.barrier()
qc.rz(theta, range(n))
qc.barrier()
for i in reversed(range(n - 1)):
qc.cx(i, i + 1)
qc.h(0)
qc.measure(0, 0)
theta_range = numpy.linspace(0, 2 * numpy.pi, 128)
circuits = [qc.assign_parameters({theta: theta_val}) for theta_val in theta_range]
self.assertEqual(len(circuits), len(theta_range))
for theta_val, bound_circ in zip(theta_range, circuits):
rz_gates = [
inst.operation for inst in bound_circ.data if isinstance(inst.operation, RZGate)
]
self.assertEqual(len(rz_gates), n)
self.assertTrue(all(float(gate.params[0]) == theta_val for gate in rz_gates))
def test_substituting_parameter_with_simple_expression(self):
"""Substitute a simple parameter expression for a parameter."""
x = Parameter("x")
y = Parameter("y")
sub_ = y / 2
updated_expr = x.subs({x: sub_})
expected = y / 2
self.assertEqual(updated_expr, expected)
def test_substituting_parameter_with_compound_expression(self):
"""Substitute a simple parameter expression for a parameter."""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
sub_ = y * z
updated_expr = x.subs({x: sub_})
expected = y * z
self.assertEqual(updated_expr, expected)
def test_substituting_simple_with_simple_expression(self):
"""Substitute a simple parameter expression in a parameter expression."""
x = Parameter("x")
expr = x * x
y = Parameter("y")
sub_ = y / 2
updated_expr = expr.subs({x: sub_})
expected = y * y / 4
self.assertEqual(updated_expr, expected)
def test_substituting_compound_expression(self):
"""Substitute a compound parameter expression in a parameter expression."""
x = Parameter("x")
expr = x * x
y = Parameter("y")
z = Parameter("z")
sub_ = y + z
updated_expr = expr.subs({x: sub_})
expected = (y + z) * (y + z)
self.assertEqual(updated_expr, expected)
def test_conjugate(self):
"""Test calling conjugate on a ParameterExpression."""
x = Parameter("x")
self.assertEqual((x.conjugate() + 1j), (x - 1j).conjugate())
@data(
circlib.RGate,
circlib.RXGate,
circlib.RYGate,
circlib.RZGate,
circlib.RXXGate,
circlib.RYYGate,
circlib.RZXGate,
circlib.RZZGate,
circlib.CRXGate,
circlib.CRYGate,
circlib.CRZGate,
circlib.XXPlusYYGate,
)
def test_bound_gate_to_matrix(self, gate_class):
"""Test to_matrix works if previously free parameters are bound.
The conversion might fail, if trigonometric functions such as cos are called on the
parameters and the parameters are still of type ParameterExpression.
"""
num_parameters = 2 if gate_class == circlib.RGate else 1
params = list(range(1, 1 + num_parameters))
free_params = ParameterVector("th", num_parameters)
gate = gate_class(*params)
num_qubits = gate.num_qubits
circuit = QuantumCircuit(num_qubits)
circuit.append(gate_class(*free_params), list(range(num_qubits)))
bound_circuit = circuit.assign_parameters({free_params: params})
numpy.testing.assert_array_almost_equal(Operator(bound_circuit).data, gate.to_matrix())
def test_parameter_expression_grad(self):
"""Verify correctness of ParameterExpression gradients."""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
with self.subTest(msg="first order gradient"):
expr = (x + y) * z
self.assertEqual(expr.gradient(x), z)
self.assertEqual(expr.gradient(z), (x + y))
with self.subTest(msg="second order gradient"):
expr = x * x
self.assertEqual(expr.gradient(x), 2 * x)
self.assertEqual(expr.gradient(x).gradient(x), 2)
def test_bound_expression_is_real(self):
"""Test is_real on bound parameters."""
x = Parameter("x")
self.assertEqual(x.is_real(), None)
self.assertEqual((1j * x).is_real(), None)
expr = 1j * x
bound = expr.bind({x: 2})
self.assertEqual(bound.is_real(), False)
bound = x.bind({x: 0 + 0j})
self.assertEqual(bound.is_real(), True)
bound = x.bind({x: 0 + 1j})
self.assertEqual(bound.is_real(), False)
bound = x.bind({x: 1 + 0j})
self.assertEqual(bound.is_real(), True)
bound = x.bind({x: 1 + 1j})
self.assertEqual(bound.is_real(), False)
class TestParameterEquality(QiskitTestCase):
"""Test equality of Parameters and ParameterExpressions."""
def test_parameter_equal_self(self):
"""Verify a parameter is equal to it self."""
theta = Parameter("theta")
self.assertEqual(theta, theta)
def test_parameter_not_equal_param_of_same_name(self):
"""Verify a parameter is not equal to a Parameter of the same name."""
theta1 = Parameter("theta")
theta2 = Parameter("theta")
self.assertNotEqual(theta1, theta2)
def test_parameter_expression_equal_to_self(self):
"""Verify an expression is equal to itself."""
theta = Parameter("theta")
expr = 2 * theta
self.assertEqual(expr, expr)
def test_parameter_expression_equal_to_identical(self):
"""Verify an expression is equal an identical expression."""
theta = Parameter("theta")
expr1 = 2 * theta
expr2 = 2 * theta
self.assertEqual(expr1, expr2)
def test_parameter_expression_equal_floats_to_ints(self):
"""Verify an expression with float and int is identical."""
theta = Parameter("theta")
expr1 = 2.0 * theta
expr2 = 2 * theta
self.assertEqual(expr1, expr2)
def test_parameter_expression_not_equal_if_params_differ(self):
"""Verify expressions not equal if parameters are different."""
theta1 = Parameter("theta")
theta2 = Parameter("theta")
expr1 = 2 * theta1
expr2 = 2 * theta2
self.assertNotEqual(expr1, expr2)
def test_parameter_equal_to_identical_expression(self):
"""Verify parameters and ParameterExpressions can be equal if identical."""
theta = Parameter("theta")
phi = Parameter("phi")
expr = (theta + phi).bind({phi: 0})
self.assertEqual(expr, theta)
self.assertEqual(theta, expr)
def test_parameter_symbol_equal_after_ufunc(self):
"""Verfiy ParameterExpression phi
and ParameterExpression cos(phi) have the same symbol map"""
phi = Parameter("phi")
cos_phi = numpy.cos(phi)
self.assertEqual(phi._parameter_symbols, cos_phi._parameter_symbols)
class TestParameterReferences(QiskitTestCase):
"""Test the ParameterReferences class."""
def test_equal_inst_diff_instance(self):
"""Different value equal instructions are treated as distinct."""
theta = Parameter("theta")
gate1 = RZGate(theta)
gate2 = RZGate(theta)
self.assertIsNot(gate1, gate2)
self.assertEqual(gate1, gate2)
refs = ParameterReferences(((gate1, 0), (gate2, 0)))
# test __contains__
self.assertIn((gate1, 0), refs)
self.assertIn((gate2, 0), refs)
gate_ids = {id(gate1), id(gate2)}
self.assertEqual(gate_ids, {id(gate) for gate, _ in refs})
self.assertTrue(all(idx == 0 for _, idx in refs))
def test_pickle_unpickle(self):
"""Membership testing after pickle/unpickle."""
theta = Parameter("theta")
gate1 = RZGate(theta)
gate2 = RZGate(theta)
self.assertIsNot(gate1, gate2)
self.assertEqual(gate1, gate2)
refs = ParameterReferences(((gate1, 0), (gate2, 0)))
to_pickle = (gate1, refs)
pickled = pickle.dumps(to_pickle)
(gate1_new, refs_new) = pickle.loads(pickled)
self.assertEqual(len(refs_new), len(refs))
self.assertNotIn((gate1, 0), refs_new)
self.assertIn((gate1_new, 0), refs_new)
def test_equal_inst_same_instance(self):
"""Referentially equal instructions are treated as same."""
theta = Parameter("theta")
gate = RZGate(theta)
refs = ParameterReferences(((gate, 0), (gate, 0)))
self.assertIn((gate, 0), refs)
self.assertEqual(len(refs), 1)
self.assertIs(next(iter(refs))[0], gate)
self.assertEqual(next(iter(refs))[1], 0)
def test_extend_refs(self):
"""Extending references handles duplicates."""
theta = Parameter("theta")
ref0 = (RZGate(theta), 0)
ref1 = (RZGate(theta), 0)
ref2 = (RZGate(theta), 0)
refs = ParameterReferences((ref0,))
refs |= ParameterReferences((ref0, ref1, ref2, ref1, ref0))
self.assertEqual(refs, ParameterReferences((ref0, ref1, ref2)))
def test_copy_param_refs(self):
"""Copy of parameter references is a shallow copy."""
theta = Parameter("theta")
ref0 = (RZGate(theta), 0)
ref1 = (RZGate(theta), 0)
ref2 = (RZGate(theta), 0)
ref3 = (RZGate(theta), 0)
refs = ParameterReferences((ref0, ref1))
refs_copy = refs.copy()
# Check same gate instances in copy
gate_ids = {id(ref0[0]), id(ref1[0])}
self.assertEqual({id(gate) for gate, _ in refs_copy}, gate_ids)
# add new ref to original and check copy not modified
refs.add(ref2)
self.assertNotIn(ref2, refs_copy)
self.assertEqual(refs_copy, ParameterReferences((ref0, ref1)))
# add new ref to copy and check original not modified
refs_copy.add(ref3)
self.assertNotIn(ref3, refs)
self.assertEqual(refs, ParameterReferences((ref0, ref1, ref2)))
class TestParameterTable(QiskitTestCase):
"""Test the ParameterTable class."""
def test_init_param_table(self):
"""Parameter table init from mapping."""
p1 = Parameter("theta")
p2 = Parameter("theta")
ref0 = (RZGate(p1), 0)
ref1 = (RZGate(p1), 0)
ref2 = (RZGate(p2), 0)
mapping = {p1: ParameterReferences((ref0, ref1)), p2: ParameterReferences((ref2,))}
table = ParameterTable(mapping)
# make sure editing mapping doesn't change `table`
del mapping[p1]
self.assertEqual(table[p1], ParameterReferences((ref0, ref1)))
self.assertEqual(table[p2], ParameterReferences((ref2,)))
def test_set_references(self):
"""References replacement by parameter key."""
p1 = Parameter("theta")
ref0 = (RZGate(p1), 0)
ref1 = (RZGate(p1), 0)
table = ParameterTable()
table[p1] = ParameterReferences((ref0, ref1))
self.assertEqual(table[p1], ParameterReferences((ref0, ref1)))
table[p1] = ParameterReferences((ref1,))
self.assertEqual(table[p1], ParameterReferences((ref1,)))
def test_set_references_from_iterable(self):
"""Parameter table init from iterable."""
p1 = Parameter("theta")
ref0 = (RZGate(p1), 0)
ref1 = (RZGate(p1), 0)
ref2 = (RZGate(p1), 0)
table = ParameterTable({p1: ParameterReferences((ref0, ref1))})
table[p1] = (ref2, ref1, ref0)
self.assertEqual(table[p1], ParameterReferences((ref2, ref1, ref0)))
class TestParameterView(QiskitTestCase):
"""Test the ParameterView object."""
def setUp(self):
super().setUp()
x, y, z = Parameter("x"), Parameter("y"), Parameter("z")
self.params = [x, y, z]
self.view1 = ParameterView([x, y])
self.view2 = ParameterView([y, z])
self.view3 = ParameterView([x])
def test_and(self):
"""Test __and__."""
self.assertEqual(self.view1 & self.view2, {self.params[1]})
def test_or(self):
"""Test __or__."""
self.assertEqual(self.view1 | self.view2, set(self.params))
def test_xor(self):
"""Test __xor__."""
self.assertEqual(self.view1 ^ self.view2, {self.params[0], self.params[2]})
def test_len(self):
"""Test __len__."""
self.assertEqual(len(self.view1), 2)
def test_le(self):
"""Test __le__."""
self.assertTrue(self.view1 <= self.view1)
self.assertFalse(self.view1 <= self.view3)
def test_lt(self):
"""Test __lt__."""
self.assertTrue(self.view3 < self.view1)
def test_ge(self):
"""Test __ge__."""
self.assertTrue(self.view1 >= self.view1)
self.assertFalse(self.view3 >= self.view1)
def test_gt(self):
"""Test __lt__."""
self.assertTrue(self.view1 > self.view3)
def test_eq(self):
"""Test __eq__."""
self.assertTrue(self.view1 == self.view1)
self.assertFalse(self.view3 == self.view1)
def test_ne(self):
"""Test __eq__."""
self.assertTrue(self.view1 != self.view2)
self.assertFalse(self.view3 != self.view3)
if __name__ == "__main__":
unittest.main()
|
https://github.com/googlercolin/Qiskit-Course
|
googlercolin
|
# !pip install -r 'requirements.txt' --quiet
import numpy as np
import torch
from torchvision.transforms import ToTensor
from torch import no_grad
from torchvision import datasets
import torch.optim as optim
from torch.nn import (Module, Conv2d, Linear, Dropout2d, NLLLoss, MaxPool2d, Flatten, Sequential, ReLU)
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import qiskit
from qiskit import transpile, assemble
from qiskit.visualization import *
from qiskit import Aer, QuantumCircuit
from qiskit.utils import QuantumInstance
from qiskit.opflow import AerPauliExpectation
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit_machine_learning.neural_networks import CircuitQNN, TwoLayerQNN
from qiskit_machine_learning.connectors import TorchConnector
import matplotlib.pyplot as plt
# Declare Quantum instance
qi = QuantumInstance(Aer.get_backend('aer_simulator_statevector'))
### Training and test data downloaded from FashionMNIST and transformed into tensors ###
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor()
)
test_data = datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor()
)
### Inspecting the images in the training data set with their labels ###
labels_map = {
0: "T-Shirt",
1: "Trouser",
2: "Pullover",
3: "Dress",
4: "Coat",
5: "Sandal",
6: "Shirt",
7: "Sneaker",
8: "Bag",
9: "Ankle Boot",
}
figure = plt.figure(figsize=(8, 8))
cols, rows = 3, 3
for i in range(1, cols * rows + 1):
sample_idx = torch.randint(len(training_data), size=(1,)).item()
img, label = training_data[sample_idx]
figure.add_subplot(rows, cols, i)
plt.title(labels_map[label])
plt.axis("off")
plt.imshow(img.squeeze(), cmap="gray")
plt.show()
### Load training data into Torch DataLoader ###
X_train = training_data
n_samples = 500
batch_size = 64
# Filter out labels (originally 0-9), leaving only labels 0 and 1
idx = np.append(np.where(X_train.targets == 0)[0][:n_samples],
np.where(X_train.targets == 1)[0][:n_samples])
X_train.data = X_train.data[idx]
X_train.targets = X_train.targets[idx]
# A torch dataloader is defined with filtered data
train_loader = DataLoader(X_train, batch_size=64, shuffle=True)
# Load test data into Torch DataLoader
X_test = test_data
# Filter out labels (originally 0-9), leaving only labels 0 and 1
idx = np.append(np.where(X_test.targets == 0)[0][:n_samples],
np.where(X_test.targets == 1)[0][:n_samples])
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
# Define torch dataloader with filtered data
test_loader = DataLoader(X_test, batch_size=64, shuffle=True)
### Two layer QNN constructed ###
feature_map = ZZFeatureMap(feature_dimension=2, entanglement='linear')
ansatz = RealAmplitudes(2, reps=1, entanglement='linear')
qnn2 = TwoLayerQNN(2, feature_map, ansatz, input_gradients=True,
exp_val=AerPauliExpectation(), quantum_instance=qi)
print(qnn2.operator)
### Torch NN module from Qiskit ###
class Net(Module):
def __init__(self):
super().__init__()
self.conv1 = Conv2d(1, 2, kernel_size=5)
self.conv2 = Conv2d(2, 16, kernel_size=5)
self.dropout = Dropout2d()
self.fc1 = Linear(256, 64)
self.fc2 = Linear(64, 2) # 2-dimensional input to QNN
# Apply torch connector, weights chosen
self.qnn = TorchConnector(qnn2)
# uniformly at random from interval [-1,1].
self.fc3 = Linear(1, 1)
# 1-dimensional output from QNN
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.qnn(x) # apply QNN
x = self.fc3(x)
return torch.cat((x, 1 - x), -1)
### Model trained and the loss computed ###
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
### Loss convergence plotted ###
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg. Log Likelihood Loss')
plt.show()
### Model evaluated ###
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
(correct / len(test_loader) / batch_size) * 100))
### Predicted images displayed. Either T-shirt or Trouser ###
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(15, 5))
model.eval()
with no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model(data[0:1])
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(data[0].numpy().squeeze(), cmap='gray')
axes[count].set_xticks([])
axes[count].set_yticks([])
if pred.item() == 0:
axes[count].set_title('Predicted item: T-Shirt')
elif pred.item() == 1:
axes[count].set_title('Predicted item: Trouser')
count += 1
|
https://github.com/Keerthiraj-Nagaraj/IBM-quantum-challenge-2020
|
Keerthiraj-Nagaraj
|
from qiskit import QuantumCircuit
from qiskit.providers.ibmq.job import IBMQJob
from typing import Callable, Union
from qiskit.circuit.library import CXGate
from qc_grader.grade import prepare_solver, prepare_circuit, grade_job, submit_job
criteria: dict = {
'max_qubits': 28,
'min_cost': 100,
'check_gates': True
}
problem_set_ex2a = [0, 1, 1, 1, 0, 0, 1, 1, 1]
problem_set_ex2b = [
[1, 1, 1, 0, 0, 0, 1, 0, 0],
[1, 0, 1, 0, 0, 0, 1, 1, 0],
[1, 0, 1, 1, 1, 1, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0]
]
def prepare_ex2a(solver_func: Callable) -> IBMQJob:
return prepare_solver(
solver_func,
'week2', 'exA',
problem_set=problem_set_ex2a,
**criteria,
shots=8000,
seed_simulator=12345,
backend_options={'fusion_enable': True}
)
def grade_ex2a(job: Union[IBMQJob, str]) -> None:
if grade_job(job, 'week2', 'exA'):
print('Feel free to submit your answer.')
def submit_ex2a(job: Union[IBMQJob, str]) -> None:
submit_job(job, 'week2', 'exA')
def prepare_ex2b(solver_func: Callable) -> IBMQJob:
return prepare_solver(
solver_func,
'week2', 'exB',
problem_set=problem_set_ex2b,
**criteria,
shots=8000,
seed_simulator=12345,
backend_options={'fusion_enable': True}
)
def grade_ex2b(job: Union[IBMQJob, str]) -> None:
if grade_job(job, 'week2', 'exB'):
print('Feel free to submit your answer.')
def submit_ex2b(job: Union[IBMQJob, str]) -> None:
if submit_job(job, 'week2', 'exB'):
print('There seems to be huge "noise clusters" interfering with '
'Dr. Ryoko’s device. Can you please help?')
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
rx,ry,rz = symbols('r_x r_y r_z')
rho1qb = (1/2)*(id(2) + rx*pauli(1) + ry*pauli(2) + rz*pauli(3))
rho1qb
pI,pX,pZ,pY = symbols('p_I p_X p_Z p_Y')
K0 = sqrt(pI)*id(2); K1 = sqrt(pX)*pauli(1); K2 = sqrt(pZ)*pauli(3); K3 = sqrt(pY)*pauli(2)
rho_p = K0*rho1qb*K0 + K1*rho1qb*K1 + K2*rho1qb*K2 + K3*rho1qb*K3
simplify(rho_p)
p = symbols('p')
pI = (1+3*p)/4; pX = (1-p)/4; pY = pX; pZ = pX
rho_p = K0*rho1qb*K0 + K1*rho1qb*K1 + K2*rho1qb*K2 + K3*rho1qb*K3
simplify(rho_p)
import numpy as np
from matplotlib import pyplot as plt
p = np.arange(0,1.1,0.1) # PD channel
C = np.sqrt(1-p)
plt.plot(p,C)
plt.show()
from sympy import *
N,p = symbols('N p')
K0 = sqrt(1-N)*Matrix([[1,0],[0,sqrt(1-p)]])
K1 = sqrt(1-N)*Matrix([[0,sqrt(p)],[0,0]])
K2 = sqrt(N)*Matrix([[sqrt(1-p),0],[0,1]])
K3 = sqrt(N)*Matrix([[0,0],[sqrt(p),0]])
#K0
r00,r01,r10,r11 = symbols('r_{00} r_{01} r_{10} r_{11}')#; r00
rho = Matrix([[r00,r01],[r10,r11]])#; rho
rho_gad = K0*rho*K0 + K1*rho*K1.T + K2*rho*K2 + K3*rho*K3.T
simplify(rho_gad)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import torch
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123456
_ = torch.manual_seed(123456) # suppress output
import numpy as np
num_dim = 2
num_discrete_values = 8
num_qubits = num_dim * int(np.log2(num_discrete_values))
from scipy.stats import multivariate_normal
coords = np.linspace(-2, 2, num_discrete_values)
rv = multivariate_normal(mean=[0.0, 0.0], cov=[[1, 0], [0, 1]], seed=algorithm_globals.random_seed)
grid_elements = np.transpose([np.tile(coords, len(coords)), np.repeat(coords, len(coords))])
prob_data = rv.pdf(grid_elements)
prob_data = prob_data / np.sum(prob_data)
import matplotlib.pyplot as plt
from matplotlib import cm
mesh_x, mesh_y = np.meshgrid(coords, coords)
grid_shape = (num_discrete_values, num_discrete_values)
fig, ax = plt.subplots(figsize=(9, 9), subplot_kw={"projection": "3d"})
prob_grid = np.reshape(prob_data, grid_shape)
surf = ax.plot_surface(mesh_x, mesh_y, prob_grid, cmap=cm.coolwarm, linewidth=0, antialiased=False)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
from qiskit import QuantumCircuit
from qiskit.circuit.library import EfficientSU2
qc = QuantumCircuit(num_qubits)
qc.h(qc.qubits)
ansatz = EfficientSU2(num_qubits, reps=6)
qc.compose(ansatz, inplace=True)
qc.decompose().draw("mpl")
qc.num_parameters
from qiskit.primitives import Sampler
shots = 10000
sampler = Sampler(options={"shots": shots, "seed": algorithm_globals.random_seed})
from qiskit_machine_learning.connectors import TorchConnector
from qiskit_machine_learning.neural_networks import SamplerQNN
def create_generator() -> TorchConnector:
qnn = SamplerQNN(
circuit=qc,
sampler=sampler,
input_params=[],
weight_params=qc.parameters,
sparse=False,
)
initial_weights = algorithm_globals.random.random(qc.num_parameters)
return TorchConnector(qnn, initial_weights)
from torch import nn
class Discriminator(nn.Module):
def __init__(self, input_size):
super(Discriminator, self).__init__()
self.linear_input = nn.Linear(input_size, 20)
self.leaky_relu = nn.LeakyReLU(0.2)
self.linear20 = nn.Linear(20, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, input: torch.Tensor) -> torch.Tensor:
x = self.linear_input(input)
x = self.leaky_relu(x)
x = self.linear20(x)
x = self.sigmoid(x)
return x
generator = create_generator()
discriminator = Discriminator(num_dim)
def adversarial_loss(input, target, w):
bce_loss = target * torch.log(input) + (1 - target) * torch.log(1 - input)
weighted_loss = w * bce_loss
total_loss = -torch.sum(weighted_loss)
return total_loss
from torch.optim import Adam
lr = 0.01 # learning rate
b1 = 0.7 # first momentum parameter
b2 = 0.999 # second momentum parameter
generator_optimizer = Adam(generator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005)
discriminator_optimizer = Adam(
discriminator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005
)
from IPython.display import clear_output
def plot_training_progress():
# we don't plot if we don't have enough data
if len(generator_loss_values) < 2:
return
clear_output(wait=True)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 9))
# Generator Loss
ax1.set_title("Loss")
ax1.plot(generator_loss_values, label="generator loss", color="royalblue")
ax1.plot(discriminator_loss_values, label="discriminator loss", color="magenta")
ax1.legend(loc="best")
ax1.set_xlabel("Iteration")
ax1.set_ylabel("Loss")
ax1.grid()
# Relative Entropy
ax2.set_title("Relative entropy")
ax2.plot(entropy_values)
ax2.set_xlabel("Iteration")
ax2.set_ylabel("Relative entropy")
ax2.grid()
plt.show()
import time
from scipy.stats import multivariate_normal, entropy
n_epochs = 50
num_qnn_outputs = num_discrete_values**num_dim
generator_loss_values = []
discriminator_loss_values = []
entropy_values = []
start = time.time()
for epoch in range(n_epochs):
valid = torch.ones(num_qnn_outputs, 1, dtype=torch.float)
fake = torch.zeros(num_qnn_outputs, 1, dtype=torch.float)
# Configure input
real_dist = torch.tensor(prob_data, dtype=torch.float).reshape(-1, 1)
# Configure samples
samples = torch.tensor(grid_elements, dtype=torch.float)
disc_value = discriminator(samples)
# Generate data
gen_dist = generator(torch.tensor([])).reshape(-1, 1)
# Train generator
generator_optimizer.zero_grad()
generator_loss = adversarial_loss(disc_value, valid, gen_dist)
# store for plotting
generator_loss_values.append(generator_loss.detach().item())
generator_loss.backward(retain_graph=True)
generator_optimizer.step()
# Train Discriminator
discriminator_optimizer.zero_grad()
real_loss = adversarial_loss(disc_value, valid, real_dist)
fake_loss = adversarial_loss(disc_value, fake, gen_dist.detach())
discriminator_loss = (real_loss + fake_loss) / 2
# Store for plotting
discriminator_loss_values.append(discriminator_loss.detach().item())
discriminator_loss.backward()
discriminator_optimizer.step()
entropy_value = entropy(gen_dist.detach().squeeze().numpy(), prob_data)
entropy_values.append(entropy_value)
plot_training_progress()
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} sec")
with torch.no_grad():
generated_probabilities = generator().numpy()
fig = plt.figure(figsize=(18, 9))
# Generated CDF
gen_prob_grid = np.reshape(np.cumsum(generated_probabilities), grid_shape)
ax1 = fig.add_subplot(1, 3, 1, projection="3d")
ax1.set_title("Generated CDF")
ax1.plot_surface(mesh_x, mesh_y, gen_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm)
ax1.set_zlim(-0.05, 1.05)
# Real CDF
real_prob_grid = np.reshape(np.cumsum(prob_data), grid_shape)
ax2 = fig.add_subplot(1, 3, 2, projection="3d")
ax2.set_title("True CDF")
ax2.plot_surface(mesh_x, mesh_y, real_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm)
ax2.set_zlim(-0.05, 1.05)
# Difference
ax3 = fig.add_subplot(1, 3, 3, projection="3d")
ax3.set_title("Difference between CDFs")
ax3.plot_surface(
mesh_x, mesh_y, real_prob_grid - gen_prob_grid, linewidth=2, antialiased=False, cmap=cm.coolwarm
)
ax3.set_zlim(-0.05, 0.1)
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
qc2.draw('mpl')
|
https://github.com/AasthaShayla/Qiskit-Teleportation
|
AasthaShayla
|
from qiskit import *
IBMQ.load_account()
cr=ClassicalRegister(2)
qr=QuantumRegister(2)
circuit=QuantumCircuit(qr,cr)
%matplotlib inline
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()
simulator=Aer.get_backend('qasm_simulator')
result=execute(circuit,backend=simulator).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
from qiskit.visualization import plot_state_qsphere
from qiskit.visualization import plot_bloch_multivector
statevector_simulator = Aer.get_backend('statevector_simulator')
result=execute(circuit,statevector_simulator).result()
statevector_results=result.get_statevector(circuit)
plot_bloch_multivector(statevector_results)
plot_state_qsphere(statevector_results)
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
import json
import csv
# Array of JSON Objects
header = ['p', 'state', 'probability', 'mean']
length_p = 10
with open('qaoa_multiple_p.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
first_p = False
for p in range(length_p):
p = p+1
if first_p == False:
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p)
first_p = True
else:
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p)
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
mean = UNIFORM_CONVERGENCE_SAMPLE[0]["mean"]
print(mean)
state = 0
for probability in UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"]:
state += 1
writer.writerow([p,state, probability,mean])
|
https://github.com/HuangJunye/Qiskit-for-GameDev
|
HuangJunye
|
-- our API object
q_command = {}
q_command.tools_placed = false
q_command.game_running_time = 0
q_command.block_pos = {}
q_command.circuit_specs = {} -- dir_str, pos, num_wires, num_columns, is_on_grid
q_command.circuit_specs.pos = {} -- x, y, z
function q_command:create_qasm_for_node(circuit_node_pos, wire_num,
include_measurement_blocks, c_if_table, tomo_meas_basis)
local qasm_str = ""
local circuit_node_block = circuit_blocks:get_circuit_block(circuit_node_pos)
local q_block = q_command:get_q_command_block(circuit_node_pos)
if circuit_node_block then
local node_type = circuit_node_block.get_node_type()
if node_type == CircuitNodeTypes.EMPTY or
node_type == CircuitNodeTypes.TRACE or
node_type == CircuitNodeTypes.CTRL then
-- Throw away a c_if if present
c_if_table[wire_num] = ""
-- Return immediately with zero length qasm_str
return qasm_str
else
if c_if_table[wire_num] and c_if_table[wire_num] ~= "" then
qasm_str = qasm_str .. c_if_table[wire_num] .. " "
c_if_table[wire_num] = ""
end
end
local ctrl_a = circuit_node_block.get_ctrl_a()
local ctrl_b = circuit_node_block.get_ctrl_b()
local swap = circuit_node_block.get_swap()
local radians = circuit_node_block.get_radians()
-- For convenience and brevity, create a zero-based, string, wire number
--local wire_num_idx = tostring(wire_num - 1 +
-- circuit_node_block.get_circuit_specs_wire_num_offset())
--local ctrl_a_idx = tostring(ctrl_a - 1 +
-- circuit_node_block.get_circuit_specs_wire_num_offset())
--local ctrl_b_idx = tostring(ctrl_b - 1 +
-- circuit_node_block.get_circuit_specs_wire_num_offset())
-- TODO: Replace above with below?
local wire_num_idx = tostring(wire_num - 1)
local ctrl_a_idx = tostring(ctrl_a - 1)
local ctrl_b_idx = tostring(ctrl_b - 1)
local swap_idx = tostring(swap - 1)
if node_type == CircuitNodeTypes.IDEN then
-- Identity gate
qasm_str = qasm_str .. 'id q[' .. wire_num_idx .. '];'
elseif node_type == CircuitNodeTypes.X then
local threshold = 0.0001
if math.abs(radians - math.pi) <= threshold then
if ctrl_a ~= -1 then
if ctrl_b ~= -1 then
-- Toffoli gate
qasm_str = qasm_str .. 'ccx q[' .. ctrl_a_idx .. '],'
qasm_str = qasm_str .. 'q[' .. ctrl_b_idx .. '],'
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
else
-- Controlled X gate
qasm_str = qasm_str .. 'cx q[' .. ctrl_a_idx .. '],'
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
end
else
-- Pauli-X gate
qasm_str = qasm_str .. 'x q[' .. wire_num_idx .. '];'
end
else
-- Rotation around X axis
qasm_str = qasm_str .. 'rx(' .. tostring(radians) .. ') '
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
end
elseif node_type == CircuitNodeTypes.Y then
local threshold = 0.0001
if math.abs(radians - math.pi) <= threshold then
if ctrl_a ~= -1 then
-- Controlled Y gate
qasm_str = qasm_str .. 'cy q[' .. ctrl_a_idx .. '],'
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
else
-- Pauli-Y gate
qasm_str = qasm_str .. 'y q[' .. wire_num_idx .. '];'
end
else
-- Rotation around Y axis
qasm_str = qasm_str .. 'ry(' .. tostring(radians) .. ') '
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
end
elseif node_type == CircuitNodeTypes.Z then
local threshold = 0.0001
if math.abs(radians - math.pi) <= threshold then
if ctrl_a ~= -1 then
-- Controlled Z gate
qasm_str = qasm_str .. 'cz q[' .. ctrl_a_idx .. '],'
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
else
-- Pauli-Z gate
qasm_str = qasm_str .. 'z q[' .. wire_num_idx .. '];'
end
else
if circuit_node_block.get_ctrl_a() ~= -1 then
-- Controlled rotation around the Z axis
qasm_str = qasm_str .. 'crz(' .. tostring(radians) .. ') '
qasm_str = qasm_str .. 'q[' .. ctrl_a_idx .. '],'
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
else
-- Rotation around Z axis
qasm_str = qasm_str .. 'rz(' .. tostring(radians) .. ') '
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
end
end
elseif node_type == CircuitNodeTypes.S then
-- S gate
qasm_str = qasm_str .. 's q[' .. wire_num_idx .. '];'
elseif node_type == CircuitNodeTypes.SDG then
-- S dagger gate
qasm_str = qasm_str .. 'sdg q[' .. wire_num_idx .. '];'
elseif node_type == CircuitNodeTypes.T then
-- T gate
qasm_str = qasm_str .. 't q[' .. wire_num_idx .. '];'
elseif node_type == CircuitNodeTypes.TDG then
-- T dagger gate
qasm_str = qasm_str .. 'tdg q[' .. wire_num_idx .. '];'
elseif node_type == CircuitNodeTypes.H then
if ctrl_a ~= -1 then
-- Controlled Hadamard
qasm_str = qasm_str .. 'ch q[' .. ctrl_a_idx .. '],'
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
else
-- Hadamard gate
qasm_str = qasm_str .. 'h q[' .. wire_num_idx .. '];'
end
elseif node_type == CircuitNodeTypes.BARRIER then
-- barrier
qasm_str = qasm_str .. 'barrier q[' .. wire_num_idx .. '];'
elseif node_type == CircuitNodeTypes.MEASURE_Z then
if include_measurement_blocks then
-- Measurement block
--qasm_str = qasm_str .. 'measure q[' .. wire_num_idx .. '] -> c[' .. wire_num_idx .. '];'
qasm_str = qasm_str .. 'measure q[' .. wire_num_idx .. '] -> c' .. wire_num_idx .. '[0];'
end
elseif node_type == CircuitNodeTypes.QUBIT_BASIS then
qasm_str = qasm_str .. 'reset q[' .. wire_num_idx .. '];'
if circuit_node_block.get_node_name():sub(-2) == "_1" then
qasm_str = qasm_str .. 'x q[' .. wire_num_idx .. '];'
end
elseif node_type == CircuitNodeTypes.CONNECTOR_M then
-- Connector to wire extension, so traverse
local wire_extension_block_pos = circuit_node_block.get_wire_extension_block_pos()
if wire_extension_block_pos.x ~= 0 then
local wire_extension_block = circuit_blocks:get_circuit_block(wire_extension_block_pos)
local wire_extension_dir_str = wire_extension_block.get_circuit_dir_str()
local wire_extension_circuit_pos = wire_extension_block.get_circuit_pos()
if wire_extension_circuit_pos.x ~= 0 then
local wire_extension_circuit = circuit_blocks:get_circuit_block(wire_extension_circuit_pos)
local extension_wire_num = wire_extension_circuit.get_circuit_specs_wire_num_offset() + 1
local extension_num_columns = wire_extension_circuit.get_circuit_num_columns()
for column_num = 1, extension_num_columns do
-- Assume dir_str is "+Z"
local circ_node_pos = {x = wire_extension_circuit_pos.x + column_num - 1,
y = wire_extension_circuit_pos.y,
z = wire_extension_circuit_pos.z}
if wire_extension_dir_str == "+X" then
circ_node_pos = {x = wire_extension_circuit_pos.x,
y = wire_extension_circuit_pos.y,
z = wire_extension_circuit_pos.z - column_num + 1}
elseif wire_extension_dir_str == "-X" then
circ_node_pos = {x = wire_extension_circuit_pos.x,
y = wire_extension_circuit_pos.y,
z = wire_extension_circuit_pos.z + column_num - 1}
elseif wire_extension_dir_str == "-Z" then
circ_node_pos = {x = wire_extension_circuit_pos.x - column_num + 1,
y = wire_extension_circuit_pos.y,
z = wire_extension_circuit_pos.z}
end
qasm_str = qasm_str ..
q_command:create_qasm_for_node(circ_node_pos,
extension_wire_num, include_measurement_blocks,
c_if_table, tomo_meas_basis)
end
end
end
elseif node_type == CircuitNodeTypes.SWAP and swap ~= -1 then
if ctrl_a ~= -1 then
-- Controlled Swap
qasm_str = qasm_str .. 'cswap q[' .. ctrl_a_idx .. '],'
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '],'
qasm_str = qasm_str .. 'q[' .. swap_idx .. '];'
else
-- Swap gate
qasm_str = qasm_str .. 'swap q[' .. wire_num_idx .. '],'
qasm_str = qasm_str .. 'q[' .. swap_idx .. '];'
end
elseif node_type == CircuitNodeTypes.C_IF then
local node_name = circuit_node_block.get_node_name()
local register_idx_str = node_name:sub(35, 35)
local eq_val_str = node_name:sub(39, 39)
c_if_table[wire_num] = "if(c" .. register_idx_str .. "==" ..
eq_val_str .. ")"
elseif node_type == CircuitNodeTypes.BLOCH_SPHERE or
node_type == CircuitNodeTypes.COLOR_QUBIT then
if include_measurement_blocks then
if tomo_meas_basis == 1 then
-- Measure in the X basis (by first rotating -pi/2 radians on Y axis)
qasm_str = qasm_str .. 'ry(' .. tostring(-math.pi / 2) .. ') '
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
elseif tomo_meas_basis == 2 then
-- Measure in the Y basis (by first rotating pi/2 radians on X axis)
qasm_str = qasm_str .. 'rx(' .. tostring(math.pi / 2) .. ') '
qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];'
elseif tomo_meas_basis == 3 then
-- Measure in the Z basis (no rotation necessary)
end
qasm_str = qasm_str .. 'measure q[' .. wire_num_idx .. '] -> c' .. wire_num_idx .. '[0];'
end
end
else
print("Unknown gate!")
end
if LOG_DEBUG then
minetest.debug("End of create_qasm_for_node(), qasm_str:\n" .. qasm_str)
end
return qasm_str
end
|
https://github.com/WhenTheyCry96/qiskitHackathon2022
|
WhenTheyCry96
|
%load_ext autoreload
%autoreload 2
import os
import warnings
import numpy as np
import pyEPR as epr
import qiskit_metal as metal
from collections import OrderedDict
import scqubits as scq
from scipy.constants import c, h, pi, hbar, e
from qiskit_metal import designs, draw, MetalGUI, Dict, Headings
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors
from qiskit_metal.analyses.quantization import LOManalysis, EPRanalysis
from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength
from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL
from qiskit_metal.qlibrary.lumped.cap_3_interdigital import Cap3Interdigital
from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled
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
ws_path = os.getcwd()
warnings.filterwarnings("ignore")
design = designs.DesignPlanar()
design.overwrite_enabled = True
#constants:
phi0 = h/(2*e)
varphi0 = phi0/(2*pi)
# project target parameters
f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz
f_rList = f_qList + 1.8 # GHz
L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH
# initial CPW readout lengths
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(f_rList, 10, 6, 2)
design.chips.main.size_x = '12mm'
design.chips.main.size_y = '10mm'
gui = MetalGUI(design)
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)
)
connection23_pads_options = dict(
a = 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), **connection23_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), **connection23_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()
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('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()
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='330um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um'))
options = Dict(
lead=Dict(
start_straight='430um',
end_straight='0um'),
fillet='99.99um')
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()
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.png")
# constants:
phi0 = h/(2*e)
varphi0 = phi0/(2*pi)
# project target parameters
f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz
f_rList = f_qList + 1.8 # GHz
L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH
# initial CPW readout lengths
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(f_rList, 10, 6, 2)
# CPW busline length is determined to be 7 mm
cpw[0].options.total_length = '7.0mm'
cpw[1].options.total_length = '7.0mm'
cpw[2].options.total_length = '7.0mm'
cpw[3].options.total_length = '7.0mm'
gui.rebuild()
gui.autoscale()
# qubit 1 design target f: 5.25 GHz
# readout resonator target f: 7.05 GHz
# qubit 2 design target f: 5.42 GHz
# readout resonator target f: 7.22 GHz
# qubit 3 design target f: 5.58 GHz
# readout resonator target f: 7.38 GHz
# qubit 4 design target f: 5.75 GHz
# readout resonator target f: 7.55 GHz
# tuning parameters
C_JJ4f = 2
L_JJ4f = 9.8
C_JJ4 = str(C_JJ4f)+' fF'
L_JJ4 = str(L_JJ4f)+' nH'
transmons[3].options.pad_gap = '35um'
transmons[3].options.pad_width = '510um'
transmons[3].options.pad_height = '125um'
transmons[3].options.connection_pads.c.pad_gap = '30um'
transmons[3].options.connection_pads.a.pad_gap = '15um' # cpw5
transmons[3].options.connection_pads.a.pad_width = '40um' # cpw5
transmons[3].options.connection_pads.b.pad_gap = '15um' # cpw3
transmons[3].options.connection_pads.b.pad_width = '40um' # cpw3
readout_lines[3].options.total_length = '7.5mm'
gui.rebuild()
gui.autoscale()
# EPR analysis
eig_q4 = EPRanalysis(design, "hfss")
hfss4 = eig_q4.sim.renderer
hfss4.start()
hfss4.activate_ansys_design("TransmonQ4", 'eigenmode')
hfss4.render_design(['Q4', 'ol4', 'cpw3', 'cpw5'], [('cpw3', 'end'), ('cpw5', 'start'), ('ol4', 'end')])
# Analysis properties
setup4 = hfss4.pinfo.setup
setup4.n_modes = 6
setup4.passes = 10
setup4.min_freq_ghz = 4
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}
""")
pinfo4 = hfss4.pinfo
pinfo4.design.set_variable('Lj4', L_JJ4)
pinfo4.design.set_variable('Cj4', C_JJ4)
setup4.analyze()
eig_q4.sim.convergence_t, eig_q4.sim.convergence_f, _ = hfss4.get_convergences()
eig_q4.sim.plot_convergences()
pinfo4.junctions['jj'] = {'Lj_variable': 'Lj4', 'rect': 'JJ_rect_Lj_Q4_rect_jj',
'line': 'JJ_Lj_Q4_rect_jj_', 'Cj_variable': 'Cj4'}
pinfo4.validate_junction_info()
pinfo4.dissipative['dielectrics_bulk'] = ['main']
hfss4.set_mode(1, "Setup")
hfss4.modeler._modeler.ShowWindow()
hfss4.plot_fields('main')
eprd4 = epr.DistributedAnalysis(pinfo4)
ℰ_elec = eprd4.calc_energy_electric()
ℰ_elec_substrate = eprd4.calc_energy_electric(None, 'main')
ℰ_mag = eprd4.calc_energy_magnetic()
print(f"""
ℰ_elec_all = {ℰ_elec}
ℰ_elec_substrate = {ℰ_elec_substrate}
EPR of substrate = {ℰ_elec_substrate / ℰ_elec * 100 :.1f}%
ℰ_mag_all = {ℰ_mag}
ℰ_mag % of ℰ_elec_all = {ℰ_mag / ℰ_elec * 100 :.1f}%
""")
eprd4.do_EPR_analysis()
#epra4 = epr.QuantumAnalysis(eprd4.data_filename)
#epra4.analyze_all_variations(cos_trunc = 8, fock_trunc = 7)
c4 = LOManalysis(design, "q3d")
q3d4 = c4.sim.renderer
q3d4.start()
q3d4.activate_ansys_design("TransmonQ4_q3d", 'capacitive')
q3d4.render_design(['Q4'], [('Q4', 'a'),('Q4', 'b'),('Q4', 'c')])
q3d4.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5, percent_error=0.1)
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':L_JJ4f, 'Cj':C_JJ4f})
c4.setup.freq_readout = 7.45
c4.setup.freq_bus = [8.25, 8.25, 15]
c4.run_lom()
c4.lumped_oscillator_all
QuantumSystemRegistry.registry()
# Q4
path4= ws_path+"/Project71_TransmonQ4_q3d.txt"
t4_mat, _, _, _ = load_q3d_capacitance_matrix(path4)
# Cell 4 Transmon-4
opt4 = dict(
node_rename = {'a_connector_pad_Q4': 'cpw5',
'b_connector_pad_Q4': 'cpw3',
'c_connector_pad_Q4': 'readout4'},
cap_mat = t4_mat,
ind_dict = {('pad_top_Q4', 'pad_bot_Q4'): L_JJ4f}, # junction inductance in nH
jj_dict = {('pad_top_Q4', 'pad_bot_Q4'): 'j4'},
cj_dict = {('pad_top_Q4', 'pad_bot_Q4'): C_JJ4f} # junction capacitance in fF
)
cell_4 = Cell(opt4)
# subsystem 1: Transmon-4
transmon4 = Subsystem(name='transmon4', sys_type='TRANSMON', nodes=['j4'])
# Resonator Subsystems
q_opts = dict(
Z0 = 50, # characteristic impedance in Ohm
vp = 0.404314 * 3e8 # phase velocity
)
# subsystem 3: Q2 readout resonator
ro4 = Subsystem(name='readout4', sys_type='TL_RESONATOR', nodes=['readout4'], q_opts=dict(f_res = 7.57, **q_opts))
# subsystem 4: bus3 resonator
cpw3 = Subsystem(name='cpw3', sys_type='TL_RESONATOR', nodes=['cpw3'], q_opts=dict(f_res = 8.2, **q_opts))
# subsystem 15: bus5 resonator
cpw5 = Subsystem(name='cpw5', sys_type='TL_RESONATOR', nodes=['cpw5'], q_opts=dict(f_res = 8.29, **q_opts))
composite_sys = CompositeSystem(
subsystems=[transmon4, ro4, cpw3, cpw5],
cells=[cell_4],
grd_node='ground_main_plane',
nodes_force_keep=['readout4', 'cpw3', 'cpw5']
)
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/purvi1508/Quantum_Computing_Fundamentals
|
purvi1508
|
!pip install qiskit
!pip install pylatexenc
import qiskit
import pylatexenc
from qiskit import *
from pylatexenc import *
qr= QuantumRegister(2)
#quantum register is a system comprising multiple qubits
cr= ClassicalRegister(2)
circuit = QuantumCircuit(qr,cr)
%matplotlib inline
import matplotlib.pyplot as plt
circuit.draw(initial_state = True)
circuit.h(qr[0])
#applying handmard gate
circuit.draw(output='mpl',initial_state = True)
#logical if
circuit.cx(qr[0],qr[1])
circuit.draw(output='mpl')
circuit.measure(qr,cr)
#measure quantum bits and take those measurements and store in classical bits
circuit.draw(output='mpl',initial_state = True)
simulator = Aer.get_backend('qasm_simulator')
result= execute(circuit,backend=simulator).result()
from qiskit.tools.visualization import plot_histogram
print(result.get_counts(circuit))
#These outcomes correspond to the basis states |00⟩, |01⟩, |10⟩, and |11⟩, respectively.
counts = result.get_counts(circuit)
total_shots = sum(counts.values())
# Calculate the probabilities
probabilities = {state: count / total_shots for state, count in counts.items()}
plot_histogram(probabilities)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import qiskit
qr = qiskit.QuantumRegister(1)
cr = qiskit.ClassicalRegister(1)
program = qiskit.QuantumCircuit(qr, cr)
program.measure(qr,cr)
job = qiskit.execute( program, qiskit.BasicAer.get_backend('qasm_simulator') )
print( job.result().get_counts() )
qiskit.IBMQ.load_accounts()
backend = qiskit.providers.ibmq.least_busy(qiskit.IBMQ.backends(simulator=False))
print("We'll use the least busy device:",backend.name())
job = qiskit.execute( program, backend )
print( job.result().get_counts() )
|
https://github.com/rickapocalypse/final_paper_qiskit_sat
|
rickapocalypse
|
from qiskit import QuantumCircuit
from QCLG_lvl3.oracles.secret_number_oracle import SecretNUmberOracle
class BernsteinVazirani:
@classmethod
def bernstein_vazirani(cls, random_binary, eval_mode: bool) -> QuantumCircuit:
# Construct secret number oracle
secret_number_oracle = SecretNUmberOracle.create_secret_number_oracle(random_binary=random_binary, eval_mode=eval_mode)
num_of_qubits = secret_number_oracle.num_qubits
# Construct circuit according to the length of the number
dj_circuit = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
dj_circuit_before_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
# Apply H-gates
for qubit in range(num_of_qubits - 1):
dj_circuit_before_oracle.h(qubit)
# Put output qubit in state |->
dj_circuit_before_oracle.x(num_of_qubits - 1)
dj_circuit_before_oracle.h(num_of_qubits - 1)
dj_circuit += dj_circuit_before_oracle
# Add oracle
dj_circuit += secret_number_oracle
dj_circuit_after_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
# Repeat H-gates
for qubit in range(num_of_qubits - 1):
dj_circuit_after_oracle.h(qubit)
dj_circuit_after_oracle.barrier()
# Measure
for i in range(num_of_qubits - 1):
dj_circuit_after_oracle.measure(i, i)
dj_circuit += dj_circuit_after_oracle
if not eval_mode:
print("Circuit before the oracle\n")
print(QuantumCircuit.draw(dj_circuit_before_oracle))
print("Circuit after the oracle\n")
print(QuantumCircuit.draw(dj_circuit_after_oracle))
print(dj_circuit)
return dj_circuit
|
https://github.com/Alice-Bob-SW/qiskit-alice-bob-provider
|
Alice-Bob-SW
|
import pytest
from qiskit import QuantumCircuit, execute
from qiskit_alice_bob_provider.local.backend import ProcessorSimulator
from qiskit_alice_bob_provider.local.readout_errors import (
build_readout_noise_model,
)
from qiskit_alice_bob_provider.processor.description import (
ProcessorDescription,
)
from .processor_fixture import (
AllToAllProcessorWithQubitInstruction,
AllToAllReadoutErrorProcessor,
ConflictingReadoutErrorsProcessor,
QubitProcessorWithAllToAllInstruction,
ReadoutErrorProcessor,
)
def test_one_readout_error() -> None:
backend = ProcessorSimulator(processor=ReadoutErrorProcessor())
circ = QuantumCircuit(2, 2)
circ.initialize('++')
circ.measure_x(0, 0)
circ.measure_x(1, 1)
counts = execute(circ, backend, shots=1).result().get_counts()
assert counts.keys() == {'01'}
circ = QuantumCircuit(2, 2)
circ.initialize('--')
circ.measure_x(0, 0)
circ.measure_x(1, 1)
counts = execute(circ, backend, shots=1).result().get_counts()
assert counts.keys() == {'01'}
def test_all_to_all_one_readout_error() -> None:
with pytest.warns(UserWarning):
backend = ProcessorSimulator(processor=AllToAllReadoutErrorProcessor())
circ = QuantumCircuit(2, 2)
circ.initialize('++')
circ.measure_x(0, 0)
circ.measure_x(1, 1)
counts = execute(circ, backend, shots=1).result().get_counts()
assert counts.keys() == {'11'}
circ = QuantumCircuit(2, 2)
circ.initialize('--')
circ.measure_x(0, 0)
circ.measure_x(1, 1)
counts = execute(circ, backend, shots=1).result().get_counts()
assert counts.keys() == {'11'}
def test_conflicting_readout_errors() -> None:
proc = ConflictingReadoutErrorsProcessor()
with pytest.warns(UserWarning):
backend = ProcessorSimulator(processor=proc)
circ = QuantumCircuit(1, 1)
circ.initialize('+')
circ.measure_x(0, 0)
counts = execute(circ, backend, shots=1).result().get_counts()
assert counts.keys() == {'1'}
circ = QuantumCircuit(1, 1)
circ.initialize('-')
circ.measure_x(0, 0)
counts = execute(circ, backend, shots=1).result().get_counts()
assert counts.keys() == {'1'}
@pytest.mark.parametrize(
'proc',
[
AllToAllProcessorWithQubitInstruction(),
QubitProcessorWithAllToAllInstruction(),
],
)
def test_bad_instruction_with_processor_type(
proc: ProcessorDescription,
) -> None:
with pytest.raises(ValueError):
build_readout_noise_model(proc)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
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
XX = Operator([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])
XX
XX.data
input_dim, output_dim = XX.dim
input_dim, output_dim
op = Operator(np.random.rand(2 ** 1, 2 ** 2))
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
op = Operator(np.random.rand(6, 6))
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
# Force input dimension to be (4,) rather than (2, 2)
op = Operator(np.random.rand(2 ** 1, 2 ** 2), input_dims=[4])
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 input system 1:', op.input_dims([1]))
# Create an Operator from a Pauli object
pauliXX = Pauli('XX')
Operator(pauliXX)
# Create an Operator for a Gate object
Operator(CXGate())
# Create an operator from a parameterized Gate object
Operator(RXGate(np.pi / 2))
# Create an operator from a QuantumCircuit object
circ = QuantumCircuit(10)
circ.h(0)
for j in range(1, 10):
circ.cx(j-1, j)
# Convert circuit to an operator by implicit unitary simulation
Operator(circ)
# Create an operator
XX = Operator(Pauli('XX'))
# Add to a circuit
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)
# Add to a circuit
circ2 = QuantumCircuit(2, 2)
circ2.append(Pauli('XX'), [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 with an 3-qubit identity operator
op = Operator(np.eye(2 ** 3))
XZ = Operator(Pauli('XZ'))
op.compose(XZ, qargs=[0, 2])
# Compose YX in front of the previous operator
op = Operator(np.eye(2 ** 3))
YX = Operator(Pauli('YX'))
op.compose(XZ, qargs=[0, 2], front=True)
XX = Operator(Pauli('XX'))
YY = Operator(Pauli('YY'))
ZZ = Operator(Pauli('ZZ'))
op = 0.5 * (XX + YY - 3 * ZZ)
op
op.is_unitary()
# Compose with a matrix passed as a list
Operator(np.eye(2)).compose([[0, 1], [1, 0]])
Operator(Pauli('X')) == Operator(XGate())
Operator(XGate()) == np.exp(1j * 0.5) * Operator(XGate())
# Two operators which differ only by phase
op_a = Operator(XGate())
op_b = np.exp(1j * 0.5) * Operator(XGate())
# Compute process fidelity
F = process_fidelity(op_a, op_b)
print('Process fidelity =', F)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/hkhetawat/QArithmetic
|
hkhetawat
|
# Import the Qiskit SDK
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, Aer
from QArithmetic import sub
# Input N
N = 4
a = QuantumRegister(N+1)
b = QuantumRegister(N+1)
ca = ClassicalRegister(N+1)
cb = ClassicalRegister(N+1)
qc = QuantumCircuit(a, b, ca, cb)
# Input Superposition
# a = 01110
qc.x(a[1])
qc.x(a[2])
qc.x(a[3])
# b = 01011
qc.x(b[0])
qc.x(b[1])
qc.x(b[3])
sub(qc, a, b, N+1)
qc.measure(a, ca)
qc.measure(b, cb)
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
|
https://github.com/jfraxanet/BasQ_industry_workshop_Qiskit
|
jfraxanet
|
from qiskit import QuantumCircuit
# Create circuit
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
circuit.draw('mpl',style="iqp",initial_state=True)
import qiskit.quantum_info as qi
from qiskit.visualization import array_to_latex
qc = QuantumCircuit(2)
qc.x(0)
qc.h(0)
qc.cx(0, 1)
psi = qi.Statevector.from_instruction(qc)
array_to_latex(psi)
# quiz-time!
from qiskit.visualization import plot_state_qsphere
plot_state_qsphere(psi)
from qiskit.visualization import plot_state_city
plot_state_city(psi)
from qiskit.visualization import plot_state_hinton
plot_state_hinton(psi)
from qiskit.visualization import plot_state_paulivec
plot_state_paulivec(psi)
circuit.measure_all()
circuit.draw('mpl',style="iqp",initial_state=True)
from qiskit_aer import AerSimulator
backend = AerSimulator() # this is the simulator we'll use
job = backend.run(circuit,shots=1000) # this runs the experiment
result = job.result()
counts = result.get_counts()
# quiz-time!
# quiz-time!
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Options
# set account here https://quantum.ibm.com/
service = QiskitRuntimeService(instance="ibm-q-ikerbasque/industry-qiskit-/generic-project")
# when loading your IBM Quantum account for the first time you need to specify your token:
#service = QiskitRuntimeService(instance="ibm-q-ikerbasque/industry-qiskit-/generic-project", token="token")
[(b.name, b.configuration().n_qubits) for b in service.backends()]
from qiskit_ibm_provider import least_busy
backend = service.least_busy(simulator=False, operational=True)
#backend = service.backend("ibm_brisbane")
print(backend)
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
pm = generate_preset_pass_manager(backend=backend, initial_layout=[0,6], optimization_level=3)
t_qc = pm.run(circuit)
t_qc.draw('mpl',style="iqp",idle_wires=False)
from qiskit.visualization import plot_circuit_layout, plot_gate_map
display(plot_circuit_layout(t_qc, backend))
pm = generate_preset_pass_manager(backend=backend, optimization_level=3)
t_qc = pm.run(circuit)
t_qc.draw('mpl',style="iqp",idle_wires=False)
options = Options()
options.resilience_level = 1
options.optimization_level = 3
# Create a Sampler object
sampler = Sampler(backend=backend, options=options)
# Submit the circuit to Sampler
job = sampler.run(t_qc,shots=1000)
print(job.job_id())
job.status()
# get results
job = service.job('cqcbzgyapgkg008jxcwg')
result = job.result()
counts = result.quasi_dists
plot_histogram(counts)
from qiskit.quantum_info import Operator
def phase_oracle(n, indices_to_mark, name = 'Oracle'):
qc = QuantumCircuit(n, name=name)
oracle_matrix = np.identity(2**n)
for index_to_mark in indices_to_mark:
oracle_matrix[index_to_mark, index_to_mark] = -1
qc.unitary(Operator(oracle_matrix), range(n))
return qc
def diffuser(n):
qc = QuantumCircuit(n, name='Diff')
qc.h(range(n))
qc.append(phase_oracle(n,[0]),range(n))
qc.h(range(n))
return qc
def Grover(n, marked):
qc = QuantumCircuit(n, n)
r = int(np.round(np.pi/(4*np.arcsin(np.sqrt(len(marked)/2**n)))-1/2))
print(f'{n} qubits, basis state {marked} marked, {r} rounds')
qc.h(range(n))
for _ in range(r):
qc.append(phase_oracle(n,marked), range(n))
qc.append(diffuser(n), range(n))
qc.measure(range(n), range(n))
return qc
import numpy as np
n = 5
x = np.random.randint(2**n)
marked = [x]
qc = Grover(n, marked)
qc.draw('mpl',style="iqp",initial_state=True)
from qiskit_aer import AerSimulator
from qiskit import transpile
backend = AerSimulator()
tqc = transpile(qc, backend)
result = backend.run(tqc, shots=10000).result()
counts = result.get_counts(qc)
print(counts)
plot_histogram(counts)
# quiz-time!
def Grover_run_roundwise(n, marked):
r = int(np.round(np.pi/(4*np.arcsin(np.sqrt(len(marked)/2**n)))-1/2))
print(f'{n} qubits, basis state {marked} marked, {r} rounds')
counts = []
for i in range(r):
qc = QuantumCircuit(n, n)
qc.h(range(n))
for _ in range(i+1):
qc.append(phase_oracle(n,marked), range(n))
qc.append(diffuser(n), range(n))
qc.measure(range(n), range(n))
tqc = transpile(qc, backend)
result = backend.run(tqc, shots=10000).result()
counts.append(result.get_counts())
return counts
backend = AerSimulator()
counts = Grover_run_roundwise(n,marked)
# quiz-time!
n = 3
x = np.random.randint(2**n)
y = np.random.randint(2**n)
while y==x:
y = np.random.randint(2**n)
marked = [x,y]
qc = Grover(n, marked)
backend = service.least_busy(simulator=False, operational=True)
print("least busy backend: ", backend)
#backend = provider.get_backend('ibm_osaka')
shots = 10000
pm = generate_preset_pass_manager(backend=backend, optimization_level=3)
tqc = pm.run(qc)
job = sampler.run(tqc,shots=1000)
print(job.job_id())
old_job = service.job('cqcc09sqgrzg008cw7ng')
results = old_job.result()
counts = results.quasi_dists
plot_histogram(counts)
from qiskit.circuit.library import PhaseOracle
# this indicates that the input is CNF with five variables and seven clauses
input_3sat = '''
c example DIMACS-CNF 3-SAT
p cnf 5 7
-1 -5 0
1 -3 0
-1 3 0
2 4 0
-2 -3 -4 0
1 -2 0
2 -4 0
'''
with open("3sat.dimacs", "w") as text_file:
text_file.write(input_3sat)
oracle = PhaseOracle.from_dimacs_file("3sat.dimacs")
from qiskit_algorithms import Grover, AmplificationProblem
from qiskit.utils import QuantumInstance
from qiskit.primitives import Sampler
import warnings
#warnings.filterwarnings('ignore')
problem = AmplificationProblem(oracle=oracle)
# Use Grover's algorithm to solve the problem
grover = Grover(sampler = Sampler())
result = grover.amplify(problem)
result.top_measurement
plot_histogram(result.circuit_results)
# quiz-time!
# transpile the circuit for our backend
qc = grover.construct_circuit(problem, max(result.iterations))
qc.measure_all()
backend = service.backend("ibm_osaka")
grover_compiled = transpile(qc, backend=backend, optimization_level=3)
print('gates = ', grover_compiled.count_ops())
print('depth = ', grover_compiled.depth())
from qiskit import QuantumCircuit, transpile
# GHZ state
n = 3
qc = QuantumCircuit(n, n)
qc.h(1)
qc.cx(1, 0)
qc.cx(1, 2)
qc.measure(range(n), range(n))
layout = [0,14,18]
pm = generate_preset_pass_manager(backend=backend, initial_layout=layout, optimization_level=3)
t_qc = pm.run(qc)
from qiskit_ibm_runtime import Sampler
options.resilience_level = 1
sampler = Sampler(backend=backend,options=options)
#job = sampler.run(t_qc, shots=shots)
#print(job.job_id())
options.resilience_level = 0
sampler = Sampler(backend=backend,options=options)
#job = sampler.run(t_qc, shots=shots)
#print(job.job_id())
ghz_mem = service.job('cqdryehfejeg0085wt00') # [0,14,18]
ghz_nomem = service.job('cqdryfsgtagg008qr8s0')
results = ghz_nomem.result()
counts_nomem = results.quasi_dists
results = ghz_mem.result()
counts_mem = results.quasi_dists
plot_histogram([counts_nomem[0],counts_mem[0]], legend=['noisy', 'mitigated'])
# quiz-time!
print(counts_nomem[0])
print(counts_mem[0])
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/KMU-quantum-classroom/qiskit-classroom-converter
|
KMU-quantum-classroom
|
import warnings
from loguru import logger
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit_class_converter import ConversionService, ConversionType, __FULL_VERSION__
warnings.filterwarnings('ignore')
__FULL_VERSION__
input_value = [
[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0]
]
sample_converter = ConversionService(conversion_type="MATRIX_TO_QC", option={"label": "CX gate"})
result = sample_converter.convert(input_value=input_value)
quantum_circuit = QuantumCircuit(2, 2)
quantum_circuit.x(0)
quantum_circuit.append(result, [0, 1])
quantum_circuit.measure(range(2), range(2))
backend = AerSimulator()
qc_compiled = transpile(quantum_circuit, backend)
logger.info("\n" + str(quantum_circuit))
quantum_circuit = QuantumCircuit(2, 2)
quantum_circuit.x(0)
quantum_circuit.cx(0, 1)
sample_converter = ConversionService(conversion_type="QC_TO_MATRIX")
result = sample_converter.convert(input_value=quantum_circuit)
for gate in result["gate"]:
logger.info("\n" + str(gate.astype(int)))
logger.info("list: " + str(result["name"]))
result["result"].astype(int)
# quantum circuit to matrix (for print: raw option)
quantum_circuit = QuantumCircuit(2, 2)
quantum_circuit.x(0)
quantum_circuit.cx(0, 1)
sample_converter = ConversionService(conversion_type="QC_TO_MATRIX", option={"print": "raw"})
result = sample_converter.convert(input_value=quantum_circuit)
for gate in result["gate"]:
logger.info(gate)
logger.info(result["result"])
from IPython.display import Latex
Latex(result["result"])
quantum_circuit = QuantumCircuit(2, 2)
quantum_circuit.h(0)
quantum_circuit.x(0)
quantum_circuit.cx(0, 1)
sample_converter = ConversionService(conversion_type="QC_TO_BRA_KET")
result = sample_converter.convert(input_value=quantum_circuit)
result
quantum_circuit = QuantumCircuit(2, 2)
quantum_circuit.h(0)
quantum_circuit.x(0)
quantum_circuit.cx(0, 1)
sample_converter = ConversionService(conversion_type="QC_TO_BRA_KET", option={"print": "raw"})
result = sample_converter.convert(input_value=quantum_circuit)
logger.info(result)
from IPython.display import Math
Math(result)
sample_converter = ConversionService(conversion_type="STR_TO_BRA_KET")
result = sample_converter.convert(input_value="sqrt(2)*|00>/2+sqrt(2)*|11>/2")
logger.info(result)
logger.info(type(result))
sample_converter = ConversionService(conversion_type="STR_TO_BRA_KET", option={"print": "raw"})
result = sample_converter.convert(input_value="sqrt(2)*|00>/2+sqrt(2)*|11>/2")
logger.info(result)
from IPython.display import Math
Math(result)
|
https://github.com/Harshithan07/Quantum-Computing-using-Qiskit-SDK
|
Harshithan07
|
from qiskit import *
circuit = QuantumCircuit(3,3)
%matplotlib inline
circuit.draw(output='mpl')
circuit.x(0)
circuit.barrier()
circuit.draw(output='mpl')
circuit.h(1)
circuit.cx(1,2)
circuit.draw(output='mpl')
circuit.cx(0,1)
circuit.h(0)
circuit.draw(output='mpl')
circuit.barrier()
circuit.measure([0,1],[0,1])
circuit.draw(output='mpl')
circuit.barrier()
circuit.cx(1,2)
circuit.cz(0,2)
circuit.draw(output='mpl')
circuit.measure(2,2)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=simulator,shots=1024).result()
counts = result.get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
print(counts)
|
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
|
SaashaJoshi
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import json
from typing import Any, Callable, Optional, Tuple, Union
from urllib.parse import urljoin
from qiskit import QuantumCircuit, execute
from qiskit.providers import JobStatus
from qiskit.providers.ibmq.job import IBMQJob
from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint
from .exercises import get_question_id
from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate
def _circuit_criteria(
circuit: QuantumCircuit,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[int], Optional[int]]:
if max_qubits is not None and circuit.num_qubits > max_qubits:
print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.')
print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.')
return None, None
try:
if check_gates and not uses_multiqubit_gate(circuit):
print('Your circuit appears to not use any multi-quibit gates.')
print('Please review your circuit and try again.')
return None, None
cost = compute_cost(circuit)
if min_cost is not None and cost < min_cost:
print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n'
'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.')
return None, None
return circuit.num_qubits, cost
except Exception as err:
print(f'Unable to compute cost: {err}')
return None, None
def _circuit_grading(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
payload = None
server = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or '
'the grading servers are down right now.')
return None, None
else:
server = None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
payload = {
'answer': circuit_to_json(circuit)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _job_grading(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str):
print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}')
print(f'Please submit a job as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading '
'servers are down right now.')
return None, None
else:
server = None
job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id
if not job:
print('An invalid or non-existent job was specified.')
return None, None
job_status = job.status()
if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]:
print(f'Job did not successfully complete: {job_status.value}.')
return None, None
elif job_status is not JobStatus.DONE:
print(f'Job has not yet completed: {job_status.value}.')
print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.')
return None, None
header = job.result().header.to_dict()
if 'qc_cost' not in header:
if is_submit:
print('An unprepared answer was specified. '
'Please prepare() and grade() answer before submitting.')
else:
print('An unprepared answer was specified. Please prepare() answer before grading.')
return None, None
download_url, result_url = get_job_urls(job)
if not download_url or not result_url:
print('Unable to obtain job URLs')
return None, None
payload = {
'answer': json.dumps({
'download_url': download_url,
'result_url': result_url
})
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _number_grading(
answer: int,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(answer, int):
print(f'Expected a integer, but was given {type(answer)}')
print(f'Please provide a number as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server '
'or the grading servers are down right now.')
return None, None
else:
server = None
payload = {
'answer': str(answer)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def prepare_circuit(
circuit: QuantumCircuit,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit.')
return None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiment. Please wait...')
job = execute(
circuit,
qobj_header={
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def prepare_solver(
solver_func: Callable,
lab_id: str,
ex_id: str,
problem_set: Optional[Any] = None,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not callable(solver_func):
print(f'Expected a function, but was given {type(solver_func)}')
print(f'Please provide a function that returns a QuantumCircuit.')
return None
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading servers are down right now.')
return
endpoint = server + 'problem-set'
index, value = get_problem_set(lab_id, ex_id, endpoint)
print(f'Running {solver_func.__name__}...')
qc_1 = solver_func(problem_set)
_, cost = _circuit_criteria(
qc_1,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if value and index is not None and index >= 0 and cost is not None:
qc_2 = solver_func(value)
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiments. Please wait...')
job = execute(
[qc_1, qc_2],
qobj_header={
'qc_index': [None, index],
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def grade_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, server = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=False,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_job(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str
) -> bool:
payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def submit_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, _ = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=True,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_job(
job_or_id: IBMQJob,
lab_id: str,
ex_id: str,
) -> bool:
payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def get_problem_set(
lab_id: str, ex_id: str, endpoint: str
) -> Tuple[Optional[int], Optional[Any]]:
problem_set_response = None
try:
payload = {'question_id': get_question_id(lab_id, ex_id)}
problem_set_response = send_request(endpoint, query=payload, method='GET')
except Exception as err:
print('Unable to obtain the problem set')
if problem_set_response:
status = problem_set_response.get('status')
if status == 'valid':
try:
index = problem_set_response.get('index')
value = json.loads(problem_set_response.get('value'))
return index, value
except Exception as err:
print(f'Problem set could not be processed: {err}')
else:
cause = problem_set_response.get('cause')
print(f'Problem set failed: {cause}')
return None, None
def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool:
try:
answer_response = send_request(endpoint, body=payload)
status = answer_response.get('status', None)
cause = answer_response.get('cause', None)
score = cost if cost else answer_response.get('score', None)
handle_grade_response(status, score=score, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def submit_answer(payload: dict) -> bool:
try:
access_token = get_access_token()
baseurl = get_submission_endpoint()
endpoint = urljoin(baseurl, './challenges/answers')
submit_response = send_request(
endpoint,
body=payload,
query={'access_token': access_token}
)
status = submit_response.get('status', None)
if status is None:
status = submit_response.get('valid', None)
cause = submit_response.get('cause', None)
handle_submit_response(status, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def handle_grade_response(
status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None
) -> None:
if status == 'valid':
print('\nCongratulations 🎉! Your answer is correct.')
if score is not None:
print(f'Your score is {score}.')
elif status == 'invalid':
print(f'\nOops 😕! {cause}')
print('Please review your answer and try again.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete then try again.')
else:
print(f'Failed: {cause}')
print('Unable to grade your answer.')
def handle_submit_response(
status: Union[str, bool], cause: Optional[str] = None
) -> None:
if status == 'valid' or status is True:
print('\nSuccess 🎉! Your answer has been submitted.')
elif status == 'invalid' or status is False:
print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}')
print('Make sure your answer is correct and successfully graded before submitting.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete, grade it, and then try to submit again.')
else:
print(f'Failed: {cause}')
print('Unable to submit your answer at this time.')
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
| |
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the piecewise Chebyshev approximation."""
import unittest
from collections import defaultdict
import numpy as np
from ddt import ddt, data, unpack
from qiskit.test.base import QiskitTestCase
from qiskit import BasicAer, execute
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
@ddt
class TestPiecewiseChebyshev(QiskitTestCase):
"""Test the piecewise Chebyshev approximation."""
def assertFunctionIsCorrect(self, function_circuit, reference):
"""Assert that ``function_circuit`` implements the reference function ``reference``."""
function_circuit._build()
num_state_qubits = function_circuit.num_state_qubits
num_ancilla_qubits = function_circuit.num_ancillas
circuit = QuantumCircuit(num_state_qubits + 1 + num_ancilla_qubits)
circuit.h(list(range(num_state_qubits)))
circuit.append(function_circuit.to_instruction(), list(range(circuit.num_qubits)))
backend = BasicAer.get_backend("statevector_simulator")
statevector = execute(circuit, backend).result().get_statevector()
probabilities = defaultdict(float)
for i, statevector_amplitude in enumerate(statevector):
i = bin(i)[2:].zfill(circuit.num_qubits)[num_ancilla_qubits:]
probabilities[i] += np.real(np.abs(statevector_amplitude) ** 2)
unrolled_probabilities = []
unrolled_expectations = []
for i, probability in probabilities.items():
x, last_qubit = int(i[1:], 2), i[0]
if last_qubit == "0":
expected_amplitude = np.cos(reference(x)) / np.sqrt(2**num_state_qubits)
else:
expected_amplitude = np.sin(reference(x)) / np.sqrt(2**num_state_qubits)
unrolled_probabilities += [probability]
unrolled_expectations += [np.real(np.abs(expected_amplitude) ** 2)]
np.testing.assert_array_almost_equal(
unrolled_probabilities, unrolled_expectations, decimal=1
)
@data(
(lambda x: np.arcsin(1 / x), 2, [2, 4], 2),
(lambda x: x / 8, 1, [1, 8], 3),
(np.sqrt, 2, None, 2),
)
@unpack
def test_piecewise_chebyshev(self, f_x, degree, breakpoints, num_state_qubits):
"""Test the piecewise Chebyshev approximation."""
def pw_poly(x):
if breakpoints:
if len(breakpoints) > 1:
start = breakpoints[0]
end = breakpoints[-1]
else:
start = breakpoints[0]
end = 2**num_state_qubits
else:
start = 0
end = 2**num_state_qubits
if start <= x < end:
return f_x(x)
return np.arcsin(1)
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
self.assertFunctionIsCorrect(pw_approximation, pw_poly)
def test_piecewise_chebyshev_mutability(self):
"""Test the mutability of the piecewise Chebyshev approximation."""
def pw_poly(x, f_x):
if breakpoints[0] <= x < breakpoints[-1]:
return f_x(x)
return np.arcsin(1)
def f_x_1(x):
return x / 2
pw_approximation = PiecewiseChebyshev(f_x_1)
with self.subTest(msg="missing number of state qubits"):
with self.assertRaises(AttributeError): # no state qubits set
print(pw_approximation.draw())
with self.subTest(msg="default setup, just setting number of state qubits"):
pw_approximation.num_state_qubits = 2
pw_approximation.f_x = f_x_1
# set to the default breakpoints for pw_poly
breakpoints = [0, 4]
pw_approximation.breakpoints = breakpoints
self.assertFunctionIsCorrect(pw_approximation, lambda x: pw_poly(x, f_x_1))
def f_x_2(x):
return x / 4
with self.subTest(msg="setting non-default values"):
breakpoints = [0, 2]
degree = 2
pw_approximation.breakpoints = breakpoints
pw_approximation.degree = degree
pw_approximation.f_x = f_x_2
self.assertFunctionIsCorrect(pw_approximation, lambda x: pw_poly(x, f_x_2))
def f_x_3(x):
return x**2
with self.subTest(msg="changing all values"):
pw_approximation.num_state_qubits = 4
breakpoints = [1, 3, 6]
degree = 3
pw_approximation.breakpoints = breakpoints
pw_approximation.degree = degree
pw_approximation.f_x = f_x_3
self.assertFunctionIsCorrect(pw_approximation, lambda x: pw_poly(x, f_x_3))
if __name__ == "__main__":
unittest.main()
|
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
|
ronitd2002
|
from qiskit_aer import AerSimulator
import logging
from typing import Optional
import time
import numpy as np
from scipy.optimize import minimize
from qiskit import QuantumCircuit
from qiskit_ibm_runtime import (
EstimatorV2 as Estimator,
SamplerV2 as Sampler,
QiskitRuntimeService,
Session,
)
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_serverless import (
distribute_task,
get_arguments,
get,
save_result,
)
def run(params, ansatz, hamiltonian, estimator, callback_dict):
"""Return callback function that uses Estimator instance,
and stores intermediate values into a dictionary.
Parameters:
params (ndarray): Array of ansatz parameters
ansatz (QuantumCircuit): Parameterized ansatz circuit
hamiltonian (SparsePauliOp): Operator representation of Hamiltonian
estimator (Estimator): Estimator primitive instance
callback_dict (dict): Mutable dict for storing values
Returns:
Callable: Callback function object
"""
result = estimator.run([(ansatz, [hamiltonian], [params])]).result()
energy = result[0].data.evs[0]
# Keep track of the number of iterations
callback_dict["iters"] += 1
# Set the prev_vector to the latest one
callback_dict["prev_vector"] = params
# Compute the value of the cost function at the current vector
callback_dict["cost_history"].append(energy)
# Grab the current time
current_time = time.perf_counter()
# Find the total time of the execute (after the 1st iteration)
if callback_dict["iters"] > 1:
callback_dict["_total_time"] += current_time - callback_dict["_prev_time"]
# Set the previous time to the current time
callback_dict["_prev_time"] = current_time
# Compute the average time per iteration and round it
time_str = (
round(callback_dict["_total_time"] / (callback_dict["iters"] - 1), 2)
if callback_dict["_total_time"]
else "-"
)
# Print to screen on single line
print(
"Iters. done: {} [Avg. time per iter: {}]".format(
callback_dict["iters"], time_str
),
end="\r",
flush=True,
)
return energy, result
def cost_func(*args, **kwargs):
"""Return estimate of energy from estimator
Parameters:
params (ndarray): Array of ansatz parameters
ansatz (QuantumCircuit): Parameterized ansatz circuit
hamiltonian (SparsePauliOp): Operator representation of Hamiltonian
estimator (Estimator): Estimator primitive instance
Returns:
float: Energy estimate
"""
energy, result = run(*args, **kwargs)
return energy
def run_vqe(initial_parameters, ansatz, operator, estimator, method):
callback_dict = {
"prev_vector": None,
"iters": 0,
"cost_history": [],
"_total_time": 0,
"_prev_time": None,
}
result = minimize(
cost_func,
initial_parameters,
args=(ansatz, operator, estimator, callback_dict),
method=method,
)
return result, callback_dict
if __name__ == "__main__":
arguments = get_arguments()
service = arguments.get("service")
ansatz = arguments.get("ansatz")
operator = arguments.get("operator")
method = arguments.get("method", "COBYLA")
initial_parameters = arguments.get("initial_parameters")
if initial_parameters is None:
initial_parameters = 2 * np.pi * np.random.rand(ansatz.num_parameters)
if service:
backend = service.least_busy(operational=True, simulator=False)
else:
backend = AerSimulator(method='density_matrix')
if initial_parameters is None:
initial_parameters = 2 * np.pi * np.random.rand(ansatz.num_parameters)
if service:
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session)
vqe_result, callback_dict = run_vqe(
initial_parameters=initial_parameters,
ansatz=ansatz,
operator=operator,
estimator=estimator,
method=method,
)
else:
estimator = Estimator(backend=backend)
vqe_result, callback_dict = run_vqe(
initial_parameters=initial_parameters,
ansatz=ansatz,
operator=operator,
estimator=estimator,
method=method,
)
save_result(
{
"optimal_point": vqe_result.x.tolist(),
"optimal_value": vqe_result.fun,
"optimizer_time": callback_dict.get("_total_time", 0),
"iters": callback_dict["iters"],
"cost_history" : callback_dict["cost_history"]
}
)
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.providers.aer import QasmSimulator
backend = Aer.get_backend('statevector_simulator')
qc1 = QuantumCircuit(4)
# perform gate operations on individual qubits
qc1.x(0)
qc1.y(1)
qc1.z(2)
qc1.s(3)
# Draw circuit
qc1.draw()
# Plot blochshere
out1 = execute(qc1,backend).result().get_statevector()
plot_bloch_multivector(out1)
qc2 = QuantumCircuit(4)
# initialize qubits
qc2.x(range(4))
# perform gate operations on individual qubits
qc2.x(0)
qc2.y(1)
qc2.z(2)
qc2.s(3)
# Draw circuit
qc2.draw()
# Plot blochshere
out2 = execute(qc2,backend).result().get_statevector()
plot_bloch_multivector(out2)
qc3 = QuantumCircuit(4)
# initialize qubits
qc3.h(range(4))
# perform gate operations on individual qubits
qc3.x(0)
qc3.y(1)
qc3.z(2)
qc3.s(3)
# Draw circuit
qc3.draw()
# Plot blochshere
out3 = execute(qc3,backend).result().get_statevector()
plot_bloch_multivector(out3)
qc4 = QuantumCircuit(4)
# initialize qubits
qc4.x(range(4))
qc4.h(range(4))
# perform gate operations on individual qubits
qc4.x(0)
qc4.y(1)
qc4.z(2)
qc4.s(3)
# Draw circuit
qc4.draw()
# Plot blochshere
out4 = execute(qc4,backend).result().get_statevector()
plot_bloch_multivector(out4)
qc5 = QuantumCircuit(4)
# initialize qubits
qc5.h(range(4))
qc5.s(range(4))
# perform gate operations on individual qubits
qc5.x(0)
qc5.y(1)
qc5.z(2)
qc5.s(3)
# Draw circuit
qc5.draw()
# Plot blochshere
out5 = execute(qc5,backend).result().get_statevector()
plot_bloch_multivector(out5)
qc6 = QuantumCircuit(4)
# initialize qubits
qc6.x(range(4))
qc6.h(range(4))
qc6.s(range(4))
# perform gate operations on individual qubits
qc6.x(0)
qc6.y(1)
qc6.z(2)
qc6.s(3)
# Draw circuit
qc6.draw()
# Plot blochshere
out6 = execute(qc6,backend).result().get_statevector()
plot_bloch_multivector(out6)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
"""Test executing multiple-register circuits on BasicAer."""
from qiskit import BasicAer, execute
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.quantum_info import Operator, Statevector, process_fidelity, state_fidelity
from qiskit.test import QiskitTestCase
class TestCircuitMultiRegs(QiskitTestCase):
"""QuantumCircuit Qasm tests."""
def test_circuit_multi(self):
"""Test circuit multi regs declared at start."""
qreg0 = QuantumRegister(2, "q0")
creg0 = ClassicalRegister(2, "c0")
qreg1 = QuantumRegister(2, "q1")
creg1 = ClassicalRegister(2, "c1")
circ = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circ.x(qreg0[1])
circ.x(qreg1[0])
meas = QuantumCircuit(qreg0, qreg1, creg0, creg1)
meas.measure(qreg0, creg0)
meas.measure(qreg1, creg1)
qc = circ.compose(meas)
backend_sim = BasicAer.get_backend("qasm_simulator")
result = execute(qc, backend_sim, seed_transpiler=34342).result()
counts = result.get_counts(qc)
target = {"01 10": 1024}
backend_sim = BasicAer.get_backend("statevector_simulator")
result = execute(circ, backend_sim, seed_transpiler=3438).result()
state = result.get_statevector(circ)
backend_sim = BasicAer.get_backend("unitary_simulator")
result = execute(circ, backend_sim, seed_transpiler=3438).result()
unitary = Operator(result.get_unitary(circ))
self.assertEqual(counts, target)
self.assertAlmostEqual(state_fidelity(Statevector.from_label("0110"), state), 1.0, places=7)
self.assertAlmostEqual(
process_fidelity(Operator.from_label("IXXI"), unitary), 1.0, places=7
)
|
https://github.com/quantum-kittens/quantum-computing-basics
|
quantum-kittens
|
# run this cell if you're executing this notebook in your browser
!pip install qiskit
from IPython.display import clear_output
clear_output()
from qiskit import *
import numpy as np
n = 2 #number of qubits used for the example in this notebook
from qiskit.visualization import array_to_latex
target_state = [ # state vector of the target state
1/np.sqrt(n),
0,
(complex(0,1))/np.sqrt(n),
0,
]
array_to_latex(target_state, prefix = '|\\psi_{ts}> = ' ) # a nifty, clean latex representation
target_state_mathematical = [
[1/np.sqrt(n)],
[0],
[(complex(0,1))/np.sqrt(n)],
[0],
]
array_to_latex(target_state_mathematical, prefix = 'Mathematical: |\\psi_{m}> = ' )
qr_init = QuantumRegister(n)
qc_init = QuantumCircuit(qr_init)
qc_init.initialize(target_state) # the initialization
qc_init.draw('mpl')
qr_gate = QuantumRegister(n)
qc_gate = QuantumCircuit(qr_gate)
qc_gate.h(qr_gate[1])
qc_gate.s(qr_gate[1])
qc_gate.draw('mpl')
from qiskit.quantum_info import Statevector
qc_gate_statevector = Statevector(qc_gate) # alternative: qc_gate_statevector = quantum_info.Statevector.from_instruction(qc_gate)
qc_gate_statevector.draw('latex', prefix = '|\\psi_{qc-gate-statevector}> = ')
backend = Aer.get_backend('statevector_simulator') #alternative: from qiskit.providers.aer import StatevectorSimulator | backend = StatevectorSimulator()
job = execute(qc_gate, backend)
qc_gate_state_sim = job.result().get_statevector()
array_to_latex(qc_gate_state_sim, prefix = '|\\psi_{qc-gate-sim}> = ') # Note .draw() isn't used here, because .get_statevector() returns an array
from qiskit.quantum_info import state_fidelity
print('Target state and qc_gate_statevector: ')
display(state_fidelity(target_state, qc_gate_statevector))
print('\nTarget state and qc_gate_state_sim: ')
display(state_fidelity(target_state, qc_gate_state_sim))
qc_gate_statevector.draw('qsphere')
from qiskit.visualization import plot_state_qsphere
plot_state_qsphere(qc_gate_statevector)
qc_gate_statevector.draw('bloch')
from qiskit. visualization import plot_bloch_multivector
plot_bloch_multivector(qc_gate_statevector)
from qiskit.visualization import plot_state_paulivec
plot_state_paulivec(qc_gate_statevector)
from qiskit.quantum_info import DensityMatrix
rho = DensityMatrix(qc_gate) #alternative: rho = quantum_info.DensityMatrix.from_instruction(qc_gate)
rho.draw('latex', prefix = '\\rho = ')
rho_m_matrix = np.array([[1/2,0,complex(0,-1/2),0],[0,0,0,0],[complex(0,1/2),0,1/2,0],[0,0,0,0]])
rho_m = DensityMatrix(rho_m_matrix)
display(rho_m.draw('latex', prefix='\\rho = '))
ket_target_state = np.matrix(target_state).T
bra_target_state = ket_target_state.conj().T
display(array_to_latex(ket_target_state, prefix = '|\\psi_m> = ' ))
display(array_to_latex(bra_target_state, prefix = '<\\psi_m| = ' ))
target_state_matrix = np.matmul(ket_target_state, bra_target_state)
rho = DensityMatrix(target_state_matrix)
display(rho.draw('latex', prefix='\\rho = '))
from qiskit.visualization import plot_state_city
plot_state_city(rho, color = ['teal', 'black']) # colors cuz I felt like prettying it up
rho.draw('hinton')
from qiskit.visualization import plot_state_hinton
plot_state_hinton(rho)
from qiskit.quantum_info import Statevector
init_state = Statevector(qc_init)
print('\n Initial state: ')
display(init_state.draw('latex', prefix = '|\\psi_{ts}> ='))
# create circuit with Hadamards operating on each qubit
qc_hadamards = QuantumCircuit(n)
qc_hadamards.h(range(n))
display(qc_hadamards.draw('mpl'))
new_state = init_state.evolve(qc_hadamards)
print('\n Final state: ')
display(new_state.draw('latex', prefix= '|\\psi_{f}> ='))
qc_combined = qc_hadamards.compose(qc_init, range(n), front = True)
display(qc_combined.draw('mpl'))
qc_combined_state = Statevector(qc_combined)
print('\n State of circuit qc_init + qc_hadamards = ')
display(qc_combined_state.draw('latex'))
from qiskit.quantum_info import Operator
display(rho.draw('latex', prefix='Initial State, \\rho = '))
H = Operator.from_label('H') #fetches the Hadamard
display(array_to_latex(H.data, prefix ='H = '))
HH = H.expand(H) # tensor product of H with itself
display(array_to_latex(HH.data, prefix ='H \\otimes H = '))
rho_HH = rho.evolve(HH)
display(rho_HH.draw('latex', prefix='\\rho_f = H\\rho H^\\dagger = '))
ket_combined_state = np.matrix(qc_combined_state).T
bra_combined_state = ket_combined_state.conj().T
display(array_to_latex(ket_combined_state, prefix = '|\\psi_f> = ' ))
display(array_to_latex(bra_combined_state, prefix = '<\\psi_f| = ' ))
combined_state_matrix = np.matmul(ket_combined_state, bra_combined_state)
rho_comb = DensityMatrix(combined_state_matrix)
display(rho_comb.draw('latex', prefix='\\rho_f = '))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
%run ../include/quantum.py
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
qreg = QuantumRegister(3)
#No need to define classical register as we are not measuring
mycircuit = QuantumCircuit(qreg)
#set ancilla
mycircuit.x(qreg[2])
mycircuit.h(qreg[2])
Uf(mycircuit,qreg)
#set ancilla back
mycircuit.h(qreg[2])
mycircuit.x(qreg[2])
job = execute(mycircuit,Aer.get_backend('unitary_simulator'))
u=job.result().get_unitary(mycircuit,decimals=3)
#We are interested in the top-left 4x4 part
for i in range(4):
s=""
for j in range(4):
val = str(u[i][j].real)
while(len(val)<5): val = " "+val
s = s + val
print(s)
mycircuit.draw(output='mpl')
def inversion(circuit,quantum_reg):
#step 1
circuit.h(quantum_reg[1])
circuit.h(quantum_reg[0])
#step 2
circuit.x(quantum_reg[1])
circuit.x(quantum_reg[0])
#step 3
circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[2])
#step 4
circuit.x(quantum_reg[1])
circuit.x(quantum_reg[0])
#step 5
circuit.x(quantum_reg[2])
#step 6
circuit.h(quantum_reg[1])
circuit.h(quantum_reg[0])
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
qreg1 = QuantumRegister(3)
mycircuit1 = QuantumCircuit(qreg1)
#set ancilla qubit
mycircuit1.x(qreg1[2])
mycircuit1.h(qreg1[2])
inversion(mycircuit1,qreg1)
#set ancilla qubit back
mycircuit1.h(qreg1[2])
mycircuit1.x(qreg1[2])
job = execute(mycircuit1,Aer.get_backend('unitary_simulator'))
u=job.result().get_unitary(mycircuit1,decimals=3)
for i in range(4):
s=""
for j in range(4):
val = str(u[i][j].real)
while(len(val)<5): val = " "+val
s = s + val
print(s)
mycircuit1.draw(output='mpl')
%run ..\include\quantum.py
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
qreg = QuantumRegister(3)
creg = ClassicalRegister(2)
mycircuit = QuantumCircuit(qreg,creg)
#Grover
#initial step - equal superposition
for i in range(2):
mycircuit.h(qreg[i])
#set ancilla
mycircuit.x(qreg[2])
mycircuit.h(qreg[2])
mycircuit.barrier()
#change the number of iterations
iterations=1
#Grover's iterations.
for i in range(iterations):
#query
Uf(mycircuit,qreg)
mycircuit.barrier()
#inversion
inversion(mycircuit,qreg)
mycircuit.barrier()
#set ancilla back
mycircuit.h(qreg[2])
mycircuit.x(qreg[2])
mycircuit.measure(qreg[0],creg[0])
mycircuit.measure(qreg[1],creg[1])
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=10000)
counts = job.result().get_counts(mycircuit)
# print the outcome
for outcome in counts:
print(outcome,"is observed",counts[outcome],"times")
mycircuit.draw(output='mpl')
def big_inversion(circuit,quantum_reg):
for i in range(3):
circuit.h(quantum_reg[i])
circuit.x(quantum_reg[i])
circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[4])
circuit.ccx(quantum_reg[2],quantum_reg[4],quantum_reg[3])
circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[4])
for i in range(3):
circuit.x(quantum_reg[i])
circuit.h(quantum_reg[i])
circuit.x(quantum_reg[3])
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
big_qreg2 = QuantumRegister(5)
big_mycircuit2 = QuantumCircuit(big_qreg2)
#set ancilla
big_mycircuit2.x(big_qreg2[3])
big_mycircuit2.h(big_qreg2[3])
big_inversion(big_mycircuit2,big_qreg2)
#set ancilla back
big_mycircuit2.h(big_qreg2[3])
big_mycircuit2.x(big_qreg2[3])
job = execute(big_mycircuit2,Aer.get_backend('unitary_simulator'))
u=job.result().get_unitary(big_mycircuit2,decimals=3)
for i in range(8):
s=""
for j in range(8):
val = str(u[i][j].real)
while(len(val)<6): val = " "+val
s = s + val
print(s)
%run ..\include\quantum.py
def big_inversion(circuit,quantum_reg):
for i in range(3):
circuit.h(quantum_reg[i])
circuit.x(quantum_reg[i])
circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[4])
circuit.ccx(quantum_reg[2],quantum_reg[4],quantum_reg[3])
circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[4])
for i in range(3):
circuit.x(quantum_reg[i])
circuit.h(quantum_reg[i])
circuit.x(quantum_reg[3])
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
qreg8 = QuantumRegister(5)
creg8 = ClassicalRegister(3)
mycircuit8 = QuantumCircuit(qreg8,creg8)
#set ancilla
mycircuit8.x(qreg8[3])
mycircuit8.h(qreg8[3])
#Grover
for i in range(3):
mycircuit8.h(qreg8[i])
mycircuit8.barrier()
#Try 1,2,6,12 8iterations of Grover
for i in range(2):
Uf_8(mycircuit8,qreg8)
mycircuit8.barrier()
big_inversion(mycircuit8,qreg8)
mycircuit8.barrier()
#set ancilla back
mycircuit8.h(qreg8[3])
mycircuit8.x(qreg8[3])
for i in range(3):
mycircuit8.measure(qreg8[i],creg8[i])
job = execute(mycircuit8,Aer.get_backend('qasm_simulator'),shots=10000)
counts8 = job.result().get_counts(mycircuit8)
# print the reverse of the outcome
for outcome in counts8:
print(outcome,"is observed",counts8[outcome],"times")
mycircuit8.draw(output='mpl')
%run ../include/quantum.py
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
qreg12 = QuantumRegister(19)
creg12 = ClassicalRegister(10)
mycircuit12 = QuantumCircuit(qreg12,creg12)
for i in range(10):
mycircuit12.h(qreg12[i])
mycircuit12.x(qreg12[10])
mycircuit12.h(qreg12[10])
#number of iterations - change this value
iteration_count = 1
for i in range(iteration_count):
giant_oracle2(mycircuit12,qreg12)
giant_diffusion(mycircuit12,qreg12)
mycircuit12.h(qreg12[10])
mycircuit12.x(qreg12[10])
for i in range(10):
mycircuit12.measure(qreg12[i],creg12[i])
job = execute(mycircuit12,Aer.get_backend('qasm_simulator'),shots=100000)
counts12 = job.result().get_counts(mycircuit12)
# print the reverse of the outcome
for outcome in counts12:
print(outcome,"is observed",counts12[outcome],"times")
def oracle_11(circuit,qreg):
circuit1.ccx(qreg[0],qreg[1],qreg[2])
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
qreg1 = QuantumRegister(3)
circuit1 = QuantumCircuit(qreg1)
# prepare ancilla qubit
circuit1.x(qreg1[2])
circuit1.h(qreg1[2])
#call the oracle
oracle_11(circuit1,qreg1)
# put ancilla qubit back into state |0>
circuit1.h(qreg1[2])
circuit1.x(qreg1[2])
job = execute(circuit1,Aer.get_backend('unitary_simulator'))
u=job.result().get_unitary(circuit1,decimals=3)
for i in range(4):
s=""
for j in range(4):
val = str(u[i][j].real)
while(len(val)<5): val = " "+val
s = s + val
print(s)
circuit1.draw(output='mpl')
def oracle_01(circuit,qreg):
circuit.x(qreg[1])
circuit.ccx(qreg[0],qreg[1],qreg[2])
circuit.x(qreg[1])
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
qreg1 = QuantumRegister(3)
circuit1 = QuantumCircuit(qreg1)
# prepare ancilla qubit
circuit1.x(qreg1[2])
circuit1.h(qreg1[2])
#call the oracle
oracle_01(circuit1,qreg1)
# put ancilla qubit back into state |0>
circuit1.h(qreg1[2])
circuit1.x(qreg1[2])
job = execute(circuit1,Aer.get_backend('unitary_simulator'))
u=job.result().get_unitary(circuit1,decimals=3)
for i in range(4):
s=""
for j in range(4):
val = str(u[i][j].real)
while(len(val)<5): val = " "+val
s = s + val
print(s)
circuit1.draw(output='mpl')
def oracle_00(circuit,qreg):
circuit.x(qreg[0])
circuit.x(qreg[1])
circuit.ccx(qreg[0],qreg[1],qreg[2])
circuit.x(qreg[0])
circuit.x(qreg[1])
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
qreg = QuantumRegister(3)
creg = ClassicalRegister(2)
mycircuit = QuantumCircuit(qreg,creg)
#Grover
#initial step - equal superposition
for i in range(2):
mycircuit.h(qreg[i])
#set ancilla
mycircuit.x(qreg[2])
mycircuit.h(qreg[2])
mycircuit.barrier()
#change the number of iterations
iterations=1
#Grover's iterations.
for i in range(iterations):
#query
oracle_00(mycircuit,qreg)
mycircuit.barrier()
#inversion
inversion(mycircuit,qreg)
mycircuit.barrier()
#set ancilla back
mycircuit.h(qreg[2])
mycircuit.x(qreg[2])
mycircuit.measure(qreg[0],creg[0])
mycircuit.measure(qreg[1],creg[1])
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=10000)
counts = job.result().get_counts(mycircuit)
# print the reverse of the outcome
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts[outcome],"times")
mycircuit.draw(output='mpl')
def oracle_001_111(circuit,qreg):
#Your code here
#
#
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import BasicAer
from qiskit_aqua import QuantumInstance
from qiskit_aqua import Operator, run_algorithm
from qiskit_aqua.input import EnergyInput
from qiskit_aqua.translators.ising import portfolio
from qiskit_aqua.algorithms import VQE, QAOA, ExactEigensolver
from qiskit_aqua.components.optimizers import COBYLA
from qiskit_aqua.components.variational_forms import RY
import numpy as np
from qiskit import IBMQ
IBMQ.load_accounts()
# set number of assets (= number of qubits)
num_assets = 4
# get random expected return vector (mu) and covariance matrix (sigma)
mu, sigma = portfolio.random_model(num_assets, seed=42)
q = 0.5 # set risk factor
budget = int(num_assets / 2) # set budget
penalty = num_assets # set parameter to scale the budget penalty term
qubitOp, offset = portfolio.get_portfolio_qubitops(mu, sigma, q, budget, penalty)
algo_input = EnergyInput(qubitOp)
def index_to_selection(i, num_assets):
s = "{0:b}".format(i).rjust(num_assets)
x = np.array([1 if s[i]=='1' else 0 for i in reversed(range(num_assets))])
return x
def print_result(result):
selection = portfolio.sample_most_likely(result['eigvecs'][0])
value = portfolio.portfolio_value(selection, mu, sigma, q, budget, penalty)
print('Optimal: selection {}, value {:.4f}'.format(selection, value))
probabilities = np.abs(result['eigvecs'][0])**2
i_sorted = reversed(np.argsort(probabilities))
print('\n----------------- Full result ---------------------')
print('selection\tvalue\t\tprobability')
print('---------------------------------------------------')
for i in i_sorted:
x = index_to_selection(i, num_assets)
value = portfolio.portfolio_value(x, mu, sigma, q, budget, penalty)
probability = probabilities[i]
print('%10s\t%.4f\t\t%.4f' %(x, value, probability))
exact_eigensolver = ExactEigensolver(qubitOp, k=1)
result = exact_eigensolver.run()
""" the equivalent if using declarative approach
algorithm_cfg = {
'name': 'ExactEigensolver'
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg
}
result = run_algorithm(params, algo_input)
"""
print_result(result)
backend = BasicAer.get_backend('statevector_simulator')
seed = 50
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
ry = RY(qubitOp.num_qubits, depth=3, entanglement='full')
vqe = VQE(qubitOp, ry, cobyla, 'matrix')
vqe.random_seed = seed
quantum_instance = QuantumInstance(backend=backend, seed=seed, seed_mapper=seed)
result = vqe.run(quantum_instance)
"""declarative approach
algorithm_cfg = {
'name': 'VQE',
'operator_mode': 'matrix'
}
optimizer_cfg = {
'name': 'COBYLA',
'maxiter': 250
}
var_form_cfg = {
'name': 'RY',
'depth': 3,
'entanglement': 'full'
}
params = {
'problem': {'name': 'ising', 'random_seed': seed},
'algorithm': algorithm_cfg,
'optimizer': optimizer_cfg,
'variational_form': var_form_cfg
}
result = run_algorithm(params, algo_input, backend=backend)
"""
print_result(result)
backend = BasicAer.get_backend('statevector_simulator')
seed = 50
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa = QAOA(qubitOp, cobyla, 3, 'matrix')
qaoa.random_seed = seed
quantum_instance = QuantumInstance(backend=backend, seed=seed, seed_mapper=seed)
result = qaoa.run(quantum_instance)
"""declarative approach
algorithm_cfg = {
'name': 'QAOA.Variational',
'p': 3,
'operator_mode': 'matrix'
}
optimizer_cfg = {
'name': 'COBYLA',
'maxiter': 250
}
params = {
'problem': {'name': 'ising', 'random_seed': seed},
'algorithm': algorithm_cfg,
'optimizer': optimizer_cfg
}
result = run_algorithm(params, algo_input, backend=backend)
"""
print_result(result)
|
https://github.com/QuCO-CSAM/Solving-Combinatorial-Optimisation-Problems-Using-Quantum-Algorithms
|
QuCO-CSAM
|
# Important libraries and modules
import numpy as np
from itertools import permutations
import gzip
from qiskit import*
import time
from qiskit.aqua.algorithms import VQE
from qiskit.aqua.algorithms import QAOA
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua import QuantumInstance
from qiskit.aqua.components.optimizers import COBYLA
from qiskit import IBMQ
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.optimization.applications.ising.tsp import TspData
import qiskit.optimization.applications.ising.tsp as tsp
from qiskit.circuit.library import TwoLocal
from qiskit.circuit.library import RealAmplitudes
# # Load account from disk
IBMQ.load_account()
IBMQ.providers()
def readInData():
"""
Output G : N by N distance matrix from Matrices1a.txt file.
"""
G = []
p = [3, 4,5,6,7,8,9,10,11]
q = [i**(2) for i in p ]
m = 0
v = open("Matrices.txt" , "r")
w = v.read().split()
for i in range (len(w)):
w[i] = int(float(w[i]))
for i in range (len(q)):
G.append(np.reshape(w[m:m+q[i]] , (p[i] , p[i])))
m = m + q[i]
return G
distanceMatrix = readInData() #Array of different sized matrices
def determineIfFeasible(result):
"""
Determines if eigenstate is feasible or infeasible.
Output: arr = Infeasible if eiegenstate is infeasible or arr = binary array of feasible solution
"""
data = sorted(result['eigenstate'].items(), key=lambda item: item[1])[::-1]
for i in range(len(data)):
a = tsp.tsp_feasible(data[i][0])
arr = 'Infeasible'
if a == True:
b = str(data[i][0])
arr = [b , data[i][1]]
break
return arr
def optimal(a,b,c,f,u):
"""
Read in data of initial optimal point that will be used in the quantum algorithm
"""
openfile = open("optimal.txt" , "r")
readFile = openfile.read().split()
t = []
for i in readFile:
if i != ',':
q = len(i)
t.append(float(i[0:q-1]))
v, r, o, d, z = np.array(t[0:a]), np.array(t[a:a+b]), np.array(t[a+b : a+b+c]), np.array(t[a+b+c:a+b+c+f]), np.array(t[a+b+c+f:a+b+c+f+u])
return [v,r,o,d,z]
R = optimal(54,96,100,216,294) #Array of corresponding initial points
def variationalQuantumEigensolver(numIter,numShots,distanceMatrix, varForm, initialPoint, deviceName):
"""
Implementation of the VQE
Output: classial TSP solution (total length of tour) and time taken to execute algorithm
"""
# Mappining of problem to ising hamiltonian
x = TspData('tmp',len(matrix),np.zeros((3,3)),distanceMatrix)
qubitOp ,offset = tsp.get_operator(x)
seed = 10598
# Generate a circuit
spsa = SPSA(maxiter = numIter)
if varForm == 'vf1':
ry = RealAmplitudes(qubitOp.num_qubits, entanglement='linear')
elif varForm == 'vf2':
ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=5, entanglement='linear')
runVqe = VQE(qubitOp, ry, spsa,include_custom=True, initial_point = initialPoint)
my_provider = IBMQ.get_provider(ibm_hub) #Replace ibm_hub with appropriate qiskit hub name
device = my_provider.get_backend(deviceName) # deviceName is the Device of IBM quantum device in a string
quantum_instance = QuantumInstance(device, seed_simulator=seed, seed_transpiler=seed,shots = numShots,
skip_qobj_validation = False)
result = runVqe.run(quantum_instance)
#Convert quantum result into its classical form and determine if feasible or infeasible
answer = determineIfFeasible(result)
if answer == 'Infeasible':
solution = -1
else:
binarry = [int(p) for p in answer[0]]
route = tsp.get_tsp_solution(binarry)
solution = tsp.tsp_value(route, distanceMatrix)
return solution, result['optimizer_time']
## Example for 3 by 3 instance implemented using VQE:
numIter = 1
numShots = 1024
distanceMatrix = distanceMatrix[0]
varForm = 'vf1' #vf1 indicates the RealAmplitude form
deviceName = 'ibmq_cambridge'
initialPoint = R[0]
finalResult = variationalQuantumEigensolver(numIter,numShots, distanceMatrix, varForm, initialPoint, deviceName)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import enum
import math
import ddt
import qiskit.qasm2
from qiskit.circuit import Gate, library as lib
from qiskit.test import QiskitTestCase
from test import combine # pylint: disable=wrong-import-order
# We need to use this enum a _bunch_ of times, so let's not give it a long name.
# pylint: disable=invalid-name
class T(enum.Enum):
# This is a deliberately stripped-down list that doesn't include most of the expression-specific
# tokens, because we don't want to complicate matters with those in tests of the general parser
# errors. We test the expression subparser elsewhere.
OPENQASM = "OPENQASM"
BARRIER = "barrier"
CREG = "creg"
GATE = "gate"
IF = "if"
INCLUDE = "include"
MEASURE = "measure"
OPAQUE = "opaque"
QREG = "qreg"
RESET = "reset"
PI = "pi"
ARROW = "->"
EQUALS = "=="
SEMICOLON = ";"
COMMA = ","
LPAREN = "("
RPAREN = ")"
LBRACKET = "["
RBRACKET = "]"
LBRACE = "{"
RBRACE = "}"
ID = "q"
REAL = "1.5"
INTEGER = "1"
FILENAME = '"qelib1.inc"'
def bad_token_parametrisation():
"""Generate the test cases for the "bad token" tests; this makes a sequence of OpenQASM 2
statements, then puts various invalid tokens after them to verify that the parser correctly
throws an error on them."""
token_set = frozenset(T)
def without(*tokens):
return token_set - set(tokens)
# ddt isn't a particularly great parametriser - it'll only correctly unpack tuples and lists in
# the way we really want, but if we want to control the test id, we also have to set `__name__`
# which isn't settable on either of those. We can't use unpack, then, so we just need a class
# to pass.
class BadTokenCase:
def __init__(self, statement, disallowed, name=None):
self.statement = statement
self.disallowed = disallowed
self.__name__ = name
for statement, disallowed in [
# This should only include stopping points where the next token is somewhat fixed; in
# places where there's a real decision to be made (such as number of qubits in a gate,
# or the statement type in a gate body), there should be a better error message.
#
# There's a large subset of OQ2 that's reducible to a regular language, so we _could_
# define that, build a DFA for it, and use that to very quickly generate a complete set
# of tests. That would be more complex to read and verify for correctness, though.
(
"",
without(
T.OPENQASM,
T.ID,
T.INCLUDE,
T.OPAQUE,
T.GATE,
T.QREG,
T.CREG,
T.IF,
T.RESET,
T.BARRIER,
T.MEASURE,
T.SEMICOLON,
),
),
("OPENQASM", without(T.REAL, T.INTEGER)),
("OPENQASM 2.0", without(T.SEMICOLON)),
("include", without(T.FILENAME)),
('include "qelib1.inc"', without(T.SEMICOLON)),
("opaque", without(T.ID)),
("opaque bell", without(T.LPAREN, T.ID, T.SEMICOLON)),
("opaque bell (", without(T.ID, T.RPAREN)),
("opaque bell (a", without(T.COMMA, T.RPAREN)),
("opaque bell (a,", without(T.ID, T.RPAREN)),
("opaque bell (a, b", without(T.COMMA, T.RPAREN)),
("opaque bell (a, b)", without(T.ID, T.SEMICOLON)),
("opaque bell (a, b) q1", without(T.COMMA, T.SEMICOLON)),
("opaque bell (a, b) q1,", without(T.ID, T.SEMICOLON)),
("opaque bell (a, b) q1, q2", without(T.COMMA, T.SEMICOLON)),
("gate", without(T.ID)),
("gate bell (", without(T.ID, T.RPAREN)),
("gate bell (a", without(T.COMMA, T.RPAREN)),
("gate bell (a,", without(T.ID, T.RPAREN)),
("gate bell (a, b", without(T.COMMA, T.RPAREN)),
("gate bell (a, b) q1", without(T.COMMA, T.LBRACE)),
("gate bell (a, b) q1,", without(T.ID, T.LBRACE)),
("gate bell (a, b) q1, q2", without(T.COMMA, T.LBRACE)),
("qreg", without(T.ID)),
("qreg reg", without(T.LBRACKET)),
("qreg reg[", without(T.INTEGER)),
("qreg reg[5", without(T.RBRACKET)),
("qreg reg[5]", without(T.SEMICOLON)),
("creg", without(T.ID)),
("creg reg", without(T.LBRACKET)),
("creg reg[", without(T.INTEGER)),
("creg reg[5", without(T.RBRACKET)),
("creg reg[5]", without(T.SEMICOLON)),
("CX", without(T.LPAREN, T.ID, T.SEMICOLON)),
("CX(", without(T.PI, T.INTEGER, T.REAL, T.ID, T.LPAREN, T.RPAREN)),
("CX()", without(T.ID, T.SEMICOLON)),
("CX q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)),
("CX q[", without(T.INTEGER)),
("CX q[0", without(T.RBRACKET)),
("CX q[0]", without(T.COMMA, T.SEMICOLON)),
("CX q[0],", without(T.ID, T.SEMICOLON)),
("CX q[0], q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)),
# No need to repeatedly "every" possible number of arguments.
("measure", without(T.ID)),
("measure q", without(T.LBRACKET, T.ARROW)),
("measure q[", without(T.INTEGER)),
("measure q[0", without(T.RBRACKET)),
("measure q[0]", without(T.ARROW)),
("measure q[0] ->", without(T.ID)),
("measure q[0] -> c", without(T.LBRACKET, T.SEMICOLON)),
("measure q[0] -> c[", without(T.INTEGER)),
("measure q[0] -> c[0", without(T.RBRACKET)),
("measure q[0] -> c[0]", without(T.SEMICOLON)),
("reset", without(T.ID)),
("reset q", without(T.LBRACKET, T.SEMICOLON)),
("reset q[", without(T.INTEGER)),
("reset q[0", without(T.RBRACKET)),
("reset q[0]", without(T.SEMICOLON)),
("barrier", without(T.ID, T.SEMICOLON)),
("barrier q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)),
("barrier q[", without(T.INTEGER)),
("barrier q[0", without(T.RBRACKET)),
("barrier q[0]", without(T.COMMA, T.SEMICOLON)),
("if", without(T.LPAREN)),
("if (", without(T.ID)),
("if (cond", without(T.EQUALS)),
("if (cond ==", without(T.INTEGER)),
("if (cond == 0", without(T.RPAREN)),
("if (cond == 0)", without(T.ID, T.RESET, T.MEASURE)),
]:
for token in disallowed:
yield BadTokenCase(statement, token.value, name=f"'{statement}'-{token.name.lower()}")
def eof_parametrisation():
for tokens in [
("OPENQASM", "2.0", ";"),
("include", '"qelib1.inc"', ";"),
("opaque", "bell", "(", "a", ",", "b", ")", "q1", ",", "q2", ";"),
("gate", "bell", "(", "a", ",", "b", ")", "q1", ",", "q2", "{", "}"),
("qreg", "qr", "[", "5", "]", ";"),
("creg", "cr", "[", "5", "]", ";"),
("CX", "(", ")", "q", "[", "0", "]", ",", "q", "[", "1", "]", ";"),
("measure", "q", "[", "0", "]", "->", "c", "[", "0", "]", ";"),
("reset", "q", "[", "0", "]", ";"),
("barrier", "q", ";"),
# No need to test every combination of `if`, really.
("if", "(", "cond", "==", "0", ")", "CX q[0], q[1];"),
]:
prefix = ""
for token in tokens[:-1]:
prefix = f"{prefix} {token}".strip()
yield prefix
@ddt.ddt
class TestIncompleteStructure(QiskitTestCase):
PRELUDE = "OPENQASM 2.0; qreg q[5]; creg c[5]; creg cond[1];"
@ddt.idata(bad_token_parametrisation())
def test_bad_token(self, case):
"""Test that the parser raises an error when an incorrect token is given."""
statement = case.statement
disallowed = case.disallowed
prelude = "" if statement.startswith("OPENQASM") else self.PRELUDE
full = f"{prelude} {statement} {disallowed}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "needed .*, but instead"):
qiskit.qasm2.loads(full)
@ddt.idata(eof_parametrisation())
def test_eof(self, statement):
"""Test that the parser raises an error when the end-of-file is reached instead of a token
that is required."""
prelude = "" if statement.startswith("OPENQASM") else self.PRELUDE
full = f"{prelude} {statement}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "unexpected end-of-file"):
qiskit.qasm2.loads(full)
def test_loading_directory(self):
"""Test that the correct error is raised when a file fails to open."""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "failed to read"):
qiskit.qasm2.load(".")
class TestVersion(QiskitTestCase):
def test_invalid_version(self):
program = "OPENQASM 3.0;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only handle OpenQASM 2.0"):
qiskit.qasm2.loads(program)
program = "OPENQASM 2.1;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only handle OpenQASM 2.0"):
qiskit.qasm2.loads(program)
program = "OPENQASM 20.e-1;"
with self.assertRaises(qiskit.qasm2.QASM2ParseError):
qiskit.qasm2.loads(program)
def test_openqasm_must_be_first_statement(self):
program = "qreg q[0]; OPENQASM 2.0;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "only the first statement"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestScoping(QiskitTestCase):
def test_register_use_before_definition(self):
program = "CX after[0], after[1]; qreg after[2];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined in this scope"):
qiskit.qasm2.loads(program)
program = "qreg q[2]; measure q[0] -> c[0]; creg c[2];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined in this scope"):
qiskit.qasm2.loads(program)
@combine(
definer=["qreg reg[2];", "creg reg[2];", "gate reg a {}", "opaque reg a;"],
bad_definer=["qreg reg[2];", "creg reg[2];"],
)
def test_register_already_defined(self, definer, bad_definer):
program = f"{definer} {bad_definer}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_qelib1_not_implicit(self):
program = """
OPENQASM 2.0;
qreg q[2];
cx q[0], q[1];
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_gates_before_definition(self):
program = """
qreg q[2];
cx q[0], q[1];
gate cx a, b {
CX a, b;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_gate_recursively(self):
program = """
gate cx a, b {
cx a, b;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_qubits_from_previous_gate(self):
program = """
gate cx a, b {
CX a, b;
}
gate other c {
CX a, b;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'a' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_parameters_from_previous_gate(self):
program = """
gate first(a, b) q {
U(a, 0, b) q;
}
gate second q {
U(a, 0, b) q;
}
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "'a' is not a parameter.*defined"
):
qiskit.qasm2.loads(program)
def test_cannot_access_quantum_registers_within_gate(self):
program = """
qreg q[2];
gate my_gate a {
CX a, q;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a quantum register"):
qiskit.qasm2.loads(program)
def test_parameters_not_defined_outside_gate(self):
program = """
gate my_gate(a) q {}
qreg qr[2];
U(a, 0, 0) qr;
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "'a' is not a parameter.*defined"
):
qiskit.qasm2.loads(program)
def test_qubits_not_defined_outside_gate(self):
program = """
gate my_gate(a) q {}
U(0, 0, 0) q;
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is not defined"):
qiskit.qasm2.loads(program)
@ddt.data('include "qelib1.inc";', "gate h q { }")
def test_gates_cannot_redefine(self, definer):
program = f"{definer} gate h q {{ }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_cannot_use_undeclared_register_conditional(self):
program = "qreg q[1]; if (c == 0) U(0, 0, 0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestTyping(QiskitTestCase):
@ddt.data(
"CX q[0], U;",
"measure U -> c[0];",
"measure q[0] -> U;",
"reset U;",
"barrier U;",
"if (U == 0) CX q[0], q[1];",
"gate my_gate a { U(0, 0, 0) U; }",
)
def test_cannot_use_gates_incorrectly(self, usage):
program = f"qreg q[2]; creg c[2]; {usage}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'U' is a gate"):
qiskit.qasm2.loads(program)
@ddt.data(
"measure q[0] -> q[1];",
"if (q == 0) CX q[0], q[1];",
"q q[0], q[1];",
"gate my_gate a { U(0, 0, 0) q; }",
)
def test_cannot_use_qregs_incorrectly(self, usage):
program = f"qreg q[2]; creg c[2]; {usage}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a quantum register"):
qiskit.qasm2.loads(program)
@ddt.data(
"CX q[0], c[1];",
"measure c[0] -> c[1];",
"reset c[0];",
"barrier c[0];",
"c q[0], q[1];",
"gate my_gate a { U(0, 0, 0) c; }",
)
def test_cannot_use_cregs_incorrectly(self, usage):
program = f"qreg q[2]; creg c[2]; {usage}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'c' is a classical register"):
qiskit.qasm2.loads(program)
def test_cannot_use_parameters_incorrectly(self):
program = "gate my_gate(p) q { CX p, q; }"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'p' is a parameter"):
qiskit.qasm2.loads(program)
def test_cannot_use_qubits_incorrectly(self):
program = "gate my_gate(p) q { U(q, q, q) q; }"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a gate qubit"):
qiskit.qasm2.loads(program)
@ddt.data(("h", 0), ("h", 2), ("CX", 0), ("CX", 1), ("CX", 3), ("ccx", 2), ("ccx", 4))
@ddt.unpack
def test_gates_accept_only_valid_number_qubits(self, gate, bad_count):
arguments = ", ".join(f"q[{i}]" for i in range(bad_count))
program = f'include "qelib1.inc"; qreg q[5];\n{gate} {arguments};'
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "takes .* quantum arguments?"):
qiskit.qasm2.loads(program)
@ddt.data(("U", 2), ("U", 4), ("rx", 0), ("rx", 2), ("u3", 1))
@ddt.unpack
def test_gates_accept_only_valid_number_parameters(self, gate, bad_count):
arguments = ", ".join("0" for _ in [None] * bad_count)
program = f'include "qelib1.inc"; qreg q[5];\n{gate}({arguments}) q[0];'
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "takes .* parameters?"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestGateDefinition(QiskitTestCase):
def test_no_zero_qubit(self):
program = "gate zero {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
program = "gate zero(a) {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
def test_no_zero_qubit_opaque(self):
program = "opaque zero;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
program = "opaque zero(a);"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
def test_cannot_subscript_qubit(self):
program = """
gate my_gate a {
CX a[0], a[1];
}
"""
with self.assertRaises(qiskit.qasm2.QASM2ParseError):
qiskit.qasm2.loads(program)
def test_cannot_repeat_parameters(self):
program = "gate my_gate(a, a) q {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_cannot_repeat_qubits(self):
program = "gate my_gate a, a {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_qubit_cannot_shadow_parameter(self):
program = "gate my_gate(a) a {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
@ddt.data("measure q -> c;", "reset q", "if (c == 0) U(0, 0, 0) q;", "gate my_x q {}")
def test_definition_cannot_contain_nonunitary(self, statement):
program = f"OPENQASM 2.0; creg c[5]; gate my_gate q {{ {statement} }}"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "only gate applications are valid"
):
qiskit.qasm2.loads(program)
def test_cannot_redefine_u(self):
program = "gate U(a, b, c) q {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_cannot_redefine_cx(self):
program = "gate CX a, b {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestBitResolution(QiskitTestCase):
def test_disallow_out_of_range(self):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"):
qiskit.qasm2.loads("qreg q[2]; U(0, 0, 0) q[2];")
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"):
qiskit.qasm2.loads("qreg q[2]; creg c[2]; measure q[2] -> c[0];")
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"):
qiskit.qasm2.loads("qreg q[2]; creg c[2]; measure q[0] -> c[2];")
@combine(
conditional=[True, False],
call=[
"CX q1[0], q1[0];",
"CX q1, q1[0];",
"CX q1[0], q1;",
"CX q1, q1;",
"ccx q1[0], q1[1], q1[0];",
"ccx q2, q1, q2[0];",
],
)
def test_disallow_duplicate_qubits(self, call, conditional):
program = """
include "qelib1.inc";
qreg q1[3];
qreg q2[3];
qreg q3[3];
"""
if conditional:
program += "creg cond[1]; if (cond == 0) "
program += call
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "duplicate qubit"):
qiskit.qasm2.loads(program)
@ddt.data(
(("q1[1]", "q2[2]"), "CX q1, q2"),
(("q1[1]", "q2[2]"), "CX q2, q1"),
(("q1[3]", "q2[2]"), "CX q1, q2"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q1, q2, q3"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q2, q3, q1"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q3, q1, q2"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q1, q2[0], q3"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q2[0], q3, q1"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q3, q1, q2[0]"),
)
@ddt.unpack
def test_incorrect_gate_broadcast_lengths(self, registers, call):
setup = 'include "qelib1.inc";\n' + "\n".join(f"qreg {reg};" for reg in registers)
program = f"{setup}\n{call};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
cond = "creg cond[1];\nif (cond == 0)"
program = f"{setup}\n{cond} {call};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
@ddt.data(
("qreg q[2]; creg c[2];", "q[0] -> c"),
("qreg q[2]; creg c[2];", "q -> c[0]"),
("qreg q[1]; creg c[2];", "q -> c[0]"),
("qreg q[2]; creg c[1];", "q[0] -> c"),
("qreg q[2]; creg c[3];", "q -> c"),
)
@ddt.unpack
def test_incorrect_measure_broadcast_lengths(self, setup, operands):
program = f"{setup}\nmeasure {operands};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
program = f"{setup}\ncreg cond[1];\nif (cond == 0) measure {operands};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestCustomInstructions(QiskitTestCase):
def test_cannot_use_custom_before_definition(self):
program = "qreg q[2]; my_gate q[0], q[1];"
class MyGate(Gate):
def __init__(self):
super().__init__("my_gate", 2, [])
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "cannot use .* before definition"
):
qiskit.qasm2.loads(
program,
custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 0, 2, MyGate)],
)
def test_cannot_misdefine_u(self):
program = "qreg q[1]; U(0.5, 0.25) q[0]"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "custom instruction .* mismatched"
):
qiskit.qasm2.loads(
program, custom_instructions=[qiskit.qasm2.CustomInstruction("U", 2, 1, lib.U2Gate)]
)
def test_cannot_misdefine_cx(self):
program = "qreg q[1]; CX q[0]"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "custom instruction .* mismatched"
):
qiskit.qasm2.loads(
program, custom_instructions=[qiskit.qasm2.CustomInstruction("CX", 0, 1, lib.XGate)]
)
def test_builtin_is_typechecked(self):
program = "qreg q[1]; my(0.5) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' takes 2 quantum arguments"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate, builtin=True)
],
)
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' takes 2 parameters"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 2, 1, lib.U2Gate, builtin=True)
],
)
def test_cannot_define_builtin_twice(self):
program = "gate builtin q {}; gate builtin q {};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'builtin' is already defined"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("builtin", 0, 1, lambda: Gate("builtin", 1, []))
],
)
def test_cannot_redefine_custom_u(self):
program = "gate U(a, b, c) q {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("U", 3, 1, lib.UGate, builtin=True)
],
)
def test_cannot_redefine_custom_cx(self):
program = "gate CX a, b {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("CX", 0, 2, lib.CXGate, builtin=True)
],
)
@combine(
program=["gate my(a) q {}", "opaque my(a) q;"],
builtin=[True, False],
)
def test_custom_definition_must_match_gate(self, program, builtin):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' is mismatched"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate, builtin=builtin)
],
)
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' is mismatched"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 2, 1, lib.U2Gate, builtin=builtin)
],
)
def test_cannot_have_duplicate_customs(self):
customs = [
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate),
qiskit.qasm2.CustomInstruction("x", 0, 1, lib.XGate),
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RZZGate),
]
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "duplicate custom instruction"):
qiskit.qasm2.loads("", custom_instructions=customs)
def test_qiskit_delay_float_input_wraps_exception(self):
program = "opaque delay(t) q; qreg q[1]; delay(1.5) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only accept an integer"):
qiskit.qasm2.loads(program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS)
def test_u0_float_input_wraps_exception(self):
program = "opaque u0(n) q; qreg q[1]; u0(1.1) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "must be an integer"):
qiskit.qasm2.loads(program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS)
@ddt.ddt
class TestCustomClassical(QiskitTestCase):
@ddt.data("cos", "exp", "sin", "sqrt", "tan", "ln")
def test_cannot_override_builtin(self, builtin):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"cannot override builtin"):
qiskit.qasm2.loads(
"",
custom_classical=[qiskit.qasm2.CustomClassical(builtin, 1, math.exp)],
)
def test_duplicate_names_disallowed(self):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"duplicate custom classical"):
qiskit.qasm2.loads(
"",
custom_classical=[
qiskit.qasm2.CustomClassical("f", 1, math.exp),
qiskit.qasm2.CustomClassical("f", 1, math.exp),
],
)
def test_cannot_shadow_custom_instruction(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"custom classical.*naming clash"
):
qiskit.qasm2.loads(
"",
custom_instructions=[
qiskit.qasm2.CustomInstruction("f", 0, 1, lib.RXGate, builtin=True)
],
custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)],
)
def test_cannot_shadow_builtin_instruction(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"custom classical.*cannot shadow"
):
qiskit.qasm2.loads(
"",
custom_classical=[qiskit.qasm2.CustomClassical("U", 1, math.exp)],
)
def test_cannot_shadow_with_gate_definition(self):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"'f' is already defined"):
qiskit.qasm2.loads(
"gate f q {}",
custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)],
)
@ddt.data("qreg", "creg")
def test_cannot_shadow_with_register_definition(self, regtype):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"'f' is already defined"):
qiskit.qasm2.loads(
f"{regtype} f[2];",
custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)],
)
@ddt.data((0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1))
@ddt.unpack
def test_mismatched_argument_count(self, n_good, n_bad):
arg_string = ", ".join(["0" for _ in [None] * n_bad])
program = f"""
qreg q[1];
U(f({arg_string}), 0, 0) q[0];
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"custom function argument-count mismatch"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", n_good, lambda *_: 0)]
)
def test_output_type_error_is_caught(self):
program = """
qreg q[1];
U(f(), 0, 0) q[0];
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"user.*returned non-float"):
qiskit.qasm2.loads(
program,
custom_classical=[qiskit.qasm2.CustomClassical("f", 0, lambda: "not a float")],
)
def test_inner_exception_is_wrapped(self):
inner_exception = Exception("custom exception")
def raises():
raise inner_exception
program = """
qreg q[1];
U(raises(), 0, 0) q[0];
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "caught exception when constant folding"
) as excinfo:
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("raises", 0, raises)]
)
assert excinfo.exception.__cause__ is inner_exception
def test_cannot_be_used_as_gate(self):
program = """
qreg q[1];
f(0) q[0];
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)]
)
def test_cannot_be_used_as_qarg(self):
program = """
U(0, 0, 0) f;
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)]
)
def test_cannot_be_used_as_carg(self):
program = """
qreg q[1];
measure q[0] -> f;
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)]
)
@ddt.ddt
class TestStrict(QiskitTestCase):
@ddt.data(
"gate my_gate(p0, p1,) q0, q1 {}",
"gate my_gate(p0, p1) q0, q1, {}",
"opaque my_gate(p0, p1,) q0, q1;",
"opaque my_gate(p0, p1) q0, q1,;",
'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125,) q[0], q[1];',
'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125) q[0], q[1],;',
"qreg q[2]; barrier q[0], q[1],;",
'include "qelib1.inc"; qreg q[1]; rx(sin(pi,)) q[0];',
)
def test_trailing_comma(self, program):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*trailing comma"):
qiskit.qasm2.loads("OPENQASM 2.0;\n" + program, strict=True)
def test_trailing_semicolon_after_gate(self):
program = "OPENQASM 2.0; gate my_gate q {};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*extra semicolon"):
qiskit.qasm2.loads(program, strict=True)
def test_empty_statement(self):
program = "OPENQASM 2.0; ;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*empty statement"):
qiskit.qasm2.loads(program, strict=True)
def test_required_version_regular(self):
program = "qreg q[1];"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] the first statement"
):
qiskit.qasm2.loads(program, strict=True)
def test_required_version_empty(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] .*needed a version statement"
):
qiskit.qasm2.loads("", strict=True)
def test_barrier_requires_args(self):
program = "OPENQASM 2.0; qreg q[2]; barrier;"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] barrier statements must have at least one"
):
qiskit.qasm2.loads(program, strict=True)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test registerless QuantumCircuit and Gates on wires"""
import numpy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit, AncillaQubit
from qiskit.circuit.exceptions import CircuitError
from qiskit.test import QiskitTestCase
class TestRegisterlessCircuit(QiskitTestCase):
"""Test registerless QuantumCircuit."""
def test_circuit_constructor_qwires(self):
"""Create a QuantumCircuit directly with quantum wires"""
circuit = QuantumCircuit(2)
expected = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(circuit, expected)
def test_circuit_constructor_wires_wrong(self):
"""Create a registerless QuantumCircuit wrongly"""
self.assertRaises(CircuitError, QuantumCircuit, 1, 2, 3) # QuantumCircuit(1, 2, 3)
def test_circuit_constructor_wires_wrong_mix(self):
"""Create an almost-registerless QuantumCircuit"""
# QuantumCircuit(1, ClassicalRegister(2))
self.assertRaises(CircuitError, QuantumCircuit, 1, ClassicalRegister(2))
class TestAddingBitsWithoutRegisters(QiskitTestCase):
"""Test adding Bit instances outside of Registers."""
def test_circuit_constructor_on_bits(self):
"""Verify we can add bits directly to a circuit."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit()]
ancillas = [AncillaQubit(), AncillaQubit()]
qc = QuantumCircuit(qubits, clbits, ancillas)
self.assertEqual(qc.qubits, qubits + ancillas)
self.assertEqual(qc.clbits, clbits)
self.assertEqual(qc.ancillas, ancillas)
self.assertEqual(qc.qregs, [])
self.assertEqual(qc.cregs, [])
def test_circuit_constructor_on_invalid_bits(self):
"""Verify we raise if passed not a Bit."""
with self.assertRaisesRegex(CircuitError, "Expected an instance of"):
_ = QuantumCircuit([3.14])
def test_raise_if_bits_already_present(self):
"""Verify we raise when attempting to add a Bit already in the circuit."""
qubits = [Qubit()]
with self.assertRaisesRegex(CircuitError, "bits found already"):
_ = QuantumCircuit(qubits, qubits)
qc = QuantumCircuit(qubits)
with self.assertRaisesRegex(CircuitError, "bits found already"):
qc.add_bits(qubits)
qr = QuantumRegister(1, "qr")
qc = QuantumCircuit(qr)
with self.assertRaisesRegex(CircuitError, "bits found already"):
qc.add_bits(qr[:])
def test_addding_individual_bit(self):
"""Verify we can add a single bit to a circuit."""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
new_bit = Qubit()
qc.add_bits([new_bit])
self.assertEqual(qc.qubits, list(qr) + [new_bit])
self.assertEqual(qc.qregs, [qr])
def test_inserted_ancilla_bits_are_added_to_qubits(self):
"""Verify AncillaQubits added via .add_bits are added to .qubits."""
anc = AncillaQubit()
qb = Qubit()
qc = QuantumCircuit()
qc.add_bits([anc, qb])
self.assertEqual(qc.qubits, [anc, qb])
class TestGatesOnWires(QiskitTestCase):
"""Test gates on wires."""
def test_circuit_single_wire_h(self):
"""Test circuit on wire (H gate)."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
circuit.h(1)
expected = QuantumCircuit(qreg)
expected.h(qreg[1])
self.assertEqual(circuit, expected)
def test_circuit_two_wire_cx(self):
"""Test circuit two wires (CX gate)."""
qreg = QuantumRegister(2)
expected = QuantumCircuit(qreg)
expected.cx(qreg[0], qreg[1])
circuit = QuantumCircuit(qreg)
circuit.cx(0, 1)
self.assertEqual(circuit, expected)
def test_circuit_single_wire_measure(self):
"""Test circuit on wire (measure gate)."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
circuit.measure(1, 1)
expected = QuantumCircuit(qreg, creg)
expected.measure(qreg[1], creg[1])
self.assertEqual(circuit, expected)
def test_circuit_multi_qregs_h(self):
"""Test circuit multi qregs and wires (H gate)."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
circuit = QuantumCircuit(qreg0, qreg1)
circuit.h(0)
circuit.h(2)
expected = QuantumCircuit(qreg0, qreg1)
expected.h(qreg0[0])
expected.h(qreg1[0])
self.assertEqual(circuit, expected)
def test_circuit_multi_qreg_cregs_measure(self):
"""Test circuit multi qregs/cregs and wires (measure)."""
qreg0 = QuantumRegister(2)
creg0 = ClassicalRegister(2)
qreg1 = QuantumRegister(2)
creg1 = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circuit.measure(0, 2)
circuit.measure(2, 1)
expected = QuantumCircuit(qreg0, qreg1, creg0, creg1)
expected.measure(qreg0[0], creg1[0])
expected.measure(qreg1[0], creg0[1])
self.assertEqual(circuit, expected)
def test_circuit_barrier(self):
"""Test barrier on wires."""
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.barrier(0)
circuit.barrier(2)
expected = QuantumCircuit(qreg01, qreg23)
expected.barrier(qreg01[0])
expected.barrier(qreg23[0])
self.assertEqual(circuit, expected)
def test_circuit_conditional(self):
"""Test conditional on wires."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(4)
circuit = QuantumCircuit(qreg, creg)
circuit.h(0).c_if(creg, 3)
expected = QuantumCircuit(qreg, creg)
expected.h(qreg[0]).c_if(creg, 3)
self.assertEqual(circuit, expected)
def test_circuit_qwire_out_of_range(self):
"""Fail if quantum wire is out of range."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, 99) # circuit.h(99)
def test_circuit_cwire_out_of_range(self):
"""Fail if classical wire is out of range."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
self.assertRaises(CircuitError, circuit.measure, 1, 99) # circuit.measure(1, 99)
def test_circuit_initialize(self):
"""Test initialize on wires."""
init_vector = [0.5, 0.5, 0.5, 0.5]
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.initialize(init_vector, [0, 2])
expected = QuantumCircuit(qreg01, qreg23)
expected.initialize(init_vector, [qreg01[0], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_initialize_single_qubit(self):
"""Test initialize on single qubit."""
init_vector = [numpy.sqrt(0.5), numpy.sqrt(0.5)]
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
circuit.initialize(init_vector, qreg[0])
expected = QuantumCircuit(qreg)
expected.initialize(init_vector, [qreg[0]])
self.assertEqual(circuit, expected)
def test_mixed_register_and_registerless_indexing(self):
"""Test indexing if circuit contains bits in and out of registers."""
bits = [Qubit(), Qubit()]
qreg = QuantumRegister(3, "q")
circuit = QuantumCircuit(bits, qreg)
for i in range(len(circuit.qubits)):
circuit.rz(i, i)
expected_qubit_order = bits + qreg[:]
expected_circuit = QuantumCircuit(bits, qreg)
for i in range(len(expected_circuit.qubits)):
expected_circuit.rz(i, expected_qubit_order[i])
self.assertEqual(circuit.data, expected_circuit.data)
class TestGatesOnWireRange(QiskitTestCase):
"""Test gates on wire range."""
def test_wire_range(self):
"""Test gate wire range"""
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(range(0, 2))
expected = QuantumCircuit(qreg)
expected.h(qreg[0:2])
self.assertEqual(circuit, expected)
def test_circuit_multi_qregs_h(self):
"""Test circuit multi qregs in range of wires (H gate)."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
circuit = QuantumCircuit(qreg0, qreg1)
circuit.h(range(0, 3))
expected = QuantumCircuit(qreg0, qreg1)
expected.h(qreg0[0])
expected.h(qreg0[1])
expected.h(qreg1[0])
self.assertEqual(circuit, expected)
def test_circuit_multi_qreg_cregs_measure(self):
"""Test circuit multi qregs in range of wires (measure)."""
qreg0 = QuantumRegister(2)
creg0 = ClassicalRegister(2)
qreg1 = QuantumRegister(2)
creg1 = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circuit.measure(range(1, 3), range(0, 4, 2))
expected = QuantumCircuit(qreg0, qreg1, creg0, creg1)
expected.measure(qreg0[1], creg0[0])
expected.measure(qreg1[0], creg1[0])
self.assertEqual(circuit, expected)
def test_circuit_barrier(self):
"""Test barrier on range of wires with multi regs."""
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.barrier(range(0, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.barrier(qreg01[0], qreg01[1], qreg23[0])
self.assertEqual(circuit, expected)
def test_circuit_initialize(self):
"""Test initialize on wires."""
init_vector = [0.5, 0.5, 0.5, 0.5]
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.initialize(init_vector, range(1, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.initialize(init_vector, [qreg01[1], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_conditional(self):
"""Test conditional on wires."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg)
circuit.h(range(1, 3)).c_if(creg, 3)
expected = QuantumCircuit(qreg0, qreg1, creg)
expected.h(qreg0[1]).c_if(creg, 3)
expected.h(qreg1[0]).c_if(creg, 3)
self.assertEqual(circuit, expected)
def test_circuit_qwire_out_of_range(self):
"""Fail if quantum wire is out of range."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, range(9, 99)) # circuit.h(range(9,99))
def test_circuit_cwire_out_of_range(self):
"""Fail if classical wire is out of range."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
# circuit.measure(1, range(9,99))
self.assertRaises(CircuitError, circuit.measure, 1, range(9, 99))
class TestGatesOnWireSlice(QiskitTestCase):
"""Test gates on wire slice."""
def test_wire_slice(self):
"""Test gate wire slice"""
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(slice(0, 2))
expected = QuantumCircuit(qreg)
expected.h(qreg[0:2])
self.assertEqual(circuit, expected)
def test_wire_list(self):
"""Test gate wire list of integers"""
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h([0, 1])
expected = QuantumCircuit(qreg)
expected.h(qreg[0:2])
self.assertEqual(circuit, expected)
def test_wire_np_int(self):
"""Test gate wire with numpy int"""
numpy_int = numpy.dtype("int").type(2)
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(numpy_int)
expected = QuantumCircuit(qreg)
expected.h(qreg[2])
self.assertEqual(circuit, expected)
def test_wire_np_1d_array(self):
"""Test gate wire with numpy array (one-dimensional)"""
numpy_arr = numpy.array([0, 1])
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(numpy_arr)
expected = QuantumCircuit(qreg)
expected.h(qreg[0])
expected.h(qreg[1])
self.assertEqual(circuit, expected)
def test_circuit_multi_qregs_h(self):
"""Test circuit multi qregs in slices of wires (H gate)."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
circuit = QuantumCircuit(qreg0, qreg1)
circuit.h(slice(0, 3))
expected = QuantumCircuit(qreg0, qreg1)
expected.h(qreg0[0])
expected.h(qreg0[1])
expected.h(qreg1[0])
self.assertEqual(circuit, expected)
def test_circuit_multi_qreg_cregs_measure(self):
"""Test circuit multi qregs in slices of wires (measure)."""
qreg0 = QuantumRegister(2)
creg0 = ClassicalRegister(2)
qreg1 = QuantumRegister(2)
creg1 = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circuit.measure(slice(1, 3), slice(0, 4, 2))
expected = QuantumCircuit(qreg0, qreg1, creg0, creg1)
expected.measure(qreg0[1], creg0[0])
expected.measure(qreg1[0], creg1[0])
self.assertEqual(circuit, expected)
def test_circuit_barrier(self):
"""Test barrier on slice of wires with multi regs."""
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.barrier(slice(0, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.barrier([qreg01[0], qreg01[1], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_initialize(self):
"""Test initialize on wires."""
init_vector = [0.5, 0.5, 0.5, 0.5]
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.initialize(init_vector, slice(1, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.initialize(init_vector, [qreg01[1], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_conditional(self):
"""Test conditional on wires."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg)
circuit.h(slice(1, 3)).c_if(creg, 3)
expected = QuantumCircuit(qreg0, qreg1, creg)
expected.h(qreg0[1]).c_if(creg, 3)
expected.h(qreg1[0]).c_if(creg, 3)
self.assertEqual(circuit, expected)
def test_circuit_qwire_out_of_range(self):
"""Fail if quantum wire is out of range."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, slice(9, 99)) # circuit.h(slice(9,99))
def test_circuit_cwire_out_of_range(self):
"""Fail if classical wire is out of range."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
# circuit.measure(1, slice(9,99))
self.assertRaises(CircuitError, circuit.measure, 1, slice(9, 99))
def test_wire_np_2d_array(self):
"""Test gate wire with numpy array (two-dimensional). Raises."""
numpy_arr = numpy.array([[0, 1], [2, 3]])
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, numpy_arr) # circuit.h(numpy_arr)
class TestBitConditional(QiskitTestCase):
"""Test gates with single bit conditionals."""
def test_bit_conditional_single_gate(self):
"""Test circuit with a single gate conditioned on a bit."""
qreg = QuantumRegister(1)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
circuit.h(0).c_if(0, True)
expected = QuantumCircuit(qreg, creg)
expected.h(qreg[0]).c_if(creg[0], True)
self.assertEqual(circuit, expected)
def test_bit_conditional_multiple_gates(self):
"""Test circuit with multiple gates conditioned on individual bits."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
creg1 = ClassicalRegister(1)
circuit = QuantumCircuit(qreg, creg, creg1)
circuit.h(0).c_if(0, True)
circuit.h(1).c_if(1, False)
circuit.cx(1, 0).c_if(2, True)
expected = QuantumCircuit(qreg, creg, creg1)
expected.h(qreg[0]).c_if(creg[0], True)
expected.h(qreg[1]).c_if(creg[1], False)
expected.cx(qreg[1], qreg[0]).c_if(creg1[0], True)
self.assertEqual(circuit, expected)
|
https://github.com/108mk/Quantum_Algorithms_and_Qiskit
|
108mk
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.monitor import job_monitor
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
nQubits = 4 # number of physical qubits
a = 11 #DECIMAL----the hidden integer whose bitstring is 1011 in BINARY
# make sure that a can be represented with nQubits
a = a % 2**(nQubits)
# Creating registers
# qubits for querying the oracle and finding the hidden integer
qr = QuantumRegister(nQubits)
# for recording the measurement on qr
cr = ClassicalRegister(nQubits)
circuitName = "BernsteinVazirani"
bvCircuit = QuantumCircuit(qr, cr)
# Apply Hadamard gates before querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Apply barrier so that it is not optimized by the compiler
bvCircuit.barrier()
# Apply the inner-product oracle
for i in range(nQubits):
if (a & (1 << i)):
bvCircuit.z(qr[i])
else:
bvCircuit.id(qr[i])
# Apply barrier
bvCircuit.barrier()
#Apply Hadamard gates after querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Measurement
bvCircuit.barrier(qr)
bvCircuit.measure(qr, cr)
bvCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
results = execute(bvCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
from qiskit import IBMQ
IBMQ.save_account('87e81a3de8a45f8a9ee4b2ccdb65b7b1d60dceec51f8541ac31f74fcec029dc63ec26a70a3d6ee88184bfe4719aa82eed0eca8a396e364c28b727ea8f42c4ec3', overwrite=True)
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider.backends()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibm_oslo')
shots = 1000
bvCompiled = transpile(bvCircuit, backend=backend, optimization_level=1)
job_exp = execute(bvCircuit, backend=backend, shots=shots)
job_monitor(job_exp)
results = job_exp.result()
answer = results.get_counts(bvCircuit)
threshold = int(0.01 * shots) #the threshold of plotting significant measurements
filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} #filter the answer for better view of plots
removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) #number of counts removed
filteredAnswer['other_bitstrings'] = removedCounts #the removed counts is assigned to a new index
plot_histogram(filteredAnswer)
print(filteredAnswer)
#-----unable to run on actual IBMQ device-----
|
https://github.com/qiskit-community/qiskit-sat-synthesis
|
qiskit-community
|
%load_ext autoreload
%autoreload 2
# imports
from qiskit.circuit import QuantumCircuit
from qiskit.quantum_info import Clifford, Operator, StabilizerState, Statevector
from qiskit.transpiler import CouplingMap
from synthesis.sat_problem_clifford import SatProblemClifford
from synthesis.utils import line_coupling_map
from synthesis.synthesize import synthesize_optimal
from synthesis.synthesize_clifford import synthesize_clifford_depth2q
# naive preparation of the state of interest (does not adhere to LNN connectivity)
nq = 13 # number of qubits
k = 3 # number of consequtive ones (0: GHZ, 1: checkerboard, n/2: hartree-fock)
ones = [i for m in range(1, int(nq / k), 2) for i in range(m * k, (m + 1) * k)]
qc = QuantumCircuit(nq)
qc.h(nq - 1)
for target in ones:
qc.cx(nq - 1, target)
display(Statevector(qc).draw("latex"))
qc.draw("mpl")
# prepackaged clifford synthesis routine
cliff = Clifford(qc)
res = synthesize_clifford_depth2q(
cliff, coupling_map=line_coupling_map(cliff.num_qubits), state_preparation_mode=True
)
res.circuit.draw("mpl", fold=-1)
# Create a custom problem: we want to use a single H-gate in the first layer and only CX-gates after that
def create_problem_custom(cliff, depth):
nq = cliff.num_qubits
sat_problem = SatProblemClifford(nq, verbosity=1)
sat_problem.set_init_matrix_to_identity(nq)
sat_problem.set_final_clifford(cliff)
sat_problem.set_state_preparation_mode(True)
sat_problem.add_layer(gates=["H"], coupling_maps=[])
for _ in range(depth):
sat_problem.add_layer(gates=["CX"], coupling_maps=[line_coupling_map(nq)])
return sat_problem
def synthesize_clifford_custom(cliff):
res = synthesize_optimal(
target_obj=cliff, create_sat_problem_fn=create_problem_custom, verbosity=1
)
return res.circuit
cliff = Clifford(qc)
circuit = synthesize_clifford_custom(cliff)
circuit.draw("mpl", fold=-1)
# let's say we also want at most 2 unique layers
def create_problem_custom_u(cliff, depth):
nq = cliff.num_qubits
sat_problem = SatProblemClifford(nq, verbosity=1)
sat_problem.set_init_matrix_to_identity(nq)
sat_problem.set_final_clifford(cliff)
sat_problem.set_state_preparation_mode(True)
sat_problem.add_layer(gates=["H"], coupling_maps=[])
two_qubit_layers = []
for _ in range(depth):
layer = sat_problem.add_layer(
gates=["CX"], coupling_maps=[line_coupling_map(nq)]
)
two_qubit_layers.append(layer)
sat_problem.add_max_unique_layers_constraint(two_qubit_layers, 2)
return sat_problem
def synthesize_clifford_custom_u(cliff):
res = synthesize_optimal(
target_obj=cliff, create_sat_problem_fn=create_problem_custom_u, verbosity=1
)
return res.circuit
circuit = synthesize_clifford_custom_u(cliff)
circuit.draw("mpl", fold=-1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
pw_approximation._build()
qc = QuantumCircuit(pw_approximation.num_qubits)
qc.h(list(range(num_state_qubits)))
qc.append(pw_approximation.to_instruction(), qc.qubits)
qc.draw(output='mpl')
|
https://github.com/chunfuchen/qiskit-chemistry
|
chunfuchen
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Test of Symmetry UCCSD processing.
"""
import itertools
from test.common import QiskitChemistryTestCase
from qiskit import BasicAer
from qiskit.aqua import QuantumInstance, Operator
from qiskit.aqua.algorithms.adaptive import VQE
from qiskit.aqua.components.optimizers import SLSQP
from qiskit.chemistry import QiskitChemistryError
from qiskit.chemistry.core import Hamiltonian, TransformationType, QubitMappingType
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock
# from qiskit.chemistry import set_qiskit_chemistry_logging
# import logging
class TestSymmetries(QiskitChemistryTestCase):
"""Test for symmetry processing."""
def setUp(self):
super().setUp()
try:
driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6',
unit=UnitsType.ANGSTROM,
charge=0,
spin=0,
basis='sto3g')
except QiskitChemistryError:
self.skipTest('PYSCF driver does not appear to be installed')
self.qmolecule = driver.run()
self.core = Hamiltonian(transformation=TransformationType.FULL,
qubit_mapping=QubitMappingType.PARITY,
two_qubit_reduction=True,
freeze_core=True,
orbital_reduction=[])
self.qubit_op, _ = self.core.run(self.qmolecule)
self.symmetries, self.sq_paulis, self.cliffords, self.sq_list = self.qubit_op.find_Z2_symmetries()
self.reference_energy = -7.882096489442
def test_symmetries(self):
labels = [symm.to_label() for symm in self.symmetries]
self.assertSequenceEqual(labels, ['ZIZIZIZI', 'ZZIIZZII'])
def test_sq_paulis(self):
labels = [sq.to_label() for sq in self.sq_paulis]
self.assertSequenceEqual(labels, ['IIIIIIXI', 'IIIIIXII'])
def test_cliffords(self):
self.assertEqual(2, len(self.cliffords))
def test_sq_list(self):
self.assertSequenceEqual(self.sq_list, [1, 2])
def test_tapered_op(self):
# set_qiskit_chemistry_logging(logging.DEBUG)
tapered_ops = []
for coeff in itertools.product([1, -1], repeat=len(self.sq_list)):
tapered_op = Operator.qubit_tapering(self.qubit_op, self.cliffords, self.sq_list, list(coeff))
tapered_ops.append((list(coeff), tapered_op))
smallest_idx = 0 # Prior knowledge of which tapered_op has ground state
the_tapered_op = tapered_ops[smallest_idx][1]
the_coeff = tapered_ops[smallest_idx][0]
optimizer = SLSQP(maxiter=1000)
init_state = HartreeFock(num_qubits=the_tapered_op.num_qubits,
num_orbitals=self.core._molecule_info['num_orbitals'],
qubit_mapping=self.core._qubit_mapping,
two_qubit_reduction=self.core._two_qubit_reduction,
num_particles=self.core._molecule_info['num_particles'],
sq_list=self.sq_list)
var_form = UCCSD(num_qubits=the_tapered_op.num_qubits, depth=1,
num_orbitals=self.core._molecule_info['num_orbitals'],
num_particles=self.core._molecule_info['num_particles'],
active_occupied=None, active_unoccupied=None,
initial_state=init_state,
qubit_mapping=self.core._qubit_mapping,
two_qubit_reduction=self.core._two_qubit_reduction,
num_time_slices=1,
cliffords=self.cliffords, sq_list=self.sq_list,
tapering_values=the_coeff, symmetries=self.symmetries)
algo = VQE(the_tapered_op, var_form, optimizer, 'matrix')
backend = BasicAer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend=backend)
algo_result = algo.run(quantum_instance)
lines, result = self.core.process_algorithm_result(algo_result)
self.assertAlmostEqual(result['energy'], self.reference_energy, places=6)
|
https://github.com/JohnBurke4/qaoa_testing_framework
|
JohnBurke4
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Quantum Shannon Decomposition.
Method is described in arXiv:quant-ph/0406176.
"""
from __future__ import annotations
import scipy
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info.synthesis import two_qubit_decompose, one_qubit_decompose
from qiskit.quantum_info.operators.predicates import is_hermitian_matrix
from qiskit.circuit.library.generalized_gates.uc_pauli_rot import UCPauliRotGate, _EPS
from qiskit.circuit.library.generalized_gates.ucry import UCRYGate
from qiskit.circuit.library.generalized_gates.ucrz import UCRZGate
def qs_decomposition(
mat: np.ndarray,
opt_a1: bool = True,
opt_a2: bool = True,
decomposer_1q=None,
decomposer_2q=None,
*,
_depth=0,
):
"""
Decomposes unitary matrix into one and two qubit gates using Quantum Shannon Decomposition.
┌───┐ ┌───┐ ┌───┐ ┌───┐
─┤ ├─ ───────┤ Rz├─────┤ Ry├─────┤ Rz├─────
│ │ ≃ ┌───┐└─┬─┘┌───┐└─┬─┘┌───┐└─┬─┘┌───┐
/─┤ ├─ /─┤ ├──□──┤ ├──□──┤ ├──□──┤ ├
└───┘ └───┘ └───┘ └───┘ └───┘
The number of CX gates generated with the decomposition without optimizations is,
.. math::
\frac{9}{16} 4^n - frac{3}{2} 2^n
If opt_a1 = True, the default, the CX count is reduced by,
.. math::
\frac{1}{3} 4^{n - 2} - 1.
If opt_a2 = True, the default, the CX count is reduced by,
.. math::
4^{n-2} - 1.
This decomposition is described in arXiv:quant-ph/0406176.
Arguments:
mat (ndarray): unitary matrix to decompose
opt_a1 (bool): whether to try optimization A.1 from Shende. This should eliminate 1 cnot
per call. If True CZ gates are left in the output. If desired these can be further decomposed
to CX.
opt_a2 (bool): whether to try optimization A.2 from Shende. This decomposes two qubit
unitaries into a diagonal gate and a two cx unitary and reduces overal cx count by
4^(n-2) - 1.
decomposer_1q (None or Object): optional 1Q decomposer. If None, uses
:class:`~qiskit.quantum_info.synthesis.one_qubit_decomposer.OneQubitEulerDecomser`
decomposer_2q (None or Object): optional 2Q decomposer. If None, uses
:class:`~qiskit.quantum_info.synthesis.two_qubit_decomposer.two_qubit_cnot_decompose
Return:
QuantumCircuit: Decomposed quantum circuit.
"""
# _depth (int): Internal use parameter to track recursion depth.
dim = mat.shape[0]
print(dim)
nqubits = int(np.log2(dim))
if np.allclose(np.identity(dim), mat):
return QuantumCircuit(nqubits)
if dim == 2:
if decomposer_1q is None:
decomposer_1q = one_qubit_decompose.OneQubitEulerDecomposer()
circ = decomposer_1q(mat)
elif dim == 4:
if decomposer_2q is None:
if opt_a2 and _depth > 0:
from qiskit.circuit.library import UnitaryGate # pylint: disable=cyclic-import
def decomp_2q(mat):
ugate = UnitaryGate(mat)
qc = QuantumCircuit(2, name="qsd2q")
qc.append(ugate, [0, 1])
return qc
decomposer_2q = decomp_2q
else:
decomposer_2q = two_qubit_decompose.two_qubit_cnot_decompose
circ = decomposer_2q(mat)
else:
qr = QuantumRegister(nqubits)
circ = QuantumCircuit(qr)
dim_o2 = dim // 2
# perform cosine-sine decomposition
(u1, u2), vtheta, (v1h, v2h) = scipy.linalg.cossin(mat, separate=True, p=dim_o2, q=dim_o2)
# left circ
left_circ = _demultiplex(v1h, v2h, opt_a1=opt_a1, opt_a2=opt_a2, _depth=_depth)
circ.append(left_circ.to_instruction(), qr)
# middle circ
if opt_a1:
nangles = len(vtheta)
half_size = nangles // 2
# get UCG in terms of CZ
circ_cz = _get_ucry_cz(nqubits, (2 * vtheta).tolist())
circ.append(circ_cz.to_instruction(), range(nqubits))
# merge final cz with right-side generic multiplexer
u2[:, half_size:] = np.negative(u2[:, half_size:])
else:
ucry = UCRYGate((2 * vtheta).tolist())
circ.append(ucry, [qr[-1]] + qr[:-1])
# right circ
right_circ = _demultiplex(u1, u2, opt_a1=opt_a1, opt_a2=opt_a2, _depth=_depth)
circ.append(right_circ.to_instruction(), qr)
if opt_a2 and _depth == 0 and dim > 4:
return _apply_a2(circ)
return circ
def _demultiplex(um0, um1, opt_a1=False, opt_a2=False, *, _depth=0):
"""Decompose a generic multiplexer.
────□────
┌──┴──┐
/─┤ ├─
└─────┘
represented by the block diagonal matrix
┏ ┓
┃ um0 ┃
┃ um1 ┃
┗ ┛
to
┌───┐
───────┤ Rz├──────
┌───┐└─┬─┘┌───┐
/─┤ w ├──□──┤ v ├─
└───┘ └───┘
where v and w are general unitaries determined from decomposition.
Args:
um0 (ndarray): applied if MSB is 0
um1 (ndarray): applied if MSB is 1
opt_a1 (bool): whether to try optimization A.1 from Shende. This should elliminate 1 cnot
per call. If True CZ gates are left in the output. If desired these can be further decomposed
opt_a2 (bool): whether to try optimization A.2 from Shende. This decomposes two qubit
unitaries into a diagonal gate and a two cx unitary and reduces overal cx count by
4^(n-2) - 1.
_depth (int): This is an internal variable to track the recursion depth.
Returns:
QuantumCircuit: decomposed circuit
"""
dim = um0.shape[0] + um1.shape[0] # these should be same dimension
nqubits = int(np.log2(dim))
um0um1 = um0 @ um1.T.conjugate()
if is_hermitian_matrix(um0um1):
eigvals, vmat = scipy.linalg.eigh(um0um1)
else:
evals, vmat = scipy.linalg.schur(um0um1, output="complex")
eigvals = evals.diagonal()
dvals = np.emath.sqrt(eigvals)
dmat = np.diag(dvals)
wmat = dmat @ vmat.T.conjugate() @ um1
circ = QuantumCircuit(nqubits)
# left gate
left_gate = qs_decomposition(
wmat, opt_a1=opt_a1, opt_a2=opt_a2, _depth=_depth + 1
).to_instruction()
circ.append(left_gate, range(nqubits - 1))
# multiplexed Rz
angles = 2 * np.angle(np.conj(dvals))
ucrz = UCRZGate(angles.tolist())
circ.append(ucrz, [nqubits - 1] + list(range(nqubits - 1)))
# right gate
right_gate = qs_decomposition(
vmat, opt_a1=opt_a1, opt_a2=opt_a2, _depth=_depth + 1
).to_instruction()
circ.append(right_gate, range(nqubits - 1))
return circ
def _get_ucry_cz(nqubits, angles):
"""
Get uniformly controlled Ry gate in in CZ-Ry as in UCPauliRotGate.
"""
nangles = len(angles)
qc = QuantumCircuit(nqubits)
q_controls = qc.qubits[:-1]
q_target = qc.qubits[-1]
if not q_controls:
if np.abs(angles[0]) > _EPS:
qc.ry(angles[0], q_target)
else:
angles = angles.copy()
UCPauliRotGate._dec_uc_rotations(angles, 0, len(angles), False)
for (i, angle) in enumerate(angles):
if np.abs(angle) > _EPS:
qc.ry(angle, q_target)
if not i == len(angles) - 1:
binary_rep = np.binary_repr(i + 1)
q_contr_index = len(binary_rep) - len(binary_rep.rstrip("0"))
else:
# Handle special case:
q_contr_index = len(q_controls) - 1
# leave off last CZ for merging with adjacent UCG
if i < nangles - 1:
qc.cz(q_controls[q_contr_index], q_target)
return qc
def _apply_a2(circ):
from qiskit import transpile
from qiskit.quantum_info import Operator
from qiskit.circuit.library.generalized_gates import UnitaryGate
decomposer = two_qubit_decompose.TwoQubitDecomposeUpToDiagonal()
ccirc = transpile(circ, basis_gates=["u", "cx", "qsd2q"], optimization_level=0)
ind2q = []
# collect 2q instrs
for i, instruction in enumerate(ccirc.data):
if instruction.operation.name == "qsd2q":
ind2q.append(i)
if len(ind2q) == 0:
return ccirc
elif len(ind2q) == 1:
# No neighbors to merge diagonal into; revert name
ccirc.data[ind2q[0]].operation.name = "Unitary"
return ccirc
# rolling over diagonals
ind2 = None # lint
for ind1, ind2 in zip(ind2q[0:-1:], ind2q[1::]):
# get neigboring 2q gates separated by controls
instr1 = ccirc.data[ind1]
mat1 = Operator(instr1.operation).data
instr2 = ccirc.data[ind2]
mat2 = Operator(instr2.operation).data
# rollover
dmat, qc2cx = decomposer(mat1)
ccirc.data[ind1] = instr1.replace(operation=qc2cx.to_gate())
mat2 = mat2 @ dmat
ccirc.data[ind2] = instr2.replace(UnitaryGate(mat2))
qc3 = two_qubit_decompose.two_qubit_cnot_decompose(mat2)
ccirc.data[ind2] = ccirc.data[ind2].replace(operation=qc3.to_gate())
return ccirc
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# Testing Circuits
import warnings
warnings.simplefilter("ignore")
%run "mpl/circuit/test_circuit_matplotlib_drawer.py"
# Testing Graphs
%run "mpl/graph/test_graph_matplotlib_drawer.py"
%run -i "results.py"
RESULTS_CIRCUIT
RESULTS_GRAPH
|
https://github.com/bibscore/qiskit_kindergarten
|
bibscore
|
import os
import glob
import numpy as np
from numpy import pi
from qiskit import *
from qiskit.tools.visualization import *
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.providers.aer import Aer
import kaleidoscope.qiskit
from kaleidoscope import qsphere
import matplotlib.pyplot as plt
%matplotlib inline
qreg_q = QuantumRegister(1, 'q')
creg_c = ClassicalRegister(1, 'c')
circuits = []
for i in range(0, 6):
circuits.append(QuantumCircuit(qreg_q, creg_c))
inits = []
circuits[0].reset(qreg_q[0])
inits.append(circuits[0].copy())
circuits[0].x(qreg_q[0])
circuits[0].measure(qreg_q[0], creg_c[0])
circuits[0].draw(output="mpl")
circuits[1].x(qreg_q[0])
inits.append(circuits[1].copy())
circuits[1].z(qreg_q[0])
circuits[1].measure(qreg_q[0], creg_c[0])
circuits[1].draw(output='mpl')
circuits[2].x(qreg_q[0])
inits.append(circuits[2].copy())
circuits[2].s(qreg_q[0])
circuits[2].measure(qreg_q[0], creg_c[0])
circuits[2].draw(output='mpl')
circuits[3].x(qreg_q[0])
inits.append(circuits[3].copy())
circuits[3].t(qreg_q[0])
circuits[3].measure(qreg_q[0], creg_c[0])
circuits[3].draw(output='mpl')
circuits[4].x(qreg_q[0])
inits.append(circuits[4].copy())
circuits[4].y(qreg_q[0])
circuits[4].measure(qreg_q[0], creg_c[0])
circuits[4].draw(output='mpl')
circuits[5].x(qreg_q[0])
inits.append(circuits[5].copy())
circuits[5].p(np.pi/2, qreg_q[0])
circuits[5].measure(qreg_q[0], creg_c[0])
circuits[5].draw(output='mpl')
simulator_aer = Aer.get_backend("aer_simulator")
statevector_init = []
statevector_circ = []
for i in range(0, 6):
inits[i].save_statevector()
statevector_init.append(simulator_aer.run(inits[i]).result().get_statevector())
circuits[i].save_statevector()
statevector_circ.append(simulator_aer.run(circuits[i]).result().get_statevector())
archive_path = os.path.abspath('')
os.chdir(archive_path)
for index in range(0, len(statevector_init)):
initial_figure = qsphere(statevector_init[index])
initial_figure.savefig("images/bloch_init" + str(index) + ".png")
for index in range(0, len(statevector_circ)):
final_figure = qsphere(statevector_circ[index])
final_figure.savefig("images/bloch_final" + str(index) + ".png")
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import *
from qiskit.visualization import plot_bloch_vector
qc = QuantumCircuit(1)
# z measurement of qubit 0
measure_z = QuantumCircuit(1,1)
measure_z.measure(0,0);
# x measurement of qubit 0
measure_x = QuantumCircuit(1,1)
measure_x.h(0)
measure_x.measure(0,0)
# y measurement of qubit 0
measure_y = QuantumCircuit(1,1)
measure_y.sdg(0)
measure_y.h(0)
measure_y.measure(0,0);
shots = 2**14 # number of samples used for statistics
bloch_vector = []
for measure_circuit in [measure_x, measure_y, measure_z]:
# run the circuit with a the selected measurement and get the number of samples that output each bit value
counts = execute(qc+measure_circuit,Aer.get_backend('qasm_simulator'),shots=shots).result().get_counts()
# calculate the probabilities for each bit value
probs = {}
for output in ['0','1']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
bloch_vector.append( probs['0'] - probs['1'] )
plot_bloch_vector( bloch_vector )
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
#
# your solution is here
#
# Find expression to create the states
def expression(a, b, c):
return (1/(a**(0.5) - (b + 2 * (c)**(0.5))**(0.5)))
# Construct the quantum state
quantum_state = [expression(3, 5, 6), expression(3, 7, 12), expression(5, 13, 40), expression(7, 15, 26)]
# Verify validity of the quantum state
# Square root of items must add up to 1 (comes from definition of quantum state)
# Each item correspons probability of observing the system in states |00>, |01>, |10>, |11>
print("The probability of observing the states 00, 01, 10, 11:")
prob = 0
for state in quantum_state:
print("probability of current state " + str(state))
prob += state ** 2
print("Verify validity of state - should be approximately 1: " + str(prob) )
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# import randrange for random choices
from random import randrange
#
# your code is here
#
# Registers with 5 bits
qreg1 = QuantumRegister(5)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg1 = ClassicalRegister(5)
# define our quantum circuit
mycircuit1 = QuantumCircuit(qreg1,creg1)
# store index of random z gates
z_gate_idx = []
# apply H gate to every bit
for i in range(5):
mycircuit1.h(qreg1[i])
if randrange(2) == 0: # 0.5 chance apply z gate
mycircuit1.z(qreg1[i])
z_gate_idx.append(i)
# apply h gate again
mycircuit1.h(qreg1[i])
# measure the first qubit, and store the result in the first classical bit
mycircuit1.measure(qreg1,creg1)
# get the numbers
job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit1)
print(counts) # print the outcomes
print("z gate applied to: " + str(z_gate_idx))
# It can be seen that Z-gate changes value of the q-bit
# draw the circuit
mycircuit1.draw(output='mpl',reverse_bits=True)
# reexecute this cell if you DO NOT see the circuit diagram
|
https://github.com/mspronesti/qlearnkit
|
mspronesti
|
import numbers
from abc import ABC, abstractmethod
from qiskit import QuantumCircuit
class EncodingMap(ABC):
"""
Abstract Base class for qlearnkit encoding maps
"""
def __init__(self, n_features: int = 2) -> None:
"""
Creates a generic Encoding Map for classical data
of size `n_features`
Args:
n_features: number of features (default: 2)
"""
if n_features <= 0:
raise ValueError(f"Expected n_features > 0. Got {n_features}")
elif not isinstance(n_features, numbers.Integral):
raise TypeError(
"n_features does not take %s value, enter integer value"
% type(n_features)
)
self._num_features = n_features
self._num_qubits = 0
@abstractmethod
def construct_circuit(self, x) -> QuantumCircuit:
"""construct and return quantum circuit encoding data"""
raise NotImplementedError("Must have implemented this.")
@property
def num_qubits(self):
"""getter for number of qubits"""
return self._num_qubits
@property
def num_features(self):
"""getter for number of features"""
return self._num_features
def _check_feature_vector(self, x):
if len(x) != self.num_features:
raise ValueError(f"Expected features dimension "
f"{self.num_features}, but {len(x)} was passed")
|
https://github.com/qiskit-community/qgss-2023
|
qiskit-community
|
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def step_1_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
##1 Initialization
q0, q1 = qr
# apply Hadamard on the auxiliary qubit
qc.h(q0)
# put the system qubit into the |1> state
qc.x(q1)
##2 Apply control-U operator as many times as needed to get the least significant phase bit
# controlled-S is equivalent to CPhase with angle pi / 2
s_angle = np.pi / 2
# we want to apply controlled-S 2^k times
k = 1
# calculate the angle of CPhase corresponding to 2^k applications of controlled-S
cphase_angle = s_angle * 2**k
# apply the controlled phase gate
qc.cp(cphase_angle, q0, q1)
##3 Measure the auxiliary qubit in x-basis into the first classical bit
# apply Hadamard to change to the X basis
qc.h(q0)
# measure the auxiliary qubit into the first classical bit
c0, _ = cr
qc.measure(q0, c0)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_1_circuit(qr, cr)
qc.draw("mpl")
# Submit your circuit
from qc_grader.challenges.qgss_2023 import grade_lab4_ex1
grade_lab4_ex1(qc)
def step_2_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
# begin with the circuit from Step 1
qc = step_1_circuit(qr, cr)
####### your code goes here #######
##1 Reset and re-initialize the auxiliary qubit
q0, q1 = qr
# reset the auxiliary qubit
qc.reset(q0)
# apply Hadamard on the auxiiliary qubit
qc.h(q0)
##2 Apply phase correction conditioned on the first classical bit
c0, c1 = cr
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
##3 Apply control-U operator as many times as needed to get the next phase bit
# controlled-S is equivalent to CPhase with angle pi / 2
s_angle = np.pi / 2
# we want to apply controlled-S 2^k times
k = 0
# calculate the angle of CPhase corresponding to 2^k applications of controlled-S
cphase_angle = s_angle * 2**k
# apply the controlled phase gate
qc.cp(cphase_angle, q0, q1)
##4 Measure the auxiliary qubit in x-basis into the second classical bit
# apply Hadamard to change to the X basis
qc.h(q0)
# measure the auxiliary qubit into the first classical bit
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_2_circuit(qr, cr)
qc.draw("mpl")
# Submit your circuit
from qc_grader.challenges.qgss_2023 import grade_lab4_ex2
grade_lab4_ex2(qc)
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def t_gate_ipe_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 3 bits
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
t_angle = np.pi / 4
k = 2
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the first classical bit
qc.h(q0)
c0, c1, c2 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 1
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first and second classical bits
with qc.if_test((c0, 1)):
qc.p(-np.pi / 4, q0)
with qc.if_test((c1, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 0
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the third classical bit
qc.h(q0)
qc.measure(q0, c2)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(3, "c")
qc = QuantumCircuit(qr, cr)
qc = t_gate_ipe_circuit(qr, cr)
qc.draw("mpl")
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
# Submit your circuit
from qc_grader.challenges.qgss_2023 import grade_lab4_ex3
grade_lab4_ex3(qc)
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
u_angle = 2 * np.pi / 3
k = 1
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the first classical bit
qc.h(q0)
c0, c1 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 0
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
print(counts)
success_probability = counts["01"] / counts.shots()
print(f"Success probability: {success_probability}")
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 1 bits
qc = QuantumCircuit(qr, cr)
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
u_angle = 2 * np.pi / 3
k = 1
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis
qc.h(q0)
(c0,) = cr
qc.measure(q0, c0)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
job = sim.run(qc, shots=15)
result = job.result()
counts = result.get_counts()
print(counts)
step1_bit: int
####### your code goes here #######
step1_bit = 1 if counts["1"] > counts["0"] else 0
print(step1_bit)
# Submit your result
from qc_grader.challenges.qgss_2023 import grade_lab4_ex4
grade_lab4_ex4(step1_bit)
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
# Initialization
q0, q1 = qr
if step1_bit:
qc.x(q0)
qc.x(q1)
# Measure the auxiliary qubit
c0, c1 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
u_angle = 2 * np.pi / 3
k = 0
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
# Submit your result
from qc_grader.challenges.qgss_2023 import grade_lab4_ex5
grade_lab4_ex5(qc)
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
print(counts)
success_probability = counts["01"] / counts.shots()
print(f"Success probability: {success_probability}")
from qiskit.circuit import Gate
def iterative_phase_estimation(
qr: QuantumRegister,
cr: ClassicalRegister,
controlled_unitaries: list[Gate],
state_prep: Gate,
) -> QuantumCircuit:
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
auxiliary_qubit = qr[0]
system_qubits = qr[1:]
qc.append(state_prep, system_qubits)
for i in range(len(cr)):
k = len(cr) - 1 - i
qc.reset(auxiliary_qubit)
qc.h(auxiliary_qubit)
for j in range(i):
with qc.if_test((cr[j], 1)):
qc.p(-np.pi / 2 ** (i - j), auxiliary_qubit)
qc.append(controlled_unitaries[k], qr)
qc.h(auxiliary_qubit)
qc.measure(auxiliary_qubit, cr[i])
return qc
from qiskit.circuit.library import CPhaseGate, XGate
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
s_angle = np.pi / 2
controlled_unitaries = [CPhaseGate(s_angle * 2**k) for k in range(2)]
qc = iterative_phase_estimation(qr, cr, controlled_unitaries, XGate())
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
from qiskit_ibm_provider import IBMProvider
provider = IBMProvider()
hub = "YOUR_HUB"
group = "YOUR_GROUP"
project = "YOUR_PROJECT"
backend_name = "ibmq_manila"
backend = provider.get_backend(backend_name, instance=f"{hub}/{group}/{project}")
from qiskit import transpile
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_2_circuit(qr, cr)
qc_transpiled = transpile(qc, backend)
job = backend.run(qc_transpiled, shots=1000, dynamic=True)
job_id = job.job_id()
print(job_id)
retrieve_job = provider.retrieve_job(job_id)
retrieve_job.status()
from qiskit.tools.visualization import plot_histogram
counts = retrieve_job.result().get_counts()
plot_histogram(counts)
|
https://github.com/oierajenjo/q-Grover-Algorithm
|
oierajenjo
|
# -*- 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.
"""
Created on Wed Mar 11 18:03:12 2020
Functional interface to Qasm2 source loading and exporting
Supersede QuantumCircuit member functions
Provide for pluggable qasm translator
Based on conversation with Dr. Luciano Bello
@author: jax
"""
from importlib import import_module
from os import linesep
from typing import List, BinaryIO, TextIO
from qiskit import QuantumCircuit, QiskitError
from qiskit_openqasm2 import Qasm
from .funhelp import qasm_load, qasm_export
def _load_from_string(qasm_src: str or List[str],
loader: str = None,
include_path: str = '') -> QuantumCircuit:
"""
Parameters
----------
qasm_src : str or List[str]
Qasm program source as string or list of string.
loader : str, optional
Name of module with functional attribute
load(filename: str = None,
data: str = None,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
include_path : str, optional
Loader-specific include path for qasm include directives.
The default is ''.
Raises
------
QiskitError
If unknown loader.
Returns
-------
QuantumCircuit
Circuit factoried from Qasm src.
"""
circ = None
if not loader:
if isinstance(qasm_src, list):
qasm_src = ''.join(s + linesep for s in qasm_src)
qasm = Qasm(data=qasm_src)
circ = qasm_load(qasm)
else:
m_m = import_module(loader)
circ = getattr(m_m, 'load')(data=qasm_src,
include_path=include_path)
return circ
def _load_from_file(filename: str,
loader: str = None,
include_path: str = '') -> QuantumCircuit:
"""
Parameters
----------
filename : str
Filepath to qasm program source.
loader : str, optional
Name of module with functional attribute
load(filename: str = None,
data: str = None,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
include_path : str, optional
Loader-specific include path for qasm include directives.
The default is ''.
Returns
-------
QuantumCircuit
Circuit factoried from Qasm src.
"""
circ = None
if not loader:
qasm = Qasm(filename=filename)
circ = qasm_load(qasm)
else:
m_m = import_module(loader)
circ = getattr(m_m, 'load')(filename=filename,
include_path=include_path)
return circ
def load(data: str or List[str] = None,
filename: str = None,
loader: str = None,
include_path: str = None) -> QuantumCircuit:
"""
Parameters
----------
data : str or List[str], optional
Qasm program source as string or list of string. The default is None.
filename : str, optional
Filepath to qasm program source. The default is None.
loader : str, optional
Name of module with functional attribute
load(filename: str = None,
data: str = None,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
include_path : str, optional
Loader-specific include path for qasm include directives.
The default is None.
Raises
------
QiskitError
If both filename and data or neither filename nor data.
Returns
-------
QuantumCircuit
The factoried circuit.
"""
if (not data and not filename) or (data and filename):
raise QiskitError("To load, either filename or data (and not both) must be provided.")
circ = None
if data:
circ = _load_from_string(data, loader=loader, include_path=include_path)
elif filename:
circ = _load_from_file(filename, loader=loader, include_path=include_path)
return circ
def export(qc: QuantumCircuit,
exporter: str = None,
file: BinaryIO or TextIO = None,
filename: str = None,
include_path: str = None,) -> str:
"""
Decompile a QuantumCircuit into Return OpenQASM string
Parameters
----------
qc : QuantumCircuit
Circuit to decompile ("export")
exporter : str, optional
Name of module with functional attribute
export(qc: QuantumCircuit,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
file : BinaryIO or TextIO, optional
File object to write to as well as return str
Written in UTF-8
Caller must close file.
Mutually exclusive with filename=
The default is None.
filename : str, optional
Name of file to write export to as well as return str
Mutually exclusive with file=
The default is None.
include_path: str, optional
Unloader-specific include path for qasm include directives
Raises
------
QiskitError
If both filename and file
Returns
-------
str
OpenQASM source for circuit.
"""
if filename and file:
raise QiskitError("export: file= and filename= are mutually exclusive")
qasm_src = None
if not exporter:
qasm_src = qasm_export(qc)
else:
m_m = import_module(exporter)
qasm_src = getattr(m_m, 'export')(qc, include_path=include_path)
if filename:
f_f = open(filename, 'w')
f_f.write(qasm_src)
f_f.close()
elif file:
if 'b' in file.mode:
file.write(bytes(qasm_src, 'utf-8'))
else:
file.write(qasm_src)
return qasm_src
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Classical Real Evolver."""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from ddt import data, ddt, unpack
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit_algorithms import SciPyRealEvolver, TimeEvolutionProblem
from qiskit.quantum_info import Statevector, SparsePauliOp
def zero(n):
"""Auxiliary function to create an initial state on n qubits."""
qr = QuantumRegister(n)
qc = QuantumCircuit(qr)
return Statevector(qc)
def one(n):
"""Auxiliary function to create an initial state on n qubits."""
qr = QuantumRegister(n)
qc = QuantumCircuit(qr)
qc.x(qr)
return Statevector(qc)
@ddt
class TestClassicalRealEvolver(QiskitAlgorithmsTestCase):
"""Test Classical Real Evolver."""
@data(
(one(1), np.pi / 2, SparsePauliOp("X"), -1.0j * zero(1)),
(
one(1).expand(zero(1)),
np.pi / 2,
SparsePauliOp(["XX", "YY"], [0.5, 0.5]),
-1.0j * zero(1).expand(one(1)),
),
(
one(1).expand(zero(1)),
np.pi / 4,
SparsePauliOp(["XX", "YY"], [0.5, 0.5]),
((one(1).expand(zero(1)) - 1.0j * zero(1).expand(one(1)))) / np.sqrt(2),
),
(zero(12), np.pi / 2, SparsePauliOp("X" * 12), -1.0j * (one(12))),
)
@unpack
def test_evolve(
self,
initial_state: Statevector,
time_ev: float,
hamiltonian: SparsePauliOp,
expected_state: Statevector,
):
"""Initializes a classical real evolver and evolves a state."""
evolution_problem = TimeEvolutionProblem(hamiltonian, time_ev, initial_state)
classic_evolver = SciPyRealEvolver(num_timesteps=1)
result = classic_evolver.evolve(evolution_problem)
np.testing.assert_allclose(
result.evolved_state.data,
expected_state.data,
atol=1e-10,
rtol=0,
)
def test_observables(self):
"""Tests if the observables are properly evaluated at each timestep."""
initial_state = zero(1)
time_ev = 10.0
hamiltonian = SparsePauliOp("X")
observables = {"Energy": SparsePauliOp("X"), "Z": SparsePauliOp("Z")}
evolution_problem = TimeEvolutionProblem(
hamiltonian, time_ev, initial_state, aux_operators=observables
)
classic_evolver = SciPyRealEvolver(num_timesteps=10)
result = classic_evolver.evolve(evolution_problem)
z_mean, z_std = result.observables["Z"]
timesteps = z_mean.shape[0]
time_vector = np.linspace(0, time_ev, timesteps)
expected_z = 1 - 2 * (np.sin(time_vector)) ** 2
expected_z_std = np.zeros_like(expected_z)
np.testing.assert_allclose(z_mean, expected_z, atol=1e-10, rtol=0)
np.testing.assert_allclose(z_std, expected_z_std, atol=1e-10, rtol=0)
np.testing.assert_equal(time_vector, result.times)
def test_quantum_circuit_initial_state(self):
"""Tests if the system can be evolved with a quantum circuit as an initial state."""
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, range(1, 3))
evolution_problem = TimeEvolutionProblem(
hamiltonian=SparsePauliOp("X" * 3), time=2 * np.pi, initial_state=qc
)
classic_evolver = SciPyRealEvolver(num_timesteps=500)
result = classic_evolver.evolve(evolution_problem)
np.testing.assert_almost_equal(
result.evolved_state.data,
np.array([1, 0, 0, 0, 0, 0, 0, 1]) / np.sqrt(2),
decimal=10,
)
def test_error_time_dependency(self):
"""Tests if an error is raised for time dependent hamiltonian."""
evolution_problem = TimeEvolutionProblem(
hamiltonian=SparsePauliOp("X" * 3), time=1.0, initial_state=zero(3), t_param=0
)
classic_evolver = SciPyRealEvolver(num_timesteps=5)
with self.assertRaises(ValueError):
classic_evolver.evolve(evolution_problem)
def test_no_time_steps(self):
"""Tests if the evolver handles some edge cases related to the number of timesteps."""
evolution_problem = TimeEvolutionProblem(
hamiltonian=SparsePauliOp("X"),
time=1.0,
initial_state=zero(1),
aux_operators={"Energy": SparsePauliOp("X")},
)
with self.subTest("0 timesteps"):
with self.assertRaises(ValueError):
classic_evolver = SciPyRealEvolver(num_timesteps=0)
classic_evolver.evolve(evolution_problem)
with self.subTest("1 timestep"):
classic_evolver = SciPyRealEvolver(num_timesteps=1)
result = classic_evolver.evolve(evolution_problem)
np.testing.assert_equal(result.times, np.array([0.0, 1.0]))
with self.subTest("Negative timesteps"):
with self.assertRaises(ValueError):
classic_evolver = SciPyRealEvolver(num_timesteps=-5)
classic_evolver.evolve(evolution_problem)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
|
SaashaJoshi
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
from qiskit.quantum_info import Operator
from qiskit import QuantumCircuit
import numpy as np
def phase_oracle(n, indices_to_mark, name = 'Oracle'):
# create a quantum circuit on n qubits
qc = QuantumCircuit(n, name=name)
### WRITE YOUR CODE BETWEEN THESE LINES - START
for qubits in range(n):
qc.h(qubits)
for index, value in enumerate(indices_to_mark):
if index == 0:
for qubits in range(1, n):
qc.x(qubits)
qc.cz()
for qubits in range(1, n):
qc.x(qubits)
oracle_matrix = qc.diagonal
if index == 1:
for qubits in range(1, n, 2):
qc.x(qubits)
qc.cz()
for qubits in range(1, n, 2):
qc.x(qubits)
oracle_matrix = qc.diagonal
### WRITE YOUR CODE BETWEEN THESE LINES - END
# convert your matrix (called oracle_matrix) into an operator, and add it to the quantum circuit
qc.unitary(Operator(oracle_matrix), range(n))
return qc
def diffuser(n):
# create a quantum circuit on n qubits
qc = QuantumCircuit(n, name='Diffuser')
### WRITE YOUR CODE BETWEEN THESE LINES - START
### WRITE YOUR CODE BETWEEN THESE LINES - END
return qc
def Grover(n, indices_of_marked_elements):
# Create a quantum circuit on n qubits
qc = QuantumCircuit(n, n)
# Determine r
r = int(np.floor(np.pi/4*np.sqrt(2**n/len(indices_of_marked_elements))))
print(f'{n} qubits, basis states {indices_of_marked_elements} marked, {r} rounds')
# step 1: apply Hadamard gates on all qubits
qc.h(range(n))
# step 2: apply r rounds of the phase oracle and the diffuser
for _ in range(r):
qc.append(phase_oracle(n, indices_of_marked_elements), range(n))
qc.append(diffuser(n), range(n))
# step 3: measure all qubits
qc.measure(range(n), range(n))
return qc
mycircuit = Grover(6, [1, 42])
mycircuit.draw(output='text')
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
counts = execute(mycircuit, backend=simulator, shots=1000).result().get_counts(mycircuit)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
name = 'Saasha Joshi'
email = 'saashajoshi08@gmail.com'
### Do not change the lines below
from qiskit import transpile
mycircuit_t = transpile(mycircuit, basis_gates=['u1', 'u2', 'u3', 'cx'], optimization_level=0)
from grading_tools import grade
grade(answer=mycircuit_t, name=name, email=email, labid='lab2', exerciseid='ex1')
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
import numpy as np
from qiskit import BasicAer
from qiskit.visualization import plot_histogram
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle
"""
Examples:
c This is an example DIMACS CNF file with 3 satisfying assignments: 1 -2 3, -1 -2 -3, 1 2 -3.
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
(¬𝑥1∨¬𝑥2∨¬𝑥3)∧(𝑥1∨¬𝑥2∨𝑥3)∧(𝑥1∨𝑥2∨¬𝑥3)∧(𝑥1∨¬𝑥2∨¬𝑥3)∧(¬𝑥1∨𝑥2∨𝑥3)
"""
input_3sat = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
oracle = LogicalExpressionOracle(input_3sat)
oracle.circuit.draw('mpl')
grover = Grover(oracle)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
result = grover.run(quantum_instance)
print(result['result'])
## Non deterministic solutions, could be [1,-2,3], [-1, -2, -3], [1,2,-3]
plot_histogram(result['measurement'])
## REAL DEVICE LIMITATIONS
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_16_melbourne')
from qiskit.compiler import transpile
# transpile the circuit for ibmq_16_melbourne
grover_compiled = transpile(result['circuit'], backend=backend, optimization_level=3)
print('gates = ', grover_compiled.count_ops())
print('depth = ', grover_compiled.depth())
grover_compiled.draw('mpl')
from qiskit import execute
from qiskit.tools.monitor import job_monitor
job_exp = execute(grover_compiled, shots=1024, backend=backend)
job_monitor(job_exp)
# Get the results from the computation
results = job_exp.result()
answer = results.get_counts(grover_compiled)
plot_histogram(answer)
# Too much noise!
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
import numpy as np
import random
from qiskit import QuantumCircuit, Aer, execute
from math import log2, ceil, pi
from numpy import savetxt, save, savez_compressed
#=====================================================================================================================
simulator = Aer.get_backend('statevector_simulator')
def disp_isv(circ, msg="", all=True, precision=1e-8):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
qb = int(log2(len(statevector)))
print("\n============ State Vector ============", msg)
s = 0
for i in statevector:
if (all == True): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
else:
if (abs(i) > precision): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
s = s+1
print("============..............============")
return
# 24 qubits with Hadamard on 12 qubits log size: 880 MB csv, 816 MB txt, 256 MB npy, 255 KB npz
def save_isv(statevector, mode=1):
if (mode == 1): savez_compressed('output.npz', statevector)
elif (mode == 2): save('output.npy', statevector)
elif (mode == 3):
qb = int(log2(len(statevector)))
f = open("output.txt", "w")
f.write("============ State Vector ============\n")
s = 0
for i in statevector:
f.write(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb)+'\n')
s = s+1
f.write("============..............============")
f.close()
elif (mode == 4): savetxt('output.csv', statevector, delimiter=',')
else: print('Invalid mode selected')
return
#=====================================================================================================================
def nCX(k,c,t,b):
nc = len(c)
if nc == 1:
k.cx(c[0], t[0])
elif nc == 2:
k.toffoli(c[0], c[1], t[0])
else:
nch = ceil(nc/2)
c1 = c[:nch]
c2 = c[nch:]
c2.append(b[0])
nCX(k,c1,b,[nch+1])
nCX(k,c2,t,[nch-1])
nCX(k,c1,b,[nch+1])
nCX(k,c2,t,[nch-1])
return
#=====================================================================================================================
def U_init(qcirc, circ_width, fsm):
for i in fsm:
qcirc.h(i)
qcirc.barrier()
return
def U_read(qcirc, read, head, tape, ancilla):
# Reset read (prepz measures superposed states... need to uncompute)
for cell in range(0, len(tape)):
enc = format(cell, '#0'+str(len(head)+2)+'b') # 2 for '0b' prefix
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
qcirc.barrier(read, head)
nCX(qcirc, head+[tape[cell]], read, [ancilla[0]])
qcirc.barrier(read, head)
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
qcirc.barrier(read, head, tape, ancilla)
qcirc.barrier()
return
def U_fsm(qcirc, tick, fsm, state, read, write, move, ancilla):
# Description Number Encoding: {M/W}{R}
# [ M1 W1 M0 W0 ] LSQ = W0 = fsm[0]
qcirc.x(read[0]) # If read == 0
nCX(qcirc, [fsm[0],read[0]], write, [ancilla[0]]) # Update write
nCX(qcirc, [fsm[1],read[0]], move, [ancilla[0]]) # Update move
qcirc.x(read[0]) # If read == 1
nCX(qcirc, [fsm[2],read[0]], write, [ancilla[0]]) # Update write
nCX(qcirc, [fsm[3],read[0]], move, [ancilla[0]]) # Update move
qcirc.barrier()
return
def U_write(qcirc, write, head, tape, ancilla):
# Reset write (prepz measures superposed states... need to uncompute)
for cell in range(0, len(tape)):
enc = format(cell, '#0'+str(len(head)+2)+'b') # 2 for '0b' prefix
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
qcirc.barrier(write, head)
nCX(qcirc, head+write, [tape[cell]], [ancilla[0]])
qcirc.barrier(write, head)
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
qcirc.barrier(write, head, tape, ancilla)
qcirc.barrier()
return
def U_move(qcirc, move, head, ancilla):
# Increment/Decrement using Adder
reg_a = move
reg_a.extend([-1]*(len(head)-len(move)))
reg_b = head
reg_c = [-1] # No initial carry
reg_c.extend(ancilla)
reg_c.append(-1) # Ignore Head position under/overflow. Trim bits. Last carry not accounted, All-ones overflows to All-zeros
def q_carry(qcirc, q0, q1, q2, q3):
if (q1 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q1, q2, q3)
if (q1 != -1 and q2 != -1): qcirc.cx(q1, q2)
if (q0 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q0, q2, q3)
def q_mid(qcirc, q0, q1):
if (q0 != -1 and q1 != -1): qcirc.cx(q0, q1)
def q_sum(qcirc, q0, q1, q2):
if (q0 != -1 and q2 != -1): qcirc.cx(q0, q2)
if (q1 != -1 and q2 != -1): qcirc.cx(q1, q2)
def q_rcarry(qcirc, q0, q1, q2, q3):
if (q0 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q0, q2, q3)
if (q1 != -1 and q2 != -1): qcirc.cx(q1, q2)
if (q1 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q1, q2, q3)
# Quantum Adder
for i in range(0,len(head)):
q_carry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
q_mid(qcirc,reg_a[i],reg_b[i])
q_sum(qcirc,reg_c[i],reg_a[i],reg_b[i])
for i in range(len(head)-2,-1,-1):
q_rcarry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
q_sum(qcirc,reg_c[i],reg_a[i],reg_b[i])
qcirc.x(reg_a[0])
# Quantum Subtractor
for i in range(0,len(head)-1):
q_sum(qcirc,reg_c[i],reg_a[i],reg_b[i])
q_carry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
q_sum(qcirc,reg_c[i+1],reg_a[i+1],reg_b[i+1])
q_mid(qcirc,reg_a[i+1],reg_b[i+1])
for i in range(len(head)-2,-1,-1):
q_rcarry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
qcirc.x(reg_a[0])
qcirc.barrier()
return
def U_rst(qcirc, tick, fsm, state, read, write, move, ancilla):
# Reset write and move
qcirc.x(read[0])
nCX(qcirc, [fsm[0],read[0]], write, [ancilla[0]])
nCX(qcirc, [fsm[1],read[0]], move, [ancilla[0]])
qcirc.x(read[0])
nCX(qcirc, [fsm[2],read[0]], write, [ancilla[0]])
nCX(qcirc, [fsm[3],read[0]], move, [ancilla[0]])
qcirc.barrier()
return
#=====================================================================================================================
def Test_cfg(block):
global fsm, state, move, head, read, write, tape, ancilla, test
if (block == 'none'):
return
elif (block == 'read'):
fsm = []
state = []
move = []
head = [0,1,2,3]
read = [4]
write = []
tape = [5,6,7,8,9,10,11,12,13,14,15,16]
ancilla = [17]
test = [18]
elif (block == 'fsm'):
fsm = [0,1,2,3,4,5,6,7,8,9,10,11]
state = [12,13]
move = [14]
head = []
read = [15]
write = [16]
tape = []
ancilla = [17]
test = [18,19,20]
elif (block == 'move'):
fsm = []
state = []
move = [0]
head = [1,2,3,4]
read = []
write = []
tape = []
ancilla = [5,6,7]
test = [8,9,10,11]
elif (block == 'write'):
fsm = []
state = []
move = []
head = [0,1,2,3]
read = []
write = [4]
tape = [5,6,7,8,9,10,11,12,13,14,15,16]
ancilla = [17]
test = []#[18,19,20,21,22,23,24,25,26,27,28,29]
elif (block == 'rst'):
fsm = [0,1,2,3,4,5,6,7,8,9,10,11]
state = [12,13]
move = [14]
head = []
read = [15]
write = [16]
tape = []
ancilla = [17]
test = [18,19,20,21]
print("\n\nTEST CONFIGURATION\n\tFSM\t:",fsm,"\n\tSTATE\t:",state,"\n\tMOVE\t:",move,"\n\tHEAD\t:",head,"\n\tREAD\t:",read,"\n\tWRITE\t:",write,"\n\tTAPE\t:",tape,"\n\tANCILLA :",ancilla,"\n\tTEST\t:",test)
def Test_read(qcirc, read, head, tape, ancilla, test):
# Test using full superposition of head and some random tape qubits
# Test associated to read
for i in range(0,len(head)):
qcirc.h(head[i])
# Create random binary string of length tape
randbin = ""
for i in range(len(tape)): randbin += str(random.randint(0, 1))
for i in range(0,len(tape)):
if (randbin[i] == '1'):
qcirc.h(tape[i]) # Replace H with X for ease
qcirc.cx(read[0],test[0])
print("Test tape:",randbin)
qcirc.barrier()
return
def Test_fsm(qcirc, tick, fsm, state, read, write, move, ancilla, test):
# Test using full superposition of fsm, current state, read
# Test associated to move, write, new state
# fsm superposition part of U_init
qcirc.barrier()
qcirc.h(state[0])
qcirc.h(read[0])
qcirc.barrier()
qcirc.cx(write[0],test[0])
qcirc.cx(move[0],test[1])
qcirc.cx(state[1],test[2])
qcirc.barrier()
return
def Test_write(qcirc, write, head, tape, ancilla, test):
# Test using full superposition of head and write
# Test associated to tape (optional)
for i in range(0,len(head)):
qcirc.h(head[i])
qcirc.h(write)
# for i in range(0,len(tape)):
# qcirc.cx(tape[i],test[i])
return
def Test_move(qcirc, move, head, ancilla, test):
# Test using full superposition of head, both inc/dec
# Test associated to head
for i in range(0,len(head)):
qcirc.h(head[i])
qcirc.cx(head[i],test[i])
qcirc.h(move[0])
qcirc.barrier()
return
def Test_rst(qcirc, tick, fsm, state, read, write, move, ancilla, test):
# Test using full superposition of fsm, current state, read
# Test associated to move, write, new state
# fsm superposition part of U_init
for i in range(0,len(state)):
qcirc.h(state[i])
qcirc.h(read[0])
qcirc.h(write[0])
qcirc.h(move[0])
qcirc.barrier()
for i in range(0,len(state)):
qcirc.cx(state[i],test[i])
qcirc.cx(write[0],test[len(state)])
qcirc.cx(move[0],test[len(state)+1])
qcirc.barrier()
return
#=====================================================================================================================
asz = 2 # Alphabet size: Binary (0 is blank/default)
ssz = 1 # State size (Initial state is all 0)
tdim = 1 # Tape dimension
csz = ceil(log2(asz)) # Character symbol size
senc = ceil(log2(ssz)) # State encoding size
transitions = ssz * asz # Number of transition arrows in FSM
dsz = transitions * (tdim + csz + senc) # Description size
machines = 2 ** dsz
print("\nNumber of "+str(asz)+"-symbol "+str(ssz)+"-state "+str(tdim)+"-dimension Quantum Parallel Universal Linear Bounded Automata: "+str(machines))
tsz = dsz # Turing Tape size (same as dsz to estimating self-replication and algorithmic probability)
hsz = ceil(log2(tsz)) # Head size
sim_tick = tsz # Number of ticks of the FSM before abort
#sim_tick = 1 # Just 1 QPULBA cycle for proof-of-concept
tlog = (sim_tick+1) * senc # Transition log # required?
nanc = 3
qnos = [dsz, tlog, tdim, hsz, csz, csz, tsz, nanc]
fsm = list(range(sum(qnos[0:0]),sum(qnos[0:1])))
state = list(range(sum(qnos[0:1]),sum(qnos[0:2]))) # States (Binary coded)
move = list(range(sum(qnos[0:2]),sum(qnos[0:3])))
head = list(range(sum(qnos[0:3]),sum(qnos[0:4]))) # Binary coded, 0-MSB 2-LSB, [001] refers to Tape pos 1, not 4
read = list(range(sum(qnos[0:4]),sum(qnos[0:5])))
write = list(range(sum(qnos[0:5]),sum(qnos[0:6]))) # Can be MUXed with read?
tape = list(range(sum(qnos[0:6]),sum(qnos[0:7])))
ancilla = list(range(sum(qnos[0:7]),sum(qnos[0:8])))
print("\nFSM\t:",fsm,"\nSTATE\t:",state,"\nMOVE\t:",move,"\nHEAD\t:",head,"\nREAD\t:",read,"\nWRITE\t:",write,"\nTAPE\t:",tape,"\nANCILLA :",ancilla)
#=====================================================================================================================
test = []
unit = 'none' # 'read', 'fsm', 'write', 'move', 'rst'
Test_cfg(unit)
qcirc_width = sum(qnos[0:8]) + len(test)
qcirc = QuantumCircuit(qcirc_width)
# 1. Initialize
U_init(qcirc, qcirc_width, fsm)
# 2. Run machine for n-iterations:
for tick in range(0, sim_tick):
# 2.1 {read} << U_read({head, tape})
if (unit == 'read'): Test_read(qcirc, read, head, tape, ancilla, test)
U_read(qcirc, read, head, tape, ancilla)
# 2.2 {write, state, move} << U_fsm({read, state, fsm})
if (unit == 'fsm'): Test_fsm(qcirc, tick, fsm, state, read, write, move, ancilla, test)
U_fsm(qcirc, tick, fsm, state, read, write, move, ancilla)
# 2.3 {tape} << U_write({head, write})
if (unit == 'write'): Test_write(qcirc, write, head, tape, ancilla, test)
U_write(qcirc, write, head, tape, ancilla)
# 2.4 {head, err} << U_move({head, move})
if (unit == 'move'): Test_move(qcirc, move, head, ancilla, test)
U_move(qcirc, move, head, ancilla)
# 2.5 reset
if (unit == 'rst'): Test_rst(qcirc, tick, fsm, state, read, write, move, ancilla, test)
U_rst(qcirc, tick, fsm, state, read, write, move, ancilla)
print()
print(qcirc.draw())
print()
print(qcirc.qasm())
print()
disp_isv(qcirc, "Step: Test all", all=False, precision=1e-4)
#=====================================================================================================================
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
es_problem = driver.run()
from qiskit_nature.second_q.mappers import JordanWignerMapper
mapper = JordanWignerMapper()
from qiskit.algorithms.eigensolvers import NumPyEigensolver
numpy_solver = NumPyEigensolver(filter_criterion=es_problem.get_default_filter_criterion())
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.algorithms import GroundStateEigensolver, QEOM
from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD
ansatz = UCCSD(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
mapper,
initial_state=HartreeFock(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
mapper,
),
)
estimator = Estimator()
# This first part sets the ground state solver
# see more about this part in the ground state calculation tutorial
solver = VQE(estimator, ansatz, SLSQP())
solver.initial_point = [0.0] * ansatz.num_parameters
gse = GroundStateEigensolver(mapper, solver)
# The qEOM algorithm is simply instantiated with the chosen ground state solver and Estimator primitive
qeom_excited_states_solver = QEOM(gse, estimator, "sd")
from qiskit_nature.second_q.algorithms import ExcitedStatesEigensolver
numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, numpy_solver)
numpy_results = numpy_excited_states_solver.solve(es_problem)
qeom_results = qeom_excited_states_solver.solve(es_problem)
print(numpy_results)
print("\n\n")
print(qeom_results)
import numpy as np
def filter_criterion(eigenstate, eigenvalue, aux_values):
return np.isclose(aux_values["ParticleNumber"][0], 2.0)
new_numpy_solver = NumPyEigensolver(filter_criterion=filter_criterion)
new_numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, new_numpy_solver)
new_numpy_results = new_numpy_excited_states_solver.solve(es_problem)
print(new_numpy_results)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
import numpy as np
%matplotlib widget
from slam.utils.gates.custom_gates import ConversionGainGate
from slam.utils.polytopes.polytope_wrap import (
monodromy_range_from_target,
coverage_to_haar_expectation,
)
from slam.basis import CircuitTemplate, MixedOrderBasisCircuitTemplate
from slam.utils.visualize import (
unitary_to_weyl,
unitary_2dlist_weyl,
coordinate_2dlist_weyl,
)
from slam.utils.gates.custom_gates import CustomCostGate
from qiskit.circuit.library import CXGate, SwapGate
from weylchamber import c1c2c3
from slam.utils.gates.snail_death_gate import SpeedLimitedGate
from tqdm import tqdm
import matplotlib.pyplot as plt
# # verifying that relative phase doesn't change 2Q gate location
# unitary = [ConversionGainGate(0, 0, p*0.5*np.pi, (1-p)*0.4*np.pi) for p in np.linspace(0,1,16)]
# print([u.cost() for u in unitary])
# unitary_to_weyl(*unitary);
# the first version of this file was exploring the conversion gain hamiltonian, let's also explore Heavy-Fluxonion, and Flux Qubit
from slam.utils.gates.duraton_scaling import cost_scaling
from slam.utils.gates.bare_candidates import (
build_gates,
get_group_name,
plot_eharr,
collect_data,
)
from slam.utils.gates.winner_selection import pick_winner
unitary_list, coordinate_list = build_gates()
coordinate_2dlist_weyl(*coordinate_list)
# # monkey patch, iterate through every gate and save its gc/gg mirror to base costs data set
# from slam.scripts.gate_exploration.bgatev2script import filename
# import h5py
# with h5py.File(filename, "a") as hf:
# g = hf.require_group("bare_cost")
# for gate, data in g.items():
# gc, gg = data[0][2], data[0][3]
# if gc == gg:
# continue
# # create mirror gate
# mirror = ConversionGainGate(0,0, gg, gc)
# #save a copy of the data with new gate
# mirror_data = [mirror.params, list(data[1])] # scores stay the same
# g.create_dataset(str(mirror), data=mirror_data)
# ## %%
# TODO put this in its own file
# """use 2 different 2Q gates and see minimum cost to build SWAP
# just see if a solution exists for 2Q gates only using 2 instances of each gate then stop (rather than using coverage set)"""
# from slam.utils.polytope_wrap import get_polytope_from_circuit, unitary_to_monodromy_coordinate
# from qiskit import QuantumCircuit
# from qiskit.circuit.library import SwapGate
# import itertools
# # interested in a hetero basis of 2 applications to build a SWAP target
# target_coords = unitary_to_monodromy_coordinate(SwapGate().to_matrix())
# #taking product over search space to build pairs of gates
# # a - might want to remove constraint of left side of x-axis only (I'm not sure if this makes a difference or not)
# # b - may need to increase density of gates to sample from
# unitary_pairs = list(itertools.product(unitary_list, repeat=2))
# #if find a solution, save it
# sol = []
# for gate1, gate2 in tqdm(unitary_pairs):
# #basis can just be a circuit with 2Q gates
# basis = QuantumCircuit(2)
# basis.append(gate1, [0,1])
# basis.append(gate2, [0,1])
# circuit_polytope = get_polytope_from_circuit(basis)
# if circuit_polytope.has_element(target_coords):
# sol.append((gate1, gate2))
# logging.info((gate1, gate2))
# print(sol)
# XXX
# template = MixedOrderBasisCircuitTemplate(base_gates=[CustomCostGate(CXGate(), "CX")], chatty_build=1)
# coverage_to_haar_expectation(template.coverage, chatty=1)
# set logger level to critical to suppress warnings
logger.setLevel(logging.CRITICAL)
# TODO I need to recompute everything, but to save time just do iswap family
filtered_unitary_list = list(filter(lambda x: x.params[2] == 0, unitary_list))
collect_data(filtered_unitary_list)
method = "linear"
duration_1q = 0.1
group_name = get_group_name(method, duration_1q)
cost_scaling(speed_method=method, duration_1q=duration_1q)
plot_eharr(group_name, metric=0)
pick_winner(group_name, metric=2)
method = "hardware"
duration_1q = 0.1
group_name = get_group_name(method, duration_1q)
cost_scaling(speed_method=method, duration_1q=duration_1q)
plot_eharr(group_name)
pick_winner(group_name)
method = "mid"
duration_1q = 0.1
group_name = get_group_name(method, duration_1q)
cost_scaling(speed_method=method, duration_1q=duration_1q)
# plot_eharr(group_name, metric=0)
pick_winner(group_name, metric=0)
method = "squared"
duration_1q = 0.1
group_name = get_group_name(method, duration_1q)
cost_scaling(speed_method=method, duration_1q=duration_1q)
plot_eharr(group_name, metric=0)
pick_winner(group_name, metric=0)
|
https://github.com/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
from slam.basis import MixedOrderBasisCircuitTemplate
import numpy as np
from slam.utils.gates.duraton_scaling import atomic_cost_scaling
from slam.utils.gates.family_extend import recursive_sibling_check
from slam.utils.polytopes.polytope_wrap import monodromy_range_from_target
from slam.utils.gates.custom_gates import ConversionGainGate
params = [0, 0, 0, np.pi / 32, 1]
basis = ConversionGainGate(*params)
template = MixedOrderBasisCircuitTemplate(
base_gates=[basis], chatty_build=False, use_smush_polytope=0
)
from qiskit.circuit.library import CPhaseGate
target_list = []
fam_list = []
no_fam_list = []
# iterate over CPHASe targets
for t_phase in range(1, 16):
t_phase = np.pi / 2 * (1 / t_phase)
target_list.append(t_phase)
target = CPhaseGate(theta=t_phase).to_matrix()
duration = atomic_cost_scaling(params, 1, speed_method="linear", duration_1q=0)
ret = recursive_sibling_check(
template, target, cost_1q=0.1, basis_factor=duration[1]
)
decomp_cost = ret[1]
# print(f"Relative cost {ret[1]}")
# ret[0].circuit.draw()
fam_list.append(decomp_cost)
# compare to no family
template = MixedOrderBasisCircuitTemplate(
base_gates=[basis], chatty_build=False, use_smush_polytope=0
)
ki = monodromy_range_from_target(template, target)[0]
decomp_cost = ki * duration[1] + (ki + 1) * 0.1
no_fam_list.append(decomp_cost)
# plot results
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(target_list, fam_list, label="with family", marker="o")
ax.plot(target_list, no_fam_list, label="no family", marker="o")
# reverse axis
ax.invert_xaxis()
# unit axis in pi
ax.set_xticks([np.pi / 2, np.pi / 4, np.pi / 8, np.pi / 16])
ax.set_xticklabels(["$\pi/2$", "$\pi/4$", "$\pi/8$", "$\pi/16$"])
# legend
ax.legend()
from slam.utils.gates.custom_gates import ConversionGainGate
params = [0, 0, 0, np.pi / 32, 1]
basis = ConversionGainGate(*params)
template = MixedOrderBasisCircuitTemplate(
base_gates=[basis], chatty_build=False, use_smush_polytope=0
)
from qiskit.circuit.library import CPhaseGate
target_list = []
fam_list = []
no_fam_list = []
# iterate over CPHASe targets
for t_phase in range(1, 16):
t_phase = np.pi / 2 * (1 / t_phase)
target_list.append(t_phase)
target = CPhaseGate(theta=t_phase).to_matrix()
duration = atomic_cost_scaling(params, 1, speed_method="linear", duration_1q=0)
ret = recursive_sibling_check(
template, target, cost_1q=0.1, basis_factor=duration[1]
)
decomp_cost = ret[1]
# print(f"Relative cost {ret[1]}")
# ret[0].circuit.draw()
fam_list.append(decomp_cost)
# compare to no family
template = MixedOrderBasisCircuitTemplate(
base_gates=[basis], chatty_build=False, use_smush_polytope=0
)
ki = monodromy_range_from_target(template, target)[0]
decomp_cost = ki * duration[1] + (ki + 1) * 0.1
no_fam_list.append(decomp_cost)
# plot results
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(target_list, fam_list, label="with family", marker="o")
ax.plot(target_list, no_fam_list, label="no family", marker="o")
# reverse axis
ax.invert_xaxis()
# unit axis in pi
ax.set_xticks([np.pi / 2, np.pi / 4, np.pi / 8, np.pi / 16])
ax.set_xticklabels(["$\pi/2$", "$\pi/4$", "$\pi/8$", "$\pi/16$"])
# legend
ax.legend()
# make a plot that shows E[haar] as a function of nth root of iswap for varying 1Q durations
from slam.scripts.gate_exploration.bgatev2script import build_gates
from slam.scripts.gate_exploration.bgatev2script import cost_scaling
unitary_list, coordinate_list = build_gates()
gates = unitary_list
import matplotlib.pyplot as plt
# use matplotlib scientific style
with plt.style.context(["science", "ieee"]):
plt.rcParams.update({"text.latex.preamble": r"\usepackage{amsfonts}"})
# create plot
h2_list = []
fig, ax = plt.subplots()
for duration_1q in [0, 0.1, 0.25]:
h_list = []
x_list = []
for gate in gates[1:]:
if gate.params[2] != 0: # only want to keep iswap gates
continue
h = cost_scaling(
speed_method="linear", duration_1q=duration_1q, query_params=gate.params
)[1][0]
x_list.append(gate.params[3] / (np.pi / 2))
h_list.append(h)
# tracking bare costs, but only need to do over a single 1Q duration
if duration_1q == 0:
h2 = cost_scaling(
speed_method="bare", duration_1q=0, query_params=gate.params
)[1][0]
h2_list.append(h2)
ax.plot(x_list, h_list, label=f"D[1Q]={duration_1q}", marker="o", markersize=3)
# plot h2 on a second y-axis
ax2 = ax.twinx()
ax2.plot(
x_list,
h2_list,
label=r"Gate count ($k$)",
marker="s",
markersize=3,
color="green",
)
# reverse x axis
ax.set_xlim(ax.get_xlim()[::-1])
# xaxis
ax.set_xlabel(r"\sqrt[1/x{\texttt{iSWAP}} Basis")
# yaxis
ax.set_ylabel("Expected Duration of Haar Gate")
# title
# ax.set_title(r"$\mathbb{E}$[D[Haar]]" + " vs. " + r"D[$\sqrt[1/x]{\texttt{iSwap}}]$")
# legend off plot to the right
ax.legend(loc="center left", bbox_to_anchor=(1.05, 0.63))
ax2.legend(loc="center left", bbox_to_anchor=(1.05, 0.8))
# figure size for column width of IEEE
fig.set_size_inches(3.5, 2.5)
# shrink plot to fit legend
plt.tight_layout()
plt.show()
from slam.utils.visualize import fpath_images
# save as png
fig.savefig(f"{fpath_images}/haar_vs_iswap.png", format="png")
# save matplotlib fig as pdf
fig.savefig(f"{fpath_images}/haar_vs_iswap.pdf", format="pdf")
# make a plot that shows E[haar] as a function of nth root of iswap for varying 1Q durations'
# Similar as above but we want to use family extended haar scores
from slam.utils.gates.custom_gates import ConversionGainGate
from slam.scripts.gate_exploration.bgatev2script import build_gates
from slam.scripts.gate_exploration.bgatev2script import cost_scaling
from qiskit.circuit.library import CXGate, SwapGate
from tqdm import tqdm
from qiskit.quantum_info.random import random_unitary
unitary_list, coordinate_list = build_gates()
gates = unitary_list
import matplotlib.pyplot as plt
# use matplotlib scientific style
x_list = []
fam_haar = []
no_fam_haar = []
fam_swap = []
no_fam_swap = []
fam_cx = []
no_fam_cx = []
params = [0, 0, 0, np.pi / 2]
for di, duration_1q in enumerate([0.25]):
fam_haar_inner = []
no_fam_haar_inner = []
swap_inner = []
swap_no_fam_inner = []
cnot_inner = []
cnot_no_fam_inner = []
for frac_gate in range(1, 16):
if di == 0:
x_list.append(1 / frac_gate)
basis = ConversionGainGate(*params, t_el=(1 / frac_gate))
template = MixedOrderBasisCircuitTemplate(
base_gates=[basis], chatty_build=False, use_smush_polytope=0
)
# compute the new haar score
haar_score = 0
no_fam_score = 0
duration = atomic_cost_scaling(
params + [1 / frac_gate], 1, speed_method="linear", duration_1q=0
)
target = CXGate().to_matrix()
ret = recursive_sibling_check(
template, target, cost_1q=0.1, basis_factor=duration[1]
)
cnot_inner.append(ret[1])
template = MixedOrderBasisCircuitTemplate(
base_gates=[basis], chatty_build=False, use_smush_polytope=0
)
ki = monodromy_range_from_target(template, target)[0]
decomp_cost = ki * duration[1] + (ki + 1) * 0.1
cnot_no_fam_inner.append(decomp_cost)
target = SwapGate().to_matrix()
ret = recursive_sibling_check(
template, target, cost_1q=0.1, basis_factor=duration[1]
)
swap_inner.append(ret[1])
template = MixedOrderBasisCircuitTemplate(
base_gates=[basis], chatty_build=False, use_smush_polytope=0
)
ki = monodromy_range_from_target(template, target)[0]
decomp_cost = ki * duration[1] + (ki + 1) * 0.1
swap_no_fam_inner.append(decomp_cost)
N = 2000
for target in tqdm(range(N)):
# score with family
target = random_unitary(dims=4, seed=42).data
#
ret = recursive_sibling_check(
template, target, cost_1q=0.1, basis_factor=duration[1]
)
haar_score += ret[1]
# compare to no family
template = MixedOrderBasisCircuitTemplate(
base_gates=[basis], chatty_build=False, use_smush_polytope=0
)
ki = monodromy_range_from_target(template, target)[0]
decomp_cost = ki * duration[1] + (ki + 1) * 0.1
no_fam_score += decomp_cost
fam_haar_inner.append(haar_score / N)
no_fam_haar_inner.append(no_fam_score / N)
fam_swap.append(swap_inner)
no_fam_swap.append(swap_no_fam_inner)
fam_cx.append(cnot_inner)
no_fam_cx.append(cnot_no_fam_inner)
fam_haar.append(fam_haar_inner)
no_fam_haar.append(no_fam_haar_inner)
# #tracking bare costs, but only need to do over a single 1Q duration
# if duration_1q == 0:
# h2 = cost_scaling(speed_method='bare', duration_1q=0, query_params=gate.params)[1][0]
# h2_list.append(h2)
# use ieee science style
with plt.style.context(["ieee", "science"]):
# plot the results
# make figure size smaller for column width
fig, ax = plt.subplots(figsize=(3.5, 2.5))
for di, duration_1q in enumerate([0.25]):
ax.plot(
x_list[1:],
no_fam_haar[di][1:],
label=f"E[Haar]",
marker="o",
markersize=1,
color="k",
linestyle="--",
)
ax.plot(
x_list[1:],
no_fam_swap[di][1:],
label=f"D[Swap]",
marker="o",
markersize=1,
color="b",
linestyle="--",
)
ax.plot(
x_list[1:],
no_fam_cx[di][1:],
label=f"D[CX]",
marker="o",
markersize=1,
color="r",
linestyle="--",
)
ax.plot(
x_list[1:],
fam_haar[di][1:],
label=f"E[Haar], Family-Extend",
marker="o",
markersize=1,
color="k",
linestyle="-",
)
ax.plot(
x_list[1:],
fam_swap[di][1:],
label=f"D[Swap], Family-Extend",
marker="o",
markersize=1,
color="b",
linestyle="-",
)
ax.plot(
x_list[1:],
fam_cx[di][1:],
label=f"D[CX], Family-Extend",
marker="o",
markersize=1,
color="r",
linestyle="-",
)
# legend on bottom
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.125), ncol=2, frameon=False)
# make legend text smaller
# reverse x axis
plt.xlim(plt.xlim()[::-1])
# set x axis label
ax.set_xlabel(r"$\sqrt[1/x]{iSwap}$ Fractional Basis")
# set y axis label
ax.set_ylabel("Duration Cost")
plt.show();
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Contains functions used by the basic aer simulators.
"""
from string import ascii_uppercase, ascii_lowercase
from typing import List, Optional
import numpy as np
import qiskit.circuit.library.standard_gates as gates
from qiskit.exceptions import QiskitError
# Single qubit gates supported by ``single_gate_params``.
SINGLE_QUBIT_GATES = ("U", "u1", "u2", "u3", "rz", "sx", "x")
def single_gate_matrix(gate: str, params: Optional[List[float]] = None):
"""Get the matrix for a single qubit.
Args:
gate: the single qubit gate name
params: the operation parameters op['params']
Returns:
array: A numpy array representing the matrix
Raises:
QiskitError: If a gate outside the supported set is passed in for the
``Gate`` argument.
"""
if params is None:
params = []
if gate == "U":
gc = gates.UGate
elif gate == "u3":
gc = gates.U3Gate
elif gate == "u2":
gc = gates.U2Gate
elif gate == "u1":
gc = gates.U1Gate
elif gate == "rz":
gc = gates.RZGate
elif gate == "id":
gc = gates.IGate
elif gate == "sx":
gc = gates.SXGate
elif gate == "x":
gc = gates.XGate
else:
raise QiskitError("Gate is not a valid basis gate for this simulator: %s" % gate)
return gc(*params).to_matrix()
# Cache CX matrix as no parameters.
_CX_MATRIX = gates.CXGate().to_matrix()
def cx_gate_matrix():
"""Get the matrix for a controlled-NOT gate."""
return np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]], dtype=complex)
def einsum_matmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.einsum matrix-matrix multiplication.
The returned indices are to perform a matrix multiplication A.B where
the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and
M <= N, and identity matrices are implied on the subsystems where A has no
support on B.
Args:
gate_indices (list[int]): the indices of the right matrix subsystems
to contract with the left matrix.
number_of_qubits (int): the total number of qubits for the right matrix.
Returns:
str: An indices string for the Numpy.einsum function.
"""
mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits)
# Right indices for the N-qubit input and output tensor
tens_r = ascii_uppercase[:number_of_qubits]
# Combine indices into matrix multiplication string format
# for numpy.einsum function
return "{mat_l}{mat_r}, ".format(
mat_l=mat_l, mat_r=mat_r
) + "{tens_lin}{tens_r}->{tens_lout}{tens_r}".format(
tens_lin=tens_lin, tens_lout=tens_lout, tens_r=tens_r
)
def einsum_vecmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.einsum matrix-vector multiplication.
The returned indices are to perform a matrix multiplication A.v where
the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and
M <= N, and identity matrices are implied on the subsystems where A has no
support on v.
Args:
gate_indices (list[int]): the indices of the right matrix subsystems
to contract with the left matrix.
number_of_qubits (int): the total number of qubits for the right matrix.
Returns:
str: An indices string for the Numpy.einsum function.
"""
mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits)
# Combine indices into matrix multiplication string format
# for numpy.einsum function
return f"{mat_l}{mat_r}, " + "{tens_lin}->{tens_lout}".format(
tens_lin=tens_lin, tens_lout=tens_lout
)
def _einsum_matmul_index_helper(gate_indices, number_of_qubits):
"""Return the index string for Numpy.einsum matrix multiplication.
The returned indices are to perform a matrix multiplication A.v where
the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and
M <= N, and identity matrices are implied on the subsystems where A has no
support on v.
Args:
gate_indices (list[int]): the indices of the right matrix subsystems
to contract with the left matrix.
number_of_qubits (int): the total number of qubits for the right matrix.
Returns:
tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for
that may be combined into a Numpy.einsum function string.
Raises:
QiskitError: if the total number of qubits plus the number of
contracted indices is greater than 26.
"""
# Since we use ASCII alphabet for einsum index labels we are limited
# to 26 total free left (lowercase) and 26 right (uppercase) indexes.
# The rank of the contracted tensor reduces this as we need to use that
# many characters for the contracted indices
if len(gate_indices) + number_of_qubits > 26:
raise QiskitError("Total number of free indexes limited to 26")
# Indices for N-qubit input tensor
tens_in = ascii_lowercase[:number_of_qubits]
# Indices for the N-qubit output tensor
tens_out = list(tens_in)
# Left and right indices for the M-qubit multiplying tensor
mat_left = ""
mat_right = ""
# Update left indices for mat and output
for pos, idx in enumerate(reversed(gate_indices)):
mat_left += ascii_lowercase[-1 - pos]
mat_right += tens_in[-1 - idx]
tens_out[-1 - idx] = ascii_lowercase[-1 - pos]
tens_out = "".join(tens_out)
# Combine indices into matrix multiplication string format
# for numpy.einsum function
return mat_left, mat_right, tens_in, tens_out
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open(filename, "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for uniformly controlled Rx,Ry and Rz gates"""
import itertools
import unittest
import numpy as np
from scipy.linalg import block_diag
from qiskit import BasicAer, QuantumCircuit, QuantumRegister, execute
from qiskit.test import QiskitTestCase
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.compiler import transpile
angles_list = [
[0],
[0.4],
[0, 0],
[0, 0.8],
[0, 0, 1, 1],
[0, 1, 0.5, 1],
(2 * np.pi * np.random.rand(2**3)).tolist(),
(2 * np.pi * np.random.rand(2**4)).tolist(),
(2 * np.pi * np.random.rand(2**5)).tolist(),
]
rot_axis_list = ["X", "Y", "Z"]
class TestUCRXYZ(QiskitTestCase):
"""Qiskit tests for UCRXGate, UCRYGate and UCRZGate rotations gates."""
def test_ucy(self):
"""Test the decomposition of uniformly controlled rotations."""
for angles, rot_axis in itertools.product(angles_list, rot_axis_list):
with self.subTest(angles=angles, rot_axis=rot_axis):
num_contr = int(np.log2(len(angles)))
q = QuantumRegister(num_contr + 1)
qc = QuantumCircuit(q)
if rot_axis == "X":
qc.ucrx(angles, q[1 : num_contr + 1], q[0])
elif rot_axis == "Y":
qc.ucry(angles, q[1 : num_contr + 1], q[0])
else:
qc.ucrz(angles, q[1 : num_contr + 1], q[0])
# Decompose the gate
qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"])
# Simulate the decomposed gate
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
unitary_desired = _get_ucr_matrix(angles, rot_axis)
self.assertTrue(matrix_equal(unitary_desired, unitary, ignore_phase=True))
def _get_ucr_matrix(angles, rot_axis):
if rot_axis == "X":
gates = [
np.array(
[
[np.cos(angle / 2), -1j * np.sin(angle / 2)],
[-1j * np.sin(angle / 2), np.cos(angle / 2)],
]
)
for angle in angles
]
elif rot_axis == "Y":
gates = [
np.array(
[[np.cos(angle / 2), -np.sin(angle / 2)], [np.sin(angle / 2), np.cos(angle / 2)]]
)
for angle in angles
]
else:
gates = [
np.array([[np.exp(-1.0j * angle / 2), 0], [0, np.exp(1.0j * angle / 2)]])
for angle in angles
]
return block_diag(*gates)
if __name__ == "__main__":
unittest.main()
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
### removed x gate ###
pass
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
%matplotlib inline
from qiskit import *
from qiskit.visualization import *
from qiskit.tools.monitor import *
import numpy as np
def init_grover(q):
circ = QuantumCircuit(q)
n = len(q)
circ.x(n-1) # The qubit that receives the oracle output must be set to |1>
for i in range(n):
circ.h(q[i])
circ.barrier()
return circ
def difussion(q):
circ = QuantumCircuit(q)
# Diffusion operator
n = len(q)
for i in range(n-1):
circ.h(q[i])
for i in range(n-1):
circ.x(q[i])
# To implement a multicontrolled Z we use a multicontrolled Z rotation
mcz = QuantumCircuit(q, name = 'cZ')
if(n>2):
mcz.mcrz(np.pi,q[0:n-2],q[n-2])
else:
mcz.z(q[0]) # If there is only input qubit for the oracle, we don't have controls
circ.append(mcz.to_instruction(),q)
for i in range(n-1):
circ.x(q[i])
for i in range(n-1):
circ.h(q[i])
circ.barrier()
return circ
def ones(q):
# We will use a multicontrolled X gate
circ = QuantumCircuit(q)
n = len(q)
circ.mcx(q[0:n-1],q[n-1])
return circ
def grover(n, oracle, it = 10, measurement = True):
q = QuantumRegister(n, name = 'q') # We create the quantum register
if(measurement):
c = ClassicalRegister(n-1,name='c') # We are only going to measure the qubits that are the input to the oracle
circ = QuantumCircuit(q,c) # We create the circuit
else:
circ = QuantumCircuit(q) # Circuit without measurements
circ += init_grover(q) # We add the initial part
for _ in range(it): # We add it repetitions of the oracle plus the diffusion operator
circ += oracle(q)
circ += difussion(q)
if(measurement): # Measurements
circ.measure(q[0:n-1],c)
return circ
n = 3
circ_grover = grover(n,ones,1)
circ_grover.draw(output = 'mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(circ_grover, backend)
counts = job.result().get_counts()
print(counts)
import matplotlib.pyplot as plt
n = 5
max_it = 20
shots = 1000
backend = Aer.get_backend('qasm_simulator')
target=(n-1)*'1' # The marked element as a string, to retrieve its probability
prob = [0.0 for _ in range(max_it+1)]
for it in range(max_it+1):
circ_grover2 = grover(n,ones,it)
job = execute(circ_grover2, backend, shots = shots)
counts = job.result().get_counts()
if target in counts.keys():
prob[it]=counts[target]/shots
else:
prob[it] = 0 # Element not found
iter = range(max_it+1)
plt.xlabel('Iterations')
plt.ylabel('Probability')
plt.plot(iter,prob)
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can make the bars more transparent to better see the ones that are behind
# if they overlap.
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
state = Statevector(qc)
plot_state_city(state, alpha=0.6)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test boolean expression."""
import unittest
from os import path
from ddt import ddt, unpack, data
from qiskit.test.base import QiskitTestCase
from qiskit import execute, BasicAer
from qiskit.utils.optionals import HAS_TWEEDLEDUM
if HAS_TWEEDLEDUM:
from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
@ddt
class TestBooleanExpression(QiskitTestCase):
"""Test boolean expression."""
@data(
("x | x", "1", True),
("x & x", "0", False),
("(x0 & x1 | ~x2) ^ x4", "0110", False),
("xx & xxx | ( ~z ^ zz)", "0111", True),
)
@unpack
def test_evaluate(self, expression, input_bitstring, expected):
"""Test simulate"""
expression = BooleanExpression(expression)
result = expression.simulate(input_bitstring)
self.assertEqual(result, expected)
@data(
("x", False),
("not x", True),
("(x0 & x1 | ~x2) ^ x4", True),
("xx & xxx | ( ~z ^ zz)", True),
)
@unpack
def test_synth(self, expression, expected):
"""Test synth"""
expression = BooleanExpression(expression)
expr_circ = expression.synth()
new_creg = expr_circ._create_creg(1, "c")
expr_circ.add_register(new_creg)
expr_circ.measure(expression.num_qubits - 1, new_creg)
[result] = (
execute(
expr_circ,
backend=BasicAer.get_backend("qasm_simulator"),
shots=1,
seed_simulator=14,
)
.result()
.get_counts()
.keys()
)
self.assertEqual(bool(int(result)), expected)
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
class TestBooleanExpressionDIMACS(QiskitTestCase):
"""Loading from a cnf file"""
def normalize_filenames(self, filename):
"""Given a filename, returns the directory in terms of __file__."""
dirname = path.dirname(__file__)
return path.join(dirname, filename)
def test_simple(self):
"""Loads simple_v3_c2.cnf and simulate"""
filename = self.normalize_filenames("dimacs/simple_v3_c2.cnf")
simple = BooleanExpression.from_dimacs_file(filename)
self.assertEqual(simple.name, "simple_v3_c2.cnf")
self.assertEqual(simple.num_qubits, 4)
self.assertTrue(simple.simulate("101"))
def test_quinn(self):
"""Loads quinn.cnf and simulate"""
filename = self.normalize_filenames("dimacs/quinn.cnf")
simple = BooleanExpression.from_dimacs_file(filename)
self.assertEqual(simple.name, "quinn.cnf")
self.assertEqual(simple.num_qubits, 16)
self.assertFalse(simple.simulate("1010101010101010"))
if __name__ == "__main__":
unittest.main()
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from typing import Tuple
import numpy as np
import qiskit
from qiskit.circuit import Parameter
from dc_qiskit_algorithms import MöttönenStatePreparationGate
from dc_qiskit_algorithms import ControlledStatePreparationGate
from scipy import sparse
from .discrete_stochastic_process import DiscreteStochasticProcess
from .dsp_common import apply_level
LOG = logging.getLogger(__name__)
def _index_prep_level_0(probabilities: np.ndarray, **kwargs) -> qiskit.QuantumCircuit:
"""
The function adds an index register of appropriate size and uses the state preparation by Möttönen et al.
> Möttönen, Mikko, et al. "Transformation of quantum states using uniformly controlled rotations."
> Quantum Information & Computation 5.6 (2005): 467-473.
:param level: The level for register naming purposes
:param probabilities: the probabilities for this level
:return: the quantum circuit with the state preparation for the index
"""
_, m = probabilities.shape
qubits_target = int(np.ceil(np.log2(m)))
# check if we have a probability density
assert probabilities.shape[0] == 1
assert np.linalg.norm(np.sum(probabilities) - 1) < 1e-6, "The vector's entries must sum to 1"
qc = qiskit.QuantumCircuit(name='index_state_prep')
qreg_current = qiskit.QuantumRegister(qubits_target, f'level_0')
qc.add_register(qreg_current)
# Möttönen State-prep with row
amplitudes = np.sqrt(probabilities)
vector = sparse.dok_matrix(amplitudes).transpose()
gate = MöttönenStatePreparationGate(vector, neglect_absolute_value=False)
qc.append(gate, list(qreg_current), [])
return qc
def _index_prep(level: int, probabilities: np.ndarray, with_debug_circuit: bool = False, **kwargs) -> qiskit.QuantumCircuit:
"""
The function adds an index register of appropriate size and uses the state preparation by Möttönen et al.
> Möttönen, Mikko, et al. "Transformation of quantum states using uniformly controlled rotations."
> Quantum Information & Computation 5.6 (2005): 467-473.
:param level: The level for register naming purposes
:param probabilities: the probabilities for this level
:return: the quantum circuit with the state preparation for the index
"""
assert level > 0, "This call is only for the level 1, and beyond."
n, m = probabilities.shape
qubits_source = int(np.ceil(np.log2(n)))
qubits_target = int(np.ceil(np.log2(m)))
# check if we have a stochastic matrix
# assert np.linalg.norm(np.sum(probabilities, axis=0) - 1) < 1e-6, "The probability matrix must be a stochastic matrix"
assert np.linalg.norm(np.sum(probabilities, axis=1) - 1) < 1e-6, "The probability matrix must be a stochastic matrix"
qc = qiskit.QuantumCircuit(name='index_state_prep')
qreg_last = qiskit.QuantumRegister(qubits_source, f'level_{level - 1}')
qreg_current = qiskit.QuantumRegister(qubits_target, f'level_{level}')
qc.add_register(qreg_last)
qc.add_register(qreg_current)
# Möttönen State-prep with row
amplitudes = probabilities ** 0.5
matrix = sparse.dok_matrix(amplitudes)
gate = ControlledStatePreparationGate(matrix)
if with_debug_circuit:
from qiskit import QuantumCircuit
qc_def: QuantumCircuit = gate.definition
qc = qc.compose(qc_def, qubits=list(qreg_last) + list(qreg_current))
else:
qc.append(gate, list(qreg_last) + list(qreg_current), [])
return qc
def _index(level, probabilities, **kwargs):
# Deliver the index register which encodes the joint probability of realizations
# Given the initial value, select the row that is encoding the first step
level_probabilities = np.asarray(probabilities)
if level == 0:
return _index_prep_level_0(level_probabilities, **kwargs)
else:
return _index_prep(level, level_probabilities, **kwargs)
def _level(level, realizations, scaling, **kwargs):
# Deliver the index register which encodes the joint probability of realizations
# Given the initial value, select the row that is encoding the first step
return apply_level(level, realizations, scaling, **kwargs)
class StateMachineDSP(DiscreteStochasticProcess):
def __init__(self, initial_value: float, probabilities: np.ndarray, realizations: np.ndarray):
# FIXME: this is wrong, find assertions that reflect this situation
# assert probabilities.shape == realizations.shape
_probabilities = np.asarray([np.asarray(p) for p in probabilities])
_realizations = np.asarray([np.asarray(r) for r in realizations])
super().__init__(initial_value, _probabilities, _realizations)
last_target_states = -1
for step in range(self.length):
source_states, target_states = self.number_of_states(step)
if last_target_states != -1:
assert source_states == last_target_states
last_target_states = target_states
@property
def length(self):
return self.probabilities.shape[0]
def number_of_states(self, step: int) -> Tuple[int, ...]:
return np.asarray(self.probabilities[step]).shape
def get_level_transition_matrix(self, level: int) -> np.ndarray:
return self.probabilities[level]
def _proposition_one_circuit(self, scaling: Parameter, level_func=None, index_state_prep=None, **kwargs):
index_state_prep = _index if index_state_prep is None else index_state_prep
level_func = _level if level_func is None else level_func
return super(StateMachineDSP, self)._proposition_one_circuit(scaling, level_func, index_state_prep, **kwargs)
#
# def benchmark(self, evaluations: Union[List[float], np.ndarray, scipy.sparse.dok_matrix],
# func=None, samples: int = 100) -> Union[NDArray[complex], np.ndarray]:
# return benchmark_monte_carlo(
# probabilities=self.probabilities,
# realizations=self.realizations,
# evaluations=evaluations,
# initial_value=self.initial_value,
# samples=samples,
# func=func
# )
|
https://github.com/joe5218/Quantum-Distortions
|
joe5218
|
!pip install qiskit ipywidgets pylatexenc python-resize-image qiskit[visualization]
from qiskit import IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, QuantumRegister
from qiskit.qasm import pi
from qiskit.tools.visualization import plot_histogram, circuit_drawer, plot_state_city
from qiskit import execute, Aer, BasicAer, transpile
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from resizeimage import resizeimage
import random
import frqi
import qiskit.quantum_info as qi
import math
# Quantum Fourier Transform
def qft_rotations(circuit, n):
if n == 0: # Exit function if circuit is empty
return circuit
n -= 1 # Indexes start from 0
circuit.h(n) # Apply the H-gate to the most significant qubit
for qubit in range(n):
# For each less significant qubit, we need to do a
# smaller-angled controlled rotation:
circuit.cp(pi/2**(n-qubit), qubit, n)
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
"""QFT on the first n qubits in circuit"""
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
# Inverse Quantum Fourier Transform
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)
anc = QuantumRegister(1, "anc")
img = QuantumRegister(11, "img")
anc2 = QuantumRegister(1, "anc2")
c = ClassicalRegister(12)
qc = QuantumCircuit(anc, img, anc2, c)
imageNames = ["1.jpg", "2.jpg", "3.jpg"]
imageNum1 = 0
imageNum2 = 2
image1 = Image.open(imageNames[imageNum1]).convert('LA')
image2 = Image.open(imageNames[imageNum2]).convert('LA')
def image_normalization(image):
image = resizeimage.resize_cover(image, [32, 32])
w, h = 32, 32
image = np.array([[image.getpixel((x,y))[0] for x in range(w)] for y in range(h)])
# 2-dimensional data convert to 1-dimensional array
image = image.flatten()
# change type
image = image.astype('float64')
# Normalization(0~pi/2)
image /= 255.0
generated_image = np.arcsin(image)
return generated_image
image1 = image_normalization(image1)
image2 = image_normalization(image2)
# apply hadamard gates
for i in range(1, len(img)):
qc.h(img[i])
# encode ref image
for i in range(len(image1)):
if image1[i] != 0:
frqi.c10ry(qc, 2 * image1[i], format(i, '010b'), img[0], anc2[0], [img[j] for j in range(1,len(img))])
# TRANSFORMATION 1: Quantum Fourier Transform
qft(qc, len(img))
# DECRYPTION FOR 1: Inverse Quantum Fourier Transform
qft_dagger(qc, len(img))
# TRANSFORMATION 2: Rotation in Frequency Space
qft(qc, len(img))
# random.random() * 2 * math.pi
angle = 0.1
for i in range(len(img)):
qc.rx(angle, i)
qft_dagger(qc, len(img))
# TRANSFORMATION 3 : Randomized Angle on Each Qubit Transform (like an encryption algorithm)
angleArr = []
for i in range(len(img)):
angle = random.random() * 2 * math.pi
angleArr.append(angle)
qc.rx(angle, i)
# DECRYPTION FOR 3: Randomized Angle on Each Qubit Transform (like an encryption algorithm)
for i in range(len(img)):
qc.rx(-angleArr[i], i)
# TRANSFORMATION 4 : Uniform Random Rotation on all Qbits
angle = random.random() * 2 * math.pi
for i in range(len(img)):
qc.rx(angle, i)
qc.measure(anc, c[0])
qc.measure(img, c[1:12])
print(qc.depth())
numOfShots = 8192
result = execute(qc, Aer.get_backend('qasm_simulator'), shots=numOfShots, backend_options={"fusion_enable":True}).result()
#circuit_drawer(qc).show()
#plot_histogram(result.get_counts(qc))
print(result.get_counts(qc))
# generated image
genimg = np.array([])
#### decode
for i in range(len(image1)):
try:
genimg = np.append(genimg,[np.sqrt(result.get_counts(qc)[format(i, '010b')+'10']/numOfShots)])
except KeyError:
genimg = np.append(genimg,[0.0])
# inverse nomalization
genimg *= 32.0 * 255.0
# convert type
genimg = genimg.astype('int')
# back to 2-dimensional data
genimg = genimg.reshape((32,32))
plt.imshow(genimg, cmap='gray', vmin=0, vmax=255)
plt.savefig('gen_'+str(imageNum1)+'.png')
plt.show()
|
https://github.com/sooodos/Quantum-Computing-Learning-Gate
|
sooodos
|
from qiskit import execute, Aer, QuantumCircuit
class Interference:
@classmethod
def run(cls):
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(1, 1)
# Add a H gate on qubit 0
circuit.h(0)
# Add another H gate to qubit 0
circuit.h(0)
# Map the quantum measurement to the classical bits
circuit.measure(0, 0)
# Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(circuit)
print("Results for the Quantum Interference experiment.")
print("\nTotal count for 0 and 1 are:", counts)
print(circuit)
|
https://github.com/KathrinKoenig/QuantumTopologicalDataAnalysis
|
KathrinKoenig
|
import numpy as np
import qtda_module as qtda
from qiskit.visualization import plot_histogram
point_data = np.array([
[0.,0.],
[1.,0.],
[1.,1.],
[0.,1.],
])
# alternatively a distance matrix (here generated from the point data for exemplification)
# can be used
from scipy.spatial import distance_matrix
dist_mat = distance_matrix(point_data, point_data)
filtration = qtda.DataFiltration(
data=point_data,
# distance_matrix=dist_mat,
max_dimension=3,
max_edge_length=2
)
filtration.plot_persistence_diagram()
shots = 1000
num_eval_qubits = 10
# epsilons = [0.1, 1.1, 1.5]
data = qtda.Q_persistent_top_spectra(
data = point_data,
# distance_matrix=distance_matrix,
max_dimension=3,
max_edge_length=2,
num_eval_qubits=num_eval_qubits,
shots=shots)
eigenvalue_dict = data.get_eigenvalues()
for eps in eigenvalue_dict.keys():
print()
print()
print('Filtration scale: ', eps)
for top_order in eigenvalue_dict[eps].keys():
print()
print('Topological order: ', top_order)
print('Number of holes: ', eigenvalue_dict[eps][top_order][0.0])
print('Dimension of the k-simplex subspace: ', len(data.state_dict[eps][top_order]))
print('Eigenvalues of the combinatorial laplacian with dimension of corresponding eigenspaces: ')
print(eigenvalue_dict[eps][top_order])
display(plot_histogram(data.get_counts()[eps][top_order]))
import qiskit
qiskit.__qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
config = backend.configuration()
# Basic Features
print("This backend is called {0}, and is on version {1}. It has {2} qubit{3}. It "
"{4} OpenPulse programs. The basis gates supported on this device are {5}."
"".format(config.backend_name,
config.backend_version,
config.n_qubits,
'' if config.n_qubits == 1 else 's',
'supports' if config.open_pulse else 'does not support',
config.basis_gates))
config.dt # units of seconds
config.meas_levels
config.dtm
config.meas_map
config.drive(0)
config.measure(0)
config.acquire(0)
props = backend.properties()
def describe_qubit(qubit, properties):
"""Print a string describing some of reported properties of the given qubit."""
# Conversion factors from standard SI units
us = 1e6
ns = 1e9
GHz = 1e-9
print("Qubit {0} has a \n"
" - T1 time of {1} microseconds\n"
" - T2 time of {2} microseconds\n"
" - U2 gate error of {3}\n"
" - U2 gate duration of {4} nanoseconds\n"
" - resonant frequency of {5} GHz".format(
qubit,
properties.t1(qubit) * us,
properties.t2(qubit) * us,
properties.gate_error('sx', qubit),
properties.gate_length('sx', qubit) * ns,
properties.frequency(qubit) * GHz))
describe_qubit(0, props)
defaults = backend.defaults()
q0_freq = defaults.qubit_freq_est[0] # Hz
q0_meas_freq = defaults.meas_freq_est[0] # Hz
GHz = 1e-9
print("DriveChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_freq * GHz))
print("MeasureChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_meas_freq * GHz))
calibrations = defaults.instruction_schedule_map
print(calibrations)
measure_schedule = calibrations.get('measure', range(config.n_qubits))
measure_schedule.draw(backend=backend)
# You can use `has` to see if an operation is defined. Ex: Does qubit 3 have an x gate defined?
calibrations.has('x', 3)
# Some circuit operations take parameters. U1 takes a rotation angle:
calibrations.get('u1', 0, P0=3.1415)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXDebugging(), backend=FakeBoeblingen())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.