repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0)
plot_circuit_layout(new_circ_lv0, backend)
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
from qiskit import *
import matplotlib.pyplot as plt
from channel_class import Channel
#Bob Part
circ_bob = QuantumCircuit(3)
bob_channel = Channel(myport = 5001, remote_port = 5000)
#circ_bob.h(0)
#circ_bob.draw(output='mpl','test.png')
circ_bob, offset = bob_channel.receive(circ_bob)#,to_tpc)
# Add new gates to circ2
circ_bob.x(0+offset)
#circ_bob.cx(0+offset, 1+offset)
#psi2 = Statevector.from_instruction(circ_bob)
import time
time.sleep(2)
to_tpc = bob_channel.send(circ_bob,[1])
circ_bob.draw()
|
https://github.com/DuarteSerranoR/qiskit_quantum_algorithms
|
DuarteSerranoR
|
from qiskit import *
from qiskit.extensions import *
from qiskit.tools.visualization import *
def NAND(inp1,inp2):
"""An NAND gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output NAND circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum NAND gate goes
qc.ccx(0,1,2) # Toffoli gate
qc.x(2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('aer_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc,shots=1,memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = NAND(inp1, inp2)
print('NAND with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
import json
import csv
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SHOTS = 10000
UNIFORM_CONVERGENCE_SAMPLE = []
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def tsp_obj(x, G):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, LAMBDA)
cost = 0
# z term
for index in range(len(x)):
z = (int(x[index]) * 2 ) -1
cost += z_classic_term[index] * z
## zz term
for i in range(len(x)):
z_1 = (int(x[i]) * 2 ) -1
for j in range(len(x)):
z_2 = (int(x[j]) * 2 ) -1
cost += zz_classic_term[i][j] * z_1 * z_1
return cost
# Sample expectation value
def compute_tsp_energy(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj(meas, G)
energy += obj_for_meas*meas_count
total_counts += meas_count
return energy/total_counts
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_black_box_objective(G,p):
backend = Aer.get_backend('qasm_simulator')
def f(theta):
beta = theta[:p]
gamma = theta[p:]
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
counts = execute(qc, backend, seed_simulator=10, shots=SHOTS).result().get_counts()
return compute_tsp_energy(invert_counts(counts),G)
return f
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
def f(theta):
beta = theta[:p]
gamma = theta[p:]
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=10, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
global UNIFORM_CONVERGENCE_SAMPLE
UNIFORM_CONVERGENCE_SAMPLE.append({
"beta" : beta,
"gamma" : gamma,
"counts" : counts,
"mean" : mean,
"probabilities" : probabilities,
"expected_value" : expected_value
})
return mean
return f
def compute_tsp_min_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
min = 1000000000000000000000
index = 0
min_meas = ""
for meas, meas_count in counts.items():
index = index + 1
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
if obj_for_meas < min:
min = obj_for_meas
min_meas = meas
return index, min, min_meas
def compute_tsp_min_energy_1(counts, G):
energy = 0
get_counts = 0
total_counts = 0
min = 1000000000000000000000
index = 0
min_meas = ""
for meas, meas_count in counts.items():
index = index + 1
obj_for_meas = tsp_obj(meas, G)
if obj_for_meas < min:
min = obj_for_meas
min_meas = meas
return index, min, min_meas
def test_counts_2(counts, G):
mean_energy2 = compute_tsp_energy_2(invert_counts(counts),G)
cantidad, min, min_meas = compute_tsp_min_energy_2(invert_counts(counts),G)
print("*************************")
print("En el algoritmo 2 (Marina) el valor esperado como resultado es " + str(mean_energy2))
print("El valor minimo de todos los evaluados es " + str(min) + " se evaluaron un total de " + str(cantidad))
print("El vector minimo es " + min_meas)
def test_counts_1(counts, G):
mean_energy1 = compute_tsp_energy(invert_counts(counts),G)
cantidad, min, min_meas = compute_tsp_min_energy_1(invert_counts(counts),G)
print("*************************")
print("En el algoritmo 1 (Pablo) el valor esperado como resultado es " + str(mean_energy1))
print("El valor minimo de todos los evaluados es " + str(min) + " se evaluaron un total de " + str(cantidad))
print("El vector minimo es " + min_meas)
def test_solution(grafo=None, p=7):
global UNIFORM_CONVERGENCE_SAMPLE
UNIFORM_CONVERGENCE_SAMPLE = []
if grafo == None:
cantidad_ciudades = 2
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
print(mejor_costo)
print(mejor_camino)
print(G.edges())
print(G.nodes())
else:
G = grafo
bounds = []
intial_random = []
for i in range(p):
bounds.append((0, np.pi))
intial_random.append(np.random.uniform(0,np.pi))
for i in range(p):
bounds.append((0, np.pi * 2))
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
# Marina Solutions
obj = get_black_box_objective_2(G,p)
res_sample_2 = minimize(obj, init_point, method="COBYLA", options={"maxiter":2500,"disp":True})
theta_2 = res_sample_2.x
beta = theta_2[:p]
gamma = theta_2[p:]
_lambda = LAMBDA
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
backend = Aer.get_backend('qasm_simulator')
job_2 = execute(qc, backend, shots = SHOTS)
resutls_2 = job_2.result().get_counts()
test_counts_2(resutls_2, G)
return job_2, G, UNIFORM_CONVERGENCE_SAMPLE
def create_multiple_p_mismo_grafo():
header = ['p', 'state', 'probability', 'mean']
length_p = 10
with open('qaoa_multiple_p.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
writer.writerow(header)
first_p = False
uniform_convergence_sample = []
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])
def create_multiple_p_mismo_grafo_multiples_instanncias():
header = ['instance','p','distance', 'mean']
length_p = 4
length_instances = 10
with open('qaoa_multiple_p_distance.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
writer.writerow(header)
instance_index = 0
for instance in range(length_instances):
instance_index += 1
first_p = False
UNIFORM_CONVERGENCE_P = []
uniform_convergence_sample = []
for p in range(length_p):
p = p+1
print("p es igual " + str(p))
if first_p == False:
print("Vuelve a llamar a test_solution")
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["expected_value"])
convergence_min = uniform_convergence_sample[0]
UNIFORM_CONVERGENCE_P.append({
"mean":convergence_min["expected_value"],
"probabilities": convergence_min["probabilities"]
})
cauchy_function_nk = UNIFORM_CONVERGENCE_P[len(UNIFORM_CONVERGENCE_P) - 1]
p_index = 0
for p_state in UNIFORM_CONVERGENCE_P:
p_index += 1
print(p_index)
mean = p_state["mean"]
distance_p_cauchy_function_nk = np.max(np.abs(cauchy_function_nk["probabilities"] - p_state["probabilities"]))
writer.writerow([instance_index, p_index, distance_p_cauchy_function_nk, mean])
if __name__ == '__main__':
create_multiple_p_mismo_grafo_multiples_instanncias()
def defult_init():
cantidad_ciudades = 2
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
print(mejor_costo)
print(mejor_camino)
print(G.edges())
print(G.nodes())
print("labels")
labels = nx.get_edge_attributes(G,'weight')
p = 5
obj = get_black_box_objective(G,p)
init_point = np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1])
# Marina Solutions
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
theta_2 = [0.72685401, 2.15678239, 0.86389827, 2.19403121, 0.26916675, 2.19832144, 7.06651453, 3.20333137, 3.81301611, 6.08893568]
theta_1 = [0.90644898, 2.15994212, 1.8609325 , 2.14042604, 1.49126214, 2.4127999, 6.10529434, 2.18238732, 3.84056674, 6.07097744]
beta = theta_1[:p]
gamma = theta_1[p:]
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend)
beta = theta_2[:p]
gamma = theta_2[p:]
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend)
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import QuantumCircuit, Aer,execute, IBMQ
from qiskit.visualization import plot_histogram
## Sample Program: Bell Circuit
qc=QuantumCircuit(2,2) # 2 qubits and 2 classical bits
qc.h(0)
qc.cx(0,1)
qc.draw(output="mpl")
qc.measure([0,1],[0,1])
qc.draw(output="mpl")
backend=Aer.get_backend('qasm_simulator')
job=execute(qc,backend,shots=1024)
result=job.result()
counts=result.get_counts()
print(counts)
plot_histogram(counts,title="Bell State without noise")
#Load the account
provider=IBMQ.load_account()
#List all the available backends for the account
#provider.backends()
#Get the backend
backend=provider.get_backend('ibmq_bogota')
#Execute the circuit on the backend
job=execute(qc,backend,shots=1024)
#job.cancel()
job.status()
from qiskit.tools import job_monitor
job_monitor(job)
job.status()
result=job.result()
counts=result.get_counts()
print(counts)
plot_histogram(counts,title="Bell State with noise")
job.job_id()
from qiskit.compiler import transpile
backend=provider.get_backend('ibmq_qasm_simulator')
transpile_circuit=transpile(qc,backend)
transpile_circuit.draw(output="mpl")
from qiskit.compiler import transpile,assemble
backend=provider.get_backend('ibmq_bogota')
transpile_circuit=transpile(qc,backend)
transpile_circuit.draw(output="mpl")
backend.configuration().basis_gates
backend=provider.get_backend('ibmq_bogota')
transpile_circuit=transpile(qc,backend)
job=backend.run(transpile_circuit)
job.status()
job_monitor(job)
result=job.result()
counts=result.get_counts()
print(counts)
plot_histogram(counts)
|
https://github.com/PKXH/quantum-algorithms
|
PKXH
|
from random import randint,sample
def get_random_bitstring(sz):
return [randint(0,1) for i in range(sz)]
from qiskit import (QuantumCircuit, execute, Aer)
default_backend = Aer.get_backend('qasm_simulator')
X_BASIS = 0
Z_BASIS = 1
def encode_key_bit(qbit, tx_bit, tx_base):
'''
Append encoding of the specified classical bit 'tx_bit' into the specified
base 'tx_base' to the quantum circuit
'''
# flip the quantum 0 to quantum 1 if we received a '1' bit; otherwise leave
# it as a quantum 0.
if tx_bit:
qbit.x(0)
# if we're transmitting using the x-basis, then leave it in the x-basis;
# otherwise flip the qubit into the z-basis
if tx_base == Z_BASIS:
qbit.h(0)
return qbit
def decode_key_bit(qbit, rx_base):
'''
Append measurement of the specified qubit 'qbit' in the specified base 'rx_base'
to the quantum circuit
'''
# flip the qubit if we're measureing in the Z_BASIS so if the qubit
# is originally in the X_BASIS, it will not be in superposition. Then
# go ahead and measure it.
if rx_base == Z_BASIS:
qbit.h(0)
qbit.measure([0],[0])
return qbit
datum = 1
tx_base = 1
rx_base = 1
test_qc = QuantumCircuit(1,1)
test_qc = encode_key_bit(test_qc,datum,tx_base)
test_qc.barrier(0)
test_qc = decode_key_bit(test_qc,rx_base)
test_qc.draw('mpl')
num_bits = 32
# set up Alice's transmission bits
random_tx_bits = get_random_bitstring(num_bits)
random_tx_bases = get_random_bitstring(num_bits)
# set up Bob's receiving bits
random_rx_bases = get_random_bitstring(num_bits)
decoded_rx_bits = []
class SharedChannel:
def __init__(self):
self.datum = None
self.active = False
def transmit_datum(self, datum):
self.datum = datum
self.active = True
def receive_datum(self):
return_datum = self.datum
self.active = False
self.datum = []
return return_datum
class SharedQuantumChannel(SharedChannel):
def __init__(self):
super().__init__()
class SharedClassicalChannel(SharedChannel):
def __init__(self):
super().__init__()
def transmit_data(self, datum):
super().transmit_datum(datum)
def receive_data(self):
return super().receive_datum()
# create shared quantum and classical channels that Alice and Bob will
# use to communicate to each other
sqc = SharedQuantumChannel()
scc = SharedClassicalChannel()
scc.transmit_datum('1')
print(scc.receive_datum())
# Clear decoded bits list and transmit the qbits one by one until the
# receiver has measured every one
decoded_rx_bits = []
for i in range(num_bits):
# create a qubit, encode it, transmit it, receive it,
# and decode it
qbit = QuantumCircuit(1,1)
tx_qbit = encode_key_bit(qbit, random_tx_bits[i], random_tx_bases[i])
sqc.transmit_datum(tx_qbit)
rx_qbit = sqc.receive_datum()
full_circuit = decode_key_bit(rx_qbit, random_rx_bases[i])
job = execute(full_circuit, backend=default_backend, shots=1)
results = job.result()
counts = results.get_counts()
decoded_rx_bits.append(int(max(counts, key=counts.get)))
# decoder reports rx bases to transmitter
scc.transmit_data(random_rx_bases)
rx_bases_used = scc.receive_data()
# sender determines which random rx bases were right
assert(len(rx_bases_used) == len(random_tx_bits))
rx_base_hits = [rx_bases_used[i] == random_tx_bases[i] for i in range(len(random_tx_bits))]
# sender notifies receiver of key hits
scc.transmit_data(rx_base_hits)
rcvd_rx_base_hits = scc.receive_data()
# sender and receiver drop non-hit key bits
sender_key_candidate = [j for i,j in enumerate(random_tx_bits) if rx_base_hits[i]]
receiver_key_candidate = [j for i,j in enumerate(decoded_rx_bits) if rcvd_rx_base_hits[i]]
assert(sender_key_candidate == receiver_key_candidate)
# the receiver chooses some verification bits (1/4th of the decoded key bits)
num_verify_bits = len(receiver_key_candidate)//4
verify_bits_ix = sample(range(len(receiver_key_candidate)), num_verify_bits)
verify_bits = {i:receiver_key_candidate[i] for i in verify_bits_ix}
# the receiver shares verification bits with sender
scc.transmit_data(verify_bits)
chk_verify_bits = scc.receive_data()
assert(verify_bits == chk_verify_bits)
# verify the check bits
verified = all([verify_bits[i] == sender_key_candidate[i] for i in verify_bits.keys()])
# if the check bits check out, strip them out of the key and we're done
if verified:
sender_key = [j for i,j in enumerate(sender_key_candidate) if i not in chk_verify_bits.keys()]
receiver_key = [j for i,j in enumerate(receiver_key_candidate) if i not in verify_bits.keys()]
assert(sender_key == receiver_key)
print('skey: ' + str(sender_key))
print('rkey: ' + str(receiver_key))
|
https://github.com/qiskit-community/Qiskit-Hackathon-at-World-of-QUANTUM
|
qiskit-community
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, assemble, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
#Apply the CNOT gate to the 00 state
#
qc=QuantumCircuit(2,2)
#
# FILL YOUR CODE IN HERE
#
qc.draw()
#Apply the CNOT gate to the 00 state
#
qc=QuantumCircuit(2,2)
#
# FILL YOUR CODE IN HERE
#
qc.draw()
#Apply the CNOT gate to the 00 state
#
qc=QuantumCircuit(2,2)
#
# FILL YOUR CODE IN HERE
#
# for i in range(2):
# qc.measure(i,i)
# backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
# counts = execute(qc, backend, shots = 1024).result().get_counts() # we run the simulation and get the counts
# plot_histogram(counts)
#Apply the CNOT gate to the 00 state
#
qc=QuantumCircuit(2,2)
#
# FILL YOUR CODE IN HERE
#
for i in range(2):
qc.measure(i,i)
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1024).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts)
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 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.
"""Evaluator of observables for algorithms."""
from __future__ import annotations
from collections.abc import Sequence
from typing import Any
import numpy as np
from qiskit import QuantumCircuit
from qiskit.opflow import PauliSumOp
from qiskit.quantum_info import SparsePauliOp
from .exceptions import AlgorithmError
from .list_or_dict import ListOrDict
from ..primitives import BaseEstimator
from ..quantum_info.operators.base_operator import BaseOperator
def estimate_observables(
estimator: BaseEstimator,
quantum_state: QuantumCircuit,
observables: ListOrDict[BaseOperator | PauliSumOp],
parameter_values: Sequence[float] | None = None,
threshold: float = 1e-12,
) -> ListOrDict[tuple[complex, dict[str, Any]]]:
"""
Accepts a sequence of operators and calculates their expectation values - means
and metadata. They are calculated with respect to a quantum state provided. A user
can optionally provide a threshold value which filters mean values falling below the threshold.
Args:
estimator: An estimator primitive used for calculations.
quantum_state: A (parameterized) quantum circuit preparing a quantum state that expectation
values are computed against.
observables: A list or a dictionary of operators whose expectation values are to be
calculated.
parameter_values: Optional list of parameters values to evaluate the quantum circuit on.
threshold: A threshold value that defines which mean values should be neglected (helpful for
ignoring numerical instabilities close to 0).
Returns:
A list or a dictionary of tuples (mean, metadata).
Raises:
AlgorithmError: If a primitive job is not successful.
"""
if isinstance(observables, dict):
observables_list = list(observables.values())
else:
observables_list = observables
if len(observables_list) > 0:
observables_list = _handle_zero_ops(observables_list)
quantum_state = [quantum_state] * len(observables)
if parameter_values is not None:
parameter_values = [parameter_values] * len(observables)
try:
estimator_job = estimator.run(quantum_state, observables_list, parameter_values)
expectation_values = estimator_job.result().values
except Exception as exc:
raise AlgorithmError("The primitive job failed!") from exc
metadata = estimator_job.result().metadata
# Discard values below threshold
observables_means = expectation_values * (np.abs(expectation_values) > threshold)
# zip means and metadata into tuples
observables_results = list(zip(observables_means, metadata))
else:
observables_results = []
return _prepare_result(observables_results, observables)
def _handle_zero_ops(
observables_list: list[BaseOperator | PauliSumOp],
) -> list[BaseOperator | PauliSumOp]:
"""Replaces all occurrence of operators equal to 0 in the list with an equivalent ``PauliSumOp``
operator."""
if observables_list:
zero_op = SparsePauliOp.from_list([("I" * observables_list[0].num_qubits, 0)])
for ind, observable in enumerate(observables_list):
if observable == 0:
observables_list[ind] = zero_op
return observables_list
def _prepare_result(
observables_results: list[tuple[complex, dict]],
observables: ListOrDict[BaseOperator | PauliSumOp],
) -> ListOrDict[tuple[complex, dict[str, Any]]]:
"""
Prepares a list of tuples of eigenvalues and metadata tuples from
``observables_results`` and ``observables``.
Args:
observables_results: A list of tuples (mean, metadata).
observables: A list or a dictionary of operators whose expectation values are to be
calculated.
Returns:
A list or a dictionary of tuples (mean, metadata).
"""
if isinstance(observables, list):
# by construction, all None values will be overwritten
observables_eigenvalues: ListOrDict[tuple[complex, complex]] = [None] * len(observables)
key_value_iterator = enumerate(observables_results)
else:
observables_eigenvalues = {}
key_value_iterator = zip(observables.keys(), observables_results)
for key, value in key_value_iterator:
observables_eigenvalues[key] = value
return observables_eigenvalues
|
https://github.com/Shashankaubaru/NISQ-TDA
|
Shashankaubaru
|
run test_rank.py
import test_rank
import importlib
importlib.reload(test_rank)
for j in range(2,20,2):
betti_BP = betti_boundary_projection(vit_vec, project_on_simplices, boundary_sum_matrix, num_vertices,j, nv, 0.3, 2)
for i in range(num_vertices):
print("Betti Bound_proj",i, " = ", betti_BP[i] , "with deg = ", j)
from scipy.sparse.linalg.eigen.arpack import eigsh as largest_eigsh
points = np.random.rand(7,4)
#points = [[0, 0, 0], [0, 1, 0], [1,0,0],[1,1,0], [0.5,0.5,1]]
vit_comp = vitoris_rips_complex(points, 0.4)
vit_vec = simplices_to_count_vector(vit_comp)
num_basis = len(vit_vec)
num_vertices = num_underlying_vertices_vector_length(num_basis)
boundary = boundary_operator(num_vertices)
boundary_matrix = matrix_from_pauli_operator(boundary)
#print("Boundary sum:")
boundary_sum = boundary_operator_hermitian(num_vertices)
boundary_sum_matrix = matrix_from_pauli_operator(boundary_sum)
project_on_simplices = np.zeros(np.shape(boundary_matrix)+(num_vertices,))
for i in range(num_vertices):
project_on_simplices[..., i] = np.array(np.diag(d_dim_simplices_mask(i,vit_vec)), dtype=float)
laplacian_restricted = np.zeros(np.shape(boundary_sum_matrix)+(num_vertices,))
dim_simplices = np.zeros(num_vertices+1)
for i in range(num_vertices):
dim_simplices[i] = np.sum(d_dim_simplices_mask(i,vit_vec))
if i>0:
project_up_down = project_on_simplices[...,i-1]
else:
project_up_down = np.zeros(np.shape(boundary_sum_matrix))
if i < num_vertices-1:
project_up_down += project_on_simplices[...,i+1]
laplacian_restricted[...,i] = \
project_on_simplices[...,i] \
@ boundary_sum_matrix \
@ project_up_down \
@ boundary_sum_matrix \
@ project_on_simplices[...,i] \
betti = np.zeros(num_vertices)
for i in range(num_vertices):
rows = d_dim_simplices_mask(i, vit_vec)
cols = rows
if np.any(rows) and np.any(cols):
tmp_mat = laplacian_restricted[..., i][rows][:,cols]
v, w = np.linalg.eig(tmp_mat)
print(tmp_mat.shape)
print(v)
from scipy.sparse.linalg.eigen.arpack import eigsh as largest_eigsh
points = np.random.rand(8,3)
#points = [[0, 0, 0], [0, 1, 0], [1,0,0],[1,1,0], [0.5,0.5,1]]
vit_comp = vitoris_rips_complex(points, 0.7)
vit_vec = simplices_to_count_vector(vit_comp)
num_basis = len(vit_vec)
num_vertices = num_underlying_vertices_vector_length(num_basis)
boundary = boundary_operator(num_vertices)
boundary_matrix = matrix_from_pauli_operator(boundary)
#print("Boundary sum:")
boundary_sum = boundary_operator_hermitian(num_vertices)
boundary_sum_matrix = matrix_from_pauli_operator(boundary_sum)
project_on_simplices = np.zeros(np.shape(boundary_matrix)+(num_vertices,))
for i in range(num_vertices):
project_on_simplices[..., i] = np.array(np.diag(d_dim_simplices_mask(i,vit_vec)), dtype=float)
for i in range(num_vertices):
i_dim_simplices = d_dim_simplices_mask(i,vit_vec)
i_minus_1_dim_simplices = d_dim_simplices_mask(i-1, vit_vec)
tmp_mat = project_on_simplices[...,i] @ (boundary_sum_matrix @ project_on_simplices[...,i-1])
tmp_mat = tmp_mat[i_minus_1_dim_simplices][:,i_dim_simplices]
v, w = np.linalg.eig(tmp_mat.T @ tmp_mat)
# e, vec = largest_eigsh(tmp_mat.T @ tmp_mat, 1, which ='LM')
print(tmp_mat.shape)
print(v)
for j in range(2,20,2):
betti_lap = betti_Laplacian_restricted(vit_vec, project_on_simplices, boundary_sum_matrix, num_vertices,j, nv, 0.2, 2)
for i in range(num_vertices):
print("Betti Bound_proj",i, " = ", betti_lap[i] , "with deg = ", j)
run classical_homology.py
points = np.random.rand(6,3)
points
a = range(10)
b = np.zeros(10)
A = np.diag(np.concatenate([a,b]))
rank_estimation(A, 10, 30, 0.1, 1)
LA.matrix_rank(A)
v = np.random.randn(20)
v= v/LA.norm(v)
mom = compute_moments(A, v, deg)
mom
import matplotlib.pyplot as plt
from rank_estimation import Chebyshev_step
from rank_estimation import compute_Chebyshev_moments
import numpy as np
deg = 3
x = np.linspace(0,1,num=100)
y= np.zeros(len(x))
y1= np.zeros(len(x))
cheb_mom = np.zeros((len(x), deg+1))
for i in range(len(x)):
xi = x[i]
mom = np.zeros(deg+1)
for j in range(deg+1):
if j == 0:
mom[j] = 1
else:
mom[j] = np.dot(xi, mom[j-1])
cheb_mom[i,:] = compute_Chebyshev_moments(mom)
mu = Chebyshev_step(deg, 0.1, 1)
y[i] = np.dot(mu,cheb_mom[i,:])
mu = Chebyshev_step(deg, 0.1, 2)
y1[i] = np.dot(mu,cheb_mom[i,:])
plt.plot(x,y)
plt.plot(x,y1)
A = boundary_matrix(10)
r = rank_estimation((A+A.transpose())/2, 4, 30, 0.01, 2)
int(r)
qiskit.__version__
np.zeros([2,2])
import numpy as np
points = [[0, 0], [1, 0.5], [0,1.5],[1,2]]
np.mean(points,0)
from scipy.stats import kurtosis
kurtosis(points,0)
np.var(points,0)
from scipy.stats import skew
skew(points,0)
A = np.array([[ 0., 1., 1., 0.],
[ 1., 0., 0., 1.],
[ 1., 0., 0., -1.],
[ 0., 1., -1., 0.]])
from numpy import linalg as LA
LA.matrix_rank(A)
B= A @ A
from classical_homology import one_skeleton_square, one_skeleton_unfilled_cube
from quantum_homology import expectation_over_random_hadamard_vecs
edges_in, num_ver= one_skeleton_unfilled_cube()
exp_value = expectation_over_random_hadamard_vecs(num_ver, edges_in, powers=range(2), num_samples=1)
exp_value
eps = 0.01
damp = 2
deg = 4
pwr = range(deg)
nv = 4
rank = np.zeros([nv,num_ver-1])
exp_tensor = expectation_over_random_hadamard_vecs(num_ver, edges_in, powers=pwr, num_samples=nv)
#exp_tensor = exp_value
for l in range(nv):
for k in range(num_ver-1):
# scal = num_ver**(k+1)
exp_value = np.append([1], exp_tensor[l,:,k])
cheb_mom = compute_Chebyshev_moments(exp_value)
mu = Chebyshev_step(deg, eps, damp)
rk = np.dot(cheb_mom, mu)
rank[l,k] = num_ver*rk
np.mean(rank,0)
for l in range(nv):
for k in range(num_ver-1):
#scal = num_ver**(k+1)
exp_value = np.append([1], exp_tensor[l,:,k])
cheb_mom = compute_Chebyshev_moments(exp_value)
print(exp_value)
mu = Chebyshev_step(deg, eps, damp)
rk = np.dot(cheb_mom, mu)
rank[l,k] = num_ver*rk
np.mean(rank,0)
from classical_homology import vitoris_rips_complex_from_one_skeleton, classical_laplacian_of_vit_vec, simplices_to_count_vector
vit_comp = vitoris_rips_complex_from_one_skeleton(num_ver, edges_in)
vit_vec = simplices_to_count_vector(vit_comp)
laplacian_restricted = classical_laplacian_of_vit_vec(vit_vec)
betti = np.zeros(num_ver)
for i in range(num_ver):
rows = d_dim_simplices_mask(i, vit_vec)
cols = rows
if np.any(rows) and np.any(cols):
tmp_mat = laplacian_restricted[..., i][rows][:, cols]
betti[i] = (rank_estimation(
(tmp_mat @ tmp_mat.T), deg, nv, eps, damp))
# np.sum(rows) equivalent to d_dim_simplices[i]
else:
betti[i] = 0
betti
import test.test_quantum_homology_advanced
mylaplace = test.test_quantum_homology_advanced.Expectation_of_Laplacian_TestCase()
mylaplace.setUp()
mylaplace.test_expectation_01()
#mylaplace.test_run_random()
from classical_homology import vitoris_rips_complex_from_one_skeleton, classical_laplacian_of_vit_vec, simplices_to_count_vector
from rank_estimation import expectation_hadamard
vit_comp = vitoris_rips_complex_from_one_skeleton(num_ver, edges_in)
vit_vec = simplices_to_count_vector(vit_comp)
laplacian_restricted = classical_laplacian_of_vit_vec(vit_vec)
for i in range(num_ver):
rows = d_dim_simplices_mask(i, vit_vec)
cols = rows
if np.any(rows) and np.any(cols):
tmp_mat = laplacian_restricted[..., i][rows][:, cols]
mom = (expectation_hadamard(
(tmp_mat @ tmp_mat.T), deg, nv, eps, damp))
print(mom)
else:
betti[i] = 0
!pip3 install qiskit-honeywell-provider
from qiskit.providers.honeywell import Honeywell
Honeywell.save_account('lhoresh@us.ibm.com')
Honeywell.load_account()
backends = Honeywell.backends()
device = 'HQS-LT-S2'
backend = Honeywell.get_backend(device)
job = backend.retrieve_job('c90c48da23c448dc97f6054bd9d45cee') # Substitute your own job_id here
result = job.result()
counts = result.get_counts()
import sys
stdoutOrigin=sys.stdout
sys.stdout = open("square_counts.txt", "w")
print(counts)
sys.stdout.close()
sys.stdout=stdoutOrigin
backends = Honeywell.backends()
device = 'HQS-LT-S2-SIM'
backend = Honeywell.get_backend(device)
job = backend.retrieve_job('a4a1b5e611834caeb36282d41000b827') # Substitute your own job_id here
result = job.result()
counts = result.get_counts()
stdoutOrigin=sys.stdout
sys.stdout = open("Count_square_sim_500_shots_deg3_vec4.txt", "w")
print(counts)
sys.stdout.close()
sys.stdout=stdoutOrigin
print(result)
with open('Count_cube_sim_1000_shots.txt') as f:
data = f.read()
print(data)
from qiskit.visualization import plot_histogram
!pip3 install qiskit-terra
from quantum_rank_estimation import quantum_rank_estimation, quantum_Betti_estimation
from classical_homology import one_skeleton_square, one_skeleton_unfilled_cube
eps = 0.01
damp = 2
deg = 5
nv = 1
pwr = range(deg)
edges_in, num_ver= one_skeleton_square()
#edges_in, num_ver = [[0,1]] , 2
#edges_in, num_ver= one_skeleton_unfilled_cube()
#dimHk = [ 8, 18, 12, 0, 0, 0, 0]
dimHk = [4, 4, 0]
#rank = quantum_rank_estimation(edges_in, num_ver, pwr, nv, eps, damp)
Betti = quantum_Betti_estimation(edges_in, num_ver, dimHk, pwr, nv, eps, damp, [0.00,0.0], expt_name = None, save = False)
Betti
No noise : array([1.39792841, 1.27119665, 0. ])
Noise (0.001): array([1.42281703, 1.35898137, 0. ])
Noise (0.005): array([1.45420094, 1.45964984, 0. ])
Noise (0.01): array([1.46864872, 1.41010404, 0. ])
Noise (0.05): array([1.58682813, 1.53805871, 0. ])
Noise (0.1): array([1.65800044, 1.67416625, 0. ])
from quantum_rank_estimation import quantum_rank_estimation, quantum_Betti_estimation
from classical_homology import one_skeleton_square, one_skeleton_unfilled_cube, one_skeleton_random
from classical_homology import complex_one_skeleton, one_skeleton_remap
import matplotlib.pyplot as plt
import numpy as np
# import json
# points = json.load(open('cmb_sample_points.json', "r"))
# epsilon = 15
# edges_in, num_ver = one_skeleton_remap(complex_one_skeleton(points[0:7], epsilon))
eps = 0.05
damp = 2
deg = 5
nv = 5
pwr = range(deg)
#edges_in, num_ver= one_skeleton_random()
edges_in, num_ver = [[0,1]] , 2
alpha = range(-2,3)
dimHk = [4,4,0]
#dimHk = [ 0, 0, 0, 0, 0, 0, 0]
#rank = quantum_rank_estimation(edges_in, num_ver, pwr, nv, eps, damp)
Betti = np.zeros((3, len(alpha)))
fig, axs = plt.subplots(3)
for idx, i in enumerate(alpha):
Betti[:,idx] = quantum_Betti_estimation(edges_in, num_ver, dimHk, pwr, nv, eps, damp, \
[0.001*(10**i),min(0.01*(10**i),0.1)], save = False)
#"edge-surf-"+str(idx)
true_betti = [1,1,0]
xval =['(0.00001,0.0001)','(0.0001,0.001)','(0.001,0.01)','(0.01,0.1)','(0.1,0.1)']
for k in range(3):
axs[k].plot(xval,Betti[k,:],'*-')
axs[k].plot(xval,np.tile(true_betti[k],len(alpha)),'k--')
#plt.savefig('random8_noise_lvl_quantum.png')
from quantum_rank_estimation import quantum_Betti_estimation_json
from classical_homology import one_skeleton_square, one_skeleton_unfilled_cube
eps = 0.05
damp = 0
deg = 5
nv = 5
pwr = range(deg)
#edges_in, num_ver= one_skeleton_square()
edges_in, num_ver= one_skeleton_unfilled_cube()
dimHk = [ 8, 18, 12, 0, 0, 0, 0]
#dimHk = [4, 4, 0]
Betti = quantum_Betti_estimation_json( num_ver, dimHk, pwr, nv, eps, damp, expt_name = "cube")
Betti
import numpy as np
import matplotlib.pyplot as plt
from quantum_rank_estimation import quantum_rank_estimation, quantum_Betti_estimation
from classical_homology import one_skeleton_square, one_skeleton_unfilled_cube
from classical_homology import complex_one_skeleton, one_skeleton_remap
eps = 0.005
damp = 0
deg = range(2,9)
nv = 10
num_vertices = 4
edges_in, num_ver= one_skeleton_square()
#edges_in, num_ver= one_skeleton_unfilled_cube()
#dimHk = [ 8, 18, 12, 0, 0, 0, 0]
dimHk = [4, 4, 0]
fig, axs = plt.subplots(3)
Betti = np.zeros([num_vertices-1,len(deg)])
for idx,i in enumerate(deg):
pwr= range(i)
# Betti[:,idx] = classical_betti_from_rank_estimation_of_laplacian(vit_vec, i, nv, eps, damp)
Betti[:,idx] = quantum_Betti_estimation(edges_in, num_ver, dimHk, pwr, nv, eps, damp, [0.000,0.000])
true_betti = [1,1,0]
for k in range(3):
axs[k].plot(deg,Betti[k,:],'*-')
axs[k].plot(deg,np.tile(true_betti[k],len(deg)),'k--')
plt.savefig('square_deg_quantum.png')
import numpy as np
import matplotlib.pyplot as plt
from quantum_rank_estimation import quantum_rank_estimation, quantum_Betti_estimation
from classical_homology import one_skeleton_square, one_skeleton_unfilled_cube
eps = 0.005
damp = 0
deg = 4
nv = range(5,31,5)
pwr= range(deg)
num_vertices = 4
edges_in, num_ver= one_skeleton_square()
#edges_in, num_ver= one_skeleton_unfilled_cube()
#dimHk = [ 8, 18, 12, 0, 0, 0, 0]
dimHk = [4, 4, 0]
fig, axs = plt.subplots(3)
Betti = np.zeros([num_vertices-1,len(nv)])
for idx,i in enumerate(nv):
# Betti[:,idx] = classical_betti_from_rank_estimation_of_laplacian(vit_vec, deg, i, eps, damp)
Betti[:,idx] = quantum_Betti_estimation(edges_in, num_ver, dimHk, pwr, i, eps, damp, [0.001,0.01])
true_betti = [1,1,0]
for k in range(3):
axs[k].plot(nv,Betti[k,:],'*-')
axs[k].plot(nv,np.tile(true_betti[k],len(nv)),'k--')
plt.savefig('square_nv_quantum_noisy.png')
Betti
import numpy as np
import matplotlib.pyplot as plt
from quantum_rank_estimation import quantum_rank_estimation, quantum_Betti_estimation
from classical_homology import complex_one_skeleton, one_skeleton_remap
import json
epsilon = 15
eps = 0.005
damp = 0
deg = 5
nv = 30
pwr = range(deg)
points = json.load(open('cmb_sample_points.json', "r"))
edges_in, num_ver = one_skeleton_remap(complex_one_skeleton(points[0:7], epsilon))
dimHk = [ 3, 0, 0, 0, 0, 0, 0]
Betti = quantum_Betti_estimation(edges_in, num_ver, dimHk, pwr, nv, eps, damp, [0.001,0.01], expt_name = "CMB_8_nv-", save = True)
Betti
from classical_homology import classical_betti_from_exact_kernel_of_boundary, vitoris_rips_complex_from_one_skeleton, simplices_to_count_vector
from classical_homology import complex_one_skeleton, one_skeleton_remap
import json
points = json.load(open('cmb_sample_points.json', "r"))
epsilon = 15
edges_in, num_ver = one_skeleton_remap(complex_one_skeleton(points[0:7], epsilon))
vit_comp = vitoris_rips_complex_from_one_skeleton(num_ver, edges_in)
vit_vec = simplices_to_count_vector(vit_comp)
true_betti = classical_betti_from_exact_kernel_of_boundary(vit_vec)
true_betti
#Betti =[[4.08669333, 4.08662073, 4.08645737, 4.08640292, 4.08665703],
# [9.19424321, 9.19522336, 9.19567259, 9.19473328, 9.19534588],
# [6.13028428, 6.13001277, 6.13020336, 6.1299311 , 6.1299311 ]]
Err = Betti[0:1,:] - np.tile(1.5,[2,5])
edge_error = np.sort(np.mean(np.abs(Err),0))
edge_error
Betti
import numpy as np
import json
from quantum_rank_estimation import Chebyshev_step, compute_Chebyshev_moments
eps = 0.005
damp = 0
deg = 5
nv = 30
num_ver = 7
dimHk = [ 3, 0, 0, 0, 0, 0, 0]
rank = np.zeros([nv,num_ver])
mu = Chebyshev_step(deg, eps, damp)
temp = np.loadtxt('resultsCMB_8_nv-.txt', dtype=float)
exp_tensor = temp.reshape(temp.shape[0], temp.shape[1] // num_ver, num_ver)
for l in range(nv):
for k in range(num_ver):
if np.sum(exp_tensor[l,:,k]) ==0:
rank[l,k] = 0
continue
exp_value = np.append([1], exp_tensor[l,:,k])
cheb_mom = compute_Chebyshev_moments(exp_value)
rank[l,k] = dimHk[k]*np.dot(cheb_mom, mu)
Betti = (dimHk - (np.mean(rank,0)))
Betti
from qiskit.quantum_info import hellinger_distance as compare_counts_hellinger
import glob
import numpy as np
from quantum_homology import merge_counts, calc_circuit_depths
names = ["edge","square","cube"]
dist = np.zeros([3,5])
for i in range(5):
no_noise_data = "edge-no-noisedegree0sample0.json"
noisy_data = "edge-noise-"+str(i)+"degree0sample0.json"
raw_data_globs = [no_noise_data, noisy_data]
dist[0,i] = compare_counts_hellinger(merge_counts(glob.glob(raw_data_globs[0])),merge_counts(glob.glob(raw_data_globs[1])))
no_noise_data = "square-no-noisedegree0sample0.json"
noisy_data = "square-noise-"+str(i)+"degree0sample0.json"
raw_data_globs = [no_noise_data, noisy_data]
dist[1,i] = compare_counts_hellinger(merge_counts(glob.glob(raw_data_globs[0])),merge_counts(glob.glob(raw_data_globs[1])))
no_noise_data = "cube-no-noisedegree0sample0.json"
noisy_data = "cube-noise-"+str(i)+"degree0sample0.json"
raw_data_globs = [no_noise_data, noisy_data]
dist[2,i] = compare_counts_hellinger(merge_counts(glob.glob(raw_data_globs[0])),merge_counts(glob.glob(raw_data_globs[1])))
id = np.nonzero(rank[:,0])
3.3-rank[id,0]
0.001*(10**-2)
|
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.
#
# 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 QASM simulator."""
import os
import unittest
import io
from logging import StreamHandler, getLogger
import sys
import numpy as np
from qiskit import execute
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.compiler import transpile, assemble
from qiskit.providers.basicaer import QasmSimulatorPy
from qiskit.test import providers
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestBasicAerQasmSimulator(providers.BackendTestCase):
"""Test the Basic qasm_simulator."""
backend_cls = QasmSimulatorPy
def setUp(self):
super().setUp()
self.seed = 88
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
qasm_filename = os.path.join(qasm_dir, "example.qasm")
transpiled_circuit = QuantumCircuit.from_qasm_file(qasm_filename)
transpiled_circuit.name = "test"
transpiled_circuit = transpile(transpiled_circuit, backend=self.backend)
self.qobj = assemble(transpiled_circuit, shots=1000, seed_simulator=self.seed)
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel("DEBUG")
self.log_output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.log_output))
def assertExecuteLog(self, log_msg):
"""Runs execute and check for logs containing specified message"""
shots = 100
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(4, "cr")
circuit = QuantumCircuit(qr, cr)
execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed)
self.log_output.seek(0)
# Filter unrelated log lines
output_lines = self.log_output.readlines()
execute_log_lines = [x for x in output_lines if log_msg in x]
self.assertTrue(len(execute_log_lines) > 0)
def test_submission_log_time(self):
"""Check Total Job Submission Time is logged"""
self.assertExecuteLog("Total Job Submission Time")
def test_qasm_simulator_single_shot(self):
"""Test single shot run."""
shots = 1
self.qobj.config.shots = shots
result = self.backend.run(self.qobj).result()
self.assertEqual(result.success, True)
def test_measure_sampler_repeated_qubits(self):
"""Test measure sampler if qubits measured more than once."""
shots = 100
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(4, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
circuit.measure(qr[1], cr[2])
circuit.measure(qr[0], cr[3])
target = {"0110": shots}
job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target)
def test_measure_sampler_single_qubit(self):
"""Test measure sampler if single-qubit is measured."""
shots = 100
num_qubits = 5
qr = QuantumRegister(num_qubits, "qr")
cr = ClassicalRegister(1, "cr")
for qubit in range(num_qubits):
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[qubit])
circuit.measure(qr[qubit], cr[0])
target = {"1": shots}
job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target)
def test_measure_sampler_partial_qubit(self):
"""Test measure sampler if single-qubit is measured."""
shots = 100
num_qubits = 5
qr = QuantumRegister(num_qubits, "qr")
cr = ClassicalRegister(4, "cr")
# ░ ░ ░ ┌─┐ ░
# qr_0: ──────░─────░─────░─┤M├─░────
# ┌───┐ ░ ░ ┌─┐ ░ └╥┘ ░
# qr_1: ┤ X ├─░─────░─┤M├─░──╫──░────
# └───┘ ░ ░ └╥┘ ░ ║ ░
# qr_2: ──────░─────░──╫──░──╫──░────
# ┌───┐ ░ ┌─┐ ░ ║ ░ ║ ░ ┌─┐
# qr_3: ┤ X ├─░─┤M├─░──╫──░──╫──░─┤M├
# └───┘ ░ └╥┘ ░ ║ ░ ║ ░ └╥┘
# qr_4: ──────░──╫──░──╫──░──╫──░──╫─
# ░ ║ ░ ║ ░ ║ ░ ║
# cr: 4/═════════╩═════╩═════╩═════╩═
# 1 0 2 3
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[3])
circuit.x(qr[1])
circuit.barrier(qr)
circuit.measure(qr[3], cr[1])
circuit.barrier(qr)
circuit.measure(qr[1], cr[0])
circuit.barrier(qr)
circuit.measure(qr[0], cr[2])
circuit.barrier(qr)
circuit.measure(qr[3], cr[3])
target = {"1011": shots}
job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target)
def test_qasm_simulator(self):
"""Test data counts output for single circuit run against reference."""
result = self.backend.run(self.qobj).result()
shots = 1024
threshold = 0.04 * shots
counts = result.get_counts("test")
target = {
"100 100": shots / 8,
"011 011": shots / 8,
"101 101": shots / 8,
"111 111": shots / 8,
"000 000": shots / 8,
"010 010": shots / 8,
"110 110": shots / 8,
"001 001": shots / 8,
}
self.assertDictAlmostEqual(counts, target, threshold)
def test_if_statement(self):
"""Test if statements."""
shots = 100
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
# ┌───┐┌─┐ ┌─┐
# qr_0: ┤ X ├┤M├──────────┤M├──────
# ├───┤└╥┘┌─┐ └╥┘┌─┐
# qr_1: ┤ X ├─╫─┤M├────────╫─┤M├───
# └───┘ ║ └╥┘ ┌───┐ ║ └╥┘┌─┐
# qr_2: ──────╫──╫──┤ X ├──╫──╫─┤M├
# ║ ║ └─╥─┘ ║ ║ └╥┘
# ║ ║ ┌──╨──┐ ║ ║ ║
# cr: 3/══════╩══╩═╡ 0x3 ╞═╩══╩══╩═
# 0 1 └─────┘ 0 1 2
circuit_if_true = QuantumCircuit(qr, cr)
circuit_if_true.x(qr[0])
circuit_if_true.x(qr[1])
circuit_if_true.measure(qr[0], cr[0])
circuit_if_true.measure(qr[1], cr[1])
circuit_if_true.x(qr[2]).c_if(cr, 0x3)
circuit_if_true.measure(qr[0], cr[0])
circuit_if_true.measure(qr[1], cr[1])
circuit_if_true.measure(qr[2], cr[2])
# ┌───┐┌─┐ ┌─┐
# qr_0: ┤ X ├┤M├───────┤M├──────
# └┬─┬┘└╥┘ └╥┘┌─┐
# qr_1: ─┤M├──╫─────────╫─┤M├───
# └╥┘ ║ ┌───┐ ║ └╥┘┌─┐
# qr_2: ──╫───╫──┤ X ├──╫──╫─┤M├
# ║ ║ └─╥─┘ ║ ║ └╥┘
# ║ ║ ┌──╨──┐ ║ ║ ║
# cr: 3/══╩═══╩═╡ 0x3 ╞═╩══╩══╩═
# 1 0 └─────┘ 0 1 2
circuit_if_false = QuantumCircuit(qr, cr)
circuit_if_false.x(qr[0])
circuit_if_false.measure(qr[0], cr[0])
circuit_if_false.measure(qr[1], cr[1])
circuit_if_false.x(qr[2]).c_if(cr, 0x3)
circuit_if_false.measure(qr[0], cr[0])
circuit_if_false.measure(qr[1], cr[1])
circuit_if_false.measure(qr[2], cr[2])
job = execute(
[circuit_if_true, circuit_if_false],
backend=self.backend,
shots=shots,
seed_simulator=self.seed,
)
result = job.result()
counts_if_true = result.get_counts(circuit_if_true)
counts_if_false = result.get_counts(circuit_if_false)
self.assertEqual(counts_if_true, {"111": 100})
self.assertEqual(counts_if_false, {"001": 100})
def test_bit_cif_crossaffect(self):
"""Test if bits in a classical register other than
the single conditional bit affect the conditioned operation."""
# ┌───┐ ┌─┐
# q0_0: ────────┤ H ├──────────┤M├
# ┌───┐ └─╥─┘ ┌─┐ └╥┘
# q0_1: ┤ X ├─────╫──────┤M├────╫─
# ├───┤ ║ └╥┘┌─┐ ║
# q0_2: ┤ X ├─────╫───────╫─┤M├─╫─
# └───┘┌────╨─────┐ ║ └╥┘ ║
# c0: 3/═════╡ c0_0=0x1 ╞═╩══╩══╬═
# └──────────┘ 1 2 ║
# c1: 1/════════════════════════╩═
# 0
shots = 100
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
cr1 = ClassicalRegister(1)
circuit = QuantumCircuit(qr, cr, cr1)
circuit.x([qr[1], qr[2]])
circuit.measure(qr[1], cr[1])
circuit.measure(qr[2], cr[2])
circuit.h(qr[0]).c_if(cr[0], True)
circuit.measure(qr[0], cr1[0])
job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed)
result = job.result().get_counts()
target = {"0 110": 100}
self.assertEqual(result, target)
def test_teleport(self):
"""Test teleportation as in tutorials"""
# ┌─────────┐ ┌───┐ ░ ┌─┐
# qr_0: ┤ Ry(π/4) ├───────■──┤ H ├─░─┤M├────────────────────
# └──┬───┬──┘ ┌─┴─┐└───┘ ░ └╥┘┌─┐
# qr_1: ───┤ H ├─────■──┤ X ├──────░──╫─┤M├─────────────────
# └───┘ ┌─┴─┐└───┘ ░ ║ └╥┘ ┌───┐ ┌───┐ ┌─┐
# qr_2: ───────────┤ X ├───────────░──╫──╫──┤ Z ├──┤ X ├─┤M├
# └───┘ ░ ║ ║ └─╥─┘ └─╥─┘ └╥┘
# ║ ║ ┌──╨──┐ ║ ║
# cr0: 1/═════════════════════════════╩══╬═╡ 0x1 ╞═══╬════╬═
# 0 ║ └─────┘┌──╨──┐ ║
# cr1: 1/════════════════════════════════╩════════╡ 0x1 ╞═╬═
# 0 └─────┘ ║
# cr2: 1/═════════════════════════════════════════════════╩═
# 0
self.log.info("test_teleport")
pi = np.pi
shots = 2000
qr = QuantumRegister(3, "qr")
cr0 = ClassicalRegister(1, "cr0")
cr1 = ClassicalRegister(1, "cr1")
cr2 = ClassicalRegister(1, "cr2")
circuit = QuantumCircuit(qr, cr0, cr1, cr2, name="teleport")
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
circuit.ry(pi / 4, qr[0])
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.barrier(qr)
circuit.measure(qr[0], cr0[0])
circuit.measure(qr[1], cr1[0])
circuit.z(qr[2]).c_if(cr0, 1)
circuit.x(qr[2]).c_if(cr1, 1)
circuit.measure(qr[2], cr2[0])
job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed)
results = job.result()
data = results.get_counts("teleport")
alice = {
"00": data["0 0 0"] + data["1 0 0"],
"01": data["0 1 0"] + data["1 1 0"],
"10": data["0 0 1"] + data["1 0 1"],
"11": data["0 1 1"] + data["1 1 1"],
}
bob = {
"0": data["0 0 0"] + data["0 1 0"] + data["0 0 1"] + data["0 1 1"],
"1": data["1 0 0"] + data["1 1 0"] + data["1 0 1"] + data["1 1 1"],
}
self.log.info("test_teleport: circuit:")
self.log.info(circuit.qasm())
self.log.info("test_teleport: data %s", data)
self.log.info("test_teleport: alice %s", alice)
self.log.info("test_teleport: bob %s", bob)
alice_ratio = 1 / np.tan(pi / 8) ** 2
bob_ratio = bob["0"] / float(bob["1"])
error = abs(alice_ratio - bob_ratio) / alice_ratio
self.log.info("test_teleport: relative error = %s", error)
self.assertLess(error, 0.05)
def test_memory(self):
"""Test memory."""
# ┌───┐ ┌─┐
# qr_0: ┤ H ├──■─────┤M├───
# └───┘┌─┴─┐ └╥┘┌─┐
# qr_1: ─────┤ X ├────╫─┤M├
# └┬─┬┘ ║ └╥┘
# qr_2: ──────┤M├─────╫──╫─
# ┌───┐ └╥┘ ┌─┐ ║ ║
# qr_3: ┤ X ├──╫──┤M├─╫──╫─
# └───┘ ║ └╥┘ ║ ║
# cr0: 2/══════╬═══╬══╩══╩═
# ║ ║ 0 1
# ║ ║
# cr1: 2/══════╩═══╩═══════
# 0 1
qr = QuantumRegister(4, "qr")
cr0 = ClassicalRegister(2, "cr0")
cr1 = ClassicalRegister(2, "cr1")
circ = QuantumCircuit(qr, cr0, cr1)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.x(qr[3])
circ.measure(qr[0], cr0[0])
circ.measure(qr[1], cr0[1])
circ.measure(qr[2], cr1[0])
circ.measure(qr[3], cr1[1])
shots = 50
job = execute(circ, backend=self.backend, shots=shots, memory=True)
result = job.result()
memory = result.get_memory()
self.assertEqual(len(memory), shots)
for mem in memory:
self.assertIn(mem, ["10 00", "10 11"])
def test_unitary(self):
"""Test unitary gate instruction"""
max_qubits = 4
x_mat = np.array([[0, 1], [1, 0]])
# Test 1 to max_qubits for random n-qubit unitary gate
for i in range(max_qubits):
num_qubits = i + 1
# Apply X gate to all qubits
multi_x = x_mat
for _ in range(i):
multi_x = np.kron(multi_x, x_mat)
# Target counts
shots = 1024
target_counts = {num_qubits * "1": shots}
# Test circuit
qr = QuantumRegister(num_qubits, "qr")
cr = ClassicalRegister(num_qubits, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.unitary(multi_x, qr)
circuit.measure(qr, cr)
job = execute(circuit, self.backend, shots=shots)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target_counts)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-dell-runtime
|
qiskit-community
|
import itertools
import json
import numpy as np
from numpy.random import RandomState
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.compiler import transpile
from cvxopt import matrix, solvers # pylint: disable=import-error
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
import qiskit
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from tsp_qaoa import marina_solution
G=nx.Graph()
i=1
G.add_node(i,pos=(i,i))
G.add_node(2,pos=(2,2))
G.add_node(3,pos=(1,0))
G.add_edge(1,2,weight=20.5)
G.add_edge(1,3,weight=9.8)
pos=nx.get_node_attributes(G,'pos')
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
def append_zz_term(qc,q1,q2,gamma):
qc.cx(q1,q2)
qc.rz(2*gamma,q2)
qc.cx(q1,q2)
def get_cost_circuit(G,gamma):
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
for i,j in G.edges():
append_zz_term(qc,i,j,gamma)
return qc
#print(get_cost_circuit(G,0.5))
def append_x_term(qc,q1,beta):
qc.rx(2*beta,q1)
def get_mixer_operator(G,beta):
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
for n in G.nodes():
append_x_term(qc,n,beta)
return qc
#print(get_mixer_operator(G,0.5))
def get_QAOA_circuit(G,beta,gamma):
assert(len(beta)==len(gamma))
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
qc.h(range(N))
p=len(beta)
#aplicamos las p rotaciones
for i in range(p):
qc=qc.compose(get_cost_circuit(G,gamma[i]))
qc=qc.compose(get_mixer_operator(G,beta[i]))
qc.barrier(range(N))
qc.measure(range(N),range(N))
return qc
print(get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6]))
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
qc=get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6])
backend=Aer.get_backend('qasm_simulator')
job=execute(qc,backend)
result=job.result()
print(invert_counts(result.get_counts()))
def maxcut_obj(x,G):
cut=0
for i,j in G.edges():
if x[i]!=x[j]:
cut = cut-1
return cut
print(maxcut_obj("00011",G))
def compute_maxcut_energy(counts,G):
energy=0
get_counts=0
total_counts=0
for meas, meas_count in counts.items():
obj_for_meas=maxcut_obj(meas,G)
energy+=obj_for_meas*meas_count
total_counts+=meas_count
return energy/total_counts
def get_black_box_objective(G,p):
backend=Aer.get_backend('qasm_simulator')
def f(theta):
beta=theta[:p]
gamma=theta[p:]
qc=get_QAOA_circuit(G,beta,gamma)
counts=execute(qc,backend,seed_simulator=10).result().get_counts()
return compute_maxcut_energy(invert_counts(counts),G)
return f
p=5
obj=get_black_box_objective(G,p)
init_point=np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1])#([2,2,1,1,1,1,1,1,1,1])
res_sample=minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
res_sample
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
cantidad_ciudades = 4
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
pos=nx.spring_layout(G)
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
G
pos=nx.get_node_attributes(G,'weight')
pos
labels = nx.get_edge_attributes(G,'weight')
labels
def funcion_costo(multiplicador_lagrange, cantidad_ciudades, pesos, conexiones ):
N = G.number_of_nodes()
N_square = N^2
# restriccion 1
for i in range(cantidad_ciudades):
cur = sI(N_square)
for j in range(num_cities):
cur -= D(i, j)
ret += cur**2
# retorna el indice de qubit por conversion al problema
def quibit_indice(i, l, N):
return i * N + l
from qiskit.quantum_info.operators import Operator, Pauli
# Create an operator
XX = Operator(Pauli(label='XX'))
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(XX, [0, 1])
circ.measure([0,1], [0,1])
circ.draw('mpl')
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(a, [0])
#circ.measure([0,1], [0,1])
circ.draw('mpl')
a = I - ( 0.5*(I+ Z))**2
a = Operator(a)
a.is_unitary()
print(I @ Z)
|
https://github.com/h-rathee851/Pulse_application_qiskit
|
h-rathee851
|
from calibration import *
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-research', group='iserc-1', project='main')
"""
Object to calibrate pulse of backend and qubit of interest.
"""
# Importing required python packages
from warnings import warn
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.signal import find_peaks
from sklearn.model_selection import train_test_split
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
# Importing standard Qiskit libraries
from qiskit import IBMQ, execute, pulse
from qiskit.providers.ibmq import IBMQBackend
from qiskit.pulse import DriveChannel, Schedule, Play
from qiskit.pulse import library as pulse_lib
from qiskit.pulse.library import Waveform, Gaussian
from qiskit.tools.monitor import job_monitor
from qiskit.providers.exceptions import QiskitBackendNotFoundError, BackendConfigurationError
# Loading your IBM Q account(s)
#IBMQ.load_account()
#provider = IBMQ.get_provider()
class PulseCalibration():
"""Creates an object that is used for pulse calibration.
Args:
backend (IBMQBackend) : The IBMQBackend for which pulse calibration needs to be done.
qubit (int) : The qubit for which the pulse calibration is done.
qubit_freq_ground (float) : Custom frequency for 0->1 transition.
qubit_freq_excited (float) : Custom frequency for 1->2 transition.
pi_amp_ground (float) : Custom pi amplitude for 0->1 transition.
The value should be between 0 and 1.
pi_amp_excited (float) : Custom pi amplitude for 1->2 transition.
The value should be between 0 and 1.
pulse_dur (int) : The duration of the pi pulse to be used for calibration.
pulse_sigma (int) : The standard deviation of the pi pulse to be used for calibration.
"""
def __init__(self, backend, qubit, qubit_freq_ground=None, qubit_freq_excited=None,
pi_amp_ground=None, pi_amp_excited=None, pulse_dur=None, pulse_sigma=None):
# pylint: disable=too-many-locals
# pylint: disable=too-many-arguments
if not isinstance(backend, IBMQBackend):
raise QiskitBackendNotFoundError("Provided backend not available." +
"Please provide backend after obtaining from IBMQ.")
self._backend = backend
self._back_config = backend.configuration()
if qubit >= self._back_config.n_qubits:
raise BackendConfigurationError(f"Qubit {qubit} not present in the provided backend.")
self._qubit = qubit
self._back_defaults = backend.defaults()
self._qubit_anharmonicity = backend.properties().qubit_property(self._qubit)['anharmonicity'][0]
self._dt = self._back_config.dt
self._qubit_freq = self._back_defaults.qubit_freq_est[self._qubit]
self._inst_sched_map = self._back_defaults.instruction_schedule_map
self._drive_chan = DriveChannel(qubit)
if pulse_sigma:
self._pulse_sigma = pulse_sigma
else:
if self._backend.name() == 'ibmq_armonk':
self._pulse_sigma = 80
else:
self._pulse_sigma = 40
if pulse_dur:
self._pulse_duration = pulse_dur
else:
self._pulse_duration = (4*self._pulse_sigma)-((4*self._pulse_sigma) % 16)
self._qubit_freq_ground = qubit_freq_ground
self._qubit_freq_excited = qubit_freq_excited
self._pi_amp_ground = pi_amp_ground
self._pi_amp_excited = pi_amp_excited
self._state_discriminator_012 = None
# Find out which measurement map index is needed for this qubit
meas_map_idx = None
for i, measure_group in enumerate(self._back_config.meas_map):
if qubit in measure_group:
meas_map_idx = i
break
assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!"
# The measurement pulse for measuring the qubit of interest.
self._measure = self._inst_sched_map.get('measure',
qubits=self._back_config.meas_map[meas_map_idx])
def create_cal_circuit(self, amp):
"""Constructs and returns a schedule containing Gaussian pulse with amplitude as 'amp',
sigma as 'pulse_sigma' and duration as 'pulse_duration'."""
sched = Schedule()
sched += Play(Gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma,
amp=amp), self._drive_chan)
sched += self._measure << sched.duration
return sched
def create_cal_circuit_excited(self, base_pulse, freq):
""" Constructs and returns a schedule containing a pi pulse for 0->1 transition followed by
a sidebanded pulse which corresponds to applying 'base_pulse' at frequency 'freq'."""
sched = Schedule()
sched += Play(Gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma,
amp=self._pi_amp_ground), self._drive_chan)
sched += Play(self.apply_sideband(base_pulse, freq), self._drive_chan)
sched += self._measure << sched.duration
return sched
@staticmethod
def _fit_function(x_values, y_values, function, init_params):
""" A function fitter. Returns the fit parameters of 'function'."""
fitparams, _ = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
@staticmethod
def _baseline_remove(values):
"""Centering data around zero."""
return np.array(values) - np.mean(values)
def apply_sideband(self, pulse, frequency):
"""Apply a sine sideband to 'pulse' at frequency 'freq'.
Args:
pulse (Waveform): The pulse to which sidebanding is to be applied.
frequency (float): LO frequency at which the pulse is to be applied.
Returns:
Waveform: The sidebanded pulse.
"""
t_samples = np.linspace(0, self._dt*self._pulse_duration, self._pulse_duration)
sine_pulse = np.sin(2*np.pi*(frequency-self._qubit_freq_ground)*t_samples)
sideband_pulse = Waveform(np.multiply(np.real(pulse.samples), sine_pulse),
name='sideband_pulse')
return sideband_pulse
def get_job_data(self, job, average):
"""Retrieve data from a job that has already run.
Args:
job (Job): The job whose data you want.
average (bool): If True, gets the data assuming data is an average.
If False, gets the data assuming it is for single shots.
Return:
list: List containing job result data.
"""
scale_factor = 1e-14
job_results = job.result(timeout=120) # timeout parameter set to 120 s
result_data = []
for i in range(len(job_results.results)):
if average: # get avg data
result_data.append(job_results.get_memory(i)[self._qubit]*scale_factor)
else: # get single data
result_data.append(job_results.get_memory(i)[:, self._qubit]*scale_factor)
return result_data
# Prints out relative maxima frequencies in output_data; height gives lower bound (abs val)
@staticmethod
def _rel_maxima(freqs, output_data, height, distance):
"""Prints out relative maxima frequencies in output_data (can see peaks);
height gives upper bound (abs val). Be sure to set the height properly or
the peak will be ignored!
Args:
freqs (list): frequency list
output_data (list): list of resulting signals
height (float): upper bound (abs val) on a peak
width (float):
Returns:
list: List containing relative maxima frequencies
"""
peaks, _ = find_peaks(x=output_data, height=height, distance=distance)
return freqs[peaks]
def find_freq_ground(self, verbose=False, visual=False):
"""Sets and returns the calibrated frequency corresponding to 0->1 transition."""
# pylint: disable=too-many-locals
sched_list = [self.create_cal_circuit(0.5)]*75
freq_list = np.linspace(self._qubit_freq-(45*1e+6), self._qubit_freq+(45*1e+6), 75)
sweep_job = execute(sched_list, backend=self._backend, meas_level=1, meas_return='avg',
shots=1024, schedule_los = [{self._drive_chan: freq} for freq in freq_list])
jid = sweep_job.job_id()
if verbose:
print("Executing the Frequency sweep job for 0->1 transition.")
print('Job Id : ', jid)
# job_monitor(sweep_job)
sweep_job = self._backend.retrieve_job(jid)
sweep_result = sweep_job.result()
sweep_values = []
for i in range(len(sweep_result.results)):
# Get the results from the ith experiment
res = sweep_result.get_memory(i)*1e-14
# Get the results for `qubit` from this experiment
sweep_values.append(res[self._qubit])
freq_list_GHz = freq_list/1e+9
if visual:
print("The frequency-signal plot for frequency sweep: ")
plt.scatter(freq_list_GHz, np.real(sweep_values), color='black')
plt.xlim([min(freq_list_GHz), max(freq_list_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
# def find_init_params(freq_list, res_values):
# hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0]
# hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0]
# if hmin_index < hmax_index:
# est_baseline = min(res_values)
# est_slope = (res_values[hmax_index] - res_values[hmin_index])/(freq_list[hmax_index] - freq_list[hmin_index])
# else:
# est_baseline = max(res_values)
# est_slope = (res_values[hmin_index] - res_values[hmax_index])/(freq_list[hmin_index] - freq_list[hmax_index])
# return [est_slope, self._qubit_freq/1e9, 1, est_baseline]
def find_init_params_gauss(freq_list, res_values):
hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0]
hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0]
mean_est = freq_list[hmax_index]
var_est = np.abs(freq_list[hmax_index]-freq_list[hmin_index])/2
scale_est = max(res_values)-min(res_values)
shift_est = min(res_values)
return [mean_est, var_est, scale_est, shift_est]
def gauss(x, mean, var, scale, shift):
return (scale*(1/var*np.sqrt(2*np.pi))*np.exp(-(1/2)*(((x-mean)/var)**2)))+shift
def lorentzian(xval, scale, q_freq, hwhm, shift):
return (scale / np.pi) * (hwhm / ((xval - q_freq)**2 + hwhm**2)) + shift
# do fit in Hz
init_params = find_init_params_gauss(freq_list_GHz, np.real(sweep_values))
# init_params = find_init_params(freq_list_GHz, np.real(sweep_values))
print('ground freq init params : ', init_params)
# Obtain the optimal paramters that fit the result data.
# fit_params, y_fit = self._fit_function(freq_list_GHz,
# np.real(sweep_values),
# lorentzian,
# init_params # init parameters for curve_fit
# )
fit_params, y_fit = self._fit_function(freq_list_GHz,
np.real(sweep_values),
gauss,
init_params # init parameters for curve_fit
)
if visual:
print("The frequency-signal plot for frequency sweep: ")
plt.scatter(freq_list_GHz, np.real(sweep_values), color='black')
plt.plot(freq_list_GHz, y_fit, color='red')
plt.xlim([min(freq_list_GHz), max(freq_list_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
qubit_freq_new, _, _, _ = fit_params
self._qubit_freq_ground = qubit_freq_new*1e9
if verbose:
print(f"The calibrate frequency for the 0->1 transition is {self._qubit_freq_ground}")
return [self._qubit_freq_ground, freq_list_GHz, sweep_values]
def find_pi_amp_ground(self, verbose=False, visual=False):
"""Sets and returns the amplitude of the pi pulse corresponding to 0->1 transition."""
# pylint: disable=too-many-locals
if not self._qubit_freq_ground:
warn("ground_qubit_freq not computed yet and custom qubit freq not provided." +
"Computing ground_qubit_freq now.")
self._qubit_freq_ground = self.find_freq_ground(verbose, visual)
amp_list = np.linspace(0, 1, 75)
rabi_sched_list = [self.create_cal_circuit(amp) for amp in amp_list]
rabi_list_len = len(rabi_sched_list)
rabi_job = execute(rabi_sched_list,backend=self._backend, meas_level=1, meas_return='avg',
shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*len(rabi_sched_list))
jid = rabi_job.job_id()
if verbose:
print("Executing the rabi oscillation job to get Pi pulse for 0->1 transition.")
print('Job Id : ', jid)
# job_monitor(rabi_job)
rabi_job = self._backend.retrieve_job(jid)
rabi_results = rabi_job.result()
scale_factor = 1e-14
rabi_values = []
for i in range(75):
# Get the results for `qubit` from the ith experiment
rabi_values.append(rabi_results.get_memory(i)[self._qubit]*scale_factor)
rabi_values = np.real(self._baseline_remove(rabi_values))
def find_init_params_amp(amp_list, rabi_values):
min_index = np.where(rabi_values==min(rabi_values))[0][0]
max_index = np.where(rabi_values==max(rabi_values))[0][0]
scale_est = (max(rabi_values) - min(rabi_values))/2
shift_est = (max(rabi_values) + min(rabi_values))/2
shift_est = np.mean(rabi_values)
period_est = 0.5
if ((max(rabi_values)-rabi_values[0])/(2*scale_est)) < 0.5:
phi_est = np.pi/2
else:
phi_est = -np.pi/2
return [scale_est, shift_est, period_est, phi_est]
# Obtain the optimal paramters that fit the result data.
init_params = find_init_params_amp(amp_list,rabi_values)
fit_params, y_fit = self._fit_function(amp_list,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B),
init_params)
drive_period = fit_params[2]
self._pi_amp_ground = drive_period/2
if verbose:
print(f"The Pi amplitude of 0->1 transition is {self._pi_amp_ground}.")
if visual:
print("The amplitude-signal plot for rabi oscillation for 0->1 transition.")
plt.figure()
plt.scatter(amp_list, rabi_values, color='black')
plt.plot(amp_list, y_fit, color='red')
plt.axvline(drive_period/2, color='red', linestyle='--')
plt.axvline(drive_period, color='red', linestyle='--')
plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2, 0),
arrowprops=dict(arrowstyle="<->", color='red'))
#plt.annotate("$\pi$", xy=(drive_period/2-0.03, 0.1), color='red')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
return [self._pi_amp_ground, amp_list, rabi_values]
def find_freq_excited(self, verbose=False, visual=False):
"""Sets and returns the frequency corresponding to 1->2 transition."""
# pylint: disable=too-many-locals
if not self._qubit_freq_ground:
raise ValueError("The qubit_freq_ground is not determined. Please determine" +
"qubit_freq_ground first.")
if not self._pi_amp_ground:
raise ValueError("The pi_amp_ground is not determined.\
Please determine pi_amp_ground first.")
base_pulse = pulse_lib.gaussian(duration=self._pulse_duration,
sigma=self._pulse_sigma, amp=0.3)
sched_list = []
# Here we assume that the anharmocity is about 8% for all qubits.
excited_freq_list = self._qubit_freq_ground + self._qubit_anharmonicity + np.linspace(-30*1e+6, 30*1e+6, 75)
for freq in excited_freq_list:
sched_list.append(self.create_cal_circuit_excited(base_pulse, freq))
excited_sweep_job = execute(sched_list, backend=self._backend,
meas_level=1, meas_return='avg', shots=1024,
schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*len(excited_freq_list)
)
jid = excited_sweep_job.job_id()
excited_freq_list_GHz = excited_freq_list/1e+9
if verbose:
print("Executing the Frequency sweep job for 1->2 transition.")
print('Job Id : ', jid)
# job_monitor(excited_sweep_job)
excited_sweep_job = self._backend.retrieve_job(jid)
excited_sweep_data = self.get_job_data(excited_sweep_job, average=True)
if visual:
print("The frequency-signal plot of frequency sweep for 1->2 transition.")
# Note: we are only plotting the real part of the signal
plt.scatter(excited_freq_list_GHz, excited_sweep_data, color='black')
plt.xlim([min(excited_freq_list_GHz), max(excited_freq_list_GHz)])
plt.xlabel("Frequency [GHz]", fontsize=15)
plt.ylabel("Measured Signal [a.u.]", fontsize=15)
plt.title("1->2 Frequency Sweep", fontsize=15)
plt.show()
def find_init_params_gauss(freq_list, res_values):
hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0]
hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0]
mean_est = freq_list[hmax_index]
var_est = np.abs(freq_list[hmax_index]-freq_list[hmin_index])/2
scale_est = max(res_values)-min(res_values)
shift_est = min(res_values)
return [mean_est, var_est, scale_est, shift_est]
def gauss(x, mean, var, scale, shift):
return (scale*(1/var*np.sqrt(2*np.pi))*np.exp(-(1/2)*(((x-mean)/var)**2)))+shift
def lorentzian(xval, scale, q_freq, hwhm, shift):
return (scale / np.pi) * (hwhm / ((xval - q_freq)**2 + hwhm**2)) + shift
# do fit in Hz
# init_params = find_init_params(excited_freq_list_GHz, np.real(excited_sweep_data))
init_params = find_init_params_gauss(excited_freq_list_GHz, np.real(excited_sweep_data))
print("Init params : ", init_params)
excited_sweep_fit_params, excited_sweep_y_fit = self._fit_function(excited_freq_list_GHz,
excited_sweep_data,
gauss,
init_params
)
if visual:
print("The frequency-signal plot of frequency sweep for 1->2 transition.")
# Note: we are only plotting the real part of the signal
plt.scatter(excited_freq_list/1e+9, excited_sweep_data, color='black')
plt.plot(excited_freq_list/1e+9, excited_sweep_y_fit, color='red')
plt.xlim([min(excited_freq_list/1e+9), max(excited_freq_list/1e+9)])
plt.xlabel("Frequency [GHz]", fontsize=15)
plt.ylabel("Measured Signal [a.u.]", fontsize=15)
plt.title("1->2 Frequency Sweep", fontsize=15)
plt.show()
qubit_freq_12, _, _, _ = excited_sweep_fit_params
self._qubit_freq_excited = qubit_freq_12*1e+9
if verbose:
print(f"The calibrated frequency for the 1->2 transition\
is {self._qubit_freq_excited}.")
return [self._qubit_freq_excited, excited_freq_list, excited_sweep_data]
def find_pi_amp_excited(self, verbose=False, visual=False):
"""Sets and returns the amplitude of the pi pulse corresponding to 1->2 transition."""
if not self._qubit_freq_excited:
warn("ground_qubit_freq not computed yet and custom qubit freq not provided." +
"Computing ground_qubit_freq now.")
self._qubit_freq_ground = self.find_freq_excited(verbose, visual)
amp_list = np.linspace(0, 1.0, 75)
rabi_sched_list = []
for amp in amp_list:
base_pulse = pulse_lib.gaussian(duration=self._pulse_duration,
sigma=self._pulse_sigma, amp=amp)
rabi_sched_list.append(self.create_cal_circuit_excited(base_pulse,
self._qubit_freq_excited))
rabi_job = execute(rabi_sched_list, backend=self._backend,
meas_level=1, meas_return='avg', shots=1024,
schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*75
)
jid = rabi_job.job_id()
if verbose:
print("Executing the rabi oscillation job for 1->2 transition.")
print('Job Id : ', jid)
# job_monitor(rabi_job)
rabi_job = self._backend.retrieve_job(jid)
rabi_data = self.get_job_data(rabi_job, average=True)
rabi_data = np.real(self._baseline_remove(rabi_data))
if visual:
print("The amplitude-signal plot of rabi oscillation for 1->2 transition.")
plt.figure()
plt.scatter(amp_list, rabi_data, color='black')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.title('Rabi Experiment (1->2)', fontsize=20)
plt.show()
def find_init_params_amp(amp_list, rabi_values):
min_index = np.where(rabi_values==min(rabi_values))[0][0]
max_index = np.where(rabi_values==max(rabi_values))[0][0]
scale_est = (max(rabi_values) - min(rabi_values))/2
shift_est = (max(rabi_values) + min(rabi_values))/2
shift_est = np.mean(rabi_values)
period_est = 0.5
if ((max(rabi_values)-rabi_values[0])/(2*scale_est)) < 0.5:
phi_est = np.pi/2
else:
phi_est = -np.pi/2
return [scale_est, shift_est, period_est, phi_est]
init_params = find_init_params_amp(amp_list, rabi_data)
print('Init params for 01 amp : ', init_params)
(rabi_fit_params,
rabi_y_fit) = self._fit_function(amp_list,
rabi_data,
lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B),
init_params)
drive_period_excited = rabi_fit_params[2]
pi_amp_excited = (drive_period_excited/2/np.pi) * (np.pi+rabi_fit_params[3])
self._pi_amp_excited = pi_amp_excited
if visual:
print("The amplitude-signal plot of rabi oscillation for 1->2 transition.")
plt.figure()
plt.scatter(amp_list, rabi_data, color='black')
plt.plot(amp_list, rabi_y_fit, color='red')
# account for phi in computing pi amp
plt.axvline(self._pi_amp_excited, color='red', linestyle='--')
plt.axvline(self._pi_amp_excited+drive_period_excited/2, color='red', linestyle='--')
plt.annotate("", xy=(self._pi_amp_excited+drive_period_excited/2, 0),
xytext=(self._pi_amp_excited, 0),
arrowprops=dict(arrowstyle="<->", color='red'))
#plt.annotate("$\\pi$", xy=(self._pi_amp_excited-0.03, 0.1), color='red')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.title('Rabi Experiment (1->2)', fontsize=20)
plt.show()
return [self._pi_amp_excited, amp_list, rabi_data]
def get_pi_pulse_ground(self):
"""Returns a pi pulse of the 0->1 transition."""
pulse = pulse_lib.gaussian(duration=self._pulse_duration,
sigma=self._pulse_sigma, amp=self._pi_amp_ground)
return pulse
def get_pi_pulse_excited(self):
"""Returns a pi pulse of the 1->2 transition."""
pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma,
amp=self._pi_amp_excited)
excited_pulse = self.apply_sideband(pulse, self._qubit_freq_excited)
return excited_pulse
def get_x90_pulse_ground(self):
"""Returns a pi/2 pulse of the 0->1 transition."""
pulse = pulse_lib.gaussian(duration=self._pulse_duration,
sigma=self._pulse_sigma, amp=self._pi_amp_ground/2)
return pulse
def get_x90_pulse_excited(self):
"""Returns a pi/2 pulse of the 1->2 transition."""
pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma,
amp=self._pi_amp_excited/2)
excited_pulse = self.apply_sideband(pulse, self._qubit_freq_excited)
return excited_pulse
def get_zero_sched(self):
"""Returns a schedule that performs only a measurement."""
zero_sched = Schedule()
zero_sched += self._measure
return zero_sched
def get_one_sched(self):
"""Returns a schedule that creates a |1> state from |0> by applying
a pi pulse of 0->1 transition and performs a measurement."""
one_sched = Schedule()
one_sched += Play(self.get_pi_pulse_ground(), self._drive_chan)
one_sched += self._measure << one_sched.duration
return one_sched
def get_two_sched(self):
"""Returns a schedule that creates a |2> state from |0> by applying
a pi pulse of 0->1 transition followed by applying a pi pulse
of 1->2 transition and performs a measurement."""
two_sched = Schedule()
two_sched += Play(self.get_pi_pulse_ground(), self._drive_chan)
two_sched += Play(self.get_pi_pulse_excited(), self._drive_chan)
two_sched += self._measure << two_sched.duration
return two_sched
@staticmethod
def _create_iq_plot(zero_data, one_data, two_data):
"""Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given
as arguments."""
# zero data plotted in blue
plt.scatter(np.real(zero_data), np.imag(zero_data),
s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$')
# one data plotted in red
plt.scatter(np.real(one_data), np.imag(one_data),
s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$')
# two data plotted in green
plt.scatter(np.real(two_data), np.imag(two_data),
s=5, cmap='viridis', c='green', alpha=0.5, label=r'$|2\rangle$')
x_min = np.min(np.append(np.real(zero_data), np.append(np.real(one_data),
np.real(two_data))))-5
x_max = np.max(np.append(np.real(zero_data), np.append(np.real(one_data),
np.real(two_data))))+5
y_min = np.min(np.append(np.imag(zero_data), np.append(np.imag(one_data),
np.imag(two_data))))-5
y_max = np.max(np.append(np.imag(zero_data), np.append(np.imag(one_data),
np.imag(two_data))))+5
# Plot a large dot for the average result of the 0, 1 and 2 states.
mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts
mean_one = np.mean(one_data)
mean_two = np.mean(two_data)
plt.scatter(np.real(mean_zero), np.imag(mean_zero),
s=200, cmap='viridis', c='black', alpha=1.0)
plt.scatter(np.real(mean_one), np.imag(mean_one),
s=200, cmap='viridis', c='black', alpha=1.0)
plt.scatter(np.real(mean_two), np.imag(mean_two),
s=200, cmap='viridis', c='black', alpha=1.0)
# plt.xlim(x_min, x_max)
# plt.ylim(y_min, y_max)
plt.legend()
plt.ylabel('I [a.u.]', fontsize=15)
plt.xlabel('Q [a.u.]', fontsize=15)
plt.title("0-1-2 discrimination", fontsize=15)
return x_min, x_max, y_min, y_max
@staticmethod
def reshape_complex_vec(vec):
"""Take in complex vector vec and return 2d array w/ real, imag entries.
This is needed for the learning.
Args:
vec (list): complex vector of data
Returns:
list: vector w/ entries given by (real(vec], imag(vec))
"""
length = len(vec)
vec_reshaped = np.zeros((length, 2))
for i, item in enumerate(vec):
vec_reshaped[i] = [np.real(item), np.imag(item)]
return vec_reshaped
def find_three_level_discriminator(self, verbose=False, visual=False):
"""Returns a discriminator for discriminating 0-1-2 states."""
# pylint: disable=too-many-locals
zero_sched = self.get_zero_sched()
one_sched = self.get_one_sched()
two_sched = self.get_two_sched()
iq_job = execute([zero_sched, one_sched, two_sched], backend=self._backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*3
)
jid = iq_job.job_id()
if verbose:
print('Job Id : ', jid)
# job_monitor(iq_job)
iq_job = self._backend.retrieve_job(jid)
iq_data = self.get_job_data(iq_job, average=False)
zero_data = iq_data[0]
one_data = iq_data[1]
two_data = iq_data[2]
if visual:
print("The discriminator plot for 0-1-2 discrimination.")
x_min, x_max, y_min, y_max = self._create_iq_plot(zero_data, one_data, two_data)
# Create IQ vector (split real, imag parts)
zero_data_reshaped = self.reshape_complex_vec(zero_data)
one_data_reshaped = self.reshape_complex_vec(one_data)
two_data_reshaped = self.reshape_complex_vec(two_data)
iq_data = np.concatenate((zero_data_reshaped, one_data_reshaped, two_data_reshaped))
# construct vector w/ 0's, 1's and 2's (for testing)
state_012 = np.zeros(1024) # shots gives number of experiments
state_012 = np.concatenate((state_012, np.ones(1024)))
state_012 = np.concatenate((state_012, 2*np.ones(1024)))
# Shuffle and split data into training and test sets
iq_012_train, iq_012_test, state_012_train, state_012_test = train_test_split(iq_data,
state_012,
test_size=0.5)
classifier_lda_012 = LinearDiscriminantAnalysis()
classifier_lda_012.fit(iq_012_train, state_012_train)
score_012 = classifier_lda_012.score(iq_012_test, state_012_test)
if verbose:
print('The accuracy score of the discriminator is: ', score_012)
self._state_discriminator_012 = classifier_lda_012
if visual:
self._separatrix_plot(classifier_lda_012, x_min, x_max, y_min, y_max, 1024)
return self._state_discriminator_012
@staticmethod
def _separatrix_plot(lda, x_min, x_max, y_min, y_max, shots):
"""Returns a sepratrix plot for the classifier."""
# pylint: disable=too-many-arguments
num_x, num_y = shots, shots
xvals, vals = np.meshgrid(np.linspace(x_min, x_max, num_x),
np.linspace(y_min, y_max, num_y))
predict_prob = lda.predict_proba(np.c_[xvals.ravel(), vals.ravel()])
predict_prob = predict_prob[:, 1].reshape(xvals.shape)
plt.contour(xvals, vals, predict_prob, [0.5], linewidths=2., colors='black')
def get_qubit_freq_ground(self):
"""Returns the set 0->1 transition frequency."""
return self._qubit_freq_ground
def get_qubit_freq_excited(self):
"""Returns the set 1->2 transition frequency."""
return self._qubit_freq_excited
def get_pi_amp_ground(self):
"""Returns the set 0->1 transition pi pulse amplitude."""
return self._pi_amp_ground
def get_pi_amp_excited(self):
"""Returns the set 1->2 transition pi pulse amplitude."""
return self._pi_amp_excited
def get_three_level_discriminator(self):
"""Returns the set 0-1-2 state discriminator."""
return self._state_discriminator_012
def calibrate_all(self, verbose=False, visual=False):
"""Calibrates and sets both the ground and excited transition frequencies and
corresponding pi pulse amplitudes. Also constructs a 0-1-2 state discriminator."""
ground_freq = self.find_freq_ground(verbose, visual)
ground_amp = self.find_pi_amp_ground(verbose, visual)
excited_freq = self.find_freq_excited(verbose, visual)
excited_amp = self.find_pi_amp_excited(verbose, visual)
state_discriminator = self.find_three_level_discriminator(verbose, visual)
return ground_freq, ground_amp, excited_freq, excited_amp, state_discriminator
anharmon = backend.properties().qubit_property(qubit)['anharmonicity'][0]
qu_freq = backend.properties().qubit_property(qubit)['frequency'][0]
print(qu_freq)
print(anharmon)
print(qu_freq+anharmon)
backend = provider.get_backend('ibmq_casablanca')
# backend = provider.get_backend('ibmq_jakarta')
# backend = provider.get_backend('ibmq_rome')
qubit = 0
cal_object = PulseCalibration(backend, qubit)
visual = True
verbose = True
ground_freq_list = cal_object.find_freq_ground(verbose, visual)
[ground_freq, freq_list, sweep_vals] = ground_freq_list
print(ground_freq)
cal_object = PulseCalibration(backend, qubit, qubit_freq_ground=ground_freq)
ground_amp_list = cal_object.find_pi_amp_ground(verbose, visual)
pi_amp_ground = ground_amp_list[0]
amp_list = ground_amp_list[1]
rabi_values = ground_amp_list[2]
def find_init_params_amp(amp_list, rabi_values):
min_index = np.where(rabi_values==min(rabi_values))[0][0]
max_index = np.where(rabi_values==max(rabi_values))[0][0]
scale_est = (max(rabi_values) - min(rabi_values))/2
shift_est = amp_list[min_index]
period_est = 2*np.abs(amp_list[max_index] - amp_list[min_index])
slope = np.sign(rabi_values[1]-rabi_values[0])
if slope < 0:
phi_est = 3*np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi)
else:
phi_est = -np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi)
return [scale_est, shift_est, period_est, phi_est]
def find_init_params_amp(amp_list, rabi_values):
min_index = np.where(rabi_values==min(rabi_values))[0][0]
max_index = np.where(rabi_values==max(rabi_values))[0][0]
scale_est = (max(rabi_values) - min(rabi_values))/2
shift_est = (max(rabi_values) + min(rabi_values))/2
shift_est = np.mean(rabi_values)
# period_est = 2*np.abs(amp_list[max_index] - amp_list[min_index])
period_est = 0.5
slope = np.sign(rabi_values[1]-rabi_values[0])
if ((max(rabi_values)-rabi_values[0])/(2*scale_est)) < 0.5:
phi_est = np.pi/2
else:
phi_est = -np.pi/2
# if slope >= 0:
# phi_est = 3*np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi)
# else:
# phi_est = -np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi)
return [scale_est, shift_est, period_est, phi_est]
def fit_function(x_values, y_values, function, init_params):
""" A function fitter. Returns the fit parameters of 'function'."""
fitparams, _ = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
# Obtain the optimal paramters that fit the result data.
init_params = find_init_params_amp(amp_list,rabi_values)
print(init_params)
# init_params = [3.0733272e-07, 0.5, 0.25, 1.57]
fit_params, y_fit = fit_function(amp_list,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B),
init_params)
drive_period = fit_params[2]
pi_amp_ground = drive_period/2
print(fit_params)
print("The amplitude-signal plot for rabi oscillation for 0->1 transition.")
plt.figure()
plt.scatter(amp_list, rabi_values, color='black')
plt.plot(amp_list, y_fit, color='red')
plt.axvline(drive_period/2, color='red', linestyle='--')
plt.axvline(drive_period, color='red', linestyle='--')
plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2, 0),
arrowprops=dict(arrowstyle="<->", color='red'))
plt.annotate("$\pi$", xy=(drive_period/2-0.04, np.mean(rabi_values)), color='red')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
fit_params
cal_object._pi_amp_ground=pi_amp_ground
print(ground_freq)
print(pi_amp_ground)
cal_object = PulseCalibration(backend, qubit, qubit_freq_ground=ground_freq, pi_amp_ground=pi_amp_ground)
excited_list = cal_object.find_freq_excited(verbose, visual)
excited_freq = excited_list[0]
excited_freq_list = excited_list[1]
excited_sweep_data = excited_list[2]
excited_freq_list_GHz = excited_freq_list/1e+9
excited_freq
if visual:
print("The frequency-signal plot of frequency sweep for 1->2 transition.")
# Note: we are only plotting the real part of the signal
plt.scatter(excited_freq_list_GHz, excited_sweep_data, color='black')
plt.xlim([min(excited_freq_list_GHz), max(excited_freq_list_GHz)])
plt.xlabel("Frequency [GHz]", fontsize=15)
plt.ylabel("Measured Signal [a.u.]", fontsize=15)
plt.title("1->2 Frequency Sweep", fontsize=15)
plt.show()
# qubit_anharmon = backend.properties().qubit_property(0)['anharmonicity'][0]
# qubit_freq = backend.properties().qubit_property(0)['frequency'][0]
# qubit_anharmon
# qubit_freq+qubit_anharmon
# def fit_function(x_values, y_values, function, init_params):
# """ A function fitter. Returns the fit parameters of 'function'."""
# fitparams, _ = curve_fit(function, x_values, y_values, init_params)
# y_fit = function(x_values, *fitparams)
# return fitparams, y_fit
# # def find_init_params(freq_list, res_values):
# # hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0]
# # hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0]
# # if hmin_index < hmax_index:
# # est_baseline = min(res_values)
# # est_slope = (res_values[hmax_index] - res_values[hmin_index])/(freq_list[hmax_index] - freq_list[hmin_index])
# # else:
# # est_baseline = max(res_values)
# # est_slope = (res_values[hmin_index] - res_values[hmax_index])/(freq_list[hmin_index] - freq_list[hmax_index])
# # return [est_slope, (qubit_freq+qubit_anharmon)/1e9, 0.05*1e+9, est_baseline]
# def find_init_params_gauss(freq_list, res_values):
# hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0]
# hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0]
# mean_est = freq_list[hmax_index]
# var_est = np.abs(freq_list[hmax_index]-freq_list[hmin_index])/2
# scale_est = max(res_values)-min(res_values)
# shift_est = min(res_values)
# return [mean_est, var_est, scale_est, shift_est]
# def lorentzian(xval, scale, q_freq, hwhm, shift):
# return ((scale / np.pi) * (hwhm / ((xval - q_freq)**2 + hwhm**2))) + shift
# def gauss(x, mean, var, scale, shift):
# return (scale*(1/var*np.sqrt(2*np.pi))*np.exp(-(1/2)*(((x-mean)/var)**2)))+shift
# # do fit in Hz
# # init_params = find_init_params(excited_freq_list_GHz, np.real(excited_sweep_data))
# init_params = find_init_params_gauss(excited_freq_list_GHz, np.real(excited_sweep_data))
# print("Init params : ", init_params)
# # excited_sweep_fit_params, excited_sweep_y_fit = fit_function(excited_freq_list_GHz,
# # excited_sweep_data,
# # lorentzian,
# # [1e-7, 4631077333.915148, 0.08, -2.6e-7]
# # )
# excited_sweep_fit_params, excited_sweep_y_fit = fit_function(excited_freq_list_GHz,
# excited_sweep_data,
# gauss,
# init_params
# )
# # xlist = qubit_freq+qubit_anharmon + np.arange(-4,4,0.1)
# # y = [lorentzian(x,0.00002,(qubit_freq+qubit_anharmon)/1e+9, 1, 0) for x in excited_freq_list_GHz]
# shift = -2.6e-7
# y = [(1e-7*lor(x,(qubit_freq+qubit_anharmon)/1e+9,0.08))+shift for x in excited_freq_list_GHz]
# if visual:
# print("The frequency-signal plot of frequency sweep for 1->2 transition.")
# # Note: we are only plotting the real part of the signal
# plt.scatter(excited_freq_list/1e+9, excited_sweep_data, color='black')
# # plt.plot(excited_freq_list_GHz, y, color='green')
# plt.plot(excited_freq_list/1e+9, excited_sweep_y_fit, color='red')
# # plt.plot(excited_freq_list_GHz, shift, color='blue')
# plt.xlim([min(excited_freq_list/1e+9), max(excited_freq_list/1e+9)])
# plt.xlabel("Frequency [GHz]", fontsize=15)
# plt.ylabel("Measured Signal [a.u.]", fontsize=15)
# plt.title("1->2 Frequency Sweep", fontsize=15)
# plt.show()
# qubit_freq_12,_, _, _ = excited_sweep_fit_params
# print('fit params : ', excited_sweep_fit_params)
# qubit_freq_excited = qubit_freq_12*1e+9
# if verbose:
# print(f"The calibrated frequency for the 1->2 transition is {qubit_freq_excited}.")
# def gauss(x, mean, var, scale, shift):
# return (scale*(1/var*np.sqrt(2*np.pi))*np.exp(-(1/2)*(((x-mean)/var)**2)))+shift
# function = gauss
# x_values = excited_freq_list_GHz
# y_values = excited_sweep_data
# init_params = [4.63, 0.02, 1e-7, 1]
# fitparams, _ = curve_fit(function, x_values, y_values, init_params)
# y_fit = function(x_values, *fitparams)
# plt.plot(excited_freq_list_GHz, y_fit, color='red')
# plt.scatter(excited_freq_list_GHz, excited_sweep_data, color='black')
cal_object = PulseCalibration(backend, qubit,
qubit_freq_ground=ground_freq, pi_amp_ground=pi_amp_ground,
qubit_freq_excited = excited_freq)
pi_amp_excited_list = cal_object.find_pi_amp_excited(verbose, visual)
[excited_amp, amp_list, rabi_data] = pi_amp_excited_list
def fit_function(x_values, y_values, function, init_params):
""" A function fitter. Returns the fit parameters of 'function'."""
fitparams, _ = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
def baseline_remove(values):
"""Centering data around zero."""
return np.array(values) - np.mean(values)
# def find_init_params_amp(amp_list, rabi_values):
# min_index = np.where(rabi_values==min(rabi_values))[0][0]
# max_index = np.where(rabi_values==max(rabi_values))[0][0]
# scale_est = (max(rabi_values) - min(rabi_values))/2
# shift_est = amp_list[min_index]
# period_est = 2*np.abs(amp_list[max_index] - amp_list[min_index])
# slope = np.sign(rabi_values[1]-rabi_values[0])
# if slope < 0:
# phi_est = 3*np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi)
# else:
# phi_est = -np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi)
# return [scale_est, shift_est, period_est, phi_est]
def find_init_params_amp(amp_list, rabi_values):
min_index = np.where(rabi_values==min(rabi_values))[0][0]
max_index = np.where(rabi_values==max(rabi_values))[0][0]
scale_est = (max(rabi_values) - min(rabi_values))/2
shift_est = (max(rabi_values) + min(rabi_values))/2
shift_est = np.mean(rabi_values)
# period_est = 2*np.abs(amp_list[max_index] - amp_list[min_index])
period_est = 0.5
slope = np.sign(rabi_values[1]-rabi_values[0])
if ((max(rabi_values)-rabi_values[0])/(2*scale_est)) < 0.5:
phi_est = np.pi/2
else:
phi_est = -np.pi/2
# if slope >= 0:
# phi_est = 3*np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi)
# else:
# phi_est = -np.pi/2 - (((max(rabi_values)-rabi_values[0])/(2*scale_est))*np.pi)
return [scale_est, shift_est, period_est, phi_est]
init_params = find_init_params_amp(amp_list, rabi_data)
print('Init params for 01 amp : ', init_params)
# init_params = [8.797258e-08, 0, 0.4, np.pi/2]
print('Init params for 01 amp : ', init_params)
(rabi_fit_params,
rabi_y_fit) = fit_function(amp_list,
rabi_data,
lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B),
init_params)
drive_period_excited = rabi_fit_params[2]
pi_amp_excited = (drive_period_excited/2/np.pi) * (np.pi+rabi_fit_params[3])
# pi_amp_excited = pi_amp_excited
if visual:
print("The amplitude-signal plot of rabi oscillation for 1->2 transition.")
plt.figure()
plt.scatter(amp_list, rabi_data, color='black')
plt.plot(amp_list, rabi_y_fit, color='red')
# # account for phi in computing pi amp
plt.axvline(pi_amp_excited, color='red', linestyle='--')
plt.axvline(pi_amp_excited+drive_period_excited/2, color='red', linestyle='--')
plt.annotate("", xy=(pi_amp_excited+drive_period_excited/2, 0),
xytext=(pi_amp_excited, 0),
arrowprops=dict(arrowstyle="<->", color='red'))
# plt.annotate("$\\pi$", xy=(pi_amp_excited-0.03, 0.1), color='red')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.title('Rabi Experiment (1->2)', fontsize=20)
plt.show()
pi_amp_excited
rabi_fit_params
print(ground_freq)
print(pi_amp_ground)
print(excited_freq)
print(pi_amp_excited)
cal_object = PulseCalibration(backend, qubit,
qubit_freq_ground=ground_freq, pi_amp_ground=pi_amp_ground,
qubit_freq_excited = excited_freq, pi_amp_excited=pi_amp_excited
)
discrim = cal_object.find_three_level_discriminator(verbose, visual)
def create_iq_plot(zero_data, one_data, two_data):
"""Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given
as arguments."""
# zero data plotted in blue
plt.scatter(np.real(zero_data), np.imag(zero_data),
s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$')
# one data plotted in red
plt.scatter(np.real(one_data), np.imag(one_data),
s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$')
# two data plotted in green
plt.scatter(np.real(two_data), np.imag(two_data),
s=5, cmap='viridis', c='green', alpha=0.5, label=r'$|2\rangle$')
x_min = np.min(np.append(np.real(zero_data), np.append(np.real(one_data),
np.real(two_data))))-5
x_max = np.max(np.append(np.real(zero_data), np.append(np.real(one_data),
np.real(two_data))))+5
y_min = np.min(np.append(np.imag(zero_data), np.append(np.imag(one_data),
np.imag(two_data))))-5
y_max = np.max(np.append(np.imag(zero_data), np.append(np.imag(one_data),
np.imag(two_data))))+5
# Plot a large dot for the average result of the 0, 1 and 2 states.
mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts
mean_one = np.mean(one_data)
mean_two = np.mean(two_data)
plt.scatter(np.real(mean_zero), np.imag(mean_zero),
s=200, cmap='viridis', c='black', alpha=1.0)
plt.scatter(np.real(mean_one), np.imag(mean_one),
s=200, cmap='viridis', c='black', alpha=1.0)
plt.scatter(np.real(mean_two), np.imag(mean_two),
s=200, cmap='viridis', c='black', alpha=1.0)
# plt.xlim(x_min, x_max)
# plt.ylim(y_min, y_max)
plt.legend()
plt.ylabel('I [a.u.]', fontsize=15)
plt.xlabel('Q [a.u.]', fontsize=15)
plt.title("0-1-2 discrimination", fontsize=15)
return x_min, x_max, y_min, y_max
def reshape_complex_vec(vec):
"""Take in complex vector vec and return 2d array w/ real, imag entries.
This is needed for the learning.
Args:
vec (list): complex vector of data
Returns:
list: vector w/ entries given by (real(vec], imag(vec))
"""
length = len(vec)
vec_reshaped = np.zeros((length, 2))
for i, item in enumerate(vec):
vec_reshaped[i] = [np.real(item), np.imag(item)]
return vec_reshaped
def separatrix_plot(lda, x_min, x_max, y_min, y_max, shots):
"""Returns a sepratrix plot for the classifier."""
# pylint: disable=too-many-arguments
num_x, num_y = shots, shots
xvals, vals = np.meshgrid(np.linspace(x_min-4, x_max+4, num_x),
np.linspace(y_min-4, y_max+4, num_y))
predict_prob = lda.predict_proba(np.c_[xvals.ravel(), vals.ravel()])
predict_prob = predict_prob[:, 1].reshape(xvals.shape)
plt.contour(xvals, vals, predict_prob, [0.5], linewidths=2., colors='black')
def get_job_data(job, average):
"""Retrieve data from a job that has already run.
Args:
job (Job): The job whose data you want.
average (bool): If True, gets the data assuming data is an average.
If False, gets the data assuming it is for single shots.
Return:
list: List containing job result data.
"""
scale_factor = 1e-14
job_results = job.result(timeout=120) # timeout parameter set to 120 s
result_data = []
for i in range(len(job_results.results)):
if average: # get avg data
result_data.append(job_results.get_memory(i)[qubit]*scale_factor)
else: # get single data
result_data.append(job_results.get_memory(i)[:, qubit]*scale_factor)
return result_data
iq_job = backend.retrieve_job('60b46e055255f0dc9738af93')
iq_data = get_job_data(iq_job, average=False)
zero_data = iq_data[0]
one_data = iq_data[1]
two_data = iq_data[2]
if visual:
print("The discriminator plot for 0-1-2 discrimination.")
x_min, x_max, y_min, y_max = create_iq_plot(zero_data, one_data, two_data)
# Create IQ vector (split real, imag parts)
zero_data_reshaped = reshape_complex_vec(zero_data)
one_data_reshaped = reshape_complex_vec(one_data)
two_data_reshaped = reshape_complex_vec(two_data)
iq_data = np.concatenate((zero_data_reshaped, one_data_reshaped, two_data_reshaped))
# construct vector w/ 0's, 1's and 2's (for testing)
state_012 = np.zeros(1024) # shots gives number of experiments
state_012 = np.concatenate((state_012, np.ones(1024)))
state_012 = np.concatenate((state_012, 2*np.ones(1024)))
# Shuffle and split data into training and test sets
iq_012_train, iq_012_test, state_012_train, state_012_test = train_test_split(iq_data,
state_012,
test_size=0.5)
classifier_lda_012 = LinearDiscriminantAnalysis()
classifier_lda_012.fit(iq_012_train, state_012_train)
score_012 = classifier_lda_012.score(iq_012_test, state_012_test)
if verbose:
print('The accuracy score of the discriminator is: ', score_012)
state_discriminator_012 = classifier_lda_012
if visual:
x_min, x_max, y_min, y_max = create_iq_plot(zero_data, one_data, two_data)
separatrix_plot(classifier_lda_012, x_min, x_max, y_min, y_max, 1024)
# return self._state_discriminator_012
back_config = backend.configuration()
back_defaults = backend.defaults()
inst_sched_map = back_defaults.instruction_schedule_map
meas_map_idx = None
for i, measure_group in enumerate(back_config.meas_map):
if qubit in measure_group:
meas_map_idx = i
break
assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!"
# The measurement pulse for measuring the qubit of interest.
measure = inst_sched_map.get('measure', qubits=back_config.meas_map[meas_map_idx])
sigma = 40
duration = 4*40
chan = DriveChannel(0)
with pulse.build(backend) as test_0:
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground), chan)
pulse.set_frequency(excited_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited), chan)
test_0 += measure << test_0.duration
test_0.draw()
test0_job = execute(test_0, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test0 = test0_job.job_id()
print(jid_test0)
test0_job = backend.retrieve_job(jid_test0)
res = get_job_data(test0_job, average=False)
res[0]
reshaped_res = reshape_complex_vec(res[0])
plt.scatter(np.real(res[0]), np.imag(res[0]))
plt.show()
output = discrim.predict(reshaped_res)
arr = [0,0,0]
for i in output:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
with pulse.build(backend) as test_00:
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground), chan)
test_00 += measure << test_00.duration
test_00.draw()
test00_job = execute(test_00, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test00 = test00_job.job_id()
print(jid_test00)
test00_job = backend.retrieve_job(jid_test00)
res00 = get_job_data(test00_job, average=False)
res[0]
reshaped_res00 = reshape_complex_vec(res00[0])
plt.scatter(np.real(res[0]), np.imag(res00[0]))
plt.show()
output00 = discrim.predict(reshaped_res00)
arr = [0,0,0]
for i in output00:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H then Z then H gate on 0-1
# Should get |1> ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_1:
# Setting 0-1 frequency for channel and applying H gate
pulse.set_frequency(ground_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
# Applying a Z pulse
pulse.shift_phase(np.pi, chan)
# Applying H gate on 0-1
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_1 += measure << test_pulse_1.duration
test_pulse_1.draw()
test1_job = execute(test_pulse_1, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test1 = test1_job.job_id()
print(jid_test1)
test1_job = backend.retrieve_job(jid_test1)
res1 = get_job_data(test1_job, average=False)
reshaped_res1 = reshape_complex_vec(res1[0])
plt.scatter(np.real(res1[0]), np.imag(res1[0]))
plt.show()
output1 = discrim.predict(reshaped_res1)
arr = [0,0,0]
for i in output1:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H then Z then H gate on 1-2
# Should get |2> ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_2:
# Exciting the qubit to |1> state
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan)
# Setting 1-2 frequency for channel and applying H gate
pulse.set_frequency(excited_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
# Applying a Z pulse
pulse.shift_phase(np.pi, chan)
# Applying H gate on 1-2
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_2 += measure << test_pulse_2.duration
test_pulse_2.draw()
test2_job = execute(test_pulse_2, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test2 = test2_job.job_id()
print(jid_test2)
test2_job = backend.retrieve_job(jid_test2)
res2 = get_job_data(test2_job, average=False)
reshaped_res2 = reshape_complex_vec(res2[0])
plt.scatter(np.real(res2[0]), np.imag(res2[0]))
plt.show()
output2 = discrim.predict(reshaped_res2)
arr = [0,0,0]
for i in output2:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H on 0-1, then H on 1-2
# then Z on 1-2 followed by H on 1-2
# Should get |0>/sqrt(2) + |2>/sqrt(2)
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_3:
# Setting 0-1 frequency for channel and applying H gate
pulse.set_frequency(ground_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
# Undoing phase appied during 0-1 transitions
pulse.shift_phase(np.pi, chan)
# Setting 1-2 frequency for channel and applying H gate
pulse.set_frequency(excited_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
# Applying a Z pulse
pulse.shift_phase(np.pi, chan)
# Applying H gate on 1-2
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_3 += measure << test_pulse_3.duration
test_pulse_3.draw()
test3_job = execute(test_pulse_3, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test3 = test3_job.job_id()
print(jid_test3)
test3_job = backend.retrieve_job(jid_test3)
res3 = get_job_data(test3_job, average=False)
reshaped_res3 = reshape_complex_vec(res3[0])
plt.scatter(np.real(res3[0]), np.imag(res3[0]))
plt.show()
output3 = discrim.predict(reshaped_res3)
arr = [0,0,0]
for i in output3:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H on 1-2
# Should get |1>/sqrt(2) + |2>/sqrt(2) ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_4:
# Exciting the qubit to |1> state
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan)
# Setting 1-2 frequency for channel and applying H gate
pulse.set_frequency(excited_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_4 += measure << test_pulse_4.duration
test_pulse_4.draw()
test4_job = execute(test_pulse_4, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test4 = test4_job.job_id()
print(jid_test4)
test4_job = backend.retrieve_job(jid_test4)
res4 = get_job_data(test4_job, average=False)
reshaped_res4 = reshape_complex_vec(res4[0])
plt.scatter(np.real(res4[0]), np.imag(res4[0]))
plt.show()
output4 = discrim.predict(reshaped_res4)
arr = [0,0,0]
for i in output4:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H on 0-1
# Should get |0>/sqrt(2) + |1>/sqrt(2) ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_5:
# Setting 0-1 frequency for channel and applying H gate
pulse.set_frequency(ground_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_5 += measure << test_pulse_5.duration
test_pulse_5.draw()
test5_job = execute(test_pulse_5, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test5 = test5_job.job_id()
print(jid_test5)
test5_job = backend.retrieve_job(jid_test5)
res5 = get_job_data(test5_job, average=False)
reshaped_res5 = reshape_complex_vec(res5[0])
plt.scatter(np.real(res5[0]), np.imag(res5[0]))
plt.show()
output5 = discrim.predict(reshaped_res5)
arr = [0,0,0]
for i in output5:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a X on 0-1
# Should get |1> ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_6:
# Setting 0-1 frequency for channel and applying X gate
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan)
test_pulse_6 += measure << test_pulse_6.duration
test_pulse_6.draw()
test6_job = execute(test_pulse_6, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test6 = test6_job.job_id()
print(jid_test6)
test6_job = backend.retrieve_job(jid_test6)
res6 = get_job_data(test6_job, average=False)
reshaped_res6 = reshape_complex_vec(res6[0])
plt.scatter(np.real(res6[0]), np.imag(res6[0]))
plt.show()
output6 = discrim.predict(reshaped_res6)
arr = [0,0,0]
for i in output6:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a X on 1-2
# Should get |2> ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_7:
# Setting 0-1 frequency for channel and applying 0-1 pi pulse
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan)
# Setting 1-2 frequency for channel and applying 1-2 pi pulse
pulse.set_frequency(excited_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited, name='X(pi)'), chan)
test_pulse_7 += measure << test_pulse_7.duration
test_pulse_7.draw()
test7_job = execute(test_pulse_7, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test7 = test7_job.job_id()
print(jid_test7)
test7_job = backend.retrieve_job(jid_test7)
res7 = get_job_data(test7_job, average=False)
reshaped_res7 = reshape_complex_vec(res7[0])
plt.scatter(np.real(res7[0]), np.imag(res7[0]))
plt.show()
output7 = discrim.predict(reshaped_res7)
arr = [0,0,0]
for i in output7:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
|
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
|
nahumsa
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit.circuit.library.standard_gates import XGate, HGate
from operator import *
n = 3
N = 8 #2**n
index_colour_table = {}
colour_hash_map = {}
index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"}
colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'}
def database_oracle(index_colour_table, colour_hash_map):
circ_database = QuantumCircuit(n + n)
for i in range(N):
circ_data = QuantumCircuit(n)
idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
# qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0
# we therefore reverse the index string -> q0, ..., qn
data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour)
circ_database.append(data_gate, list(range(n+n)))
return circ_database
# drawing the database oracle circuit
print("Database Encoding")
database_oracle(index_colour_table, colour_hash_map).draw()
circ_data = QuantumCircuit(n)
m = 4
idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
print("Internal colour encoding for the colour green (as an example)");
circ_data.draw()
def oracle_grover(database, data_entry):
circ_grover = QuantumCircuit(n + n + 1)
circ_grover.append(database, list(range(n+n)))
target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target")
# control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()'
# The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.
circ_grover.append(target_reflection_gate, list(range(n, n+n+1)))
circ_grover.append(database, list(range(n+n)))
return circ_grover
print("Grover Oracle (target example: orange)")
oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw()
def mcz_gate(num_qubits):
num_controls = num_qubits - 1
mcz_gate = QuantumCircuit(num_qubits)
target_mcz = QuantumCircuit(1)
target_mcz.z(0)
target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ")
mcz_gate.append(target_mcz, list(range(num_qubits)))
return mcz_gate.reverse_bits()
print("Multi-controlled Z (MCZ) Gate")
mcz_gate(n).decompose().draw()
def diffusion_operator(num_qubits):
circ_diffusion = QuantumCircuit(num_qubits)
qubits_list = list(range(num_qubits))
# Layer of H^n gates
circ_diffusion.h(qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of Multi-controlled Z (MCZ) Gate
circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of H^n gates
circ_diffusion.h(qubits_list)
return circ_diffusion
print("Diffusion Circuit")
diffusion_operator(n).draw()
# Putting it all together ... !!!
item = "green"
print("Searching for the index of the colour", item)
circuit = QuantumCircuit(n + n + 1, n)
circuit.x(n + n)
circuit.barrier()
circuit.h(list(range(n)))
circuit.h(n+n)
circuit.barrier()
unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator")
unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator")
M = countOf(index_colour_table.values(), item)
Q = int(np.pi * np.sqrt(N/M) / 4)
for i in range(Q):
circuit.append(unitary_oracle, list(range(n + n + 1)))
circuit.append(unitary_diffuser, list(range(n)))
circuit.barrier()
circuit.measure(list(range(n)), list(range(n)))
circuit.draw()
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
if M==1:
print("Index of the colour", item, "is the index with most probable outcome")
else:
print("Indices of the colour", item, "are the indices the most probable outcomes")
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.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]
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the 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()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/EusseJhoan/DeutschJosza_algorithm
|
EusseJhoan
|
from qiskit import QuantumCircuit, transpile, Aer
from qiskit.visualization import plot_histogram
import numpy as np
sim = Aer.get_backend('aer_simulator')
def U_f1(qc):
return qc
def U_f2(qc):
qc.x(1) #Compuerta X al segundo qubit
return qc
def U_f3(qc):
qc.cx(0,1) #Compuerta CNOT entre primer y segundo quibit (el primero es el que controla)
return qc
def U_f4(qc):
qc.cx(0,1) #Compuerta CNOT entre primer y segundo quibit (el primero es el que controla)
qc.x(1) #Compuerta X al segundo qubit
return qc
def Deutsch(U_f):
qc=QuantumCircuit(2,1) #Se crea un circuito cuántico con 2 bits cuánticos y 1 canal clásico
qc.x(1) #Compuerta X al segundo qubit (inicializar estado |1>)
qc.h(0) #Compuerta H al primer qubit
qc.h(1) #Compuerta H al segundo qubit
qc.barrier() #Barrera (empieza oráculo)
qc = U_f(qc) #Agregamos el oráculo
qc.barrier() #Barrera (termina oráculo)
qc.h(0) #Compuerta H al primer qubit
qc.measure(0,0) #Medimos el primer qubit y enviamos señal al canal clásico
return qc
qc=Deutsch(U_f1) # definición circuito con oráculo usando f_1(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=Deutsch(U_f2) #definición circuito con oráculo usando f_2(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas del simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=Deutsch(U_f3) #definición circuito con oráculo usando f_3(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=Deutsch(U_f4) #definición circuito con oráculo usando f_4(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
#oráculo para f(x) constante para un número n de bits en el registro
def constant(qc,n):
ran=np.random.randint(2) #selección aleatoria de 0 ó 1
if ran == 1:
qc.x(n) #si el número aleatorio es 1 se pone compuerta X en el objetivo (se induce fase global -1 al registro)
return qc
#oráculo para f(x) balanceado para un número n de bits en el registro
def balanced(qc,n):
for i in range(n):
qc.cx(i,n) #se crea una CNOT entre cada qubit del registro y el objetivo (los qubits del registro controlan)
ran=np.random.randint(2) #selección aleatoria de 0 ó 1
if ran == 1:
qc.x(n) #si el número aleatorio es 1 se pone compuerta X en el objetivo (se induce fase global -1 al registro)
return qc
def D_J(U_f,n):
qc=QuantumCircuit(n+1,n) #Se crea un circuito cuántico con n+1 quibits y n canales clásicos
qc.x(n) #Compuerta X al bit del registro
for i in range(n+1):
qc.h(i) #Compuerta H a todos los bits
qc.barrier() #Barrera (empieza oráculo)
qc = U_f(qc,n) #Agregamos el oráculo
qc.barrier() #Barrera (termina oráculo)
for i in range(n):
qc.h(i) #Compuerta H a los n bits del registro
qc.measure(i,i) #Medición los n bits del registro
return qc
qc=D_J(constant,3) #definición circuito con oráculo constante y 3 bits en registro
display(qc.draw()) #ver circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=D_J(balanced,3)
display(qc.draw())
counts = sim.run(qc).result().get_counts()
plot_histogram(counts)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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 the CSPLayout pass"""
import unittest
from time import process_time
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes import CSPLayout
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeTenerife, FakeRueschlikon, FakeTokyo, FakeYorktownV2
from qiskit.utils import optionals
@unittest.skipUnless(optionals.HAS_CONSTRAINT, "needs python-constraint")
class TestCSPLayout(QiskitTestCase):
"""Tests the CSPLayout pass"""
seed = 42
def test_2q_circuit_2q_coupling(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(CouplingMap([[0, 1]]), strict_direction=False, seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 1)
self.assertEqual(layout[qr[1]], 0)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_3q_circuit_5q_coupling(self):
"""3 qubits in Tenerife, without considering the direction
qr1
/ |
qr0 - qr2 - 3
| /
4
"""
cmap5 = FakeTenerife().configuration().coupling_map
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(CouplingMap(cmap5), strict_direction=False, seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 3)
self.assertEqual(layout[qr[1]], 2)
self.assertEqual(layout[qr[2]], 4)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_3q_circuit_5q_coupling_with_target(self):
"""3 qubits in Yorktown, without considering the direction
qr1
/ |
qr0 - qr2 - 3
| /
4
"""
target = FakeYorktownV2().target
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(target, strict_direction=False, seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 3)
self.assertEqual(layout[qr[1]], 2)
self.assertEqual(layout[qr[2]], 4)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_9q_circuit_16q_coupling(self):
"""9 qubits in Rueschlikon, without considering the direction
q0[1] - q0[0] - q1[3] - q0[3] - q1[0] - q1[1] - q1[2] - 8
| | | | | | | |
q0[2] - q1[4] -- 14 ---- 13 ---- 12 ---- 11 ---- 10 --- 9
"""
cmap16 = FakeRueschlikon().configuration().coupling_map
qr0 = QuantumRegister(4, "q0")
qr1 = QuantumRegister(5, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2]
circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3]
circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2]
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(CouplingMap(cmap16), strict_direction=False, seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr0[0]], 9)
self.assertEqual(layout[qr0[1]], 6)
self.assertEqual(layout[qr0[2]], 7)
self.assertEqual(layout[qr0[3]], 5)
self.assertEqual(layout[qr1[0]], 14)
self.assertEqual(layout[qr1[1]], 12)
self.assertEqual(layout[qr1[2]], 1)
self.assertEqual(layout[qr1[3]], 8)
self.assertEqual(layout[qr1[4]], 10)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_2q_circuit_2q_coupling_sd(self):
"""A simple example, considering the direction
0 -> 1
qr1 -> qr0
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(CouplingMap([[0, 1]]), strict_direction=True, seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 1)
self.assertEqual(layout[qr[1]], 0)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_3q_circuit_5q_coupling_sd(self):
"""3 qubits in Tenerife, considering the direction
qr0
↙ ↑
qr2 ← qr1 ← 3
↑ ↙
4
"""
cmap5 = FakeTenerife().configuration().coupling_map
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(CouplingMap(cmap5), strict_direction=True, seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 1)
self.assertEqual(layout[qr[1]], 2)
self.assertEqual(layout[qr[2]], 0)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_9q_circuit_16q_coupling_sd(self):
"""9 qubits in Rueschlikon, considering the direction
q0[1] → q0[0] → q1[3] → q0[3] ← q1[0] ← q1[1] → q1[2] ← 8
↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑
q0[2] ← q1[4] → 14 ← 13 ← 12 → 11 → 10 ← 9
"""
cmap16 = FakeRueschlikon().configuration().coupling_map
qr0 = QuantumRegister(4, "q0")
qr1 = QuantumRegister(5, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2]
circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3]
circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2]
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(CouplingMap(cmap16), strict_direction=True, seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr0[0]], 9)
self.assertEqual(layout[qr0[1]], 6)
self.assertEqual(layout[qr0[2]], 7)
self.assertEqual(layout[qr0[3]], 5)
self.assertEqual(layout[qr1[0]], 14)
self.assertEqual(layout[qr1[1]], 12)
self.assertEqual(layout[qr1[2]], 1)
self.assertEqual(layout[qr1[3]], 10)
self.assertEqual(layout[qr1[4]], 8)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_5q_circuit_16q_coupling_no_solution(self):
"""5 qubits in Rueschlikon, no solution
q0[1] ↖ ↗ q0[2]
q0[0]
q0[3] ↙ ↘ q0[4]
"""
cmap16 = FakeRueschlikon().configuration().coupling_map
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[3])
circuit.cx(qr[0], qr[4])
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(CouplingMap(cmap16), seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertIsNone(layout)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "nonexistent solution")
@staticmethod
def create_hard_dag():
"""Creates a particularly hard circuit (returns its dag) for Tokyo"""
circuit = QuantumCircuit(20)
circuit.cx(13, 12)
circuit.cx(6, 0)
circuit.cx(5, 10)
circuit.cx(10, 7)
circuit.cx(5, 12)
circuit.cx(2, 15)
circuit.cx(16, 18)
circuit.cx(6, 4)
circuit.cx(10, 3)
circuit.cx(11, 10)
circuit.cx(18, 16)
circuit.cx(5, 12)
circuit.cx(4, 0)
circuit.cx(18, 16)
circuit.cx(2, 15)
circuit.cx(7, 8)
circuit.cx(9, 6)
circuit.cx(16, 17)
circuit.cx(9, 3)
circuit.cx(14, 12)
circuit.cx(2, 15)
circuit.cx(1, 16)
circuit.cx(5, 3)
circuit.cx(8, 12)
circuit.cx(2, 1)
circuit.cx(5, 3)
circuit.cx(13, 5)
circuit.cx(12, 14)
circuit.cx(12, 13)
circuit.cx(6, 4)
circuit.cx(15, 18)
circuit.cx(15, 18)
return circuit_to_dag(circuit)
def test_time_limit(self):
"""Hard to solve situations hit the time limit"""
dag = TestCSPLayout.create_hard_dag()
coupling_map = CouplingMap(FakeTokyo().configuration().coupling_map)
pass_ = CSPLayout(coupling_map, call_limit=None, time_limit=1)
start = process_time()
pass_.run(dag)
runtime = process_time() - start
self.assertLess(runtime, 3)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "time limit reached")
def test_call_limit(self):
"""Hard to solve situations hit the call limit"""
dag = TestCSPLayout.create_hard_dag()
coupling_map = CouplingMap(FakeTokyo().configuration().coupling_map)
pass_ = CSPLayout(coupling_map, call_limit=1, time_limit=None)
start = process_time()
pass_.run(dag)
runtime = process_time() - start
self.assertLess(runtime, 1)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "call limit reached")
def test_seed(self):
"""Different seeds yield different results"""
seed_1 = 42
seed_2 = 43
cmap5 = FakeTenerife().configuration().coupling_map
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_1 = CSPLayout(CouplingMap(cmap5), seed=seed_1)
pass_1.run(dag)
layout_1 = pass_1.property_set["layout"]
pass_2 = CSPLayout(CouplingMap(cmap5), seed=seed_2)
pass_2.run(dag)
layout_2 = pass_2.property_set["layout"]
self.assertNotEqual(layout_1, layout_2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
input_3sat_instance = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
import os
import tempfile
from qiskit.exceptions import MissingOptionalLibraryError
from qiskit.circuit.library.phase_oracle import PhaseOracle
fp = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
fp.write(input_3sat_instance)
file_name = fp.name
fp.close()
oracle = None
try:
oracle = PhaseOracle.from_dimacs_file(file_name)
except MissingOptionalLibraryError as ex:
print(ex)
finally:
os.remove(file_name)
from qiskit.algorithms import AmplificationProblem
problem = None
if oracle is not None:
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
from qiskit.algorithms import Grover
from qiskit.primitives import Sampler
grover = Grover(sampler=Sampler())
result = None
if problem is not None:
result = grover.amplify(problem)
print(result.assignment)
from qiskit.tools.visualization import plot_histogram
if result is not None:
display(plot_histogram(result.circuit_results[0]))
expression = '(w ^ x) & ~(y ^ z) & (x & y & z)'
try:
oracle = PhaseOracle(expression)
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
display(plot_histogram(result.circuit_results[0]))
except MissingOptionalLibraryError as ex:
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, assemble, Aer
from qiskit.tools.visualization import plot_histogram
from math import pi
import matplotlib.pyplot as plt
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
qc = QuantumCircuit(q, c)
qc.h(0)
qc.measure(0,0)
qc.x(0).c_if(c, 0)
qc.draw(output='mpl')
q = QuantumRegister(3,'q')
c = ClassicalRegister(3,'c')
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.barrier()
qc.measure(q,c)
qc.draw('mpl')
print(bin(3))
print(bin(7))
q = QuantumRegister(3,'q')
c = ClassicalRegister(3,'c')
qc = QuantumCircuit(q, c)
qc.h(0)
qc.h(1)
qc.h(2)
qc.barrier()
qc.measure(q,c)
qc.x(2).c_if(c, 3) # for the 011 case
qc.x(2).c_if(c, 7) # for the 111 case
qc.draw(output='mpl')
nq = 2
m = 2
q = QuantumRegister(nq,'q')
c = ClassicalRegister(m,'c')
qc_S = QuantumCircuit(q,c)
qc_S.h(0)
qc_S.x(1)
qc_S.draw('mpl')
cu_circ = QuantumCircuit(2)
cu_circ.cp(pi/2,0,1)
cu_circ.draw('mpl')
for _ in range(2**(m-1)):
qc_S.cp(pi/2,0,1)
qc_S.draw('mpl')
def x_measurement(qc, qubit, cbit):
"""Measure 'qubit' in the X-basis, and store the result in 'cbit'"""
qc.h(qubit)
qc.measure(qubit, cbit)
x_measurement(qc_S, q[0], c[0])
qc_S.draw('mpl')
qc_S.reset(0)
qc_S.h(0)
qc_S.draw('mpl')
qc_S.p(-pi/2,0).c_if(c,1)
qc_S.draw('mpl')
## 2^t c-U operations (with t=m-2)
for _ in range(2**(m-2)):
qc_S.cp(pi/2,0,1)
x_measurement(qc_S, q[0], c[1])
qc_S.draw('mpl')
sim = Aer.get_backend('qasm_simulator')
count0 = execute(qc_S, sim).result().get_counts()
key_new = [str(int(key,2)/2**m) for key in list(count0.keys())]
count1 = dict(zip(key_new, count0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(count0, ax=ax[0])
plot_histogram(count1, ax=ax[1])
plt.tight_layout()
nq = 3 # number of qubits
m = 3 # number of classical bits
q = QuantumRegister(nq,'q')
c = ClassicalRegister(m,'c')
qc = QuantumCircuit(q,c)
qc.h(0)
qc.x([1,2])
qc.draw('mpl')
cu_circ = QuantumCircuit(nq)
cu_circ.mcp(pi/4,[0,1],2)
cu_circ.draw('mpl')
for _ in range(2**(m-1)):
qc.mcp(pi/4,[0,1],2)
qc.draw('mpl')
x_measurement(qc, q[0], c[0])
qc.draw('mpl')
qc.reset(0)
qc.h(0)
qc.draw('mpl')
qc.p(-pi/2,0).c_if(c,1)
qc.draw('mpl')
for _ in range(2**(m-2)):
qc.mcp(pi/4,[0,1],2)
x_measurement(qc, q[0], c[1])
qc.draw('mpl')
# initialization of qubit q0
qc.reset(0)
qc.h(0)
# phase correction
qc.p(-pi/4,0).c_if(c,1)
qc.p(-pi/2,0).c_if(c,2)
qc.p(-3*pi/4,0).c_if(c,3)
# c-U operations
for _ in range(2**(m-3)):
qc.mcp(pi/4,[0,1],2)
# X measurement
qc.h(0)
qc.measure(0,2)
qc.draw('mpl')
count0 = execute(qc, sim).result().get_counts()
key_new = [str(int(key,2)/2**m) for key in list(count0.keys())]
count1 = dict(zip(key_new, count0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(count0, ax=ax[0])
plot_histogram(count1, ax=ax[1])
fig.tight_layout()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXSimple
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=IQXSimple(), backend=FakeBoeblingen())
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# 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/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/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Controlled unitary gate."""
from __future__ import annotations
import copy
from typing import Optional, Union
from qiskit.circuit.exceptions import CircuitError
# pylint: disable=cyclic-import
from .quantumcircuit import QuantumCircuit
from .gate import Gate
from .quantumregister import QuantumRegister
from ._utils import _ctrl_state_to_int
class ControlledGate(Gate):
"""Controlled unitary gate."""
def __init__(
self,
name: str,
num_qubits: int,
params: list,
label: Optional[str] = None,
num_ctrl_qubits: Optional[int] = 1,
definition: Optional["QuantumCircuit"] = None,
ctrl_state: Optional[Union[int, str]] = None,
base_gate: Optional[Gate] = None,
):
"""Create a new ControlledGate. In the new gate the first ``num_ctrl_qubits``
of the gate are the controls.
Args:
name: The name of the gate.
num_qubits: The number of qubits the gate acts on.
params: A list of parameters for the gate.
label: An optional label for the gate.
num_ctrl_qubits: Number of control qubits.
definition: A list of gate rules for implementing this gate. The
elements of the list are tuples of (:meth:`~qiskit.circuit.Gate`, [qubit_list],
[clbit_list]).
ctrl_state: The control state in decimal or as
a bitstring (e.g. '111'). If specified as a bitstring the length
must equal num_ctrl_qubits, MSB on left. If None, use
2**num_ctrl_qubits-1.
base_gate: Gate object to be controlled.
Raises:
CircuitError: If ``num_ctrl_qubits`` >= ``num_qubits``.
CircuitError: ctrl_state < 0 or ctrl_state > 2**num_ctrl_qubits.
Examples:
Create a controlled standard gate and apply it to a circuit.
.. plot::
:include-source:
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
c3h_gate = HGate().control(2)
qc.append(c3h_gate, qr)
qc.draw('mpl')
Create a controlled custom gate and apply it to a circuit.
.. plot::
:include-source:
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')
"""
self.base_gate = None if base_gate is None else base_gate.copy()
super().__init__(name, num_qubits, params, label=label)
self._num_ctrl_qubits = 1
self.num_ctrl_qubits = num_ctrl_qubits
self.definition = copy.deepcopy(definition)
self._ctrl_state = None
self.ctrl_state = ctrl_state
self._name = name
@property
def definition(self) -> QuantumCircuit:
"""Return definition in terms of other basic gates. If the gate has
open controls, as determined from `self.ctrl_state`, the returned
definition is conjugated with X without changing the internal
`_definition`.
"""
if self._open_ctrl:
closed_gate = self.copy()
closed_gate.ctrl_state = None
bit_ctrl_state = bin(self.ctrl_state)[2:].zfill(self.num_ctrl_qubits)
qreg = QuantumRegister(self.num_qubits, "q")
qc_open_ctrl = QuantumCircuit(qreg)
for qind, val in enumerate(bit_ctrl_state[::-1]):
if val == "0":
qc_open_ctrl.x(qind)
qc_open_ctrl.append(closed_gate, qargs=qreg[:])
for qind, val in enumerate(bit_ctrl_state[::-1]):
if val == "0":
qc_open_ctrl.x(qind)
return qc_open_ctrl
else:
return super().definition
@definition.setter
def definition(self, excited_def: "QuantumCircuit"):
"""Set controlled gate definition with closed controls.
Args:
excited_def: The circuit with all closed controls.
"""
self._definition = excited_def
@property
def name(self) -> str:
"""Get name of gate. If the gate has open controls the gate name
will become:
<original_name_o<ctrl_state>
where <original_name> is the gate name for the default case of
closed control qubits and <ctrl_state> is the integer value of
the control state for the gate.
"""
if self._open_ctrl:
return f"{self._name}_o{self.ctrl_state}"
else:
return self._name
@name.setter
def name(self, name_str):
"""Set the name of the gate. Note the reported name may differ
from the set name if the gate has open controls.
"""
self._name = name_str
@property
def num_ctrl_qubits(self):
"""Get number of control qubits.
Returns:
int: The number of control qubits for the gate.
"""
return self._num_ctrl_qubits
@num_ctrl_qubits.setter
def num_ctrl_qubits(self, num_ctrl_qubits):
"""Set the number of control qubits.
Args:
num_ctrl_qubits (int): The number of control qubits.
Raises:
CircuitError: ``num_ctrl_qubits`` is not an integer in ``[1, num_qubits]``.
"""
if num_ctrl_qubits != int(num_ctrl_qubits):
raise CircuitError("The number of control qubits must be an integer.")
num_ctrl_qubits = int(num_ctrl_qubits)
# This is a range rather than an equality limit because some controlled gates represent a
# controlled version of the base gate whose definition also uses auxiliary qubits.
upper_limit = self.num_qubits - getattr(self.base_gate, "num_qubits", 0)
if num_ctrl_qubits < 1 or num_ctrl_qubits > upper_limit:
limit = "num_qubits" if self.base_gate is None else "num_qubits - base_gate.num_qubits"
raise CircuitError(f"The number of control qubits must be in `[1, {limit}]`.")
self._num_ctrl_qubits = num_ctrl_qubits
@property
def ctrl_state(self) -> int:
"""Return the control state of the gate as a decimal integer."""
return self._ctrl_state
@ctrl_state.setter
def ctrl_state(self, ctrl_state: Union[int, str, None]):
"""Set the control state of this gate.
Args:
ctrl_state: The control state of the gate.
Raises:
CircuitError: ctrl_state is invalid.
"""
self._ctrl_state = _ctrl_state_to_int(ctrl_state, self.num_ctrl_qubits)
@property
def params(self):
"""Get parameters from base_gate.
Returns:
list: List of gate parameters.
Raises:
CircuitError: Controlled gate does not define a base gate
"""
if self.base_gate:
return self.base_gate.params
else:
raise CircuitError("Controlled gate does not define base gate for extracting params")
@params.setter
def params(self, parameters):
"""Set base gate parameters.
Args:
parameters (list): The list of parameters to set.
Raises:
CircuitError: If controlled gate does not define a base gate.
"""
if self.base_gate:
self.base_gate.params = parameters
else:
raise CircuitError("Controlled gate does not define base gate for extracting params")
def __deepcopy__(self, _memo=None):
cpy = copy.copy(self)
cpy.base_gate = self.base_gate.copy()
if self._definition:
cpy._definition = copy.deepcopy(self._definition, _memo)
return cpy
@property
def _open_ctrl(self) -> bool:
"""Return whether gate has any open controls"""
return self.ctrl_state < 2**self.num_ctrl_qubits - 1
def __eq__(self, other) -> bool:
return (
isinstance(other, ControlledGate)
and self.num_ctrl_qubits == other.num_ctrl_qubits
and self.ctrl_state == other.ctrl_state
and self.base_gate == other.base_gate
and self.num_qubits == other.num_qubits
and self.num_clbits == other.num_clbits
and self.definition == other.definition
)
def inverse(self) -> "ControlledGate":
"""Invert this gate by calling inverse on the base gate."""
return self.base_gate.inverse().control(self.num_ctrl_qubits, ctrl_state=self.ctrl_state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
# Virtual -> physical
# 0 -> 3
# 1 -> 4
# 2 -> 2
my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2])
plot_circuit_layout(my_ghz, backend)
|
https://github.com/weiT1993/qiskit_helper_functions
|
weiT1993
|
from .Qbit_Sycamore import Qbit
from .ABCD_layer_generation import get_layers
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import math
import sys
import numpy as np
class Qgrid:
"""
Class to implement the quantum supremacy circuits as found
in Arute, F., Arya, K., Babbush, R. et al. 'Quantum supremacy using a
programmable superconducting processor'. Nature 574, 505–510 (2019)
doi:10.1038/s41586-019-1666-5
(https://www.nature.com/articles/s41586-019-1666-5)
Each instance is a 2D array whose entries at Qbit objects.
A supremacy circuit can be generated for a given instance
by calling the gen_circuit() method.
Attributes
----------
n : int
number of rows in the grid
m : int
number of columns in the grid
d : int
depth of the supremacy circuit (excludes measurement i.e. d+1)
regname : str
optional string to name the quantum and classical registers. This
allows for the easy concatenation of multiple QuantumCircuits.
qreg : QuantumRegister
Qiskit QuantumRegister holding all of the qubits
creg : ClassicalRegister
Qiskit ClassicalRegister holding all of the classical bits
circ : QuantumCircuit
Qiskit QuantumCircuit that represents the supremacy circuit
grid : array
n x m array holding Qbit objects
ABCD_layers : list
List of qubit indices for 2-qubit gates for the A, B, C, and D layers of
the supremacy circuit.
order : list
list of indices indicting the order the cz layers should be placed
singlegates : bool
Boolean indicating whether to include single qubit gates in the circuit
"""
def __init__(
self,
n,
m,
d,
order=None,
singlegates=True,
barriers=True,
measure=False,
regname=None,
):
self.n = n
self.m = m
self.d = d
if regname is None:
self.qreg = QuantumRegister(n * m)
self.creg = ClassicalRegister(n * m)
else:
self.qreg = QuantumRegister(n * m, name=regname)
self.creg = ClassicalRegister(n * m, name="c" + regname)
# It is easier to interface with the circuit cutter
# if there is no Classical Register added to the circuit
self.measure = measure
if self.measure:
self.circ = QuantumCircuit(self.qreg, self.creg)
else:
self.circ = QuantumCircuit(self.qreg)
self.grid = self.make_grid(n, m)
self.ABCD_layers = get_layers(n, m)
self.barriers = barriers
self.singlegates = singlegates
if order is None:
# Use the default Google order for full supremacy circuit
# In the Nature paper Supp Info. Table 3 shows that the
# full supremacy circuit pattern is: ABCDCDAB
# ABCD_layers = [layerA, layerB, layerC, layerD]
self.order = [0, 1, 2, 3, 2, 3, 0, 1]
else:
# Convert given order string to list of ints
self.order = [int(c) for c in order]
def make_grid(self, n, m):
temp_grid = []
index_ctr = 0
for row in range(n):
cur_row = []
for col in range(m):
cur_row += [Qbit(index_ctr, None)]
index_ctr += 1
temp_grid += [cur_row]
return temp_grid
def get_index(self, index1=None, index2=None):
if index2 is None:
return self.grid[index1[0]][index1[1]].index
else:
return self.grid[index1][index2].index
def print_circuit(self):
print(self.circ.draw(scale=0.6, output="text", reverse_bits=False))
def save_circuit(self):
str_order = [str(i) for i in self.order]
if self.mirror:
str_order.append("m")
fn = "supr_{}x{}x{}_order{}.txt".format(
self.n, self.m, self.d, "".join(str_order)
)
self.circ.draw(
scale=0.8, filename=fn, output="text", reverse_bits=False, line_length=160
)
def measure_circuit(self):
self.circ.barrier()
for i in range(self.n):
for j in range(self.m):
qubit_index = self.get_index(i, j)
self.circ.measure(self.qreg[qubit_index], self.creg[qubit_index])
def apply_random_1q_gate(self, n, m):
qb_index = self.get_index(n, m)
gate = self.grid[n][m].random_gate()
if gate == "X":
# Apply a sqrt-X gate to qubit at qb_index
self.circ.rx(math.pi / 2, self.qreg[qb_index])
elif gate == "Y":
# Apply a sqrt-Y gate to qubit at qb_index
self.circ.ry(math.pi / 2, self.qreg[qb_index])
elif gate == "W":
# Apply a sqrt-W gate to qubit at qb_index
# W = (X + Y) / sqrt(2)
self.circ.z(self.qreg[qb_index])
else:
Exception("ERROR: unrecognized gate: {}".format(gate))
def gen_circuit(self):
"""
Generate n*m depth d+1 Sycamore circuit
"""
# Iterate through d layers
for i in range(self.d):
# apply single qubit gates
for n in range(self.n):
for m in range(self.m):
self.apply_random_1q_gate(n, m)
# Apply entangling 2-qubit gates
cur_q2s = self.ABCD_layers[self.order[i % len(self.order)]]
for q2 in cur_q2s:
ctrl = self.get_index(q2[0])
trgt = self.get_index(q2[1])
# The 2 qubit gate implemented by Google's Sycamore chip
# is fSim(pi/2, pi/6) given in Eqn. 53 of the Nature Supp info
self.circ.cz(self.qreg[ctrl], self.qreg[trgt])
if self.barriers:
self.circ.barrier()
# End d layers
# Measurement
if self.measure:
self.measure_circuit()
return self.circ
def gen_qasm(self):
return self.circ.qasm()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
with pulse.build() as hahn_echo:
with pulse.align_equispaced(duration=100):
pulse.play(x90, d0)
pulse.play(x180, d0)
pulse.play(x90, d0)
hahn_echo.draw()
|
https://github.com/Antonio297/Qiskit_Algoritmo_Cuantico
|
Antonio297
|
### Original articles:
###
### (1) "Improving the Sequence Alignment Method by Quantum Multi-Pattern Recognition"
### Konstantinos Prousalis & Nikos Konofaos
### Published in: SETN '18 Proceedings of the 10th Hellenic Conference on Artificial Intelligence, Article No. 50
### Patras, Greece, July 09 - 12, 2018
###
### (2) "Quantum Pattern Recognition with Probability of 100%"
### Rigui Zhou & Qiulin Ding
### Published in: International Journal of Theoretical Physics, Springer
### Received: 3 August 2007, Accepted: 11 September 2007, Published online: 4 October 2007
###
### (3) "Initializing the amplitude distribution of a quantum state"
### Dan Ventura & Tony Martinez
### Revised 2nd November 1999
## Importing libraries
%matplotlib inline
import qiskit
from qiskit import IBMQ
from qiskit import Aer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QiskitError
from qiskit.quantum_info.operators import Operator
from qiskit.tools.visualization import circuit_drawer
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.visualization import plot_state_city
from qiskit.providers.aer import noise
import random
from math import *
import math
import matplotlib
import numpy as np
## Initializing global variables
# Quantum register is organized like the following:
# |t, x, g, c, a>, with (t+x) having n qubits (index+pattern), g having (n-1) qubits and c having 2 qubits
# Also, ancilla qubits (a) as support for mct gate
genome_file = open("Cromosoma 1-Covid 19.txt", "r") #select the data source
seq_x = genome_file.read()
genome_file.close()
seq_x = seq_x[0:200] #changes the number of characters you want to read from the file
seq_y = "TTCT" #string to compare (endonuclease recognition sequence)
Q_t = ceil(log2(len(seq_x)))
Q_x = len(seq_y)
Q_g = Q_t + Q_x - 1
Q_c = 2
Q_anc = 1
total_qubits = Q_t + Q_x + Q_g + Q_c + Q_anc
## Initialization of IBM QX
IBMQ.enable_account('My Token')
provider = IBMQ.get_provider()
# Pick an available backend
# If this isn't available pick a backend whose name containes '_qasm_simulator' from the output above
backend = provider.get_backend('ibmq_qasm_simulator')
# Uncomment if you want to use local simulator
#backend= Aer.get_backend('qasm_simulator')
## Functions for recurrence dot matrix
def delta(x, y):
return 0 if x == y else 1
def M(seq1, seq2, i, j, k):
return sum(delta(x, y) for x, y in zip(seq1[i : i+k],seq2[j : j+k]))
def makeMatrix(seq1, seq2, k):
n = len(seq1)
m = len(seq2)
return [[M(seq1, seq2, i, j, k) for j in range(m - k + 1)] for i in range(n - k + 1)]
def plotMatrix(M, t, seq1, seq2, nonblank = chr(0x25A0), blank = ' '):
print(' |' + seq2)
print('-' * (2 + len(seq2)))
for label, row in zip(seq1, M):
line = ''.join(nonblank if s < t else blank for s in row)
print(label + '|' + line)
return
def convertMatrix(M):
for i in range(0, len(M)):
for j in range(0, len(M[i])):
if M[i][j] == 0:
M[i][j] = 1
elif M[i][j] == 1:
M[i][j] = 0
return M
def dotplot(seq1, seq2, k = 1, t = 1):
if len(seq1) > len(seq2):
raise Exception("Vertical sequence cannot be longer than horizontal sequence!")
M = makeMatrix(seq1, seq2, k)
plotMatrix(M, t, seq1, seq2)
M = convertMatrix(M)
return M
def getAllDiagonalsFromMatrix(M):
D = np.array([])
d_size = -1
for i in range(0, len(M[0])):
d = np.diag(M, k=i)
if d_size == -1:
d_size = len(d)
D = d
elif d_size > len(d):
z = np.zeros((1, (d_size-len(d))), dtype=int)
d = np.append(d, z)
D = np.vstack((D, d))
else:
D = np.vstack((D, d))
return D
def convertBinArrayToStr(array):
string = ""
for bin_digit in array:
if bin_digit == 0:
string = string + '0'
elif bin_digit == 1:
string = string + '1'
return string
## Functions for Quantum Pattern Recognition
def generateInitialState(qc, qr, dot_matrix):
D = getAllDiagonalsFromMatrix(dot_matrix)
m = len(D)
print("Size of Learning Set: {}".format(len(D)))
idx = 0
for d in D:
print("{}->{}: {}".format(idx, format(idx,'0'+str(Q_t)+'b'), d))
idx = idx + 1
z_values = convertBinArrayToStr(np.zeros(Q_t+Q_x))
ancilla_qubits = []
for qi in range(0, Q_anc):
ancilla_qubits.append(qr[Q_t + Q_x + Q_g + Q_c + qi])
for p in range(m, 0, -1):
bin_diagonal = convertBinArrayToStr(D[len(D)-p])
index = format((len(D)-p), '0' + str(Q_t) + 'b')
instance = index + bin_diagonal
#print("Instance #{}, z={}".format(p, instance))
for j in range(1, Q_t + Q_x + 1):
if z_values[j-1] != instance[j-1]:
#print("F_0 #{} Applied to circuit with ctrl={} and target={}".format(j, Q_t+Q_x+Q_g+Q_c-1,j-1))
qc.x(qr[Q_t+Q_x+Q_g+Q_c-1])
qc.cx(qr[Q_t+Q_x+Q_g+Q_c-1], qr[j-1])
qc.x(qr[Q_t+Q_x+Q_g+Q_c-1])
z_values = instance
#print("F_0 Applied to circuit with ctrl={} and arget={}".format(Q_t+Q_x+Q_g+Q_c-1, Q_t+Q_x+Q_g+Q_c-2))
qc.x(qr[Q_t+Q_x+Q_g+Q_c-1])
qc.cx(qr[Q_t+Q_x+Q_g+Q_c-1], qr[Q_t+Q_x+Q_g+Q_c-2])
qc.x(qr[Q_t+Q_x+Q_g+Q_c-1])
#print("S_{},{} Applied to circuit with ctrl={} and arget={}".format(1, p, Q_t+Q_x+Q_g+Q_c-2, Q_t+Q_x+Q_g+Q_c-1))
theta = 2*np.arcsin(1/sqrt(p))
qc.cry(theta, qr[Q_t+Q_x+Q_g+Q_c-2], qr[Q_t+Q_x+Q_g+Q_c-1])
if instance[0]=='0' and instance[1]=='0':
#print("A_00 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.x(qr[0])
qc.x(qr[1])
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
qc.x(qr[1])
qc.x(qr[0])
elif instance[0]=='0' and instance[1]=='1':
#print("A_01 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.x(qr[0])
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
qc.x(qr[0])
elif instance[0]=='1' and instance[1]=='0':
#print("A_10 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.x(qr[1])
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
qc.x(qr[1])
elif instance[0]=='1' and instance[1]=='1':
#print("A_11 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
for k in range(3, Q_t+Q_x+1):
if instance[k-1]=='0':
#print("A_01 #{} Applied to circuit with ctrl={},{} and target={}".format(k-1, k-1, Q_t+Q_x+k-3, Q_t+Q_x+k-2))
qc.x(qr[k-1])
qc.mct([qr[k-1], qr[Q_t+Q_x+k-3]], qr[Q_t+Q_x+k-2], ancilla_qubits)
qc.x(qr[k-1])
elif instance[k-1]=='1':
#print("A_11 #{} Applied to circuit with ctrl={},{} and target={}".format(k-1, k-1, Q_t+Q_x+k-3, Q_t+Q_x+k-2))
qc.mct([qr[k-1], qr[Q_t+Q_x+k-3]], qr[Q_t+Q_x+k-2], ancilla_qubits)
#print("F_1 Applied to circuit with ctrl={} and target={}".format(Q_t+Q_x+Q_g-1, Q_t+Q_x+Q_g))
qc.cx(qr[Q_t+Q_x+Q_g-1], qr[Q_t+Q_x+Q_g])
for k in range(Q_t+Q_x, 2, -1):
if instance[k-1]=='0':
#print("A_01 #{} Applied to circuit with ctrl={},{} and target={}".format(k-1, k-1, Q_t+Q_x+k-3, Q_t+Q_x+k-2))
qc.x(qr[k-1])
qc.mct([qr[k-1], qr[Q_t+Q_x+k-3]], qr[Q_t+Q_x+k-2], ancilla_qubits)
qc.x(qr[k-1])
elif instance[k-1]=='1':
#print("A_11 #{} Applied to circuit with ctrl={},{} and target={}".format(k-1, k-1, Q_t+Q_x+k-3, Q_t+Q_x+k-2))
qc.mct([qr[k-1], qr[Q_t+Q_x+k-3]], qr[Q_t+Q_x+k-2], ancilla_qubits)
if instance[0]=='0' and instance[1]=='0':
#print("A_00 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.x(qr[0])
qc.x(qr[1])
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
qc.x(qr[1])
qc.x(qr[0])
elif instance[0]=='0' and instance[1]=='1':
#print("A_01 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.x(qr[0])
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
qc.x(qr[0])
elif instance[0]=='1' and instance[1]=='0':
#print("A_10 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.x(qr[1])
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
qc.x(qr[1])
elif instance[0]=='1' and instance[1]=='1':
#print("A_11 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
#print("F Applied to circuit at qubit={}".format(Q_t+Q_x+Q_g+Q_c-1))
qc.x(qr[Q_t+Q_x+Q_g+Q_c-1])
return
def getIndices(mySet):
indices = []
for i in range(0, len(mySet)):
tmp = ""
for j in range(0, len(mySet[i])):
tmp = tmp + str(int(mySet[i][j]))
indices.append(int(tmp, 2))
return indices
def oracle(query_set):
I = np.identity(2**Q_x)
b_sum = np.zeros((2**Q_x, 2**Q_x))
indices = getIndices(query_set)
for i in indices:
vs = np.zeros((1, 2**Q_x))
for j in range(0, 2**Q_x):
if j == i:
vs[0][j] = 1
b_sum = b_sum + np.dot(np.conjugate(np.transpose(vs)), vs)
U = I - (1-1j)*b_sum
return U
def inversionAboutMean(dot_matrix):
I = np.identity(2**(Q_t+Q_x))
b_sum = np.zeros((2**(Q_t+Q_x), 1))
D = getAllDiagonalsFromMatrix(dot_matrix)
mySet = np.empty([len(D), Q_t+Q_x])
for i in range(0, len(D)):
bin_arr = np.concatenate((convertIntToBinArray(i, Q_t), D[i]))
mySet[i] = bin_arr
indices = getIndices(mySet)
for i in indices:
vs = np.zeros((2**(Q_t+Q_x), 1))
for j in range(0, 2**(Q_t+Q_x)):
if j == i:
vs[j][0] = 1
b_sum = b_sum + vs
phi_zero = (1/sqrt(len(D))) * b_sum
phi_mtrx = np.dot(phi_zero, np.conjugate(np.transpose(phi_zero)))
U = (1 + 1j) * phi_mtrx - 1j * I
return U
def convertIntToBinArray(j, dim):
if not isinstance(j, int):
raise Exception("Number of bits must be an integer!")
elif (j == 0 or j == 1) and dim < 1:
raise Exception("More bits needed to convert j in binary!")
elif j > 1 and dim <= log2(j):
raise Exception("More bits needed to convert j in binary!")
bin_arr = np.array([], dtype=int)
j_bin = format(int(j), '0' + str(dim) + 'b')
for k in j_bin:
if k == '1':
bin_arr = np.append(bin_arr, 1)
elif k == '0':
bin_arr = np.append(bin_arr, 0)
return bin_arr
def QPR(dot_matrix):
qr = qiskit.QuantumRegister(total_qubits)
cr = qiskit.ClassicalRegister(Q_t)
qc = qiskit.QuantumCircuit(qr, cr)
print("Total number of qubits: {}".format(total_qubits))
print("Size of t register: {}".format(Q_t))
print("Size of x register: {}".format(Q_x))
print("Size of g register: {}".format(Q_g))
print("Size of c register: {}".format(Q_c))
print("Number of ancilla qubits: {}".format(Q_anc))
# A query set is manually defined
query_set = np.array([[1,1,1],
[0,1,1],
[1,1,0],
[1,0,1]])
O_mtrx = oracle(query_set)
U_phi_mtrx = inversionAboutMean(dot_matrix)
O = Operator(O_mtrx)
U_phi = Operator(U_phi_mtrx)
O_qubits = []
for qi in range(Q_x-1, -1, -1):
O_qubits.append(Q_t + qi)
U_phi_qubits = []
for qi in range(Q_t+Q_x-1, -1, -1):
U_phi_qubits.append(qi)
generateInitialState(qc, qr, dot_matrix)
#simulateStateVector(qc)
T = round((math.pi/4)*sqrt(len(dot_matrix[0])/len(query_set)))
it = 0
for i in range(0, T):
print("Grover Iteration #{}".format(it+1))
qc.unitary(O, O_qubits, label='O')
#simulateStateVector(qc)
#qc.unitary(U_phi, U_phi_qubits, label='U_phi')
#simulateStateVector(qc)
it = it + 1
print("Grover's algorithm had {} iterations.".format(int(it)))
finalGroverMeasurement(qc, qr, cr)
return qc
def simulateStateVector(qc):
result = qiskit.execute(qc, backend=Aer.get_backend('statevector_simulator')).result()
state = result.get_statevector(qc)
print("Number of states in vector: {}".format(len(state)))
it = 0
for item in state:
bin_str = format(it, '0'+str(total_qubits)+'b')
bin_str_rev = bin_str[len(bin_str)::-1]
if (item.real != 0 or item.imag != 0):
print("{}->{}: {}".format(it, bin_str_rev[Q_t:Q_t+Q_x], item))
it = it + 1
return
# Final measurement
def finalGroverMeasurement(qc, qr, cr):
for qi in range(0, Q_t):
qc.measure(qr[qi], cr[qi])
return
## Main function
if __name__ == '__main__':
# Printing some data for testing
M = dotplot(seq_y, seq_x)
qc = QPR(M)
print("Circuit depth: {}".format(qc.depth()))
# Total number of gates
print("Number of gates: {}".format(len(qc.data)))
gate_num = 1
for item in qc.data:
qb_list = ""
for qb in item[1]:
qb_list = qb_list + str(qb.index) + ", "
qb_list = qb_list[:len(qb_list)-2]
print("#{}: {}, {}".format(gate_num, item[0].name, qb_list))
gate_num = gate_num + 1
# Drawing circuit
qc.draw()
# Showing histogram
# BE CAREFUL!
# Qiskit uses a LSB ordering, meaning the first qubit is all the way to the right!
# For example, a state of |01> would mean the first qubit is 1 and the second qubit is 0!
sim = qiskit.execute(qc, backend=backend, shots=1024)
result = sim.result()
final=result.get_counts(qc)
print(final)
plot_histogram(final)
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit.quantum_info import Statevector
from qiskit import QuantumCircuit
import math
qc = QuantumCircuit(4)
qc.rx(math.pi/2, [0,1,2,3])
qc.i(1)
qc.u(math.pi/2, 0, math.pi, 2)
qc.u(0,0, math.pi/4, 3)
qc.draw("mpl")
state = Statevector.from_instruction(qc)
state.draw('bloch')
|
https://github.com/pedroripper/qiskit_tutoriais
|
pedroripper
|
from qiskit import *
# Para representar o qubit em uma esfera de bloch devemos pensar nele na seguinte forma:
# Depois de encontrar o theta, phi que desejamos, vamos ter os valores necessários para plotar nossa
# esfera de bloch
# Para plotar precisamos chamar a função plot_bloch_vector_spherical() que leva como parâmetro
# o vetor de bloch
# para encontrar o vetor de bloch seguimos a fórmula
# Para o exemplo vamos usar o qubit no estado |+> que fica da seguinte forma:
# Para conseguir representar esse estado no formato dado anteriormente vamos precisar
# de um theta valendo pi/2 e de um phi valendo 0
# portanto vamos ter o vetor de bloch como (1,0,0)
# Finalmente podemos exibir a esfera de bloch
from qiskit.visualization import plot_bloch_vector
%matplotlib inline
plot_bloch_vector([1,0,0], title="Minha Primeira Esfera de Bloch")
|
https://github.com/DRA-chaos/Quantum-Classical-Hyrid-Neural-Network-for-binary-image-classification-using-PyTorch-Qiskit-pipeline
|
DRA-chaos
|
!pip install qiskit
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.autograd import Function
from torchvision import datasets, transforms
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import qiskit
from qiskit import transpile, assemble
from qiskit.visualization import *
def to_numbers(tensor_list):
num_list = []
for tensor in tensor_list:
num_list += [tensor.item()]
return num_list
import numpy as np
import torch
from torch.autograd import Function
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute
from qiskit.circuit import Parameter
from qiskit import Aer
from tqdm import tqdm
from matplotlib import pyplot as plt
%matplotlib inline
class QuantumCircuit:
"""
This class provides a simple interface for interaction
with the quantum circuit
"""
def __init__(self, n_qubits, backend, shots):
# --- Circuit definition ---
self._circuit = qiskit.QuantumCircuit(n_qubits)
all_qubits = [i for i in range(n_qubits)]
self.theta = qiskit.circuit.Parameter('theta')
self._circuit.h(all_qubits)
self._circuit.barrier()
self._circuit.ry(self.theta, all_qubits)
self._circuit.measure_all()
# ---------------------------
self.backend = backend
self.shots = shots
def run(self, thetas):
t_qc = transpile(self._circuit,
self.backend)
qobj = assemble(t_qc,
shots=self.shots,
parameter_binds = [{self.theta: theta} for theta in thetas])
job = self.backend.run(qobj)
result = job.result().get_counts()
counts = np.array(list(result.values()))
states = np.array(list(result.keys())).astype(float)
# Compute probabilities for each state
probabilities = counts / self.shots
# Get state expectation
expectation = np.sum(states * probabilities)
return np.array([expectation])
simulator = qiskit.Aer.get_backend('qasm_simulator')
circuit = QuantumCircuit(1, simulator, 100)
print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0]))
circuit._circuit.draw()
class HybridFunction(Function):
""" Hybrid quantum - classical function definition """
@staticmethod
def forward(ctx, input, quantum_circuit, shift):
""" Forward pass computation """
ctx.shift = shift
ctx.quantum_circuit = quantum_circuit
expectation_z = ctx.quantum_circuit.run(input[0].tolist())
result = torch.tensor([expectation_z])
ctx.save_for_backward(input, result)
return result
@staticmethod
def backward(ctx, grad_output):
""" Backward pass computation """
input, expectation_z = ctx.saved_tensors
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.shift
shift_left = input_list - np.ones(input_list.shape) * ctx.shift
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients.append(gradient)
gradients = np.array([gradients]).T
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class Hybrid(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, shift):
super(Hybrid, self).__init__()
self.quantum_circuit = QuantumCircuit(1, backend, shots)
self.shift = shift
def forward(self, input):
return HybridFunction.apply(input, self.quantum_circuit, self.shift)
import torchvision
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors
cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform)
labels = cifar_trainset.targets # get the labels for the data
labels = np.array(labels)
idx1 = np.where(labels == 0) # filter on aeroplanes
idx2 = np.where(labels == 1) # filter on automobiles
# Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set)
n=100
# concatenate the data indices
idx = np.concatenate((idx1[0][0:n],idx2[0][0:n]))
# create the filtered dataset for our training set
cifar_trainset.targets = labels[idx]
cifar_trainset.data = cifar_trainset.data[idx]
train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True)
import numpy as np
import matplotlib.pyplot as plt
n_samples_show = 8
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 2))
while n_samples_show > 0:
images, targets = data_iter.__next__()
images=images.squeeze()
#axes[n_samples_show - 1].imshow( tf.shape( tf.squeeze(images[0]) ),cmap='gray' )
#plt.imshow((tf.squeeze(images[0])))
#plt.imshow( tf.shape( tf.squeeze(x_train) ) )
#axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray')
axes[n_samples_show - 1].imshow(images[0].numpy(), cmap='gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
#Testing data
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors
cifar_testset = datasets.CIFAR10(root='./data1', train=False, download=True, transform=transform)
labels1 = cifar_testset.targets # get the labels for the data
labels1 = np.array(labels1)
idx1_ae = np.where(labels1 == 0) # filter on aeroplanes
idx2_au = np.where(labels1 == 1) # filter on automobiles
# Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set)
n=50
# concatenate the data indices
idxa = np.concatenate((idx1_ae[0][0:n],idx2_au[0][0:n]))
# create the filtered dataset for our training set
cifar_testset.targets = labels[idxa]
cifar_testset.data = cifar_testset.data[idxa]
test_loader = torch.utils.data.DataLoader(cifar_testset, batch_size=1, shuffle=True)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(500, 500)
self.fc2 = nn.Linear(500, 1)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(1, -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x)
return torch.cat((x, 1 - x), -1)
#qc = TorchCircuit.apply
Ignore this cell
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.h1 = nn.Linear(500, 500)
self.h2 = nn.Linear(500, 1)
def forward(self,x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 500)
x = F.relu(self.h1(x))
x = F.dropout(x, training=self.training)
x = self.h2(x)
x = qc(x)
x = (x+1)/2 # Normalise the inputs to 1 or 0
x = torch.cat((x, 1-x), -1)
return x
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 5
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Now plotting the training graph
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 10
loss_list1 = []
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_list1.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list1[-1]))
#Alongside, let's also plot the data
plt.plot(loss_list1)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list2 = []
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_list2.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list2[-1]))
#Alongside, let's also plot the data
plt.plot(loss_list2)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 30
loss_list3 = []
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_list3.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list3[-1]))
#Alongside, let's also plot the data
plt.plot(loss_list3)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
import torch
import torchvision
import torchvision.transforms as transforms
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 10
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]))
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
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]))
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
#Testing the quantum hybrid in order to comapre it with the classical one
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(500, 500)
self.fc2 = nn.Linear(500,49)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(1, -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x)
return torch.cat((x, 1 - x), -1)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 99)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return F.softmax(x)
|
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/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from datasets import *
from qiskit import Aer
from qiskit_aqua.input import SVMInput
from qiskit_aqua import run_algorithm
import numpy as np
n = 2 # dimension of each data point
sample_Total, training_input, test_input, class_labels = Wine(training_size=40,
test_size=10, n=n, PLOT_DATA=True)
temp = [test_input[k] for k in test_input]
total_array = np.concatenate(temp)
aqua_dict = {
'problem': {'name': 'svm_classification', 'random_seed': 10598},
'algorithm': {
'name': 'QSVM.Kernel'
},
'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entangler_map': {0: [1]}},
'multiclass_extension': {'name': 'AllPairs'},
'backend': {'shots': 1024}
}
backend = Aer.get_backend('qasm_simulator')
algo_input = SVMInput(training_input, test_input, total_array)
result = run_algorithm(aqua_dict, algo_input, backend=backend)
for k,v in result.items():
print("'{}' : {}".format(k, v))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can set a color for all the bars.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
|
https://github.com/abbarreto/qiskit2
|
abbarreto
| |
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import RealAmplitudes
from qiskit.algorithms.optimizers import COBYLA
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, SamplingVQE
from qiskit.primitives import Sampler
from qiskit_optimization.converters import LinearEqualityToPenalty
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.translators import from_docplex_mp
from qiskit.utils import algorithm_globals
import numpy as np
import matplotlib.pyplot as plt
from docplex.mp.model import Model
algorithm_globals.random_seed = 123456
# prepare problem instance
n = 6 # number of assets
q = 0.5 # risk factor
budget = n // 2 # budget
penalty = 2 * n # scaling of penalty term
# instance from [1]
mu = np.array([0.7313, 0.9893, 0.2725, 0.8750, 0.7667, 0.3622])
sigma = np.array(
[
[0.7312, -0.6233, 0.4689, -0.5452, -0.0082, -0.3809],
[-0.6233, 2.4732, -0.7538, 2.4659, -0.0733, 0.8945],
[0.4689, -0.7538, 1.1543, -1.4095, 0.0007, -0.4301],
[-0.5452, 2.4659, -1.4095, 3.5067, 0.2012, 1.0922],
[-0.0082, -0.0733, 0.0007, 0.2012, 0.6231, 0.1509],
[-0.3809, 0.8945, -0.4301, 1.0922, 0.1509, 0.8992],
]
)
# or create random instance
# mu, sigma = portfolio.random_model(n, seed=123) # expected returns and covariance matrix
# create docplex model
mdl = Model("portfolio_optimization")
x = mdl.binary_var_list(range(n), name="x")
objective = mdl.sum([mu[i] * x[i] for i in range(n)])
objective -= q * mdl.sum([sigma[i, j] * x[i] * x[j] for i in range(n) for j in range(n)])
mdl.maximize(objective)
mdl.add_constraint(mdl.sum(x[i] for i in range(n)) == budget)
# case to
qp = from_docplex_mp(mdl)
# solve classically as reference
opt_result = MinimumEigenOptimizer(NumPyMinimumEigensolver()).solve(qp)
print(opt_result.prettyprint())
# we convert the problem to an unconstrained problem for further analysis,
# otherwise this would not be necessary as the MinimumEigenSolver would do this
# translation automatically
linear2penalty = LinearEqualityToPenalty(penalty=penalty)
qp = linear2penalty.convert(qp)
_, offset = qp.to_ising()
# set classical optimizer
maxiter = 100
optimizer = COBYLA(maxiter=maxiter)
# set variational ansatz
ansatz = RealAmplitudes(n, reps=1)
m = ansatz.num_parameters
# set sampler
sampler = Sampler()
# run variational optimization for different values of alpha
alphas = [1.0, 0.50, 0.25] # confidence levels to be evaluated
# dictionaries to store optimization progress and results
objectives = {alpha: [] for alpha in alphas} # set of tested objective functions w.r.t. alpha
results = {} # results of minimum eigensolver w.r.t alpha
# callback to store intermediate results
def callback(i, params, obj, stddev, alpha):
# we translate the objective from the internal Ising representation
# to the original optimization problem
objectives[alpha].append(np.real_if_close(-(obj + offset)))
# loop over all given alpha values
for alpha in alphas:
# initialize SamplingVQE using CVaR
vqe = SamplingVQE(
sampler=sampler,
ansatz=ansatz,
optimizer=optimizer,
aggregation=alpha,
callback=lambda i, params, obj, stddev: callback(i, params, obj, stddev, alpha),
)
# initialize optimization algorithm based on CVaR-SamplingVQE
opt_alg = MinimumEigenOptimizer(vqe)
# solve problem
results[alpha] = opt_alg.solve(qp)
# print results
print("alpha = {}:".format(alpha))
print(results[alpha].prettyprint())
print()
# plot resulting history of objective values
plt.figure(figsize=(10, 5))
plt.plot([0, maxiter], [opt_result.fval, opt_result.fval], "r--", linewidth=2, label="optimum")
for alpha in alphas:
plt.plot(objectives[alpha], label="alpha = %.2f" % alpha, linewidth=2)
plt.legend(loc="lower right", fontsize=14)
plt.xlim(0, maxiter)
plt.xticks(fontsize=14)
plt.xlabel("iterations", fontsize=14)
plt.yticks(fontsize=14)
plt.ylabel("objective value", fontsize=14)
plt.show()
# evaluate and sort all objective values
objective_values = np.zeros(2**n)
for i in range(2**n):
x_bin = ("{0:0%sb}" % n).format(i)
x = [0 if x_ == "0" else 1 for x_ in reversed(x_bin)]
objective_values[i] = qp.objective.evaluate(x)
ind = np.argsort(objective_values)
# evaluate final optimal probability for each alpha
for alpha in alphas:
probabilities = np.fromiter(
results[alpha].min_eigen_solver_result.eigenstate.binary_probabilities().values(),
dtype=float,
)
print("optimal probability (alpha = %.2f): %.4f" % (alpha, probabilities[ind][-1:]))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-toqm
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import qiskit
from qiskit.transpiler import TranspilerError
import qiskit_toqm.native as toqm
from itertools import chain
def _calc_swap_durations(coupling_map, instruction_durations, basis_gates, backend_properties, target):
"""Calculates the durations of swap gates between each coupling on the target."""
# Filter for couplings that don't already have a native swap.
couplings = [
c for c in coupling_map.get_edges()
if ("swap", c) not in instruction_durations.duration_by_name_qubits
]
if not couplings:
return
backend_aware = target is not None or (basis_gates is not None and backend_properties is not None)
if not backend_aware:
raise TranspilerError(
"`target` must be specified, or both 'basis_gates' and 'backend_properties' must be specified unless"
"'instruction_durations' has durations for all swap gates."
)
def gen_swap_circuit(s, t):
# Generates a circuit with a single swap gate between src and tgt
c = qiskit.QuantumCircuit(coupling_map.size())
c.swap(s, t)
return c
# Batch transpile generated swap circuits
swap_circuits = qiskit.transpile(
[gen_swap_circuit(*pair) for pair in couplings],
basis_gates=basis_gates,
coupling_map=coupling_map,
backend_properties=backend_properties if target is None else None,
instruction_durations=instruction_durations,
target=target,
optimization_level=0,
layout_method="trivial",
scheduling_method="asap"
)
for (src, tgt), qc in zip(couplings, swap_circuits):
if instruction_durations.dt is None and qc.unit == "dt":
# TODO: should be able to convert by looking up an op in both
raise TranspilerError("Incompatible units.")
duration = qc.qubit_duration(src, tgt)
yield src, tgt, duration
def latencies_from_target(
coupling_map=None,
instruction_durations=None,
basis_gates=None,
backend_properties=None,
target=None,
normalize_scale=2
):
"""
Generate a list of native ``LatencyDescription`` objects for
the specified target device.
Args:
coupling_map (Optional[CouplingMap]): CouplingMap of the target backend.
Required unless ``target`` is specified.
instruction_durations (Optional[InstructionDurations]): Durations for gates
in the target's basis. Must include durations for all gates
that appear in input DAGs other than ``swap`` (for which
durations are calculated through decomposition if not supplied).
Required unless ``target`` is specified.
basis_gates (Optional[List[str]]): The list of basis gates for the
target. Required unless ``instruction_durations``
contains durations for all swap gates or ``target`` is specified.
backend_properties (Optional[BackendProperties]): The backend
properties of the target. Required unless
``instruction_durations`` contains durations for all swap gates
or ``target`` is specified.
target (Optional[Target]): The backend transpiler target. If specified,
overrides ``coupling_map``, ``instruction_durations``, ``basis_gates``,
and ``backend_properties``. All gates that appear in input DAG other
than ``swap`` must be supported by the target and have duration
information available therein.
normalize_scale (int): Multiple by this factor when converting
relative durations to cycle count. The conversion is:
cycles = ceil(duration * NORMALIZE_SCALE / min_duration)
where min_duration is the length of the fastest non-zero duration
instruction on the target.
"""
if target is not None:
coupling_map = target.build_coupling_map()
instruction_durations = target.durations()
basis_gates = target.operation_names
unit = "dt" if instruction_durations.dt else "s"
swap_durations = list(_calc_swap_durations(coupling_map, instruction_durations, basis_gates, backend_properties, target))
default_op_durations = [
(op_name, instruction_durations.get(op_name, [], unit))
for op_name in instruction_durations.duration_by_name
]
op_durations = [
(op_name, bits, instruction_durations.get(op_name, bits, unit))
for (op_name, bits) in instruction_durations.duration_by_name_qubits
]
non_zero_durations = [d for d in chain(
(d for (_, d) in default_op_durations),
(d for (_, _, d) in op_durations),
(d for (_, _, d) in swap_durations)
) if d > 0]
if not non_zero_durations:
raise TranspilerError("Durations must be specified for the target.")
min_duration = min(non_zero_durations)
def normalize(d):
return round(d * normalize_scale / min_duration)
# Yield latency descriptions with durations interpolated to cycles.
for op_name, duration in default_op_durations:
# We don't know if the instruction is for 1 or 2 qubits, so emit
# defaults for both.
yield toqm.LatencyDescription(1, op_name, normalize(duration))
yield toqm.LatencyDescription(2, op_name, normalize(duration))
for op_name, qubits, duration in op_durations:
yield toqm.LatencyDescription(op_name, *qubits, normalize(duration))
for src, tgt, duration in swap_durations:
yield toqm.LatencyDescription("swap", src, tgt, normalize(duration))
def latencies_from_simple(one_qubit_cycles, two_qubit_cycles, swap_cycles):
"""
Generate a list of native ``LatencyDescription`` objects for
the specified hard-coded cycle counts.
The resulting latency descriptions describe a circuit in which
all 1Q, 2Q, and SWAP gates execute in the corresponding number
of cycles, irrespective of which qubits they execute on.
Args:
one_qubit_cycles (int): The number of cycles for all 1Q gates.
two_qubit_cycles (int): The number of cycles for all 2Q gates.
swap_cycles (int): The number of cycles for all swap gates.
"""
return [
toqm.LatencyDescription(1, one_qubit_cycles),
toqm.LatencyDescription(2, two_qubit_cycles),
toqm.LatencyDescription(2, "swap", swap_cycles)
]
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
import numpy as np
coeff_list = []
for y in range(16):
coeff = 0
coeff += np.exp(-np.pi * 1j * 3 * y / 8)
coeff += np.exp(-np.pi * 1j * 7 * y / 8)
coeff += np.exp(-np.pi * 1j * 11 * y / 8)
coeff += np.exp(-np.pi * 1j * 15 * y / 8)
if np.abs(coeff.real) > 1e-14 or np.abs(coeff.imag) > 1e-14:
coeff_list.append(coeff)
else:
coeff_list.append(0)
for c in range(len(coeff_list)):
print(f'{c} : {coeff_list[c]}')
|
https://github.com/JackHidary/quantumcomputingbook
|
JackHidary
|
!pip install openfermion openfermioncirq pyscf openfermionpyscf
import openfermion as of
op = of.FermionOperator(((4, 1), (3, 1), (9, 0), (1, 0)), 1+2j) + of.FermionOperator(((3, 1), (1, 0)), -1.7)
print(op.terms)
op = of.FermionOperator('4^ 3^ 9 1', 1+2j) + of.FermionOperator('3^ 1', -1.7)
print(op.terms)
print(op)
op = of.QubitOperator(((1, 'X'), (2, 'Y'), (3, 'Z')))
op += of.QubitOperator('X3 Z4', 3.0)
print(op)
op = of.FermionOperator('2^ 15')
print(of.jordan_wigner(op))
print()
print(of.bravyi_kitaev(op, n_qubits=16))
a2 = of.FermionOperator('2')
print(of.jordan_wigner(a2))
print()
a2dag = of.FermionOperator('2^')
print(of.jordan_wigner(a2dag*a2))
print()
a7 = of.FermionOperator('7')
a7dag = of.FermionOperator('7^')
print(of.jordan_wigner((1+2j)*(a2dag*a7) + (1-2j)*(a7dag*a2)))
a2 = of.FermionOperator('2')
a2dag = of.FermionOperator('2^')
a7 = of.FermionOperator('7')
a7dag = of.FermionOperator('7^')
print(of.jordan_wigner(a2dag))
print()
print(of.jordan_wigner(a2dag*a2))
print()
op = (2+3j)*a2dag*a7
op += of.hermitian_conjugated(op)
print(of.jordan_wigner(op))
a2_jw = of.jordan_wigner(a2)
a2dag_jw = of.jordan_wigner(a2dag)
a7_jw = of.jordan_wigner(a7)
a7dag_jw = of.jordan_wigner(a7dag)
print(a2_jw * a7_jw + a7_jw * a2_jw)
print(a2_jw * a7dag_jw + a7dag_jw * a2_jw)
print(a2_jw * a2dag_jw + a2dag_jw * a2_jw)
import openfermionpyscf as ofpyscf
# Set molecule parameters
geometry = [('H', (0.0, 0.0, 0.0)), ('H', (0.0, 0.0, 0.8))]
basis = 'sto-3g'
multiplicity = 1
charge = 0
# Perform electronic structure calculations and
# obtain Hamiltonian as an InteractionOperator
hamiltonian = ofpyscf.generate_molecular_hamiltonian(
geometry, basis, multiplicity, charge)
# Convert to a FermionOperator
hamiltonian_ferm_op = of.get_fermion_operator(hamiltonian)
print(hamiltonian_ferm_op)
import scipy.sparse
# Map to QubitOperator using the JWT
hamiltonian_jw = of.jordan_wigner(hamiltonian_ferm_op)
# Convert to Scipy sparse matrix
hamiltonian_jw_sparse = of.get_sparse_operator(hamiltonian_jw)
# Compute ground energy
eigs, _ = scipy.sparse.linalg.eigsh(hamiltonian_jw_sparse, k=1, which='SA')
ground_energy = eigs[0]
print('Ground_energy: {}'.format(ground_energy))
print('JWT transformed Hamiltonian:')
print(hamiltonian_jw)
import scipy.sparse
# Map to QubitOperator using the JWT
hamiltonian_bk = of.bravyi_kitaev(hamiltonian_ferm_op)
# Convert to Scipy sparse matrix
hamiltonian_bk_sparse = of.get_sparse_operator(hamiltonian_bk)
# Compute ground energy
eigs, _ = scipy.sparse.linalg.eigsh(hamiltonian_bk_sparse, k=1, which='SA')
ground_energy = eigs[0]
print('Ground_energy: {}'.format(ground_energy))
print('BK transformed Hamiltonian:')
print(hamiltonian_bk)
# Map to QubitOperator using the BKT
hamiltonian_bk = of.bravyi_kitaev(hamiltonian_ferm_op)
# Convert to Scipy sparse matrix
hamiltonian_bk_sparse = of.get_sparse_operator(hamiltonian_bk)
# Compute ground state energy
eigs, _ = scipy.sparse.linalg.eigsh(hamiltonian_bk_sparse, k=1, which='SA')
ground_energy = eigs[0]
print('Ground_energy: {}'.format(ground_energy))
print('BKT transformed Hamiltonian:')
print(hamiltonian_bk)
# Create a random initial state
n_qubits = of.count_qubits(hamiltonian)
initial_state = of.haar_random_vector(2**n_qubits, seed=7)
# Set evolution time
time = 1.0
# Apply exp(-i H t) to the state
exact_state = scipy.sparse.linalg.expm_multiply(-1j*hamiltonian_jw_sparse*time, initial_state)
import cirq
import openfermioncirq as ofc
import numpy as np
# Initialize qubits
qubits = cirq.LineQubit.range(n_qubits)
# Create circuit
circuit = cirq.Circuit.from_ops(
ofc.simulate_trotter(
qubits, hamiltonian, time,
n_steps=10,
order=0,
algorithm=ofc.trotter.LOW_RANK)
)
# Apply the circuit to the initial state
result = circuit.apply_unitary_effect_to_state(initial_state)
# Compute the fidelity with the final state from exact evolution
fidelity = abs(np.dot(exact_state, result.conj()))**2
print(fidelity)
print(circuit.to_text_diagram(transpose=True))
import cirq
import openfermioncirq as ofc
ansatz = ofc.LowRankTrotterAnsatz(hamiltonian)
cirq.DropNegligible().optimize_circuit(ansatz.circuit)
print(ansatz.circuit.to_text_diagram(transpose=True))
import scipy.optimize
def energy_from_params(x):
param_resolver = ansatz.param_resolver(x)
circuit = cirq.resolve_parameters(ansatz.circuit, param_resolver)
final_state = circuit.apply_unitary_effect_to_state(0b1100)
return of.expectation(hamiltonian_jw_sparse, final_state).real
initial_guess = ansatz.default_initial_params()
result = scipy.optimize.minimize(energy_from_params, initial_guess)
print('Initial energy: {}'.format(energy_from_params(initial_guess)))
print('Optimized energy: {}'.format(result.fun))
n_qubits = 5
quad_ham = of.random_quadratic_hamiltonian(
n_qubits, conserves_particle_number=True, seed=7)
print(of.get_fermion_operator(quad_ham))
_, basis_change_matrix, _ = quad_ham.diagonalizing_bogoliubov_transform()
qubits = cirq.LineQubit.range(n_qubits)
circuit = cirq.Circuit.from_ops(
ofc.bogoliubov_transform(
qubits,
basis_change_matrix))
print(circuit.to_text_diagram(transpose=True))
orbital_energies, constant = quad_ham.orbital_energies()
print(orbital_energies)
print(constant)
# Apply the circuit with initial state having the first two modes occupied.
result = circuit.apply_unitary_effect_to_state(0b11000)
# Compute the expectation value of the final state with the Hamiltonian
quad_ham_sparse = of.get_sparse_operator(quad_ham)
print(of.expectation(quad_ham_sparse, result))
# Print out the ground state energy; it should match
print(quad_ham.ground_energy())
from scipy.sparse.linalg import expm_multiply
# Create a random initial state
initial_state = of.haar_random_vector(2**n_qubits)
# Set evolution time
time = 1.0
# Apply exp(-i H t) to the state
final_state = expm_multiply(-1j*quad_ham_sparse*time, initial_state)
# Initialize qubits
qubits = cirq.LineQubit.range(n_qubits)
# Write code below to create the circuit
# You should define the `circuit` variable here
# ---------------------------------------------
# ---------------------------------------------
# Apply the circuit to the initial state
result = circuit.apply_unitary_effect_to_state(initial_state)
# Compute the fidelity with the correct final state
fidelity = abs(np.dot(final_state, result.conj()))**2
# Print fidelity; it should be 1
print(fidelity)
# Initialize qubits
qubits = cirq.LineQubit.range(n_qubits)
# Write code below to create the circuit
# You should define the `circuit` variable here
# ---------------------------------------------
def exponentiate_quad_ham(qubits, quad_ham):
_, basis_change_matrix, _ = quad_ham.diagonalizing_bogoliubov_transform()
orbital_energies, _ = quad_ham.orbital_energies()
yield cirq.inverse(
ofc.bogoliubov_transform(qubits, basis_change_matrix))
for i in range(len(qubits)):
yield cirq.Rz(rads=-orbital_energies[i]).on(qubits[i])
yield ofc.bogoliubov_transform(qubits, basis_change_matrix)
circuit = cirq.Circuit.from_ops(exponentiate_quad_ham(qubits, quad_ham))
# ---------------------------------------------
# Apply the circuit to the initial state
result = circuit.apply_unitary_effect_to_state(initial_state)
# Compute the fidelity with the correct final state
fidelity = abs(np.dot(final_state, result.conj()))**2
# Print fidelity; it should be 1
print(fidelity)
|
https://github.com/kafurakami/quantum_algorithms
|
kafurakami
|
pip install qiskit
from qiskit import assemble, Aer, QuantumCircuit, __qiskit_version__, execute
from qiskit.visualization import plot_histogram
__qiskit_version__
circ = QuantumCircuit(4,2) #4 qubits, 2 measurements
circ.x(0)#Comment this out if q0 is 0
circ.x(1)#Comment this out if q1 is 0
circ.barrier()
circ.cx(0,2)#cnot between q0 and q2;0 is the control bit, 2 is target
circ.cx(1,2)#cnot between q1 and q2;1 is the control bit, 2 is target
#if both inputs are same, then cnot will return final measurement 0;
#if both inputs are different, then cnot will return final mes 1;
#Basically, the above statements achieve a XOR gate on q0 and q1, with
#output on q2
circ.ccx(0,1,3)#Toffoli gate with q0,q1 as controls, q3 as target
#basically an AND gate between q0 and q1, with output on q3
#this is necessary because in the case we add 1+1, we get 10,i.e. we need a one on the left bit, and this will
#return one if both the inputs are 1
circ.barrier()
circ.measure(2,0)#Measuring XOR output of qubit 2 on bit 1
circ.measure(3,1)#Measuring AND output of qubit 3 on bit 2
circ.draw('mpl')
#simulator = Aer.get_backend('qasm_simulator') Initialising backend
#job = assemble(circ) Assembling the circuit
#results = simulator.run(circ).result() finding results
#counts = results.get_counts() obtaining the counts
#much better way to do this using execute
backend = Aer.get_backend('qasm_simulator')#Same as simulator above
job = execute(circ, backend)#no need to assemble
result = job.result()
status = job.status()
print(status)
counts = result.get_counts()
plot_histogram(counts)
#Note - bits printed from right to left, i.e. if q2 is bit a and q3 is bit b, then printed in the order ba, NOT ab
#in the above case, q2 is 0 and q3 is 1, so the output is 10, NOT 01(as bits printed in reverse order; would have changed if measurement of 2 taken on bit2 instead of bit1, then the output would be normal ab instead of ba)
|
https://github.com/hephaex/Quantum-Computing-Awesome-List
|
hephaex
|
import qiskit
qiskit.__qiskit_version__
from qiskit import IBMQ
IBMQ.save_account('Type in the id you get from your IBM account')
IBMQ.load_account()
from qiskit import *
qr = QuantumRegister(2)
cr = ClassicalRegister(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(output='mpl')
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))
IBMQ.load_account()
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmq_16_melbourne')
job = execute(circuit, backend=qcomp)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(circuit))
from qiskit import *
from qiskit.tools.visualization import plot_bloch_multivector
circuit = QuantumCircuit(1,1)
circuit.x(0)
simulator = Aer.get_backend('statevector_simulator')
result = execute(circuit, backend=simulator).result()
statevector = result.get_statevector()
print(statevector)
%matplotlib inline
circuit.draw(output = 'mpl')
plot_bloch_multivector(statevector)
circuit.measure([0],[0])
backend = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend = backend, shots = 1024).result()
counts = result.get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
circuit = QuantumCircuit(1,1)
circuit.x(0)
simulator = Aer.get_backend('unitary_simulator')
result = execute(circuit, backend=simulator).result()
unitary = result.get_unitary()
print(unitary)
%matplotlib inline
circuit.draw(output = 'mpl')
from qiskit import *
%matplotlib inline
circuit = QuantumCircuit(3,3)
circuit.draw(output='mpl')
circuit.x(0)
circuit.barrier()
circuit.draw(output='mpl')
circuit.h(1)
circuit.cx(1,2)
circuit.draw(output='mpl')
circuit.cx(0,1)
circuit.h(0)
circuit.draw(output='mpl')
circuit.barrier()
circuit.measure([0,1], [0,1])
circuit.draw(output='mpl')
circuit.barrier()
circuit.cx(1,2)
circuit.cz(0,2)
circuit.draw(output='mpl')
circuit.measure(2,2)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit,backend=simulator, shots=1024).result()
counts = result.get_counts()
plot_histogram(counts)
print(counts)
from qiskit import *
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
secretnumber = '10000001'
circuit = QuantumCircuit(len(secretnumber)+1, len(secretnumber))
circuit.h(range(len(secretnumber)))
circuit.x(len(secretnumber))
circuit.h(len(secretnumber))
circuit.barrier()
circuit.draw(output='mpl')
for ii, yesno in enumerate(secretnumber):
if yesno == '1':
circuit.cx(ii,len(secretnumber))
# circuit.cx(5,6)
# circuit.cx(3,6)
# circuit.cx(0,6)
circuit.barrier()
# circuit.h([0,1,2,3,4,5])
circuit.h(range(len(secretnumber)))
circuit.draw(output='mpl')
circuit.barrier()
# circuit.measure([0,1,2,3,4,5],[0,1,2,3,4,5])
circuit.measure(range(len(secretnumber)), range(len(secretnumber)))
circuit.barrier()
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend = simulator, shots = 1).result()
counts = result.get_counts()
plot_histogram(counts)
IBMQ.load_account()
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmq_16_melbourne')
job = execute(circuit, backend=qcomp)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(circuit))
import qiskit
from qiskit import *
nqubits = 3
circuit = QuantumCircuit(nqubits, nqubits)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(1,2)
circuit.measure([0,1,2], [0,1,2])
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=simulator, shots=1024).result()
plot_histogram(result.get_counts(circuit))
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
%run init.ipynb
def plot_Pr0(R1, R2):
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100)
ph_max = 2*math.pi; dph = ph_max/20; ph = np.arange(0, ph_max+dph, dph)
dimph = ph.shape[0]; P0 = np.zeros(dimph)
T1 = math.sqrt(1 - R1**2); T2 = math.sqrt(1 - R2**2)
P0 = T1**2*R2**2 + R1**2*T2**2 + 2*T1*R1*T2*R2*np.cos(ph)
plt.plot(ph, P0); plt.xlabel(r'$\phi$'); plt.ylabel(r'$Pr(0)$')
plt.xlim(0, 2*math.pi); plt.ylim(0, 1)
plt.annotate(r'$R_{1}=$'+str(R1), xy=(0.5,0.5), xytext=(0.5,0.5), fontsize=12)
plt.annotate(r'$R_{2}=$'+str(R1), xy=(0.5,0.4), xytext=(0.5,0.4), fontsize=12)
plt.show()
interactive(plot_Pr0, R1 = (0, 1, 0.05), R2 = (0, 1, 0.05))
def V1(T1, T2):
return (2*T1*T2*np.sqrt(1-T1**2)*np.sqrt(1-T2**2))/((T1**2)*(T2**2) + (1-T1**2)*(1-T2**2))
def V_3d(th, ph):
x = np.linspace(0.00001, 0.99999, 20); y = np.linspace(0.00001, 0.99999, 20); X, Y = np.meshgrid(x, y)
Z = V1(X, Y); fig = plt.figure();
ax = plt.axes(projection = "3d"); ax.plot_wireframe(X, Y, Z, color = 'blue')
ax.set_xlabel(r'$T_{1}$'); ax.set_ylabel(r'$T_{2}$'); ax.set_zlabel(r'$V_{0}$')
ax.view_init(th, ph); fig.tight_layout(); plt.show()
interactive(V_3d, th = (0,90,10), ph = (0,360,10))
from mpl_toolkits import mplot3d
def V0(T1, T2):
return (2*T1*T2*np.sqrt(1-T1**2)*np.sqrt(1-T2**2))/((T1**2)*(1-T2**2) + (1-T1**2)*T2**2)
def V_3d(th, ph):
x = np.linspace(0.00001, 0.99999, 20); y = np.linspace(0.00001, 0.99999, 20); X, Y = np.meshgrid(x, y)
Z = V0(X, Y); fig = plt.figure();
ax = plt.axes(projection = "3d"); ax.plot_wireframe(X, Y, Z, color = 'blue')
ax.set_xlabel(r'$T_{1}$'); ax.set_ylabel(r'$T_{2}$'); ax.set_zlabel(r'$V_{0}$')
ax.view_init(th, ph); fig.tight_layout(); plt.show()
interactive(V_3d, th = (0,90,10), ph = (0,360,10))
def V_3d(th, ph):
x = np.linspace(0.00001, 0.99999, 20); y = np.linspace(0.00001, 0.99999, 20); X, Y = np.meshgrid(x, y)
Z = V0(X, Y)-V1(X, Y); fig = plt.figure();
ax = plt.axes(projection = "3d"); ax.plot_wireframe(X, Y, Z, color = 'blue')
ax.set_xlabel(r'$T_{1}$'); ax.set_ylabel(r'$T_{2}$'); ax.set_zlabel(r'$V_{0}-V_{1}$')
ax.view_init(th, ph); fig.tight_layout(); plt.show()
interactive(V_3d, th = (0,90,10), ph = (0,360,10))
import math
import qiskit
def shannon_num(pv):
d = pv.shape[0]; SE = 0.0; j = -1
while (j < d-1):
j = j + 1
if pv[j] > 10**-15 and pv[j] < (1.0-10**-15):
SE -= pv[j]*math.log2(pv[j])
return SE
import scipy.linalg.lapack as lapak
def von_neumann_num(rho):
d = rho.shape[0]; b = lapak.zheevd(rho)
return shannon_num(b[0])
def coh_re_num(rho):
d = rho.shape[0]; pv = np.zeros(d)
for j in range(0,d):
pv[j] = rho[j,j].real
return shannon_num(pv) - von_neumann_num(rho)
def P_vn_num(rho):
d = rho.shape[0]; P = 0
for j in range(0, d):
if rho[j,j] > 10**-15 and rho[j,j] < (1.0-10**-15):
P += np.absolute(rho[j,j])*math.log2(np.absolute(rho[j,j]))
return math.log2(d) + P
def qc_gmzi(th, ph, ga):
qc = qiskit.QuantumCircuit(1)
qc.rx(-2*th, 0); qc.z(0); qc.y(0); qc.p(ph, 0); qc.rx(-2*ga, 0)
return qc
th, ph, ga = math.pi/3, math.pi/2, math.pi; qcgmzi = qc_gmzi(th, ph, ga); qcgmzi.draw(output = 'mpl')
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_armonk')
simulator = qiskit.Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
# for error mitigation
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
qr = qiskit.QuantumRegister(1)
qubit_list = [0] # os qubits para os quais aplicaremos calibracao de medidas
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr)
job = qiskit.execute(meas_calibs, backend = device, shots = nshots); job_monitor(job)
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels)
# for computing coherence and predictability
th_max = math.pi/2; dth = th_max/10; th = np.arange(0, th_max+dth, dth); dimth = th.shape[0]
Csim = np.zeros(dimth); Psim = np.zeros(dimth); Cexp = np.zeros(dimth); Pexp = np.zeros(dimth)
for j in range(0, dimth):
qr = qiskit.QuantumRegister(1); qc = qiskit.QuantumCircuit(qr); qc.rx(-2*th[j], qr[0])
qstc = state_tomography_circuits(qc, qr[0])
job = qiskit.execute(qstc, simulator, shots = nshots) # simulation
qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method = 'lstsq')
Csim[j] = coh_re_num(rho); Psim[j] = P_vn_num(rho)
jobE = qiskit.execute(qstc, backend = device, shots = nshots); job_monitor(jobE)
mitigated_results = meas_fitter.filter.apply(jobE.result())
qstfE = StateTomographyFitter(mitigated_results, qstc)
#qstfE = StateTomographyFitter(jobE.result(), qstc)
rhoE = qstfE.fit(method = 'lstsq')
Cexp[j] = coh_re_num(rhoE); Pexp[j] = P_vn_num(rhoE)
Cexp
Pexp
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100)
plt.plot(th, Csim, label = r'$C_{re}^{sim}$')
plt.plot(th, Psim, label = r'$P_{vn}^{sim}$')
plt.plot(th, Cexp, 'o', label = r'$C_{re}^{exp}$')
plt.plot(th, Pexp, '*', label = r'$P_{vn}^{exp}$')
plt.legend(); plt.xlabel(r'$\theta$')
plt.savefig('coh_vs_ivi_armonk_mit.pdf', format = 'pdf', dpi = 200)
plt.show()
# for computing the visibility
ph_max = 2*math.pi; dph = ph_max/10; ph = np.arange(0, ph_max+dph, dph); dimph = ph.shape[0]
P0sim = np.zeros(dimph); P0exp = np.zeros(dimph)
th[j] = math.pi/2
for k in range(0, dimph):
qr = qiskit.QuantumRegister(1); cr = qiskit.ClassicalRegister(1); qc = qiskit.QuantumCircuit(qr, cr)
qc.rx(-2*th[j], qr[0]); qc.z(qr[0]); qc.y(qr[0])
qc.p(ph[k], qr[0]); ga = th[j]; qc.rx(-2*ga, qr[0]); qc.measure(qr[0], cr[0])
job = qiskit.execute(qc, backend = simulator, shots = nshots) # simulation
counts = job.result().get_counts(qc)
if '0' in counts:
P0sim[k] = counts['0']
jobE = qiskit.execute(qc, backend = device, shots = nshots); job_monitor(jobE)
mitigated_results = meas_fitter.filter.apply(jobE.result())
countsE = mitigated_results.get_counts(qc)
#countsE = jobE.result().get_counts(qc)
if '0' in countsE:
P0exp[k] = countsE['0']
P0sim = P0sim/nshots; P0exp = P0exp/nshots
P0exp
P0sim
P0expthpi2 = np.array([0.0267666 , 0.02431936, 0.02646069, 0.03701438, 0.02340165,
0.02997859, 0.02095442, 0.02049556, 0.02156623, 0.01957785,
0.03242582])
P0simthpi2 = np.array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
P0expthpi4 = np.array([1. , 0.90838173, 0.66274091, 0.37488527, 0.11976134,
0.01881309, 0.12251453, 0.36310798, 0.65050474, 0.90455797,
1. ])
P0simthpi4 = np.array([1. , 0.90612793, 0.65258789, 0.34069824, 0.09924316,
0. , 0.09228516, 0.34741211, 0.64331055, 0.90209961,
1. ])
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100)
plt.plot(ph, P0simthpi4, label = r'$P_{0}^{sim}(\theta=\pi/4)$')
plt.plot(ph, P0expthpi4, 'o', label = r'$P_{0}^{exp}(\theta=\pi/4)$')
plt.plot(ph, P0simthpi2, '.-', label = r'$P_{0}^{sim}(\theta=\pi/2)$')
plt.plot(ph, P0expthpi2, '*', label = r'$P_{0}^{exp}(\theta=\pi/2)$')
plt.ylim(0, 2*math.pi); plt.ylim(-0.01, 1.01)
plt.legend(); plt.xlabel(r'$\phi$')
plt.savefig('P0_thpi4_armonk_mit.pdf', format = 'pdf', dpi = 200)
plt.show()
|
https://github.com/Naphann/Solving-TSP-Grover
|
Naphann
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
provider = IBMQ.load_account()
def maj(a, b, k):
qc.cx(q[k], q[b])
qc.cx(q[k], q[a])
qc.ccx(q[a], q[b], q[k])
def unmaj(a, b, k):
qc.ccx(q[a], q[b], q[k])
qc.cx(q[k], q[a])
qc.cx(q[a], q[b])
def multiple_adder(a, b, c_0, z):
arr_size = len(a)
maj(c_0, b[0], a[0])
for i in range(arr_size-1):
maj(a[i], b[i+1], a[i+1])
qc.cx(q[a[arr_size-1]], q[z])
for i in reversed(range(arr_size-1)):
unmaj(a[i], b[i+1], a[i+1])
unmaj(c_0, b[0], a[0])
qubit_num = 20 # max is 32 if you're using the simulator
q = QuantumRegister(qubit_num)
c = ClassicalRegister(10)
qc = QuantumCircuit(q, c)
qc.x(q[0:2])
qc.x(q[6])
qc.barrier(q)
# initialize_oracle_part(4)
multiple_adder([0,1,2,3], [4,5,6,7], 8, 9)
for i in range(10):
qc.measure(q[i], c[i])
r = execute(qc, Aer.get_backend('qasm_simulator')).result()
rc = r.get_counts()
print(rc)
plot_histogram(rc)
qc.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import json
import time
import warnings
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import Statevector
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.circuit.library import RawFeatureVector
from qiskit_machine_learning.neural_networks import SamplerQNN
algorithm_globals.random_seed = 42
def ansatz(num_qubits):
return RealAmplitudes(num_qubits, reps=5)
num_qubits = 5
circ = ansatz(num_qubits)
circ.decompose().draw("mpl")
def auto_encoder_circuit(num_latent, num_trash):
qr = QuantumRegister(num_latent + 2 * num_trash + 1, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.compose(ansatz(num_latent + num_trash), range(0, num_latent + num_trash), inplace=True)
circuit.barrier()
auxiliary_qubit = num_latent + 2 * num_trash
# swap test
circuit.h(auxiliary_qubit)
for i in range(num_trash):
circuit.cswap(auxiliary_qubit, num_latent + i, num_latent + num_trash + i)
circuit.h(auxiliary_qubit)
circuit.measure(auxiliary_qubit, cr[0])
return circuit
num_latent = 3
num_trash = 2
circuit = auto_encoder_circuit(num_latent, num_trash)
circuit.draw("mpl")
def domain_wall(circuit, a, b):
# Here we place the Domain Wall to qubits a - b in our circuit
for i in np.arange(int(b / 2), int(b)):
circuit.x(i)
return circuit
domain_wall_circuit = domain_wall(QuantumCircuit(5), 0, 5)
domain_wall_circuit.draw("mpl")
ae = auto_encoder_circuit(num_latent, num_trash)
qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1)
qc = qc.compose(domain_wall_circuit, range(num_latent + num_trash))
qc = qc.compose(ae)
qc.draw("mpl")
# Here we define our interpret for our SamplerQNN
def identity_interpret(x):
return x
qnn = SamplerQNN(
circuit=qc,
input_params=[],
weight_params=ae.parameters,
interpret=identity_interpret,
output_shape=2,
)
def cost_func_domain(params_values):
probabilities = qnn.forward([], params_values)
# we pick a probability of getting 1 as the output of the network
cost = np.sum(probabilities[:, 1])
# plotting part
clear_output(wait=True)
objective_func_vals.append(cost)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
return cost
opt = COBYLA(maxiter=150)
initial_point = algorithm_globals.random.random(ae.num_parameters)
objective_func_vals = []
# make the plot nicer
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
opt_result = opt.minimize(cost_func_domain, initial_point)
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} seconds")
test_qc = QuantumCircuit(num_latent + num_trash)
test_qc = test_qc.compose(domain_wall_circuit)
ansatz_qc = ansatz(num_latent + num_trash)
test_qc = test_qc.compose(ansatz_qc)
test_qc.barrier()
test_qc.reset(4)
test_qc.reset(3)
test_qc.barrier()
test_qc = test_qc.compose(ansatz_qc.inverse())
test_qc.draw("mpl")
test_qc = test_qc.assign_parameters(opt_result.x)
domain_wall_state = Statevector(domain_wall_circuit).data
output_state = Statevector(test_qc).data
fidelity = np.sqrt(np.dot(domain_wall_state.conj(), output_state) ** 2)
print("Fidelity of our Output State with our Input State: ", fidelity.real)
def zero_idx(j, i):
# Index for zero pixels
return [
[i, j],
[i - 1, j - 1],
[i - 1, j + 1],
[i - 2, j - 1],
[i - 2, j + 1],
[i - 3, j - 1],
[i - 3, j + 1],
[i - 4, j - 1],
[i - 4, j + 1],
[i - 5, j],
]
def one_idx(i, j):
# Index for one pixels
return [[i, j - 1], [i, j - 2], [i, j - 3], [i, j - 4], [i, j - 5], [i - 1, j - 4], [i, j]]
def get_dataset_digits(num, draw=True):
# Create Dataset containing zero and one
train_images = []
train_labels = []
for i in range(int(num / 2)):
# First we introduce background noise
empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape(
8, 4
)
# Now we insert the pixels for the one
for i, j in one_idx(2, 6):
empty[j][i] = algorithm_globals.random.uniform(0.9, 1)
train_images.append(empty)
train_labels.append(1)
if draw:
plt.title("This is a One")
plt.imshow(train_images[-1])
plt.show()
for i in range(int(num / 2)):
empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape(
8, 4
)
# Now we insert the pixels for the zero
for k, j in zero_idx(2, 6):
empty[k][j] = algorithm_globals.random.uniform(0.9, 1)
train_images.append(empty)
train_labels.append(0)
if draw:
plt.imshow(train_images[-1])
plt.title("This is a Zero")
plt.show()
train_images = np.array(train_images)
train_images = train_images.reshape(len(train_images), 32)
for i in range(len(train_images)):
sum_sq = np.sum(train_images[i] ** 2)
train_images[i] = train_images[i] / np.sqrt(sum_sq)
return train_images, train_labels
train_images, __ = get_dataset_digits(2)
num_latent = 3
num_trash = 2
fm = RawFeatureVector(2 ** (num_latent + num_trash))
ae = auto_encoder_circuit(num_latent, num_trash)
qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1)
qc = qc.compose(fm, range(num_latent + num_trash))
qc = qc.compose(ae)
qc.draw("mpl")
def identity_interpret(x):
return x
qnn = SamplerQNN(
circuit=qc,
input_params=fm.parameters,
weight_params=ae.parameters,
interpret=identity_interpret,
output_shape=2,
)
def cost_func_digits(params_values):
probabilities = qnn.forward(train_images, params_values)
cost = np.sum(probabilities[:, 1]) / train_images.shape[0]
# plotting part
clear_output(wait=True)
objective_func_vals.append(cost)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
return cost
with open("12_qae_initial_point.json", "r") as f:
initial_point = json.load(f)
opt = COBYLA(maxiter=150)
objective_func_vals = []
# make the plot nicer
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
opt_result = opt.minimize(fun=cost_func_digits, x0=initial_point)
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} seconds")
# Test
test_qc = QuantumCircuit(num_latent + num_trash)
test_qc = test_qc.compose(fm)
ansatz_qc = ansatz(num_latent + num_trash)
test_qc = test_qc.compose(ansatz_qc)
test_qc.barrier()
test_qc.reset(4)
test_qc.reset(3)
test_qc.barrier()
test_qc = test_qc.compose(ansatz_qc.inverse())
# sample new images
test_images, test_labels = get_dataset_digits(2, draw=False)
for image, label in zip(test_images, test_labels):
original_qc = fm.assign_parameters(image)
original_sv = Statevector(original_qc).data
original_sv = np.reshape(np.abs(original_sv) ** 2, (8, 4))
param_values = np.concatenate((image, opt_result.x))
output_qc = test_qc.assign_parameters(param_values)
output_sv = Statevector(output_qc).data
output_sv = np.reshape(np.abs(output_sv) ** 2, (8, 4))
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(original_sv)
ax1.set_title("Input Data")
ax2.imshow(output_sv)
ax2.set_title("Output Data")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 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 Qiskit's repeat instruction operation."""
import unittest
from numpy import pi
from qiskit.transpiler import PassManager
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.test import QiskitTestCase
from qiskit.extensions import UnitaryGate
from qiskit.circuit.library import SGate, U3Gate, CXGate
from qiskit.circuit import Instruction, Measure, Gate
from qiskit.transpiler.passes import Unroller
from qiskit.circuit.exceptions import CircuitError
class TestRepeatInt1Q(QiskitTestCase):
"""Test gate_q1.repeat() with integer"""
def test_standard_1Q_two(self):
"""Test standard gate.repeat(2) method."""
qr = QuantumRegister(1, "qr")
expected_circ = QuantumCircuit(qr)
expected_circ.append(SGate(), [qr[0]])
expected_circ.append(SGate(), [qr[0]])
expected = expected_circ.to_instruction()
result = SGate().repeat(2)
self.assertEqual(result.name, "s*2")
self.assertEqual(result.definition, expected.definition)
self.assertIsInstance(result, Gate)
def test_standard_1Q_one(self):
"""Test standard gate.repeat(1) method."""
qr = QuantumRegister(1, "qr")
expected_circ = QuantumCircuit(qr)
expected_circ.append(SGate(), [qr[0]])
expected = expected_circ.to_instruction()
result = SGate().repeat(1)
self.assertEqual(result.name, "s*1")
self.assertEqual(result.definition, expected.definition)
self.assertIsInstance(result, Gate)
class TestRepeatInt2Q(QiskitTestCase):
"""Test gate_q2.repeat() with integer"""
def test_standard_2Q_two(self):
"""Test standard 2Q gate.repeat(2) method."""
qr = QuantumRegister(2, "qr")
expected_circ = QuantumCircuit(qr)
expected_circ.append(CXGate(), [qr[0], qr[1]])
expected_circ.append(CXGate(), [qr[0], qr[1]])
expected = expected_circ.to_instruction()
result = CXGate().repeat(2)
self.assertEqual(result.name, "cx*2")
self.assertEqual(result.definition, expected.definition)
self.assertIsInstance(result, Gate)
def test_standard_2Q_one(self):
"""Test standard 2Q gate.repeat(1) method."""
qr = QuantumRegister(2, "qr")
expected_circ = QuantumCircuit(qr)
expected_circ.append(CXGate(), [qr[0], qr[1]])
expected = expected_circ.to_instruction()
result = CXGate().repeat(1)
self.assertEqual(result.name, "cx*1")
self.assertEqual(result.definition, expected.definition)
self.assertIsInstance(result, Gate)
class TestRepeatIntMeasure(QiskitTestCase):
"""Test Measure.repeat() with integer"""
def test_measure_two(self):
"""Test Measure.repeat(2) method."""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
expected_circ = QuantumCircuit(qr, cr)
expected_circ.append(Measure(), [qr[0]], [cr[0]])
expected_circ.append(Measure(), [qr[0]], [cr[0]])
expected = expected_circ.to_instruction()
result = Measure().repeat(2)
self.assertEqual(result.name, "measure*2")
self.assertEqual(result.definition, expected.definition)
self.assertIsInstance(result, Instruction)
self.assertNotIsInstance(result, Gate)
def test_measure_one(self):
"""Test Measure.repeat(1) method."""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
expected_circ = QuantumCircuit(qr, cr)
expected_circ.append(Measure(), [qr[0]], [cr[0]])
expected = expected_circ.to_instruction()
result = Measure().repeat(1)
self.assertEqual(result.name, "measure*1")
self.assertEqual(result.definition, expected.definition)
self.assertIsInstance(result, Instruction)
self.assertNotIsInstance(result, Gate)
class TestRepeatUnroller(QiskitTestCase):
"""Test unrolling Gate.repeat"""
def test_unroller_two(self):
"""Test unrolling gate.repeat(2)."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(SGate().repeat(2), [qr[0]])
result = PassManager(Unroller("u3")).run(circuit)
expected = QuantumCircuit(qr)
expected.append(U3Gate(0, 0, pi / 2), [qr[0]])
expected.append(U3Gate(0, 0, pi / 2), [qr[0]])
self.assertEqual(result, expected)
def test_unroller_one(self):
"""Test unrolling gate.repeat(1)."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(SGate().repeat(1), [qr[0]])
result = PassManager(Unroller("u3")).run(circuit)
expected = QuantumCircuit(qr)
expected.append(U3Gate(0, 0, pi / 2), [qr[0]])
self.assertEqual(result, expected)
class TestRepeatErrors(QiskitTestCase):
"""Test when Gate.repeat() should raise."""
def test_unitary_no_int(self):
"""Test UnitaryGate.repeat(2/3) method. Raises, since n is not int."""
with self.assertRaises(CircuitError) as context:
_ = UnitaryGate([[0, 1j], [-1j, 0]]).repeat(2 / 3)
self.assertIn("strictly positive integer", str(context.exception))
def test_standard_no_int(self):
"""Test standard Gate.repeat(2/3) method. Raises, since n is not int."""
with self.assertRaises(CircuitError) as context:
_ = SGate().repeat(2 / 3)
self.assertIn("strictly positive integer", str(context.exception))
def test_measure_zero(self):
"""Test Measure.repeat(0) method. Raises, since n<1"""
with self.assertRaises(CircuitError) as context:
_ = Measure().repeat(0)
self.assertIn("strictly positive integer", str(context.exception))
def test_standard_1Q_zero(self):
"""Test standard 2Q gate.repeat(0) method. Raises, since n<1."""
with self.assertRaises(CircuitError) as context:
_ = SGate().repeat(0)
self.assertIn("strictly positive integer", str(context.exception))
def test_standard_1Q_minus_one(self):
"""Test standard 2Q gate.repeat(-1) method. Raises, since n<1."""
with self.assertRaises(CircuitError) as context:
_ = SGate().repeat(-1)
self.assertIn("strictly positive integer", str(context.exception))
def test_standard_2Q_minus_one(self):
"""Test standard 2Q gate.repeat(-1) method. Raises, since n<1."""
with self.assertRaises(CircuitError) as context:
_ = CXGate().repeat(-1)
self.assertIn("strictly positive integer", str(context.exception))
def test_measure_minus_one(self):
"""Test Measure.repeat(-1) method. Raises, since n<1"""
with self.assertRaises(CircuitError) as context:
_ = Measure().repeat(-1)
self.assertIn("strictly positive integer", str(context.exception))
def test_standard_2Q_zero(self):
"""Test standard 2Q gate.repeat(0) method. Raises, since n<1."""
with self.assertRaises(CircuitError) as context:
_ = CXGate().repeat(0)
self.assertIn("strictly positive integer", str(context.exception))
if __name__ == "__main__":
unittest.main()
|
https://github.com/Chibikuri/qwopt
|
Chibikuri
|
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from tqdm import trange, tqdm
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit import Aer, execute
from qiskit.quantum_info import state_fidelity
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import depolarizing_error
from qiskit import transpile
QASM = Aer.get_backend('qasm_simulator')
STATEVEC = Aer.get_backend('statevector_simulator')
class FidelityAnalyzer:
'''
This analyzer is for analyzing the fidelity
performance under the noisy situation.
Errors are very naive.
If you put quantum circuit, this module analyze the
fidelity decreasing automatically.
'''
def __init__(self, one_error, two_error, measure_qubit,
extime=10, shots=5000):
if not isinstance(one_error, (float, int, np.ndarray, list)):
raise ValueError('one error is must be float, int, array or list.')
else:
# error rate of u3
self.one_error = one_error
if not isinstance(two_error, (float, int, np.ndarray, list)):
raise ValueError('one error is must be float, int, array or list.')
else:
# error rate of cx
self.two_error = two_error
# TODO: make 3D plot when one error and two error are array
self.shots = shots
self.mes_qbt = measure_qubit
self.extime = extime
def fidelity_drop(self, qc, drawing=True, **kwargs):
nqc = transpile(qc, optimization_level=0, basis_gates=['cx', 'u3'])
# HACK efficient ways?
if isinstance(self.one_error,
(float, int)) and isinstance(self.two_error,
(float, int)):
fidelitis, std = self.fixed_fidelity(nqc)
# FIXME more easy way
self.pattern = 0
# FIXME more seeable
elif isinstance(self.one_error,
(float, int)) and isinstance(self.two_error,
(np.ndarray, list)):
fidelities, std = self._u3fix(nqc)
self.pattern = 1
elif isinstance(self.two_error,
(float, int)) and isinstance(self.one_error,
(np.ndarray, list)):
cxerror = depolarizing_error(self.two_error, 2)
fidelities, std = self._cxfix(nqc)
self.pattern = 2
else:
fidelities, std = self._nofix(nqc)
self.pattern = 3
if drawing:
self._draw(fidelities, std, **kwargs)
return fidelities
def _u3fix(self, qc):
nst = 2**len(self.mes_qbt)
bins = [format(i, '0%db' % len(self.mes_qbt))
for i in range(nst)]
# ideal result of this circuit
ideal = execute(qc, backend=QASM, shots=self.shots*10)
idealcounts = ideal.result().get_counts()
idealst = np.array([idealcounts.get(i, 0)/(self.shots*10)
for i in bins])
print(idealst)
# making noise model with error rate
u3error = depolarizing_error(self.one_error, 1)
# start simulations
mean_fid = []
std_fid = []
for two_err in tqdm(self.two_error):
mid = []
noise_model = NoiseModel()
cxerror = depolarizing_error(two_err, 2)
noise_model.add_all_qubit_quantum_error(u3error, ['u3'])
noise_model.add_all_qubit_quantum_error(cxerror, ['cx'])
for t in range(self.extime):
# execute!
job = execute(qc, backend=QASM, noise_model=noise_model,
shots=self.shots)
counts = job.result().get_counts()
stvec = [counts.get(i, 0)/self.shots for i in bins]
stf = state_fidelity(idealst, stvec)
mid.append(stf)
print(stvec)
mean_fid.append(np.mean(mid))
std_fid.append(np.std(mid))
return mean_fid, std_fid
def _cxfix(self, qc):
nst = 2**len(self.mes_qbt)
bins = [format(i, '0%db' % len(self.mes_qbt))
for i in range(nst)]
# ideal result of this circuit
ideal = execute(qc, backend=QASM, shots=self.shots*10)
idealcounts = ideal.result().get_counts()
idealst = np.array([idealcounts.get(i, 0)/(self.shots*10)
for i in bins])
# making noise model with error rate
cxerror = depolarizing_error(self.two_error, 2)
# start simulations
mean_fid = []
std_fid = []
for one_er in tqdm(self.one_error):
mid = []
noise_model = NoiseModel()
u3error = depolarizing_error(one_er, 1)
noise_model.add_all_qubit_quantum_error(u3error, ['u3'])
noise_model.add_all_qubit_quantum_error(cxerror, ['cx'])
for t in range(self.extime):
job = execute(qc, backend=QASM, noise_model=noise_model,
shots=self.shots)
counts = job.result().get_counts()
stvec = [counts.get(i, 0)/self.shots for i in bins]
stf = state_fidelity(idealst, stvec)
mid.append(stf)
mean_fid.append(np.mean(mid))
std_fid.append(np.std(mid))
return mean_fid, std_fid
def _nofix(self, qc):
nst = 2**len(self.mes_qbt)
bins = [format(i, '0%db' % len(self.mes_qbt))
for i in range(nst)]
# ideal result of this circuit
ideal = execute(qc, backend=QASM, shots=self.shots*10)
idealcounts = ideal.result().get_counts()
idealst = np.array([idealcounts.get(i, 0)/(self.shots*10)
for i in bins])
# start simulations
if len(self.one_error) != len(self.two_error):
raise ValueError('length of array of one error \
and two error must be the same.')
mean_fid = []
std_fid = []
for one_er, two_er in tqdm(zip(self.one_error, self.two_error)):
mid = []
# HACK: might be efficient in top layer
noise_model = NoiseModel()
u3error = depolarizing_error(one_er, 1)
cxerror = depolarizing_error(two_er, 2)
noise_model.add_all_qubit_quantum_error(u3error, ['u3'])
noise_model.add_all_qubit_quantum_error(cxerror, ['cx'])
for t in range(self.extime):
job = execute(qc, backend=QASM, noise_model=noise_model,
shots=self.shots)
counts = job.result().get_counts()
stvec = [counts.get(i, 0)/self.shots for i in bins]
stf = state_fidelity(idealst, stvec)
mid.append(stf)
mean_fid.append(np.mean(mid))
std_fid.append(np.std(mid))
return mean_fid, std_fid
def _fixed_fidelity(self, qc):
fidelity = 0
return fidelity
def _draw(self, fidelities, std, errorbar=True, **kwargs):
'''
drawing fidelity dropping
'''
title = kwargs.get('title', 'Fidelity decrease')
fontsize = kwargs.get('fontsize', 14)
seaborn = kwargs.get('seaborn', True)
plt.ylabel('Fidelity')
if seaborn:
sns.set()
plt.title(title, fontsize=fontsize)
if self.pattern == 0:
raise Exception('No drawing is allowed in just \
one element(under construction)')
elif self.pattern == 1:
plt.xlabel('Two qubit gate error')
if errorbar:
plt.errorbar(self.two_error, fidelities, yerr=std)
else:
plt.plot(self.two_error, fidelities)
elif self.pattern == 2:
plt.xlabel('One qubit gate error')
if errorbar:
plt.errorbar(self.one_error, fidelities, yerr=std)
else:
plt.plot(self.one_error, fidelities)
elif self.pattern == 3:
raise Exception('under construction')
else:
pass
plt.show()
if __name__ == '__main__':
q = QuantumRegister(4)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.x(q[0])
for i in range(3):
qc.cx(q[0], q[1])
qc.cx(q[1], q[0])
qc.measure(q[0], c[0])
qc.measure(q[1], c[1])
analyzer = FidelityAnalyzer(0.01, np.arange(0, 0.1, 0.01), [0, 1], extime=10)
result = analyzer.fidelity_drop(qc)
print(result)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""These tests are the examples given in the arXiv paper describing OpenQASM 2. Specifically, there
is a test for each subsection (except the description of 'qelib1.inc') in section 3 of
https://arxiv.org/abs/1707.03429v2. The examples are copy/pasted from the source files there."""
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import math
import os
import tempfile
import ddt
from qiskit import qasm2
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister, Qubit
from qiskit.circuit.library import U1Gate, U3Gate, CU1Gate
from qiskit.test import QiskitTestCase
from . import gate_builder
def load(string, *args, **kwargs):
# We're deliberately not using the context-manager form here because we need to use it in a
# slightly odd pattern.
# pylint: disable=consider-using-with
temp = tempfile.NamedTemporaryFile(mode="w", delete=False)
try:
temp.write(string)
# NamedTemporaryFile claims not to be openable a second time on Windows, so close it
# (without deletion) so Rust can open it again.
temp.close()
return qasm2.load(temp.name, *args, **kwargs)
finally:
# Now actually clean up after ourselves.
os.unlink(temp.name)
@ddt.ddt
class TestArxivExamples(QiskitTestCase):
@ddt.data(qasm2.loads, load)
def test_teleportation(self, parser):
example = """\
// quantum teleportation example
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
creg c0[1];
creg c1[1];
creg c2[1];
// optional post-rotation for state tomography
gate post q { }
u3(0.3,0.2,0.1) q[0];
h q[1];
cx q[1],q[2];
barrier q;
cx q[0],q[1];
h q[0];
measure q[0] -> c0[0];
measure q[1] -> c1[0];
if(c0==1) z q[2];
if(c1==1) x q[2];
post q[2];
measure q[2] -> c2[0];"""
parsed = parser(example)
post = gate_builder("post", [], QuantumCircuit([Qubit()]))
q = QuantumRegister(3, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
qc = QuantumCircuit(q, c0, c1, c2)
qc.append(U3Gate(0.3, 0.2, 0.1), [q[0]], [])
qc.h(q[1])
qc.cx(q[1], q[2])
qc.barrier(q)
qc.cx(q[0], q[1])
qc.h(q[0])
qc.measure(q[0], c0[0])
qc.measure(q[1], c1[0])
qc.z(q[2]).c_if(c0, 1)
qc.x(q[2]).c_if(c1, 1)
qc.append(post(), [q[2]], [])
qc.measure(q[2], c2[0])
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_qft(self, parser):
example = """\
// quantum Fourier transform
OPENQASM 2.0;
include "qelib1.inc";
qreg q[4];
creg c[4];
x q[0];
x q[2];
barrier q;
h q[0];
cu1(pi/2) q[1],q[0];
h q[1];
cu1(pi/4) q[2],q[0];
cu1(pi/2) q[2],q[1];
h q[2];
cu1(pi/8) q[3],q[0];
cu1(pi/4) q[3],q[1];
cu1(pi/2) q[3],q[2];
h q[3];
measure q -> c;"""
parsed = parser(example)
qc = QuantumCircuit(QuantumRegister(4, "q"), ClassicalRegister(4, "c"))
qc.x(0)
qc.x(2)
qc.barrier(range(4))
qc.h(0)
qc.append(CU1Gate(math.pi / 2), [1, 0])
qc.h(1)
qc.append(CU1Gate(math.pi / 4), [2, 0])
qc.append(CU1Gate(math.pi / 2), [2, 1])
qc.h(2)
qc.append(CU1Gate(math.pi / 8), [3, 0])
qc.append(CU1Gate(math.pi / 4), [3, 1])
qc.append(CU1Gate(math.pi / 2), [3, 2])
qc.h(3)
qc.measure(range(4), range(4))
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_inverse_qft_1(self, parser):
example = """\
// QFT and measure, version 1
OPENQASM 2.0;
include "qelib1.inc";
qreg q[4];
creg c[4];
h q;
barrier q;
h q[0];
measure q[0] -> c[0];
if(c==1) u1(pi/2) q[1];
h q[1];
measure q[1] -> c[1];
if(c==1) u1(pi/4) q[2];
if(c==2) u1(pi/2) q[2];
if(c==3) u1(pi/2+pi/4) q[2];
h q[2];
measure q[2] -> c[2];
if(c==1) u1(pi/8) q[3];
if(c==2) u1(pi/4) q[3];
if(c==3) u1(pi/4+pi/8) q[3];
if(c==4) u1(pi/2) q[3];
if(c==5) u1(pi/2+pi/8) q[3];
if(c==6) u1(pi/2+pi/4) q[3];
if(c==7) u1(pi/2+pi/4+pi/8) q[3];
h q[3];
measure q[3] -> c[3];"""
parsed = parser(example)
q = QuantumRegister(4, "q")
c = ClassicalRegister(4, "c")
qc = QuantumCircuit(q, c)
qc.h(q)
qc.barrier(q)
qc.h(q[0])
qc.measure(q[0], c[0])
qc.append(U1Gate(math.pi / 2).c_if(c, 1), [q[1]])
qc.h(q[1])
qc.measure(q[1], c[1])
qc.append(U1Gate(math.pi / 4).c_if(c, 1), [q[2]])
qc.append(U1Gate(math.pi / 2).c_if(c, 2), [q[2]])
qc.append(U1Gate(math.pi / 4 + math.pi / 2).c_if(c, 3), [q[2]])
qc.h(q[2])
qc.measure(q[2], c[2])
qc.append(U1Gate(math.pi / 8).c_if(c, 1), [q[3]])
qc.append(U1Gate(math.pi / 4).c_if(c, 2), [q[3]])
qc.append(U1Gate(math.pi / 8 + math.pi / 4).c_if(c, 3), [q[3]])
qc.append(U1Gate(math.pi / 2).c_if(c, 4), [q[3]])
qc.append(U1Gate(math.pi / 8 + math.pi / 2).c_if(c, 5), [q[3]])
qc.append(U1Gate(math.pi / 4 + math.pi / 2).c_if(c, 6), [q[3]])
qc.append(U1Gate(math.pi / 8 + math.pi / 4 + math.pi / 2).c_if(c, 7), [q[3]])
qc.h(q[3])
qc.measure(q[3], c[3])
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_inverse_qft_2(self, parser):
example = """\
// QFT and measure, version 2
OPENQASM 2.0;
include "qelib1.inc";
qreg q[4];
creg c0[1];
creg c1[1];
creg c2[1];
creg c3[1];
h q;
barrier q;
h q[0];
measure q[0] -> c0[0];
if(c0==1) u1(pi/2) q[1];
h q[1];
measure q[1] -> c1[0];
if(c0==1) u1(pi/4) q[2];
if(c1==1) u1(pi/2) q[2];
h q[2];
measure q[2] -> c2[0];
if(c0==1) u1(pi/8) q[3];
if(c1==1) u1(pi/4) q[3];
if(c2==1) u1(pi/2) q[3];
h q[3];
measure q[3] -> c3[0];"""
parsed = parser(example)
q = QuantumRegister(4, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
c3 = ClassicalRegister(1, "c3")
qc = QuantumCircuit(q, c0, c1, c2, c3)
qc.h(q)
qc.barrier(q)
qc.h(q[0])
qc.measure(q[0], c0[0])
qc.append(U1Gate(math.pi / 2).c_if(c0, 1), [q[1]])
qc.h(q[1])
qc.measure(q[1], c1[0])
qc.append(U1Gate(math.pi / 4).c_if(c0, 1), [q[2]])
qc.append(U1Gate(math.pi / 2).c_if(c1, 1), [q[2]])
qc.h(q[2])
qc.measure(q[2], c2[0])
qc.append(U1Gate(math.pi / 8).c_if(c0, 1), [q[3]])
qc.append(U1Gate(math.pi / 4).c_if(c1, 1), [q[3]])
qc.append(U1Gate(math.pi / 2).c_if(c2, 1), [q[3]])
qc.h(q[3])
qc.measure(q[3], c3[0])
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_ripple_carry_adder(self, parser):
example = """\
// quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184
OPENQASM 2.0;
include "qelib1.inc";
gate majority a,b,c
{
cx c,b;
cx c,a;
ccx a,b,c;
}
gate unmaj a,b,c
{
ccx a,b,c;
cx c,a;
cx a,b;
}
qreg cin[1];
qreg a[4];
qreg b[4];
qreg cout[1];
creg ans[5];
// set input states
x a[0]; // a = 0001
x b; // b = 1111
// add a to b, storing result in b
majority cin[0],b[0],a[0];
majority a[0],b[1],a[1];
majority a[1],b[2],a[2];
majority a[2],b[3],a[3];
cx a[3],cout[0];
unmaj a[2],b[3],a[3];
unmaj a[1],b[2],a[2];
unmaj a[0],b[1],a[1];
unmaj cin[0],b[0],a[0];
measure b[0] -> ans[0];
measure b[1] -> ans[1];
measure b[2] -> ans[2];
measure b[3] -> ans[3];
measure cout[0] -> ans[4];"""
parsed = parser(example)
majority_definition = QuantumCircuit([Qubit(), Qubit(), Qubit()])
majority_definition.cx(2, 1)
majority_definition.cx(2, 0)
majority_definition.ccx(0, 1, 2)
majority = gate_builder("majority", [], majority_definition)
unmaj_definition = QuantumCircuit([Qubit(), Qubit(), Qubit()])
unmaj_definition.ccx(0, 1, 2)
unmaj_definition.cx(2, 0)
unmaj_definition.cx(0, 1)
unmaj = gate_builder("unmaj", [], unmaj_definition)
cin = QuantumRegister(1, "cin")
a = QuantumRegister(4, "a")
b = QuantumRegister(4, "b")
cout = QuantumRegister(1, "cout")
ans = ClassicalRegister(5, "ans")
qc = QuantumCircuit(cin, a, b, cout, ans)
qc.x(a[0])
qc.x(b)
qc.append(majority(), [cin[0], b[0], a[0]])
qc.append(majority(), [a[0], b[1], a[1]])
qc.append(majority(), [a[1], b[2], a[2]])
qc.append(majority(), [a[2], b[3], a[3]])
qc.cx(a[3], cout[0])
qc.append(unmaj(), [a[2], b[3], a[3]])
qc.append(unmaj(), [a[1], b[2], a[2]])
qc.append(unmaj(), [a[0], b[1], a[1]])
qc.append(unmaj(), [cin[0], b[0], a[0]])
qc.measure(b, ans[:4])
qc.measure(cout[0], ans[4])
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_randomised_benchmarking(self, parser):
example = """\
// One randomized benchmarking sequence
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
barrier q;
cz q[0],q[1];
barrier q;
s q[0];
cz q[0],q[1];
barrier q;
s q[0];
z q[0];
h q[0];
barrier q;
measure q -> c;
"""
parsed = parser(example)
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.barrier(q)
qc.cz(q[0], q[1])
qc.barrier(q)
qc.s(q[0])
qc.cz(q[0], q[1])
qc.barrier(q)
qc.s(q[0])
qc.z(q[0])
qc.h(q[0])
qc.barrier(q)
qc.measure(q, c)
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_process_tomography(self, parser):
example = """\
OPENQASM 2.0;
include "qelib1.inc";
gate pre q { } // pre-rotation
gate post q { } // post-rotation
qreg q[1];
creg c[1];
pre q[0];
barrier q;
h q[0];
barrier q;
post q[0];
measure q[0] -> c[0];"""
parsed = parser(example)
pre = gate_builder("pre", [], QuantumCircuit([Qubit()]))
post = gate_builder("post", [], QuantumCircuit([Qubit()]))
qc = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "c"))
qc.append(pre(), [0])
qc.barrier(qc.qubits)
qc.h(0)
qc.barrier(qc.qubits)
qc.append(post(), [0])
qc.measure(0, 0)
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_error_correction(self, parser):
example = """\
// Repetition code syndrome measurement
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
qreg a[2];
creg c[3];
creg syn[2];
gate syndrome d1,d2,d3,a1,a2
{
cx d1,a1; cx d2,a1;
cx d2,a2; cx d3,a2;
}
x q[0]; // error
barrier q;
syndrome q[0],q[1],q[2],a[0],a[1];
measure a -> syn;
if(syn==1) x q[0];
if(syn==2) x q[2];
if(syn==3) x q[1];
measure q -> c;"""
parsed = parser(example)
syndrome_definition = QuantumCircuit([Qubit() for _ in [None] * 5])
syndrome_definition.cx(0, 3)
syndrome_definition.cx(1, 3)
syndrome_definition.cx(1, 4)
syndrome_definition.cx(2, 4)
syndrome = gate_builder("syndrome", [], syndrome_definition)
q = QuantumRegister(3, "q")
a = QuantumRegister(2, "a")
c = ClassicalRegister(3, "c")
syn = ClassicalRegister(2, "syn")
qc = QuantumCircuit(q, a, c, syn)
qc.x(q[0])
qc.barrier(q)
qc.append(syndrome(), [q[0], q[1], q[2], a[0], a[1]])
qc.measure(a, syn)
qc.x(q[0]).c_if(syn, 1)
qc.x(q[2]).c_if(syn, 2)
qc.x(q[1]).c_if(syn, 3)
qc.measure(q, c)
self.assertEqual(parsed, qc)
|
https://github.com/apozas/qaoa-color
|
apozas
|
from functools import reduce
from itertools import product
from qiskit import BasicAer, QuantumRegister
from qiskit_aqua import QuantumInstance
from qiskit_aqua import Operator, run_algorithm
from qiskit.quantum_info import Pauli
from qiskit_aqua.components.optimizers import COBYLA
from qiskit_aqua.components.initial_states import Custom
from constrainedqaoa import constrainedQAOA
import numpy as np
import qutip as qt
edges = [(0, 1), (1, 2), (2, 3)]
vertices = max(reduce(lambda x, y: x + y, [list(edge) for edge in edges])) + 1
colors = 2
n_qubits = vertices * colors
zr = np.zeros(n_qubits)
ws = np.eye(n_qubits)
up = qt.basis(2, 0)
dn = qt.basis(2, 1)
def W(size, copies):
initial_list = [dn] + [up] * (size - 1)
cycles = [[initial_list[i - j] for i in range(size)] for j in range(size)]
W_1copy = sum([qt.tensor(states) for states in cycles])
return qt.tensor([W_1copy] * copies)
amplitudes = W(colors, vertices).full().T.tolist()[0]
init_state = Custom(n_qubits, state_vector=amplitudes)
cost_operator = reduce(
lambda x, y: x + y,
[
Operator([[1, (Pauli(ws[colors*v1 + j, :], zr)
*Pauli(ws[colors*v2 + j, :], zr))]])
for (v1, v2), j in product(edges, range(colors))
]
)
mixer_operator = reduce(
lambda x, y: x + y,
[
Operator([[1, (Pauli(zr, ws[colors*i + j, :])
*Pauli(zr, ws[colors*i + (j+1) % colors, :]))]]) +
Operator([[1, (Pauli(ws[colors*i + j % colors, :], ws[colors*i + j % colors, :])
*Pauli(ws[colors*i + (j+1) % colors, :], ws[colors*i + (j+1) % colors, :]))]])
for i, j in product(range(vertices), range(colors))
]
)
# Fix redundancies
if colors == 2:
mixer_operator.scaling_coeff(1/2)
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
p = 1 # steps of QAOA
constrained = constrainedQAOA(cost_operator, cobyla, mixer_operator, p, init_state)
backend = BasicAer.get_backend('statevector_simulator')
seed = 50
constrained.random_seed = seed
quantum_instance = QuantumInstance(backend=backend, seed=seed, seed_mapper=seed)
result = constrained.run(quantum_instance)
result['eigvals']
np.round(result['eigvecs'], 4)
np.savetxt('4_line_2colors_p1', result['eigvecs'][0])
|
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, 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.
"""Qobj tests."""
import copy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler import assemble
from qiskit.qobj import (
QasmQobj,
PulseQobj,
QobjHeader,
PulseQobjInstruction,
PulseQobjExperiment,
PulseQobjConfig,
QobjMeasurementOption,
PulseLibraryItem,
QasmQobjInstruction,
QasmQobjExperiment,
QasmQobjConfig,
QasmExperimentCalibrations,
GateCalibration,
)
from qiskit.test import QiskitTestCase
class TestQASMQobj(QiskitTestCase):
"""Tests for QasmQobj."""
def setUp(self):
super().setUp()
self.valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
]
)
],
)
self.valid_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.2.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
]
}
],
}
self.bad_qobj = copy.deepcopy(self.valid_qobj)
self.bad_qobj.experiments = []
def test_from_dict_per_class(self):
"""Test Qobj and its subclass representations given a dictionary."""
test_parameters = {
QasmQobj: (self.valid_qobj, self.valid_dict),
QasmQobjConfig: (
QasmQobjConfig(shots=1, memory_slots=2),
{"shots": 1, "memory_slots": 2},
),
QasmQobjExperiment: (
QasmQobjExperiment(
instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])]
),
{"instructions": [{"name": "u1", "qubits": [1], "params": [0.4]}]},
),
QasmQobjInstruction: (
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
{"name": "u1", "qubits": [1], "params": [0.4]},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item, qobj_class.from_dict(expected_dict))
def test_snapshot_instruction_to_dict(self):
"""Test snapshot instruction to dict."""
valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
QasmQobjInstruction(
name="snapshot",
qubits=[1],
snapshot_type="statevector",
label="my_snap",
),
]
)
],
)
res = valid_qobj.to_dict()
expected_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.3.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
{
"name": "snapshot",
"qubits": [1],
"snapshot_type": "statevector",
"label": "my_snap",
},
],
"config": {},
"header": {},
}
],
}
self.assertEqual(expected_dict, res)
def test_snapshot_instruction_from_dict(self):
"""Test snapshot instruction from dict."""
expected_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
QasmQobjInstruction(
name="snapshot",
qubits=[1],
snapshot_type="statevector",
label="my_snap",
),
]
)
],
)
qobj_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.2.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
{
"name": "snapshot",
"qubits": [1],
"snapshot_type": "statevector",
"label": "my_snap",
},
]
}
],
}
self.assertEqual(expected_qobj, QasmQobj.from_dict(qobj_dict))
def test_change_qobj_after_compile(self):
"""Test modifying Qobj parameters after compile."""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
qc1 = QuantumCircuit(qr, cr)
qc2 = QuantumCircuit(qr, cr)
qc1.h(qr[0])
qc1.cx(qr[0], qr[1])
qc1.cx(qr[0], qr[2])
qc2.h(qr)
qc1.measure(qr, cr)
qc2.measure(qr, cr)
circuits = [qc1, qc2]
qobj1 = assemble(circuits, shots=1024, seed=88)
qobj1.experiments[0].config.shots = 50
qobj1.experiments[1].config.shots = 1
self.assertTrue(qobj1.experiments[0].config.shots == 50)
self.assertTrue(qobj1.experiments[1].config.shots == 1)
self.assertTrue(qobj1.config.shots == 1024)
def test_gate_calibrations_to_dict(self):
"""Test gate calibrations to dict."""
pulse_library = [PulseLibraryItem(name="test", samples=[1j, 1j])]
valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2, pulse_library=pulse_library),
experiments=[
QasmQobjExperiment(
instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])],
config=QasmQobjConfig(
calibrations=QasmExperimentCalibrations(
gates=[
GateCalibration(
name="u1", qubits=[1], params=[0.4], instructions=[]
)
]
)
),
)
],
)
res = valid_qobj.to_dict()
expected_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.3.0",
"header": {},
"config": {
"memory_slots": 2,
"shots": 1024,
"pulse_library": [{"name": "test", "samples": [1j, 1j]}],
},
"experiments": [
{
"instructions": [{"name": "u1", "params": [0.4], "qubits": [1]}],
"config": {
"calibrations": {
"gates": [
{"name": "u1", "qubits": [1], "params": [0.4], "instructions": []}
]
}
},
"header": {},
}
],
}
self.assertEqual(expected_dict, res)
class TestPulseQobj(QiskitTestCase):
"""Tests for PulseQobj."""
def setUp(self):
super().setUp()
self.valid_qobj = PulseQobj(
qobj_id="12345",
header=QobjHeader(),
config=PulseQobjConfig(
shots=1024,
memory_slots=2,
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[
PulseLibraryItem(name="pulse0", samples=[0.0 + 0.0j, 0.5 + 0.0j, 0.0 + 0.0j])
],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
experiments=[
PulseQobjExperiment(
instructions=[
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=1.57),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=0.0),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase="P1"),
PulseQobjInstruction(name="setp", t0=10, ch="d0", phase=3.14),
PulseQobjInstruction(name="setf", t0=10, ch="d0", frequency=8.0),
PulseQobjInstruction(name="shiftf", t0=10, ch="d0", frequency=4.0),
PulseQobjInstruction(
name="acquire",
t0=15,
duration=5,
qubits=[0],
memory_slot=[0],
kernels=[
QobjMeasurementOption(
name="boxcar", params={"start_window": 0, "stop_window": 5}
)
],
),
]
)
],
)
self.valid_dict = {
"qobj_id": "12345",
"type": "PULSE",
"schema_version": "1.2.0",
"header": {},
"config": {
"memory_slots": 2,
"shots": 1024,
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0, 0.5, 0]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
"experiments": [
{
"instructions": [
{"name": "pulse0", "t0": 0, "ch": "d0"},
{"name": "fc", "t0": 5, "ch": "d0", "phase": 1.57},
{"name": "fc", "t0": 5, "ch": "d0", "phase": 0},
{"name": "fc", "t0": 5, "ch": "d0", "phase": "P1"},
{"name": "setp", "t0": 10, "ch": "d0", "phase": 3.14},
{"name": "setf", "t0": 10, "ch": "d0", "frequency": 8.0},
{"name": "shiftf", "t0": 10, "ch": "d0", "frequency": 4.0},
{
"name": "acquire",
"t0": 15,
"duration": 5,
"qubits": [0],
"memory_slot": [0],
"kernels": [
{"name": "boxcar", "params": {"start_window": 0, "stop_window": 5}}
],
},
]
}
],
}
def test_from_dict_per_class(self):
"""Test converting to Qobj and its subclass representations given a dictionary."""
test_parameters = {
PulseQobj: (self.valid_qobj, self.valid_dict),
PulseQobjConfig: (
PulseQobjConfig(
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
{
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
),
PulseLibraryItem: (
PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]),
{"name": "pulse0", "samples": [0.1 + 0j]},
),
PulseQobjExperiment: (
PulseQobjExperiment(
instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")]
),
{"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]},
),
PulseQobjInstruction: (
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
{"name": "pulse0", "t0": 0, "ch": "d0"},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item, qobj_class.from_dict(expected_dict))
def test_to_dict_per_class(self):
"""Test converting from Qobj and its subclass representations given a dictionary."""
test_parameters = {
PulseQobj: (self.valid_qobj, self.valid_dict),
PulseQobjConfig: (
PulseQobjConfig(
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
{
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
),
PulseLibraryItem: (
PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]),
{"name": "pulse0", "samples": [0.1 + 0j]},
),
PulseQobjExperiment: (
PulseQobjExperiment(
instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")]
),
{"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]},
),
PulseQobjInstruction: (
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
{"name": "pulse0", "t0": 0, "ch": "d0"},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item.to_dict(), expected_dict)
def _nop():
pass
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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 Qiskit's QuantumCircuit class."""
import numpy as np
from ddt import data, ddt
from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute
from qiskit.circuit import Gate, Instruction, Measure, Parameter
from qiskit.circuit.bit import Bit
from qiskit.circuit.classicalregister import Clbit
from qiskit.circuit.exceptions import CircuitError
from qiskit.circuit.controlflow import IfElseOp
from qiskit.circuit.library import CXGate, HGate
from qiskit.circuit.library.standard_gates import SGate
from qiskit.circuit.quantumcircuit import BitLocations
from qiskit.circuit.quantumcircuitdata import CircuitInstruction
from qiskit.circuit.quantumregister import AncillaQubit, AncillaRegister, Qubit
from qiskit.pulse import DriveChannel, Gaussian, Play, Schedule
from qiskit.quantum_info import Operator
from qiskit.test import QiskitTestCase
@ddt
class TestCircuitOperations(QiskitTestCase):
"""QuantumCircuit Operations tests."""
@data(0, 1, -1, -2)
def test_append_resolves_integers(self, index):
"""Test that integer arguments to append are correctly resolved."""
# We need to assume that appending ``Bit`` instances will always work, so we have something
# to test against.
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
test = QuantumCircuit(qubits, clbits)
test.append(Measure(), [index], [index])
expected = QuantumCircuit(qubits, clbits)
expected.append(Measure(), [qubits[index]], [clbits[index]])
self.assertEqual(test, expected)
@data(np.int32(0), np.int8(-1), np.uint64(1))
def test_append_resolves_numpy_integers(self, index):
"""Test that Numpy's integers can be used to reference qubits and clbits."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
test = QuantumCircuit(qubits, clbits)
test.append(Measure(), [index], [index])
expected = QuantumCircuit(qubits, clbits)
expected.append(Measure(), [qubits[int(index)]], [clbits[int(index)]])
self.assertEqual(test, expected)
@data(
slice(0, 2),
slice(None, 1),
slice(1, None),
slice(None, None),
slice(0, 2, 2),
slice(2, -1, -1),
slice(1000, 1003),
)
def test_append_resolves_slices(self, index):
"""Test that slices can be used to reference qubits and clbits with the same semantics that
they have on lists."""
qregs = [QuantumRegister(2), QuantumRegister(1)]
cregs = [ClassicalRegister(1), ClassicalRegister(2)]
test = QuantumCircuit(*qregs, *cregs)
test.append(Measure(), [index], [index])
expected = QuantumCircuit(*qregs, *cregs)
for qubit, clbit in zip(expected.qubits[index], expected.clbits[index]):
expected.append(Measure(), [qubit], [clbit])
self.assertEqual(test, expected)
def test_append_resolves_scalar_numpy_array(self):
"""Test that size-1 Numpy arrays can be used to index arguments. These arrays can be passed
to ``int``, which means they sometimes might be involved in spurious casts."""
test = QuantumCircuit(1, 1)
test.append(Measure(), [np.array([0])], [np.array([0])])
expected = QuantumCircuit(1, 1)
expected.measure(0, 0)
self.assertEqual(test, expected)
@data([3], [-3], [0, 1, 3])
def test_append_rejects_out_of_range_input(self, specifier):
"""Test that append rejects an integer that's out of range."""
test = QuantumCircuit(2, 2)
with self.subTest("qubit"), self.assertRaisesRegex(CircuitError, "out of range"):
opaque = Instruction("opaque", len(specifier), 1, [])
test.append(opaque, specifier, [0])
with self.subTest("clbit"), self.assertRaisesRegex(CircuitError, "out of range"):
opaque = Instruction("opaque", 1, len(specifier), [])
test.append(opaque, [0], specifier)
def test_append_rejects_bits_not_in_circuit(self):
"""Test that append rejects bits that are not in the circuit."""
test = QuantumCircuit(2, 2)
with self.subTest("qubit"), self.assertRaisesRegex(CircuitError, "not in the circuit"):
test.append(Measure(), [Qubit()], [test.clbits[0]])
with self.subTest("clbit"), self.assertRaisesRegex(CircuitError, "not in the circuit"):
test.append(Measure(), [test.qubits[0]], [Clbit()])
with self.subTest("qubit list"), self.assertRaisesRegex(CircuitError, "not in the circuit"):
test.append(Measure(), [[test.qubits[0], Qubit()]], [test.clbits])
with self.subTest("clbit list"), self.assertRaisesRegex(CircuitError, "not in the circuit"):
test.append(Measure(), [test.qubits], [[test.clbits[0], Clbit()]])
def test_append_rejects_bit_of_wrong_type(self):
"""Test that append rejects bits of the wrong type in an argument list."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
test = QuantumCircuit(qubits, clbits)
with self.subTest("c to q"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"):
test.append(Measure(), [clbits[0]], [clbits[1]])
with self.subTest("q to c"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"):
test.append(Measure(), [qubits[0]], [qubits[1]])
with self.subTest("none to q"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"):
test.append(Measure(), [Bit()], [clbits[0]])
with self.subTest("none to c"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"):
test.append(Measure(), [qubits[0]], [Bit()])
with self.subTest("none list"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"):
test.append(Measure(), [[qubits[0], Bit()]], [[clbits[0], Bit()]])
@data(0.0, 1.0, 1.0 + 0.0j, "0")
def test_append_rejects_wrong_types(self, specifier):
"""Test that various bad inputs are rejected, both given loose or in sublists."""
test = QuantumCircuit(2, 2)
# Use a default Instruction to be sure that there's not overridden broadcasting.
opaque = Instruction("opaque", 1, 1, [])
with self.subTest("q"), self.assertRaisesRegex(CircuitError, "Invalid bit index"):
test.append(opaque, [specifier], [0])
with self.subTest("c"), self.assertRaisesRegex(CircuitError, "Invalid bit index"):
test.append(opaque, [0], [specifier])
with self.subTest("q list"), self.assertRaisesRegex(CircuitError, "Invalid bit index"):
test.append(opaque, [[specifier]], [[0]])
with self.subTest("c list"), self.assertRaisesRegex(CircuitError, "Invalid bit index"):
test.append(opaque, [[0]], [[specifier]])
@data([], [0], [0, 1, 2])
def test_append_rejects_bad_arguments_opaque(self, bad_arg):
"""Test that a suitable exception is raised when there is an argument mismatch."""
inst = QuantumCircuit(2, 2).to_instruction()
qc = QuantumCircuit(3, 3)
with self.assertRaisesRegex(CircuitError, "The amount of qubit arguments"):
qc.append(inst, bad_arg, [0, 1])
with self.assertRaisesRegex(CircuitError, "The amount of clbit arguments"):
qc.append(inst, [0, 1], bad_arg)
def test_anding_self(self):
"""Test that qc &= qc finishes, which can be prone to infinite while-loops.
This can occur e.g. when a user tries
>>> other_qc = qc
>>> other_qc &= qc # or qc2.compose(qc)
"""
qc = QuantumCircuit(1)
qc.x(0) # must contain at least one operation to end up in a infinite while-loop
# attempt addition, times out if qc is added via reference
qc &= qc
# finally, qc should contain two X gates
self.assertEqual(["x", "x"], [x.operation.name for x in qc.data])
def test_compose_circuit(self):
"""Test composing two circuits"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc1 = QuantumCircuit(qr, cr)
qc2 = QuantumCircuit(qr, cr)
qc1.h(qr[0])
qc1.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
qc3 = qc1.compose(qc2)
backend = BasicAer.get_backend("qasm_simulator")
shots = 1024
result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result()
counts = result.get_counts()
target = {"00": shots / 2, "01": shots / 2}
threshold = 0.04 * shots
self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2})
self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place"
self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place"
self.assertDictAlmostEqual(counts, target, threshold)
def test_compose_circuit_and(self):
"""Test composing two circuits using & operator"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc1 = QuantumCircuit(qr, cr)
qc2 = QuantumCircuit(qr, cr)
qc1.h(qr[0])
qc1.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
qc3 = qc1 & qc2
backend = BasicAer.get_backend("qasm_simulator")
shots = 1024
result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result()
counts = result.get_counts()
target = {"00": shots / 2, "01": shots / 2}
threshold = 0.04 * shots
self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2})
self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place"
self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place"
self.assertDictAlmostEqual(counts, target, threshold)
def test_compose_circuit_iand(self):
"""Test composing circuits using &= operator (in place)"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc1 = QuantumCircuit(qr, cr)
qc2 = QuantumCircuit(qr, cr)
qc1.h(qr[0])
qc1.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
qc1 &= qc2
backend = BasicAer.get_backend("qasm_simulator")
shots = 1024
result = execute(qc1, backend=backend, shots=shots, seed_simulator=78).result()
counts = result.get_counts()
target = {"00": shots / 2, "01": shots / 2}
threshold = 0.04 * shots
self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 2}) # changes "in-place"
self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place"
self.assertDictAlmostEqual(counts, target, threshold)
def test_compose_circuit_fail_circ_size(self):
"""Test composing circuit fails when number of wires in circuit is not enough"""
qr1 = QuantumRegister(2)
qr2 = QuantumRegister(4)
# Creating our circuits
qc1 = QuantumCircuit(qr1)
qc1.x(0)
qc1.h(1)
qc2 = QuantumCircuit(qr2)
qc2.h([1, 2])
qc2.cx(2, 3)
# Composing will fail because qc2 requires 4 wires
self.assertRaises(CircuitError, qc1.compose, qc2)
def test_compose_circuit_fail_arg_size(self):
"""Test composing circuit fails when arg size does not match number of wires"""
qr1 = QuantumRegister(2)
qr2 = QuantumRegister(2)
qc1 = QuantumCircuit(qr1)
qc1.h(0)
qc2 = QuantumCircuit(qr2)
qc2.cx(0, 1)
self.assertRaises(CircuitError, qc1.compose, qc2, qubits=[0])
def test_tensor_circuit(self):
"""Test tensoring two circuits"""
qc1 = QuantumCircuit(1, 1)
qc2 = QuantumCircuit(1, 1)
qc2.h(0)
qc2.measure(0, 0)
qc1.measure(0, 0)
qc3 = qc1.tensor(qc2)
backend = BasicAer.get_backend("qasm_simulator")
shots = 1024
result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result()
counts = result.get_counts()
target = {"00": shots / 2, "01": shots / 2}
threshold = 0.04 * shots
self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2})
self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place"
self.assertDictEqual(qc1.count_ops(), {"measure": 1}) # no changes "in-place"
self.assertDictAlmostEqual(counts, target, threshold)
def test_tensor_circuit_xor(self):
"""Test tensoring two circuits using ^ operator"""
qc1 = QuantumCircuit(1, 1)
qc2 = QuantumCircuit(1, 1)
qc2.h(0)
qc2.measure(0, 0)
qc1.measure(0, 0)
qc3 = qc1 ^ qc2
backend = BasicAer.get_backend("qasm_simulator")
shots = 1024
result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result()
counts = result.get_counts()
target = {"00": shots / 2, "01": shots / 2}
threshold = 0.04 * shots
self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2})
self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place"
self.assertDictEqual(qc1.count_ops(), {"measure": 1}) # no changes "in-place"
self.assertDictAlmostEqual(counts, target, threshold)
def test_tensor_circuit_ixor(self):
"""Test tensoring two circuits using ^= operator"""
qc1 = QuantumCircuit(1, 1)
qc2 = QuantumCircuit(1, 1)
qc2.h(0)
qc2.measure(0, 0)
qc1.measure(0, 0)
qc1 ^= qc2
backend = BasicAer.get_backend("qasm_simulator")
shots = 1024
result = execute(qc1, backend=backend, shots=shots, seed_simulator=78).result()
counts = result.get_counts()
target = {"00": shots / 2, "01": shots / 2}
threshold = 0.04 * shots
self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 2}) # changes "in-place"
self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place"
self.assertDictAlmostEqual(counts, target, threshold)
def test_measure_args_type_cohesion(self):
"""Test for proper args types for measure function."""
quantum_reg = QuantumRegister(3)
classical_reg_0 = ClassicalRegister(1)
classical_reg_1 = ClassicalRegister(2)
quantum_circuit = QuantumCircuit(quantum_reg, classical_reg_0, classical_reg_1)
quantum_circuit.h(quantum_reg)
with self.assertRaises(CircuitError) as ctx:
quantum_circuit.measure(quantum_reg, classical_reg_1)
self.assertEqual(ctx.exception.message, "register size error")
def test_copy_circuit(self):
"""Test copy method makes a copy"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
self.assertEqual(qc, qc.copy())
def test_copy_copies_registers(self):
"""Test copy copies the registers not via reference."""
qc = QuantumCircuit(1, 1)
copied = qc.copy()
copied.add_register(QuantumRegister(1, "additional_q"))
copied.add_register(ClassicalRegister(1, "additional_c"))
self.assertEqual(len(qc.qregs), 1)
self.assertEqual(len(copied.qregs), 2)
self.assertEqual(len(qc.cregs), 1)
self.assertEqual(len(copied.cregs), 2)
def test_copy_empty_like_circuit(self):
"""Test copy_empty_like method makes a clear copy."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr, global_phase=1.0, name="qc", metadata={"key": "value"})
qc.h(qr[0])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
sched = Schedule(Play(Gaussian(160, 0.1, 40), DriveChannel(0)))
qc.add_calibration("h", [0, 1], sched)
copied = qc.copy_empty_like()
qc.clear()
self.assertEqual(qc, copied)
self.assertEqual(qc.global_phase, copied.global_phase)
self.assertEqual(qc.name, copied.name)
self.assertEqual(qc.metadata, copied.metadata)
self.assertEqual(qc.calibrations, copied.calibrations)
copied = qc.copy_empty_like("copy")
self.assertEqual(copied.name, "copy")
def test_circuit_copy_rejects_invalid_types(self):
"""Test copy method rejects argument with type other than 'string' and 'None' type."""
qc = QuantumCircuit(1, 1)
qc.h(0)
with self.assertRaises(TypeError):
qc.copy([1, "2", 3])
def test_circuit_copy_empty_like_rejects_invalid_types(self):
"""Test copy_empty_like method rejects argument with type other than 'string' and 'None' type."""
qc = QuantumCircuit(1, 1)
qc.h(0)
with self.assertRaises(TypeError):
qc.copy_empty_like(123)
def test_clear_circuit(self):
"""Test clear method deletes instructions in circuit."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.clear()
self.assertEqual(len(qc.data), 0)
self.assertEqual(len(qc._parameter_table), 0)
def test_measure_active(self):
"""Test measure_active
Applies measurements only to non-idle qubits. Creates a ClassicalRegister of size equal to
the amount of non-idle qubits to store the measured values.
"""
qr = QuantumRegister(4)
cr = ClassicalRegister(2, "measure")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[2])
circuit.measure_active()
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[2])
expected.add_register(cr)
expected.barrier()
expected.measure([qr[0], qr[2]], [cr[0], cr[1]])
self.assertEqual(expected, circuit)
def test_measure_active_copy(self):
"""Test measure_active copy
Applies measurements only to non-idle qubits. Creates a ClassicalRegister of size equal to
the amount of non-idle qubits to store the measured values.
"""
qr = QuantumRegister(4)
cr = ClassicalRegister(2, "measure")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[2])
new_circuit = circuit.measure_active(inplace=False)
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[2])
expected.add_register(cr)
expected.barrier()
expected.measure([qr[0], qr[2]], [cr[0], cr[1]])
self.assertEqual(expected, new_circuit)
self.assertFalse("measure" in circuit.count_ops().keys())
def test_measure_active_repetition(self):
"""Test measure_active in a circuit with a 'measure' creg.
measure_active should be aware that the creg 'measure' might exists.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "measure")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr)
circuit.measure_active()
self.assertEqual(len(circuit.cregs), 2) # Two cregs
self.assertEqual(len(circuit.cregs[0]), 2) # Both length 2
self.assertEqual(len(circuit.cregs[1]), 2)
def test_measure_all(self):
"""Test measure_all applies measurements to all qubits.
Creates a ClassicalRegister of size equal to the total amount of qubits to
store those measured values.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "meas")
circuit = QuantumCircuit(qr)
circuit.measure_all()
expected = QuantumCircuit(qr, cr)
expected.barrier()
expected.measure(qr, cr)
self.assertEqual(expected, circuit)
def test_measure_all_not_add_bits_equal(self):
"""Test measure_all applies measurements to all qubits.
Does not create a new ClassicalRegister if the existing one is big enough.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "meas")
circuit = QuantumCircuit(qr, cr)
circuit.measure_all(add_bits=False)
expected = QuantumCircuit(qr, cr)
expected.barrier()
expected.measure(qr, cr)
self.assertEqual(expected, circuit)
def test_measure_all_not_add_bits_bigger(self):
"""Test measure_all applies measurements to all qubits.
Does not create a new ClassicalRegister if the existing one is big enough.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(3, "meas")
circuit = QuantumCircuit(qr, cr)
circuit.measure_all(add_bits=False)
expected = QuantumCircuit(qr, cr)
expected.barrier()
expected.measure(qr, cr[0:2])
self.assertEqual(expected, circuit)
def test_measure_all_not_add_bits_smaller(self):
"""Test measure_all applies measurements to all qubits.
Raises an error if there are not enough classical bits to store the measurements.
"""
qr = QuantumRegister(3)
cr = ClassicalRegister(2, "meas")
circuit = QuantumCircuit(qr, cr)
with self.assertRaisesRegex(CircuitError, "The number of classical bits"):
circuit.measure_all(add_bits=False)
def test_measure_all_copy(self):
"""Test measure_all with inplace=False"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "meas")
circuit = QuantumCircuit(qr)
new_circuit = circuit.measure_all(inplace=False)
expected = QuantumCircuit(qr, cr)
expected.barrier()
expected.measure(qr, cr)
self.assertEqual(expected, new_circuit)
self.assertFalse("measure" in circuit.count_ops().keys())
def test_measure_all_repetition(self):
"""Test measure_all in a circuit with a 'measure' creg.
measure_all should be aware that the creg 'measure' might exists.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "measure")
circuit = QuantumCircuit(qr, cr)
circuit.measure_all()
self.assertEqual(len(circuit.cregs), 2) # Two cregs
self.assertEqual(len(circuit.cregs[0]), 2) # Both length 2
self.assertEqual(len(circuit.cregs[1]), 2)
def test_remove_final_measurements(self):
"""Test remove_final_measurements
Removes all measurements at end of circuit.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "meas")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
circuit.remove_final_measurements()
expected = QuantumCircuit(qr)
self.assertEqual(expected, circuit)
def test_remove_final_measurements_copy(self):
"""Test remove_final_measurements on copy
Removes all measurements at end of circuit.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "meas")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
new_circuit = circuit.remove_final_measurements(inplace=False)
expected = QuantumCircuit(qr)
self.assertEqual(expected, new_circuit)
self.assertTrue("measure" in circuit.count_ops().keys())
def test_remove_final_measurements_copy_with_parameters(self):
"""Test remove_final_measurements doesn't corrupt ParameterTable
See https://github.com/Qiskit/qiskit-terra/issues/6108 for more details
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "meas")
theta = Parameter("theta")
circuit = QuantumCircuit(qr, cr)
circuit.rz(theta, qr)
circuit.measure(qr, cr)
circuit.remove_final_measurements()
copy = circuit.copy()
self.assertEqual(copy, circuit)
def test_remove_final_measurements_multiple_measures(self):
"""Test remove_final_measurements only removes measurements at the end of the circuit
remove_final_measurements should not remove measurements in the beginning or middle of the
circuit.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(1)
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr[0], cr)
circuit.h(0)
circuit.measure(qr[0], cr)
circuit.h(0)
circuit.measure(qr[0], cr)
circuit.remove_final_measurements()
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr)
expected.h(0)
expected.measure(qr[0], cr)
expected.h(0)
self.assertEqual(expected, circuit)
def test_remove_final_measurements_5802(self):
"""Test remove_final_measurements removes classical bits
https://github.com/Qiskit/qiskit-terra/issues/5802.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
circuit.remove_final_measurements()
self.assertEqual(circuit.cregs, [])
self.assertEqual(circuit.clbits, [])
def test_remove_final_measurements_7089(self):
"""Test remove_final_measurements removes resulting unused registers
even if not all bits were measured into.
https://github.com/Qiskit/qiskit-terra/issues/7089.
"""
circuit = QuantumCircuit(2, 5)
circuit.measure(0, 0)
circuit.measure(1, 1)
circuit.remove_final_measurements(inplace=True)
self.assertEqual(circuit.cregs, [])
self.assertEqual(circuit.clbits, [])
def test_remove_final_measurements_bit_locations(self):
"""Test remove_final_measurements properly recalculates clbit indicies
and preserves order of remaining cregs and clbits.
"""
c0 = ClassicalRegister(1)
c1_0 = Clbit()
c2 = ClassicalRegister(1)
c3 = ClassicalRegister(1)
# add an individual bit that's not in any register of this circuit
circuit = QuantumCircuit(QuantumRegister(1), c0, [c1_0], c2, c3)
circuit.measure(0, c1_0)
circuit.measure(0, c2[0])
# assert cregs and clbits before measure removal
self.assertEqual(circuit.cregs, [c0, c2, c3])
self.assertEqual(circuit.clbits, [c0[0], c1_0, c2[0], c3[0]])
# assert clbit indices prior to measure removal
self.assertEqual(circuit.find_bit(c0[0]), BitLocations(0, [(c0, 0)]))
self.assertEqual(circuit.find_bit(c1_0), BitLocations(1, []))
self.assertEqual(circuit.find_bit(c2[0]), BitLocations(2, [(c2, 0)]))
self.assertEqual(circuit.find_bit(c3[0]), BitLocations(3, [(c3, 0)]))
circuit.remove_final_measurements()
# after measure removal, creg c2 should be gone, as should lone bit c1_0
# and c0 should still come before c3
self.assertEqual(circuit.cregs, [c0, c3])
self.assertEqual(circuit.clbits, [c0[0], c3[0]])
# there should be no gaps in clbit indices
# e.g. c3[0] is now the second clbit
self.assertEqual(circuit.find_bit(c0[0]), BitLocations(0, [(c0, 0)]))
self.assertEqual(circuit.find_bit(c3[0]), BitLocations(1, [(c3, 0)]))
def test_reverse(self):
"""Test reverse method reverses but does not invert."""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.s(1)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
qc.x(0)
qc.y(1)
expected = QuantumCircuit(2, 2)
expected.y(1)
expected.x(0)
expected.measure([0, 1], [0, 1])
expected.cx(0, 1)
expected.s(1)
expected.h(0)
self.assertEqual(qc.reverse_ops(), expected)
def test_repeat(self):
"""Test repeating the circuit works."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.h(0).c_if(cr, 1)
with self.subTest("repeat 0 times"):
rep = qc.repeat(0)
self.assertEqual(rep, QuantumCircuit(qr, cr))
with self.subTest("repeat 3 times"):
inst = qc.to_instruction()
ref = QuantumCircuit(qr, cr)
for _ in range(3):
ref.append(inst, ref.qubits, ref.clbits)
rep = qc.repeat(3)
self.assertEqual(rep, ref)
@data(0, 1, 4)
def test_repeat_global_phase(self, num):
"""Test the global phase is properly handled upon repeat."""
phase = 0.123
qc = QuantumCircuit(1, global_phase=phase)
expected = np.exp(1j * phase * num) * np.identity(2)
np.testing.assert_array_almost_equal(Operator(qc.repeat(num)).data, expected)
def test_bind_global_phase(self):
"""Test binding global phase."""
x = Parameter("x")
circuit = QuantumCircuit(1, global_phase=x)
self.assertEqual(circuit.parameters, {x})
bound = circuit.bind_parameters({x: 2})
self.assertEqual(bound.global_phase, 2)
self.assertEqual(bound.parameters, set())
def test_bind_parameter_in_phase_and_gate(self):
"""Test binding a parameter present in the global phase and the gates."""
x = Parameter("x")
circuit = QuantumCircuit(1, global_phase=x)
circuit.rx(x, 0)
self.assertEqual(circuit.parameters, {x})
ref = QuantumCircuit(1, global_phase=2)
ref.rx(2, 0)
bound = circuit.bind_parameters({x: 2})
self.assertEqual(bound, ref)
self.assertEqual(bound.parameters, set())
def test_power(self):
"""Test taking the circuit to a power works."""
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.rx(0.2, 1)
gate = qc.to_gate()
with self.subTest("power(int >= 0) equals repeat"):
self.assertEqual(qc.power(4), qc.repeat(4))
with self.subTest("explicit matrix power"):
self.assertEqual(qc.power(4, matrix_power=True).data[0].operation, gate.power(4))
with self.subTest("float power"):
self.assertEqual(qc.power(1.23).data[0].operation, gate.power(1.23))
with self.subTest("negative power"):
self.assertEqual(qc.power(-2).data[0].operation, gate.power(-2))
def test_power_parameterized_circuit(self):
"""Test taking a parameterized circuit to a power."""
theta = Parameter("th")
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.rx(theta, 1)
with self.subTest("power(int >= 0) equals repeat"):
self.assertEqual(qc.power(4), qc.repeat(4))
with self.subTest("cannot to matrix power if parameterized"):
with self.assertRaises(CircuitError):
_ = qc.power(0.5)
def test_control(self):
"""Test controlling the circuit."""
qc = QuantumCircuit(2, name="my_qc")
qc.cry(0.2, 0, 1)
c_qc = qc.control()
with self.subTest("return type is circuit"):
self.assertIsInstance(c_qc, QuantumCircuit)
with self.subTest("test name"):
self.assertEqual(c_qc.name, "c_my_qc")
with self.subTest("repeated control"):
cc_qc = c_qc.control()
self.assertEqual(cc_qc.num_qubits, c_qc.num_qubits + 1)
with self.subTest("controlled circuit has same parameter"):
param = Parameter("p")
qc.rx(param, 0)
c_qc = qc.control()
self.assertEqual(qc.parameters, c_qc.parameters)
with self.subTest("non-unitary operation raises"):
qc.reset(0)
with self.assertRaises(CircuitError):
_ = qc.control()
def test_control_implementation(self):
"""Run a test case for controlling the circuit, which should use ``Gate.control``."""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.cry(0.2, 0, 1)
qc.t(0)
qc.append(SGate().control(2), [0, 1, 2])
qc.iswap(2, 0)
c_qc = qc.control(2, ctrl_state="10")
cgate = qc.to_gate().control(2, ctrl_state="10")
ref = QuantumCircuit(*c_qc.qregs)
ref.append(cgate, ref.qubits)
self.assertEqual(ref, c_qc)
@data("gate", "instruction")
def test_repeat_appended_type(self, subtype):
"""Test repeat appends Gate if circuit contains only gates and Instructions otherwise."""
sub = QuantumCircuit(2)
sub.x(0)
if subtype == "gate":
sub = sub.to_gate()
else:
sub = sub.to_instruction()
qc = QuantumCircuit(2)
qc.append(sub, [0, 1])
rep = qc.repeat(3)
if subtype == "gate":
self.assertTrue(all(isinstance(op.operation, Gate) for op in rep.data))
else:
self.assertTrue(all(isinstance(op.operation, Instruction) for op in rep.data))
def test_reverse_bits(self):
"""Test reversing order of bits."""
qc = QuantumCircuit(3, 2)
qc.h(0)
qc.s(1)
qc.cx(0, 1)
qc.measure(0, 1)
qc.x(0)
qc.y(1)
qc.global_phase = -1
expected = QuantumCircuit(3, 2)
expected.h(2)
expected.s(1)
expected.cx(2, 1)
expected.measure(2, 0)
expected.x(2)
expected.y(1)
expected.global_phase = -1
self.assertEqual(qc.reverse_bits(), expected)
def test_reverse_bits_boxed(self):
"""Test reversing order of bits in a hierarchical circuit."""
wide_cx = QuantumCircuit(3)
wide_cx.cx(0, 1)
wide_cx.cx(1, 2)
wide_cxg = wide_cx.to_gate()
cx_box = QuantumCircuit(3)
cx_box.append(wide_cxg, [0, 1, 2])
expected = QuantumCircuit(3)
expected.cx(2, 1)
expected.cx(1, 0)
self.assertEqual(cx_box.reverse_bits().decompose(), expected)
self.assertEqual(cx_box.decompose().reverse_bits(), expected)
# box one more layer to be safe.
cx_box_g = cx_box.to_gate()
cx_box_box = QuantumCircuit(4)
cx_box_box.append(cx_box_g, [0, 1, 2])
cx_box_box.cx(0, 3)
expected2 = QuantumCircuit(4)
expected2.cx(3, 2)
expected2.cx(2, 1)
expected2.cx(3, 0)
self.assertEqual(cx_box_box.reverse_bits().decompose().decompose(), expected2)
def test_reverse_bits_with_registers(self):
"""Test reversing order of bits when registers are present."""
qr1 = QuantumRegister(3, "a")
qr2 = QuantumRegister(2, "b")
qc = QuantumCircuit(qr1, qr2)
qc.h(qr1[0])
qc.cx(qr1[0], qr1[1])
qc.cx(qr1[1], qr1[2])
qc.cx(qr1[2], qr2[0])
qc.cx(qr2[0], qr2[1])
expected = QuantumCircuit(qr2, qr1)
expected.h(qr1[2])
expected.cx(qr1[2], qr1[1])
expected.cx(qr1[1], qr1[0])
expected.cx(qr1[0], qr2[1])
expected.cx(qr2[1], qr2[0])
self.assertEqual(qc.reverse_bits(), expected)
def test_reverse_bits_with_overlapped_registers(self):
"""Test reversing order of bits when registers are overlapped."""
qr1 = QuantumRegister(2, "a")
qr2 = QuantumRegister(bits=[qr1[0], qr1[1], Qubit()], name="b")
qc = QuantumCircuit(qr1, qr2)
qc.h(qr1[0])
qc.cx(qr1[0], qr1[1])
qc.cx(qr1[1], qr2[2])
qr2 = QuantumRegister(bits=[Qubit(), qr1[0], qr1[1]], name="b")
expected = QuantumCircuit(qr2, qr1)
expected.h(qr1[1])
expected.cx(qr1[1], qr1[0])
expected.cx(qr1[0], qr2[0])
self.assertEqual(qc.reverse_bits(), expected)
def test_reverse_bits_with_registerless_bits(self):
"""Test reversing order of registerless bits."""
q0 = Qubit()
q1 = Qubit()
c0 = Clbit()
c1 = Clbit()
qc = QuantumCircuit([q0, q1], [c0, c1])
qc.h(0)
qc.cx(0, 1)
qc.x(0).c_if(1, True)
qc.measure(0, 0)
expected = QuantumCircuit([c1, c0], [q1, q0])
expected.h(1)
expected.cx(1, 0)
expected.x(1).c_if(0, True)
expected.measure(1, 1)
self.assertEqual(qc.reverse_bits(), expected)
def test_reverse_bits_with_registers_and_bits(self):
"""Test reversing order of bits with registers and registerless bits."""
qr = QuantumRegister(2, "a")
q = Qubit()
qc = QuantumCircuit(qr, [q])
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.cx(qr[1], q)
expected = QuantumCircuit([q], qr)
expected.h(qr[1])
expected.cx(qr[1], qr[0])
expected.cx(qr[0], q)
self.assertEqual(qc.reverse_bits(), expected)
def test_reverse_bits_with_mixed_overlapped_registers(self):
"""Test reversing order of bits with overlapped registers and registerless bits."""
q = Qubit()
qr1 = QuantumRegister(bits=[q, Qubit()], name="qr1")
qr2 = QuantumRegister(bits=[qr1[1], Qubit()], name="qr2")
qc = QuantumCircuit(qr1, qr2, [Qubit()])
qc.h(q)
qc.cx(qr1[0], qr1[1])
qc.cx(qr1[1], qr2[1])
qc.cx(2, 3)
qr2 = QuantumRegister(2, "qr2")
qr1 = QuantumRegister(bits=[qr2[1], q], name="qr1")
expected = QuantumCircuit([Qubit()], qr2, qr1)
expected.h(qr1[1])
expected.cx(qr1[1], qr1[0])
expected.cx(qr1[0], qr2[0])
expected.cx(1, 0)
self.assertEqual(qc.reverse_bits(), expected)
def test_cnot_alias(self):
"""Test that the cnot method alias adds a cx gate."""
qc = QuantumCircuit(2)
qc.cnot(0, 1)
expected = QuantumCircuit(2)
expected.cx(0, 1)
self.assertEqual(qc, expected)
def test_inverse(self):
"""Test inverse circuit."""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr, global_phase=0.5)
qc.h(0)
qc.barrier(qr)
qc.t(1)
expected = QuantumCircuit(qr)
expected.tdg(1)
expected.barrier(qr)
expected.h(0)
expected.global_phase = -0.5
self.assertEqual(qc.inverse(), expected)
def test_compare_two_equal_circuits(self):
"""Test to compare that 2 circuits are equal."""
qc1 = QuantumCircuit(2, 2)
qc1.h(0)
qc2 = QuantumCircuit(2, 2)
qc2.h(0)
self.assertTrue(qc1 == qc2)
def test_compare_two_different_circuits(self):
"""Test to compare that 2 circuits are different."""
qc1 = QuantumCircuit(2, 2)
qc1.h(0)
qc2 = QuantumCircuit(2, 2)
qc2.x(0)
self.assertFalse(qc1 == qc2)
def test_compare_circuits_with_single_bit_conditions(self):
"""Test that circuits with single-bit conditions can be compared correctly."""
qreg = QuantumRegister(1, name="q")
creg = ClassicalRegister(1, name="c")
qc1 = QuantumCircuit(qreg, creg, [Clbit()])
qc1.x(0).c_if(qc1.cregs[0], 1)
qc1.x(0).c_if(qc1.clbits[-1], True)
qc2 = QuantumCircuit(qreg, creg, [Clbit()])
qc2.x(0).c_if(qc2.cregs[0], 1)
qc2.x(0).c_if(qc2.clbits[-1], True)
self.assertEqual(qc1, qc2)
# Order of operations transposed.
qc1 = QuantumCircuit(qreg, creg, [Clbit()])
qc1.x(0).c_if(qc1.cregs[0], 1)
qc1.x(0).c_if(qc1.clbits[-1], True)
qc2 = QuantumCircuit(qreg, creg, [Clbit()])
qc2.x(0).c_if(qc2.clbits[-1], True)
qc2.x(0).c_if(qc2.cregs[0], 1)
self.assertNotEqual(qc1, qc2)
# Single-bit condition values not the same.
qc1 = QuantumCircuit(qreg, creg, [Clbit()])
qc1.x(0).c_if(qc1.cregs[0], 1)
qc1.x(0).c_if(qc1.clbits[-1], True)
qc2 = QuantumCircuit(qreg, creg, [Clbit()])
qc2.x(0).c_if(qc2.cregs[0], 1)
qc2.x(0).c_if(qc2.clbits[-1], False)
self.assertNotEqual(qc1, qc2)
def test_compare_a_circuit_with_none(self):
"""Test to compare that a circuit is different to None."""
qc1 = QuantumCircuit(2, 2)
qc1.h(0)
qc2 = None
self.assertFalse(qc1 == qc2)
def test_overlapped_add_bits_and_add_register(self):
"""Test add registers whose bits have already been added by add_bits."""
qc = QuantumCircuit()
for bit_type, reg_type in (
[Qubit, QuantumRegister],
[Clbit, ClassicalRegister],
[AncillaQubit, AncillaRegister],
):
bits = [bit_type() for _ in range(10)]
reg = reg_type(bits=bits)
qc.add_bits(bits)
qc.add_register(reg)
self.assertEqual(qc.num_qubits, 20)
self.assertEqual(qc.num_clbits, 10)
self.assertEqual(qc.num_ancillas, 10)
def test_overlapped_add_register_and_add_register(self):
"""Test add registers whose bits have already been added by add_register."""
qc = QuantumCircuit()
for bit_type, reg_type in (
[Qubit, QuantumRegister],
[Clbit, ClassicalRegister],
[AncillaQubit, AncillaRegister],
):
bits = [bit_type() for _ in range(10)]
reg1 = reg_type(bits=bits)
reg2 = reg_type(bits=bits)
qc.add_register(reg1)
qc.add_register(reg2)
self.assertEqual(qc.num_qubits, 20)
self.assertEqual(qc.num_clbits, 10)
self.assertEqual(qc.num_ancillas, 10)
def test_from_instructions(self):
"""Test from_instructions method."""
qreg = QuantumRegister(4)
creg = ClassicalRegister(3)
a, b, c, d = qreg
x, y, z = creg
circuit_1 = QuantumCircuit(2, 1)
circuit_1.x(0)
circuit_2 = QuantumCircuit(2, 1)
circuit_2.y(0)
def instructions():
yield CircuitInstruction(HGate(), [a], [])
yield CircuitInstruction(CXGate(), [a, b], [])
yield CircuitInstruction(Measure(), [a], [x])
yield CircuitInstruction(Measure(), [b], [y])
yield CircuitInstruction(IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z])
def instruction_tuples():
yield HGate(), [a], []
yield CXGate(), [a, b], []
yield CircuitInstruction(Measure(), [a], [x])
yield Measure(), [b], [y]
yield IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z]
def instruction_tuples_partial():
yield HGate(), [a]
yield CXGate(), [a, b], []
yield CircuitInstruction(Measure(), [a], [x])
yield Measure(), [b], [y]
yield IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z]
circuit = QuantumCircuit.from_instructions(instructions())
circuit_tuples = QuantumCircuit.from_instructions(instruction_tuples())
circuit_tuples_partial = QuantumCircuit.from_instructions(instruction_tuples_partial())
expected = QuantumCircuit([a, b, c, d], [x, y, z])
for instruction in instructions():
expected.append(instruction.operation, instruction.qubits, instruction.clbits)
self.assertEqual(circuit, expected)
self.assertEqual(circuit_tuples, expected)
self.assertEqual(circuit_tuples_partial, expected)
def test_from_instructions_bit_order(self):
"""Test from_instructions method bit order."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
a, b = qreg
c, d = creg
def instructions():
yield CircuitInstruction(HGate(), [b], [])
yield CircuitInstruction(CXGate(), [a, b], [])
yield CircuitInstruction(Measure(), [b], [d])
yield CircuitInstruction(Measure(), [a], [c])
circuit = QuantumCircuit.from_instructions(instructions())
self.assertEqual(circuit.qubits, [b, a])
self.assertEqual(circuit.clbits, [d, c])
circuit = QuantumCircuit.from_instructions(instructions(), qubits=qreg)
self.assertEqual(circuit.qubits, [a, b])
self.assertEqual(circuit.clbits, [d, c])
circuit = QuantumCircuit.from_instructions(instructions(), clbits=creg)
self.assertEqual(circuit.qubits, [b, a])
self.assertEqual(circuit.clbits, [c, d])
circuit = QuantumCircuit.from_instructions(
instructions(), qubits=iter([a, b]), clbits=[c, d]
)
self.assertEqual(circuit.qubits, [a, b])
self.assertEqual(circuit.clbits, [c, d])
def test_from_instructions_metadata(self):
"""Test from_instructions method passes metadata."""
qreg = QuantumRegister(2)
a, b = qreg
def instructions():
yield CircuitInstruction(HGate(), [a], [])
yield CircuitInstruction(CXGate(), [a, b], [])
circuit = QuantumCircuit.from_instructions(instructions(), name="test", global_phase=0.1)
expected = QuantumCircuit([a, b], global_phase=0.1)
for instruction in instructions():
expected.append(instruction.operation, instruction.qubits, instruction.clbits)
self.assertEqual(circuit, expected)
self.assertEqual(circuit.name, "test")
class TestCircuitPrivateOperations(QiskitTestCase):
"""Direct tests of some of the private methods of QuantumCircuit. These do not represent
functionality that we want to expose to users, but there are some cases where private methods
are used internally (similar to "protected" access in .NET or "friend" access in C++), and we
want to make sure they work in those cases."""
def test_previous_instruction_in_scope_failures(self):
"""Test the failure paths of the peek and pop methods for retrieving the most recent
instruction in a scope."""
test = QuantumCircuit(1, 1)
with self.assertRaisesRegex(CircuitError, r"This circuit contains no instructions\."):
test._peek_previous_instruction_in_scope()
with self.assertRaisesRegex(CircuitError, r"This circuit contains no instructions\."):
test._pop_previous_instruction_in_scope()
with test.for_loop(range(2)):
with self.assertRaisesRegex(CircuitError, r"This scope contains no instructions\."):
test._peek_previous_instruction_in_scope()
with self.assertRaisesRegex(CircuitError, r"This scope contains no instructions\."):
test._pop_previous_instruction_in_scope()
def test_pop_previous_instruction_removes_parameters(self):
"""Test that the private "pop instruction" method removes parameters from the parameter
table if that instruction is the only instance."""
x, y = Parameter("x"), Parameter("y")
test = QuantumCircuit(1, 1)
test.rx(y, 0)
last_instructions = test.u(x, y, 0, 0)
self.assertEqual({x, y}, set(test.parameters))
instruction = test._pop_previous_instruction_in_scope()
self.assertEqual(list(last_instructions), [instruction])
self.assertEqual({y}, set(test.parameters))
def test_decompose_gate_type(self):
"""Test decompose specifying gate type."""
circuit = QuantumCircuit(1)
circuit.append(SGate(label="s_gate"), [0])
decomposed = circuit.decompose(gates_to_decompose=SGate)
self.assertNotIn("s", decomposed.count_ops())
|
https://github.com/Anastasia-Sim/PoW-QCSA-fa22
|
Anastasia-Sim
|
hash_dict = {
'0000': '1111',
'0001': '0010',
'0010': '0000',
'0011': '0101',
'0100': '1010',
'0101': '1101',
'0110': '1000',
'0111': '1011',
'1000': '0111',
'1001': '1100',
'1010': '0110',
'1011': '1001',
'1100': '0011',
'1101': '1110',
'1110': '0001',
'1111': '0100'
}
import random
def get_strings(bit_count):
strarr = []
def generate(n, s=''):
if len(s) == n:
strarr.append(s)
else:
generate(n, s + '0')
generate(n, s + '1')
generate(bit_count)
random.shuffle(strarr)
return strarr
def proof_of_work(level, bitlen):
strarr = get_strings(bitlen)
count = 1
for i in strarr:
if hash_dict[i].startswith('0'*level):
# print("found hash", i, "in", count, " tries")
random.shuffle(strarr)
break;
else:
count += 1
return count
def getAvgTries(tries, level=4, bitlen=4):
sum = 0
for i in range(tries):
sum += proof_of_work(level, bitlen)
return sum/tries
getAvgTries(100)
|
https://github.com/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
from qiskit import QuantumCircuit, execute, transpile, Aer
from qiskit.extensions import UnitaryGate, Initialize
import numpy as np
from qiskit.providers.ibmq.managed import IBMQJobManager
from sys import stdout
from scipy.stats import unitary_group
class bundled_SPEA_alternate:
def __init__(self, unitary, resolution=100, error=3, max_iters=20):
# handle resolution
if not isinstance(resolution, int):
raise TypeError("Please enter the number of intervals as an integer value")
if resolution < 10 or resolution > 1e6:
raise ValueError(
"Resolution needs to be atleast 0.1 and greater than 0.000001"
)
self.resolution = resolution
# handle unitary
if (
not isinstance(unitary, np.ndarray)
and not isinstance(unitary, QuantumCircuit)
and not isinstance(unitary, UnitaryGate)
):
raise TypeError(
"A numpy array or Quantum Circuit or UnitaryGate needs to be passed as the unitary matrix"
)
# convert circuit to numpy array for uniformity
if isinstance(unitary, UnitaryGate):
U = unitary.to_matrix()
else: # both QC and ndarray type
U = unitary
# note - the unitary here is not just a single qubit unitary
if isinstance(U, np.ndarray):
self.dims = U.shape[0]
else:
self.dims = 2 ** (U.num_qubits)
if isinstance(U, np.ndarray):
self.c_unitary_gate = UnitaryGate(data=U).control(
num_ctrl_qubits=1, label="CU", ctrl_state="1"
)
else:
self.c_unitary_gate = U.control(
num_ctrl_qubits=1, label="CU", ctrl_state="1"
)
# handle error
if not isinstance(error, int):
raise TypeError(
"The allowable error should be provided as an int. Interpreted as 10**(-error)"
)
if error <= 0:
raise ValueError("The error threshold must be finite and greater than 0.")
self.error = error
# handle max_iters
if not isinstance(max_iters, int):
raise TypeError("Max iterations must be of integer type")
if max_iters <= 0 and max_iters > 1e5:
raise ValueError("Max iterations should be atleast 1 and less than 1e5")
self.iterations = max_iters
self.basis = []
def get_basis_vectors(self, randomize=True):
# get the d dimensional basis for the unitary provided
if randomize == True:
UR = unitary_group.rvs(self.dims)
else:
UR = np.identity(self.dims)
basis = []
for k in UR:
basis.append(np.array(k, dtype=complex))
return basis
def get_unitary_circuit(self, backend):
"""Return the pretranspiled circuit"""
if backend is None:
backend = Aer.get_backend("qasm_simulator")
qc = QuantumCircuit(1 + int(np.log2(self.dims)))
# make the circuit
qc.h(0)
qc = qc.compose(self.c_unitary_gate, qubits=range(1 + int(np.log2(self.dims))))
qc.barrier()
qc = transpile(qc, backend=backend, optimization_level=3)
return qc
def get_circuit(self, state, backend, shots, angle=None):
"""Given an initial state ,
return the circuit that is generated with
inverse rotation as 0."""
# all theta values are iterated over for the same state
phi = Initialize(state)
shots = 512
qc1 = QuantumCircuit(1 + int(np.log2(self.dims)), 1)
# initialize the circuit
qc1 = qc1.compose(phi, qubits=list(range(1, int(np.log2(self.dims)) + 1)))
qc1 = transpile(qc1, backend=backend)
# get the circuit2
qc2 = self.unitary_circuit
qc3 = QuantumCircuit(1 + int(np.log2(self.dims)), 1)
if angle is not None:
# add inverse rotation on the first qubit
qc3.p(-2 * np.pi * angle, 0)
# add hadamard
qc3.h(0)
qc3 = transpile(qc3, backend=backend)
# make final circuit
qc = qc1 + qc2 + qc3
# qc = assemble(qc,shots = shots)
# measure
qc.measure([0], [0])
return qc
def get_optimal_angle(self, p0, p1, angles):
"""Return the theta value which minimizes
the S metric"""
min_s = 1e5
best_theta = -1
for theta in angles:
c0 = (np.cos(np.pi * theta)) ** 2
c1 = (np.sin(np.pi * theta)) ** 2
# generate the metric ...
s = (p0 - c0) ** 2 + (p1 - c1) ** 2
if s < min_s:
s = min_s
best_theta = theta
return best_theta
def execute_job(self, progress, iteration, backend, shots, circuits):
"""Send a job to the backend using IBMQ Job Manager"""
# define IBMQManager instance
manager = IBMQJobManager()
# first run the generated circuits
if progress:
print("Transpiling circuits...")
# get the job runner instance
job_set = manager.run(
circuits, backend=backend, name="Job_set " + str(iteration), shots=shots
)
if progress:
print("Transpilation Done!\nJob sent...")
# send and get job
job_result = job_set.results()
if progress:
print("Job has returned")
# return result
return job_result
def get_eigen_pair(
self,
backend,
theta_left=0,
theta_right=1,
progress=False,
randomize=True,
basis=None,
basis_ind=None,
target_cost=None,
shots=512,
):
"""Finding the eigenstate pair for the unitary"""
self.unitary_circuit = self.get_unitary_circuit(backend)
if theta_left > theta_right:
raise ValueError(
"Left bound for theta should be smaller than the right bound"
)
elif (theta_left < 0) or (theta_right > 1):
raise ValueError("Bounds of theta are [0,1].")
if not isinstance(progress, bool):
raise TypeError("Progress must be a boolean variable")
if not isinstance(randomize, bool):
raise Exception("Randomize must be a boolean variable")
results = dict()
# first initialize the state phi
if basis is None:
self.basis = self.get_basis_vectors(randomize)
else:
self.basis = basis
# choose a random index
if basis_ind is None:
ind = np.random.choice(self.dims)
else:
ind = basis_ind
phi = self.basis[ind]
# doing the method 1 of our algorithm
# define resolution of angles and precision
precision = 1 / 10 ** self.error
samples = self.resolution
# initialization of range
left, right = theta_left, theta_right
# generate the angles
angles = np.linspace(left, right, samples)
# First execution can be done without JobManager also...
circ = self.get_circuit(phi, backend=backend, shots=shots)
job = execute(circ, backend=backend, shots=shots)
counts = job.result().get_counts()
if "0" in counts:
p0 = counts["0"]
else:
p0 = 0
if "1" in counts:
p1 = counts["1"]
else:
p1 = 0
# experimental probabilities
p0, p1 = p0 / shots, p1 / shots
# get initial angle estimate
theta_max = self.get_optimal_angle(p0, p1, angles)
# get intial cost
circ = self.get_circuit(phi, backend=backend, shots=shots, angle=theta_max)
job = execute(circ, backend=backend, shots=shots)
counts = job.result().get_counts()
if "0" in counts:
cost = counts["0"] / shots
else:
cost = 0
# update best phi
best_phi = phi
# the range upto which theta extends iin each iteration
angle_range = (right - left) / 2
# a parameter
a = 1
# start algorithm
iters = 0
found = True
while 1 - cost >= precision:
# get angles, note if theta didn't change, then we need to
# again generate the same range again
right = min(theta_right, theta_max + angle_range / 2)
left = max(theta_left, theta_max - angle_range / 2)
if progress:
print("Right :", right)
print("Left :", left)
# generate the angles only if the theta has been updated
if found == True:
angles = np.linspace(left, right, samples)
found = False # for this iteration
if progress:
print("ITERATION NUMBER", iters + 1, "...")
# generate a cost dict for each of the iterations
# final result lists
costs, states = [], []
# circuit list
circuits = []
# 1. Circuit generation loop
for i in range((2 * self.dims)):
# everyone is supplied with the same range of theta in one iteration
# define z
if i < self.dims:
z = 1
else:
z = 1j
# alter and normalise phi
curr_phi = best_phi + z * a * (1 - cost) * self.basis[i % self.dims]
curr_phi = curr_phi / np.linalg.norm(curr_phi)
states.append(curr_phi)
# bundle the circuits together ...
circuits.append(
self.get_circuit(curr_phi, backend=backend, shots=shots)
)
job_result = self.execute_job(progress, iters, backend, shots, circuits)
# define lists again
thetas, circuits = [], []
# 3. Classical work
for i in range((2 * self.dims)):
# we have that many circuits only
counts = job_result.get_counts(i)
# get the experimental counts for this state
try:
exp_p0 = counts["0"]
except:
exp_p0 = 0
try:
exp_p1 = counts["1"]
except:
exp_p1 = 0
# normalize
exp_p0 = exp_p0 / shots
exp_p1 = exp_p1 / shots
theta_val = self.get_optimal_angle(exp_p0, exp_p1, angles)
# generate the circuit and append
circuits.append(
self.get_circuit(
states[i], backend=backend, shots=shots, angle=theta_val
)
)
thetas.append(theta_val)
# again execute these circuits
job_result = self.execute_job(progress, iters, backend, shots, circuits)
# 5. Result generation loop
for i in range((2 * self.dims)):
# cost generation after execution ...
counts = job_result.get_counts(i)
if "0" in counts:
curr_cost = counts["0"] / (shots)
else:
curr_cost = 0
if (
curr_cost > cost
): # then only add this cost in the cost and states list
cost = curr_cost
best_phi = states[i]
theta_max = thetas[i]
found = True
if progress:
stdout.write("\r")
stdout.write("%f %%completed" % (100 * (i + 1) / (2 * self.dims)))
stdout.flush()
if found == False:
# phi was not updated , change a
a = a / 2
if progress:
print("\nNo change, updating a...")
else:
# if found is actually true, then only print
if progress:
print("Best Phi is :", best_phi)
print("Theta estimate :", theta_max)
print("Current cost :", cost)
angle_range /= 2 # updated phi and thus theta too -> refine theta range
# update the iterations
iters += 1
if progress:
print("\nCOST :", cost)
print("THETA :", theta_max)
if iters >= self.iterations:
print(
"Maximum iterations reached for the estimation.\nTerminating algorithm..."
)
break
# add cost, eigenvector and theta to the dict
results["cost"] = cost
results["theta"] = theta_max
results["state"] = best_phi
return results
|
https://github.com/nmoran/qiskit-qdrift-quid19
|
nmoran
|
import numpy as np
import matplotlib.pyplot as plt
import math
from qiskit import Aer, IBMQ, QuantumRegister, QuantumCircuit
from qiskit.providers.ibmq import least_busy
from qiskit.providers.aer import noise
# lib from Qiskit Aqua
from qiskit.aqua.operators.common import evolution_instruction
from qiskit.aqua import Operator, QuantumInstance
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit.aqua.components.optimizers import COBYLA, SPSA, L_BFGS_B
from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ
# lib from Qiskit Aqua Chemistry
from qiskit.chemistry import QiskitChemistry
from qiskit.chemistry import FermionicOperator
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
driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
molecule = driver.run()
nuclear_repulsion_energy = molecule.nuclear_repulsion_energy
num_particles = molecule.num_alpha + molecule.num_beta
num_spin_orbitals = molecule.num_orbitals * 2
h1 = molecule.one_body_integrals
h2 = molecule.two_body_integrals
ferOp = FermionicOperator(h1=h1, h2=h2)
map_type = 'bravyi_kitaev'
qubitOp = ferOp.mapping(map_type=map_type, threshold=10**-10)
qubitOp.chop(10**-10)
num_terms = len(qubitOp.paulis)
max_term = max([np.abs(qubitOp.paulis[i][0]) for i in range(num_terms)])
error=.01
norm = 0
probs = []
for i in range(len(qubitOp.paulis)):
norm += np.abs(qubitOp.paulis[i][0])
for i in range(len(qubitOp.paulis)):
probs.append(np.abs(qubitOp.paulis[i][0])/norm)
runs = 10
print('start of big loop')
times = np.linspace(.1,1,10)
qdrift_av_counts=[]
trotter_counts=[]
#iterate through the list of durations
for time_idx in range(len(times)):
qdrift_gate_counts = []
num_time_slices = math.ceil((num_terms*max_term*times[time_idx])**2 / 2*error)
#Iterate (runs) numbers of time to get average data
for run in range(runs):
random_pauli_list=[]
#the number of steps from the norm, time, and error
num_steps = math.ceil((2*norm*times[time_idx])**2 /error)
standard_timestep = times[time_idx]*norm/num_steps
for i in range(num_steps):
idx = np.random.choice(num_terms,p=probs)
#form the list keeping track of the sign of the coefficients
random_pauli_list.append([np.sign(qubitOp.paulis[idx][0])*standard_timestep,qubitOp.paulis[idx][1]])
instruction_qdrift=evolution_instruction(random_pauli_list, evo_time=1, num_time_slices=1, controlled=False, power=1, use_basis_gates=True, shallow_slicing=False)
print('completed {},{} qdrift evolution_instructions'.format(str(time_idx),str(run)))
quantum_registers_qdrift = QuantumRegister(qubitOp.num_qubits)
qc_qdrift = QuantumCircuit(quantum_registers_qdrift)
qc_qdrift.append(instruction_qdrift, quantum_registers_qdrift)
qc_qdrift = qc_qdrift.decompose()
total_qdrift = 0
try:
total_qdrift+=qc_qdrift.count_ops()['cx']
except:
pass
try:
total_qdrift+=qc_qdrift.count_ops()['u1']
except:
pass
try:
total_qdrift+=qc_qdrift.count_ops()['u2']
except:
pass
try:
total_qdrift+=qc_qdrift.count_ops()['u3']
except:
pass
qdrift_gate_counts.append(total_qdrift)
print('start of trotter evolution instruction')
instruction_trotter=evolution_instruction(qubitOp.paulis, evo_time=times[time_idx], num_time_slices=num_time_slices, controlled=False, power=1, use_basis_gates=True, shallow_slicing=False)
print('end of trotter evolution instruction - on to circuit construction')
quantum_registers_trotter = QuantumRegister(qubitOp.num_qubits)
qc_trotter = QuantumCircuit(quantum_registers_trotter)
qc_trotter.append(instruction_trotter, quantum_registers_trotter)
qc_trotter = qc_trotter.decompose()
total_trotter = 0
try:
total_trotter+=qc_trotter.count_ops()['cx']
except:
pass
try:
total_trotter+=qc_trotter.count_ops()['u1']
except:
pass
try:
total_trotter+=qc_trotter.count_ops()['u2']
except:
pass
try:
total_trotter+=qc_trotter.count_ops()['u3']
except:
pass
trotter_counts.append(total_trotter)
qdrift_av_counts.append(sum(qdrift_gate_counts)/len(qdrift_gate_counts))
print('got through {} iterations'.format(str(time_idx)))
plt.plot(times,qdrift_av_counts,label='qdrift_avg_counts')
plt.plot(times,trotter_counts,label = 'trotter_counts')
plt.title('Gates v Duration for Time Evol({})'.format(map_type))
plt.xlabel("Duration of evolution")
plt.ylabel("Number of Gates")
plt.legend(loc=0)
plt.yscale('log')
plt.savefig("H2_gates_v_time_{}.png".format(map_type), dpi=600)
|
https://github.com/qiskit-community/prototype-zne
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022-2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Type definitions for the Zero Noise Extrapolation (ZNE) Estimator class."""
from typing import Any, Dict, Sequence, Tuple, Union
from qiskit import QuantumCircuit
Metadata = Dict[str, Any]
EstimatorResultData = Dict[str, Union[float, Metadata]]
ParameterVector = Sequence[float] # TODO: qiskit.circuit::ParameterVector
CircuitKey = tuple
NoiseFactor = float
ZNECacheKey = Tuple[CircuitKey, NoiseFactor]
ZNECache = Dict[ZNECacheKey, QuantumCircuit]
|
https://github.com/apcarrik/qiskit-dev
|
apcarrik
|
from qiskit import QuantumCircuit
from qiskit.algorithms import AmplificationProblem
### Specify oracle for Grover's algorithm circuit
# the state we desire to find is '11'
good_state = ['11']
# specify the oracle that marks the state '11' as a good solution
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
# define Grover's algorithm
problem = AmplificationProblem(oracle, is_good_state=good_state)
# now we can have a look at the Grover operator aht is used in running the algorithm
problem.grover_operator.draw(output='mpl').show()
### Specify backend and call run method of Grover with backend to execute circuits
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit.algorithms import Grover
aer_simulator = Aer.get_backend('aer_simulator')
grover = Grover(quantum_instance=aer_simulator)
result = grover.amplify(problem)
print('Using QuantumCircuit as oracle')
print('Result type:', type(result))
print('Success!' if result.oracle_evaluation else 'Failure')
print(f'Top measurement: {result.top_measurement}')
### Using different types of classes as oracle for Grover's algorithm
# using statevector as oracle
from qiskit.quantum_info import Statevector
oracle = Statevector.from_label('11')
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(quantum_instance=aer_simulator)
result = grover.amplify(problem)
print('\nUsing Statevector as oracle')
print('Result type:', type(result))
print('Success!' if result.oracle_evaluation else 'Failure')
print(f'Top measurement: {result.top_measurement}')
problem.grover_operator.oracle.draw(output='mpl').show()
# using phase oracle
from qiskit.circuit.library.phase_oracle import PhaseOracle
from qiskit.exceptions import MissingOptionalLibraryError
# `Oracle` (`PhaseOracle`) as the `oracle` argument
expression = '(a & b)'
try:
oracle = PhaseOracle(expression)
problem = AmplificationProblem(oracle)
problem.grover_operator.oracle.draw(output='mpl').show()
except MissingOptionalLibraryError as ex:
print(ex)
### Amplitude Amplification
# specifying `state preparation` to prepare a superposition of |01>, |10>, and |11>
import numpy as np
oracle = QuantumCircuit(3)
oracle.h(2)
oracle.ccx(0,1,2)
oracle.h(2)
theta = 2 * np.arccos(1 / np.sqrt(3))
state_preparation = QuantumCircuit(3)
state_preparation.ry(theta, 0)
state_preparation.ch(0,1)
state_preparation.x(1)
state_preparation.h(2)
# we only care about the first two bits beign in state 1, thus add both possiblities for the last qubit
problem = AmplificationProblem(oracle, state_preparation=state_preparation,
is_good_state=['110','111'])
# state preperation
print('Printing state preperation circuit')
problem.grover_operator.state_preparation.draw(output='mpl').show()
# run circuit
grover = Grover(quantum_instance=aer_simulator)
result = grover.amplify(problem)
print('Success!' if result.oracle_evaluation else 'Failure :(')
print(f'Top measurement: {result.top_measurement}')
### Full Flexibility
# set good state as |111> but with 5 qubits
from qiskit.circuit.library import GroverOperator, ZGate
oracle = QuantumCircuit(5)
oracle.append(ZGate().control(2), [0,1,2])
oracle.draw(output='mpl').show()
# Grover operator implements zero reflection on all 5 qubits, as default
grover_op = GroverOperator(oracle, insert_barriers=True)
grover_op.draw(output='mpl').show()
# since we only need to consider first 3 qubits, set that as parameter to GroverOperator
grover_op = GroverOperator(oracle, reflection_qubits=[0,1,2], insert_barriers=True)
grover_op.draw(output='mpl').show()
### Specify good_state in different ways
# list of binary strings good state
oracle = QuantumCircuit(2)
oracle.cz(0,1)
good_state = ['11', '00']
problem = AmplificationProblem(oracle, is_good_state=good_state)
print('Binary strings good state')
print(f'State 11 is a good state: {problem.is_good_state("11")}')
# list of integers good state
oracle = QuantumCircuit(2)
oracle.cz(0,1)
good_state = [0, 1]
problem = AmplificationProblem(oracle, is_good_state=good_state)
print('Integer good state')
print(f'State 11 is a good state: {problem.is_good_state("11")}')
# `Statevector` good state
from qiskit.quantum_info import Statevector
oracle = QuantumCircuit(2)
oracle.cz(0,1)
good_state = Statevector.from_label('11')
problem = AmplificationProblem(oracle, is_good_state=good_state)
print('Statevector good state')
print(f'State 11 is a good state: {problem.is_good_state("11")}')
# Callable good state
def callable_good_state(bitstr):
if bitstr == '11':
return True
return False
oracle = QuantumCircuit(2)
oracle.cz(0,1)
problem = AmplificationProblem(oracle, is_good_state=callable_good_state)
print('Callable good state')
print(f'State 11 is a good state: {problem.is_good_state("11")}')
### Change number of iterations
# integer iteration
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=1)
# list iteration
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=[1,2,3])
# using sample_from_iterations
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=[1,2,3], sample_from_iterations=True)
# use optimal_num_iterations when number of solutions is known
iterations = Grover.optimal_num_iterations(num_solutions=1, num_qubits=8)
print(f'Optimal number of iterations: {iterations}')
### Apply post processing
# convert bit-representation of measurement to DIMACS CNF format
def to_DIMACS_CNF_format(bit_rep):
return [index+1 if val==1 else -1 * (index+1) for index, val in enumerate(bit_rep)]
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'],
post_processing = to_DIMACS_CNF_format)
print("DIMACS CNF format: ", problem.post_processing([1, 0, 1]))
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
"""A wrapper class for the purposes of validating modifications to
QuantumCircuit.data while maintaining the interface of a python list."""
from collections.abc import MutableSequence
import qiskit._accelerate.circuit
from .exceptions import CircuitError
from .instruction import Instruction
from .operation import Operation
CircuitInstruction = qiskit._accelerate.circuit.CircuitInstruction
class QuantumCircuitData(MutableSequence):
"""A wrapper class for the purposes of validating modifications to
QuantumCircuit.data while maintaining the interface of a python list."""
def __init__(self, circuit):
self._circuit = circuit
def __getitem__(self, i):
return self._circuit._data[i]
def __setitem__(self, key, value):
# For now (Terra 0.21), the `QuantumCircuit.data` setter is meant to perform validation, so
# we do the same qubit checks that `QuantumCircuit.append` would do.
if isinstance(value, CircuitInstruction):
operation, qargs, cargs = value.operation, value.qubits, value.clbits
else:
# Handle the legacy 3-tuple format.
operation, qargs, cargs = value
value = self._resolve_legacy_value(operation, qargs, cargs)
self._circuit._data[key] = value
if isinstance(value.operation, Instruction):
self._circuit._update_parameter_table(value.operation)
def _resolve_legacy_value(self, operation, qargs, cargs) -> CircuitInstruction:
"""Resolve the old-style 3-tuple into the new :class:`CircuitInstruction` type."""
if not isinstance(operation, Operation) and hasattr(operation, "to_instruction"):
operation = operation.to_instruction()
if not isinstance(operation, Operation):
raise CircuitError("object is not an Operation.")
expanded_qargs = [self._circuit.qbit_argument_conversion(qarg) for qarg in qargs or []]
expanded_cargs = [self._circuit.cbit_argument_conversion(carg) for carg in cargs or []]
if isinstance(operation, Instruction):
broadcast_args = list(operation.broadcast_arguments(expanded_qargs, expanded_cargs))
else:
broadcast_args = list(
Instruction.broadcast_arguments(operation, expanded_qargs, expanded_cargs)
)
if len(broadcast_args) > 1:
raise CircuitError(
"QuantumCircuit.data modification does not support argument broadcasting."
)
qargs, cargs = broadcast_args[0]
self._circuit._check_dups(qargs)
return CircuitInstruction(operation, tuple(qargs), tuple(cargs))
def insert(self, index, value):
self._circuit._data.insert(index, CircuitInstruction(None, (), ()))
try:
self[index] = value
except CircuitError:
del self._circuit._data[index]
raise
def __iter__(self):
return iter(self._circuit._data)
def __delitem__(self, i):
del self._circuit._data[i]
def __len__(self):
return len(self._circuit._data)
def __cast(self, other):
return list(other._circuit._data) if isinstance(other, QuantumCircuitData) else other
def __repr__(self):
return repr(list(self._circuit._data))
def __lt__(self, other):
return list(self._circuit._data) < self.__cast(other)
def __le__(self, other):
return list(self._circuit._data) <= self.__cast(other)
def __eq__(self, other):
return self._circuit._data == self.__cast(other)
def __gt__(self, other):
return list(self._circuit._data) > self.__cast(other)
def __ge__(self, other):
return list(self._circuit._data) >= self.__cast(other)
def __add__(self, other):
return list(self._circuit._data) + self.__cast(other)
def __radd__(self, other):
return self.__cast(other) + list(self._circuit._data)
def __mul__(self, n):
return list(self._circuit._data) * n
def __rmul__(self, n):
return n * list(self._circuit._data)
def sort(self, *args, **kwargs):
"""In-place stable sort. Accepts arguments of list.sort."""
data = list(self._circuit._data)
data.sort(*args, **kwargs)
self._circuit._data.clear()
self._circuit._data.reserve(len(data))
self._circuit._data.extend(data)
def copy(self):
"""Returns a shallow copy of instruction list."""
return list(self._circuit._data)
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
from qiskit import *
import matplotlib.pyplot as plt
from channel_class import Channel
#Bob Part
circ_bob = QuantumCircuit(3)
#circ_bob.h(0)
#circ_bob.draw(output='mpl','test.png')
bob_channel = Channel(myport = 5001, remote_port = 5000)
circ_bob, offset = bob_channel.receive(circ_bob)#,to_tpc)
# Add new gates to circ2
circ_bob.cx(-1+offset,0+offset)
circ_bob.cz(-2+offset,0+offset)
circ_bob.rx(-0.1,0 + offset)
circ_bob.ry(-0.94,0 + offset)
circ_bob.rz(-0.54,0 + offset)
circ_bob.rx(-0.234,0 + offset)
circ_bob.draw(output='mpl',filename='teleport_bob.png')
#check the teleported state:
from qiskit import Aer
backend = Aer.get_backend('statevector_simulator')
job = execute(circ_bob,backend)
result = job.result()
outputstate = result.get_statevector(circ_bob,decimals=3)
print(outputstate)
meas = QuantumCircuit(3,1)
meas.barrier(range(3))
meas.measure([2],range(1))
qc = circ_bob + meas
#channel.send(qc)
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc,backend_sim,shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print(counts)
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
from qiskit import *
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua
from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector
from qiskit.quantum_info import Statevector
from qiskit.extensions import *
provider = IBMQ.load_account()
from qiskit.quantum_info import random_unitary
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
from math import pi, sqrt
from qiskit.circuit import Parameter
from random import seed
from random import random
import cmath
#circuit 1
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(8):
theta.append((Parameter('θ'+str(i))))
for i in range(4):
qc.rx(theta[i],qr[i])
for i in range(4):
qc.rz(theta[i+4],qr[i])
qc.draw('mpl')
#circuit 2
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(8):
theta.append((Parameter('θ'+str(i))))
for i in range(4):
qc.rx(theta[i],qr[i])
for i in range(4):
qc.rz(theta[i+4],qr[i])
qc.cx(qr[3],qr[2])
qc.cx(qr[2],qr[1])
qc.cx(qr[1],qr[0])
qc.draw('mpl')
#circuit 3
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(11):
theta.append((Parameter('θ'+str(i))))
for i in range(4):
qc.rx(theta[i],qr[i])
for i in range(4):
qc.rz(theta[i+4],qr[i])
qc.crz(theta[8],qr[3],qr[2])
qc.crz(theta[9],qr[2],qr[1])
qc.crz(theta[10],qr[1],qr[0])
qc.draw('mpl')
#circuit 4
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(11):
theta.append((Parameter('θ'+str(i))))
for i in range(4):
qc.rx(theta[i],qr[i])
for i in range(4):
qc.rz(theta[i+4],qr[i])
qc.crx(theta[8],qr[3],qr[2])
qc.crx(theta[9],qr[2],qr[1])
qc.crx(theta[10],qr[1],qr[0])
qc.draw('mpl')
#circuit 5
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
for j in range(4):
for i in range(4):
if i!=j:
qc.crz(theta[count],qr[3-j],qr[3-i])
count=count+1
qc.barrier(qr)
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.draw('mpl')
#circuit 6
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
for j in range(4):
for i in range(4):
if i!=j:
qc.crx(theta[count],qr[3-j],qr[3-i])
count=count+1
qc.barrier(qr)
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.draw('mpl')
#circuit 7
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.barrier(qr)
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crz(theta[count],qr[2],qr[1])
qc.draw('mpl')
#circuit 8
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.barrier(qr)
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crx(theta[count],qr[2],qr[1])
qc.draw('mpl')
#circuit 9
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.h(qr[i])
qc.barrier(qr)
qc.cz(qr[3],qr[2])
qc.cz(qr[2],qr[1])
qc.cz(qr[1],qr[0])
qc.barrier(qr)
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
qc.draw('mpl')
#circuit 10
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.cz(qr[3],qr[2])
qc.cz(qr[2],qr[1])
qc.cz(qr[1],qr[0])
qc.cz(qr[3],qr[0])
qc.barrier(qr)
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.draw('mpl')
#circuit 11
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.cx(qr[1],qr[0])
qc.cx(qr[3],qr[2])
qc.barrier(qr)
qc.ry(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.rz(theta[count],qr[2])
qc.cx(qr[2],qr[1])
qc.draw('mpl')
#circuit 12
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.cz(qr[1],qr[0])
qc.cz(qr[3],qr[2])
qc.barrier(qr)
qc.ry(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.rz(theta[count],qr[2])
qc.cz(qr[2],qr[1])
qc.draw('mpl')
#circuit 13
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crz(theta[count],qr[3],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[1])
count=count+1
qc.barrier(qr)
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
qc.draw('mpl')
#circuit 14
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crx(theta[count],qr[3],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[1])
count=count+1
qc.barrier(qr)
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
qc.draw('mpl')
#circuit 15
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.cx(qr[3],qr[0])
count=count+1
qc.cx(qr[2],qr[3])
count=count+1
qc.cx(qr[1],qr[2])
count=count+1
qc.cx(qr[0],qr[1])
count=count+1
qc.barrier(qr)
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.cx(qr[3],qr[2])
count=count+1
qc.cx(qr[0],qr[3])
count=count+1
qc.cx(qr[1],qr[0])
count=count+1
qc.cx(qr[2],qr[1])
qc.draw('mpl')
#circuit 16
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
qc.draw('mpl')
#circuit 17
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
qc.draw('mpl')
#circuit 18
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crz(theta[count],qr[3],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[1])
qc.draw('mpl')
#circuit 19
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crx(theta[count],qr[3],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[1])
qc.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can set a color for all the bars.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import *
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error
def get_noise(p):
error_meas = pauli_error([('X',p), ('I', 1 - p)])
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error_meas, "measure") # measurement error is applied to measurements
return noise_model
noise_model = get_noise(0.01)
for state in ['00','01','10','11']:
qc = QuantumCircuit(2,2)
if state[0]=='1':
qc.x(1)
if state[1]=='1':
qc.x(0)
qc.measure(qc.qregs[0],qc.cregs[0])
print(state+' becomes',
execute(qc,Aer.get_backend('qasm_simulator'),noise_model=noise_model,shots=10000).result().get_counts())
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.measure(qc.qregs[0],qc.cregs[0])
print(execute(qc,Aer.get_backend('qasm_simulator'),noise_model=noise_model,shots=10000).result().get_counts())
import numpy as np
M = [[0.9808,0.0107,0.0095,0.0001],
[0.0095,0.9788,0.0001,0.0107],
[0.0096,0.0002,0.9814,0.0087],
[0.0001,0.0103,0.0090,0.9805]]
Cideal = [[0],
[5000],
[5000],
[0]]
Cnoisy = np.dot( M, Cideal)
print('C_noisy =\n',Cnoisy)
import scipy.linalg as la
M = [[0.9808,0.0107,0.0095,0.0001],
[0.0095,0.9788,0.0001,0.0107],
[0.0096,0.0002,0.9814,0.0087],
[0.0001,0.0103,0.0090,0.9805]]
Minv = la.pinv(M)
print(Minv)
Cmitigated = np.dot( Minv, Cnoisy)
print('C_mitigated =\n',Cmitigated)
from qiskit.ignis.mitigation.measurement import (complete_meas_cal,CompleteMeasFitter)
qr = qiskit.QuantumRegister(2)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
for circuit in meas_calibs:
print('Circuit',circuit.name)
print(circuit)
print()
# Execute the calibration circuits without noise
backend = qiskit.Aer.get_backend('qasm_simulator')
job = qiskit.execute(meas_calibs, backend=backend, shots=1000)
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
noise_model = get_noise(0.1)
backend = qiskit.Aer.get_backend('qasm_simulator')
job = qiskit.execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model)
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.measure(qc.qregs[0],qc.cregs[0])
results = qiskit.execute(qc, backend=backend, shots=10000, noise_model=noise_model).result()
noisy_counts = results.get_counts()
print(noisy_counts)
# Get the filter object
meas_filter = meas_fitter.filter
# Results with mitigation
mitigated_results = meas_filter.apply(results)
mitigated_counts = mitigated_results.get_counts(0)
from qiskit.tools.visualization import *
plot_histogram([noisy_counts, mitigated_counts], legend=['noisy', 'mitigated'])
|
https://github.com/tigerjack/qiskit_grover
|
tigerjack
|
from qiskit import IBMQ
import sys
def get_job_status(backend, job_id):
backend = IBMQ.get_backend(backend)
print("Backend {0} is operational? {1}".format(
backend.name(),
backend.status()['operational']))
print("Backend was last updated in {0}".format(
backend.properties()['last_update_date']))
print("Backend has {0} pending jobs".format(
backend.status()['pending_jobs']))
ibmq_job = backend.retrieve_job(job_id)
status = ibmq_job.status()
print(status.name)
print(ibmq_job.creation_date())
if (status.name == 'DONE'):
print("EUREKA")
result = ibmq_job.result()
count = result.get_counts()
print("Result is: {0}".format())
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
else:
print("... Work in progress ...")
print("Queue position = {0}".format(ibmq_job.queue_position()))
print("Error message = {0}".format(ibmq_job.error_message()))
IBMQ.load_accounts()
print("Account(s) loaded")
if (len(sys.argv) > 2):
get_job_status(sys.argv[1], sys.argv[2])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0)
plot_circuit_layout(new_circ_lv0, backend)
|
https://github.com/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/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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 commutation checker class ."""
import unittest
import numpy as np
from qiskit import ClassicalRegister
from qiskit.test import QiskitTestCase
from qiskit.circuit import QuantumRegister, Parameter, Qubit
from qiskit.circuit import CommutationChecker
from qiskit.circuit.library import (
ZGate,
XGate,
CXGate,
CCXGate,
MCXGate,
RZGate,
Measure,
Barrier,
Reset,
LinearFunction,
)
class TestCommutationChecker(QiskitTestCase):
"""Test CommutationChecker class."""
def test_simple_gates(self):
"""Check simple commutation relations between gates, experimenting with
different orders of gates, different orders of qubits, different sets of
qubits over which gates are defined, and so on."""
comm_checker = CommutationChecker()
# should commute
res = comm_checker.commute(ZGate(), [0], [], CXGate(), [0, 1], [])
self.assertTrue(res)
# should not commute
res = comm_checker.commute(ZGate(), [1], [], CXGate(), [0, 1], [])
self.assertFalse(res)
# should not commute
res = comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], [])
self.assertFalse(res)
# should commute
res = comm_checker.commute(XGate(), [1], [], CXGate(), [0, 1], [])
self.assertTrue(res)
# should not commute
res = comm_checker.commute(XGate(), [1], [], CXGate(), [1, 0], [])
self.assertFalse(res)
# should commute
res = comm_checker.commute(XGate(), [0], [], CXGate(), [1, 0], [])
self.assertTrue(res)
# should commute
res = comm_checker.commute(CXGate(), [1, 0], [], XGate(), [0], [])
self.assertTrue(res)
# should not commute
res = comm_checker.commute(CXGate(), [1, 0], [], XGate(), [1], [])
self.assertFalse(res)
# should commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[1, 0],
[],
)
self.assertTrue(res)
# should not commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[0, 1],
[],
)
self.assertFalse(res)
# should commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[1, 2],
[],
)
self.assertTrue(res)
# should not commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[2, 1],
[],
)
self.assertFalse(res)
# should commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[2, 3],
[],
)
self.assertTrue(res)
res = comm_checker.commute(XGate(), [2], [], CCXGate(), [0, 1, 2], [])
self.assertTrue(res)
res = comm_checker.commute(CCXGate(), [0, 1, 2], [], CCXGate(), [0, 2, 1], [])
self.assertFalse(res)
def test_passing_quantum_registers(self):
"""Check that passing QuantumRegisters works correctly."""
comm_checker = CommutationChecker()
qr = QuantumRegister(4)
# should commute
res = comm_checker.commute(CXGate(), [qr[1], qr[0]], [], CXGate(), [qr[1], qr[2]], [])
self.assertTrue(res)
# should not commute
res = comm_checker.commute(CXGate(), [qr[0], qr[1]], [], CXGate(), [qr[1], qr[2]], [])
self.assertFalse(res)
def test_caching_positive_results(self):
"""Check that hashing positive results in commutativity checker works as expected."""
comm_checker = CommutationChecker()
res = comm_checker.commute(ZGate(), [0], [], CXGate(), [0, 1], [])
self.assertTrue(res)
self.assertGreater(len(comm_checker.cache), 0)
def test_caching_negative_results(self):
"""Check that hashing negative results in commutativity checker works as expected."""
comm_checker = CommutationChecker()
res = comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], [])
self.assertFalse(res)
self.assertGreater(len(comm_checker.cache), 0)
def test_caching_different_qubit_sets(self):
"""Check that hashing same commutativity results over different qubit sets works as expected."""
comm_checker = CommutationChecker()
# All the following should be cached in the same way
# though each relation gets cached twice: (A, B) and (B, A)
comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], [])
comm_checker.commute(XGate(), [10], [], CXGate(), [10, 20], [])
comm_checker.commute(XGate(), [10], [], CXGate(), [10, 5], [])
comm_checker.commute(XGate(), [5], [], CXGate(), [5, 7], [])
self.assertEqual(len(comm_checker.cache), 2)
def test_gates_with_parameters(self):
"""Check commutativity between (non-parameterized) gates with parameters."""
comm_checker = CommutationChecker()
res = comm_checker.commute(RZGate(0), [0], [], XGate(), [0], [])
self.assertTrue(res)
res = comm_checker.commute(RZGate(np.pi / 2), [0], [], XGate(), [0], [])
self.assertFalse(res)
res = comm_checker.commute(RZGate(np.pi / 2), [0], [], RZGate(0), [0], [])
self.assertTrue(res)
def test_parameterized_gates(self):
"""Check commutativity between parameterized gates, both with free and with
bound parameters."""
comm_checker = CommutationChecker()
# gate that has parameters but is not considered parameterized
rz_gate = RZGate(np.pi / 2)
self.assertEqual(len(rz_gate.params), 1)
self.assertFalse(rz_gate.is_parameterized())
# gate that has parameters and is considered parameterized
rz_gate_theta = RZGate(Parameter("Theta"))
rz_gate_phi = RZGate(Parameter("Phi"))
self.assertEqual(len(rz_gate_theta.params), 1)
self.assertTrue(rz_gate_theta.is_parameterized())
# gate that has no parameters and is not considered parameterized
cx_gate = CXGate()
self.assertEqual(len(cx_gate.params), 0)
self.assertFalse(cx_gate.is_parameterized())
# We should detect that these gates commute
res = comm_checker.commute(rz_gate, [0], [], cx_gate, [0, 1], [])
self.assertTrue(res)
# We should detect that these gates commute
res = comm_checker.commute(rz_gate, [0], [], rz_gate, [0], [])
self.assertTrue(res)
# We should detect that parameterized gates over disjoint qubit subsets commute
res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate_theta, [1], [])
self.assertTrue(res)
# We should detect that parameterized gates over disjoint qubit subsets commute
res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate_phi, [1], [])
self.assertTrue(res)
# We should detect that parameterized gates over disjoint qubit subsets commute
res = comm_checker.commute(rz_gate_theta, [2], [], cx_gate, [1, 3], [])
self.assertTrue(res)
# However, for now commutativity checker should return False when checking
# commutativity between a parameterized gate and some other gate, when
# the two gates are over intersecting qubit subsets.
# This check should be changed if commutativity checker is extended to
# handle parameterized gates better.
res = comm_checker.commute(rz_gate_theta, [0], [], cx_gate, [0, 1], [])
self.assertFalse(res)
res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate, [0], [])
self.assertFalse(res)
def test_measure(self):
"""Check commutativity involving measures."""
comm_checker = CommutationChecker()
# Measure is over qubit 0, while gate is over a disjoint subset of qubits
# We should be able to swap these.
res = comm_checker.commute(Measure(), [0], [0], CXGate(), [1, 2], [])
self.assertTrue(res)
# Measure and gate have intersecting set of qubits
# We should not be able to swap these.
res = comm_checker.commute(Measure(), [0], [0], CXGate(), [0, 2], [])
self.assertFalse(res)
# Measures over different qubits and clbits
res = comm_checker.commute(Measure(), [0], [0], Measure(), [1], [1])
self.assertTrue(res)
# Measures over different qubits but same classical bit
# We should not be able to swap these.
res = comm_checker.commute(Measure(), [0], [0], Measure(), [1], [0])
self.assertFalse(res)
# Measures over same qubits but different classical bit
# ToDo: can we swap these?
# Currently checker takes the safe approach and returns False.
res = comm_checker.commute(Measure(), [0], [0], Measure(), [0], [1])
self.assertFalse(res)
def test_barrier(self):
"""Check commutativity involving barriers."""
comm_checker = CommutationChecker()
# A gate should not commute with a barrier
# (at least if these are over intersecting qubit sets).
res = comm_checker.commute(Barrier(4), [0, 1, 2, 3], [], CXGate(), [1, 2], [])
self.assertFalse(res)
# Does it even make sense to have a barrier over a subset of qubits?
# Though in this case, it probably makes sense to say that barrier and gate can be swapped.
res = comm_checker.commute(Barrier(4), [0, 1, 2, 3], [], CXGate(), [5, 6], [])
self.assertTrue(res)
def test_reset(self):
"""Check commutativity involving resets."""
comm_checker = CommutationChecker()
# A gate should not commute with reset when the qubits intersect.
res = comm_checker.commute(Reset(), [0], [], CXGate(), [0, 2], [])
self.assertFalse(res)
# A gate should commute with reset when the qubits are disjoint.
res = comm_checker.commute(Reset(), [0], [], CXGate(), [1, 2], [])
self.assertTrue(res)
def test_conditional_gates(self):
"""Check commutativity involving conditional gates."""
comm_checker = CommutationChecker()
qr = QuantumRegister(3)
cr = ClassicalRegister(2)
# Currently, in all cases commutativity checker should returns False.
# This is definitely suboptimal.
res = comm_checker.commute(
CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], XGate(), [qr[2]], []
)
self.assertFalse(res)
res = comm_checker.commute(
CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], XGate(), [qr[1]], []
)
self.assertFalse(res)
res = comm_checker.commute(
CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], CXGate().c_if(cr[0], 0), [qr[0], qr[1]], []
)
self.assertFalse(res)
res = comm_checker.commute(
XGate().c_if(cr[0], 0), [qr[0]], [], XGate().c_if(cr[0], 1), [qr[0]], []
)
self.assertFalse(res)
res = comm_checker.commute(XGate().c_if(cr[0], 0), [qr[0]], [], XGate(), [qr[0]], [])
self.assertFalse(res)
def test_complex_gates(self):
"""Check commutativity involving more complex gates."""
comm_checker = CommutationChecker()
lf1 = LinearFunction([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
lf2 = LinearFunction([[1, 0, 0], [0, 0, 1], [0, 1, 0]])
# lf1 is equivalent to swap(0, 1), and lf2 to swap(1, 2).
# These do not commute.
res = comm_checker.commute(lf1, [0, 1, 2], [], lf2, [0, 1, 2], [])
self.assertFalse(res)
lf3 = LinearFunction([[0, 1, 0], [0, 0, 1], [1, 0, 0]])
lf4 = LinearFunction([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
# lf3 is permutation 1->2, 2->3, 3->1.
# lf3 is the inverse permutation 1->3, 2->1, 3->2.
# These commute.
res = comm_checker.commute(lf3, [0, 1, 2], [], lf4, [0, 1, 2], [])
self.assertTrue(res)
def test_c7x_gate(self):
"""Test wide gate works correctly."""
qargs = [Qubit() for _ in [None] * 8]
res = CommutationChecker().commute(XGate(), qargs[:1], [], XGate().control(7), qargs, [])
self.assertFalse(res)
def test_wide_gates_over_nondisjoint_qubits(self):
"""Test that checking wide gates does not lead to memory problems."""
res = CommutationChecker().commute(MCXGate(29), list(range(30)), [], XGate(), [0], [])
self.assertFalse(res)
res = CommutationChecker().commute(XGate(), [0], [], MCXGate(29), list(range(30)), [])
self.assertFalse(res)
def test_wide_gates_over_disjoint_qubits(self):
"""Test that wide gates still commute when they are over disjoint sets of qubits."""
res = CommutationChecker().commute(MCXGate(29), list(range(30)), [], XGate(), [30], [])
self.assertTrue(res)
res = CommutationChecker().commute(XGate(), [30], [], MCXGate(29), list(range(30)), [])
self.assertTrue(res)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qwqmlf/qwgc
|
qwqmlf
|
import numpy as np
import random
import matplotlib.pyplot as plt
from numpy import pi
from tqdm import tqdm, trange
from sklearn.model_selection import KFold
from grakel import datasets
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from sklearn import svm
from preprocess.qwfilter import QWfilter
try:
from utils.notification import Notify
notify = True
except Exception:
notify = False
step = 3
THETA_MIN, THETA_MAX = -pi, pi
iteration = 200
backend = Aer.get_backend('qasm_simulator')
shots = 1024
'''
This is just very prototype code
'''
def qw_kernel(train_data, train_label, lam=2):
'''
Input:
train_data: 2dim array (a series of training data)
train_label: 2dim array (a series of label, one hot)
Output:
theta: array
coin_param: ?
'''
ld = len(train_data)
# start training
# to check convergence of error, prepare this list
weights = np.zeros(ld)
print('training start!')
for i in trange(iteration):
it = random.randint(0, ld-1)
decision = 0
for j in range(it):
# FIXME ambiguous error message
try:
decision += weights[j] * train_label[it] * _kernel_function(train_data[it], train_data[j], 7)
except ValueError:
continue
decision *= train_label[it]/lam
if decision < 1:
weights[it] += 1
return weights
def test(x_train, y_train, x_test, y_test, weights):
print('test start!')
errors = 0
for ila, lb_test in tqdm(enumerate(y_test)):
decision = 0
for ilb, lb_train in enumerate(y_train):
decision += weights[ilb]*y_train[ilb]*_kernel_function(x_train[ilb], x_test[ila], 7)
if decision < 0:
prediction = -1
else:
prediction = 1
if prediction != y_test[ila]:
errors += 1
return 1 - errors/len(y_test)
def _kernel_function(x, y, qsize):
# definition of coin
coin_u3s = np.array([pi, 0, pi/2])
ampdata_x = QWfilter(coin_u3s, step, 'super').single_amplitude(x)
x_amp = _zero_fill(ampdata_x, 2**qsize)
q1 = QuantumRegister(qsize)
qc1 = QuantumCircuit(q1, name='QW1')
qc1.initialize(x_amp, q1)
qw1 = qc1.to_instruction()
ampdata_y = QWfilter(coin_u3s, step, 'super').single_amplitude(y)
y_amp = _zero_fill(ampdata_y, 2**qsize)
q2 = QuantumRegister(qsize)
qc2 = QuantumCircuit(q2)
qc2.initialize(y_amp, q2)
qw2 = qc2.to_instruction()
kq = QuantumRegister(qsize)
c = ClassicalRegister(qsize)
kqc = QuantumCircuit(kq, c)
kqc.append(qw1, qargs=kq)
kqc.append(qw2, qargs=kq)
kqc.measure(kq, c)
# calc prob '000...0'
job = execute(kqc, backend=backend, shots=shots)
count = job.result().get_counts(kqc)
return count.get('0'*qsize, 0)/shots
def ceilog(x):
return int(np.ceil(np.log2(x)))
def _zero_fill(x, base, array=True):
# FIXME efficiently
xl = list(x)
x_len = len(xl)
if base - x_len < 0:
raise ValueError('Error')
xs = xl + [0 for _ in range(base-x_len)]
if array:
return np.array(xs)
else:
return xs
if __name__ == '__main__':
data_name = 'MUTAG'
Data = datasets.fetch_dataset(data_name, verbose=False)
data_x, data_y = np.array(Data.data), np.array(Data.target)
k = 5
kf = KFold(n_splits=k, shuffle=True)
accuracy = []
for train_index, test_index in kf.split(data_x):
# preprocessing for generating data.
x_train, y_train = data_x[train_index], data_y[train_index]
x_test, y_test = data_x[test_index], data_y[test_index]
weight = qw_kernel(x_train, y_train)
accs = test(x_train, y_train, x_test, y_test, weight)
print(accs)
if notify:
Notify.notify_accs(accs, 'svm')
accuracy.append(accs)
Notify.notify_accs(accuracy, 'K5 result')
Notify.notify_accs(np.mean(accuracy), 'K5 result mean')
print(accuracy)
print(np.mean(accuracy))
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.quantumcircuitdata import CircuitInstruction
from qiskit.circuit import Measure
from qiskit.circuit.library import HGate, CXGate
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
instructions = [
CircuitInstruction(HGate(), [qr[0]], []),
CircuitInstruction(CXGate(), [qr[0], qr[1]], []),
CircuitInstruction(Measure(), [qr[0]], [cr[0]]),
CircuitInstruction(Measure(), [qr[1]], [cr[1]]),
]
circuit = QuantumCircuit.from_instructions(instructions)
circuit.draw("mpl")
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
QmlStateCircuitBuilder
==============================
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state._QmlStateCircuitBuilder
This is the abstract base class to implement a custom state circuit builder which takes the classification
training data samples and labels and one to be classified sample and outputs the circuit that creates the necessary
quantum state than then can be used to apply the :py:class:`QmlHadamardNeighborClassifier`.
.. autosummary::
:nosignatures:
QmlStateCircuitBuilder
QmlStateCircuitBuilder
##############################
.. autoclass:: QmlStateCircuitBuilder
:members:
"""
import abc
from typing import List
from qiskit import QuantumCircuit
from scipy import sparse
class QmlStateCircuitBuilder(object):
"""
Interface class for creating a quantum circuit from a sparse quantum state vector.
"""
@abc.abstractmethod
def build_circuit(self, circuit_name, X_train, y_train, X_input):
# type: (QmlStateCircuitBuilder, str, List[sparse.dok_matrix], any, sparse.dok_matrix) -> QuantumCircuit
"""
Build a circuit that encodes the training (samples/labels) and input data sets into a quantum circuit
:param circuit_name: The name of the quantum circuit
:param X_train: The training data set
:param y_train: the training class label data set
:param X_input: the unclassified input data vector
:return: The circuit containing the gates to encode the input data
"""
pass
@abc.abstractmethod
def is_classifier_branch(self, branch_value):
# type: (QmlStateCircuitBuilder, int) -> bool
"""
As each state preparation algorithm uses a unique layout. The classifier has the correct classification
probabilities only on the correct branch of the ancilla qubit. However each state preparation may have
different methods making it necessary to query specific logic to assess what value must be given after the
branch qubit measurement.
:param branch_value: The measurement of the branch
:return: True is the branch is containing the classification, False if not
"""
pass
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# 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("./")
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="lq")
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"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors)
print("created zne_qcs (length:", len(zne_qcs), ")")
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-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
jobs.append(job)
# QREM
shots = 1 << 13
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
cal_results = 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 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/suvoooo/Qubits-Qiskit
|
suvoooo
|
# # install and import qiskit
# !pip3 install qiskit
import qiskit as q
import matplotlib.pyplot as plt
from qiskit import IBMQ
IBMQ.save_account('putyourtoken')
IBMQ.load_account()
qr = q.QuantumRegister(2)
cr = q.ClassicalRegister(2)
circuit = q.QuantumCircuit(qr, cr)
circuit.draw()
# apply the Hadamard gate on 0th qubit
circuit.h(qr[0])
circuit.draw(output='mpl')
# now we apply the cnot gate
# as explained before the control qubit should be in superposition state
circuit.cx(qr[0], qr[1])
circuit.draw(output='mpl')
circuit.measure(qr, cr) # measure quantum bit into classical bit
circuit.draw(output='mpl')
# let's simulate the results on a local computer
simulator = q.Aer.get_backend('qasm_simulator') # qasm : quantum assembly lang.
results = q.execute(circuit, backend=simulator).result() # execute the circuit based on the simulator as backend
q.visualization.plot_histogram(results.get_counts(circuit))
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmq_london') # check which computer has 0 jobs on queue
job = q.execute(circuit, backend=qcomp)
q_result = job.result()
q.visualization.plot_histogram(q_result.get_counts(circuit))
|
https://github.com/epelaaez/QuantumLibrary
|
epelaaez
|
from qiskit import QuantumCircuit, execute, Aer
from qiskit.opflow import One, Zero, Plus, Minus
from qiskit.opflow import I, X, Y, Z, S, H
from qiskit.visualization import plot_bloch_multivector, plot_bloch_vector, plot_histogram
from math import pi, sqrt, acos, asin, e, log, sin, cos
from numpy import angle
Zero
One
Plus
Minus
1.5 * Zero
-3 * Plus
Zero^Zero^One
Plus^Minus^Zero^Zero
Zero + One
Plus + Minus
(Zero^Zero^One) + (Zero^One^Zero) + (One^Zero^Zero)
(Zero^Zero^One) - 1.5*(Zero^One^Zero) + 3*(One^Zero^Zero)
def arbitrary_state(beta):
##### ==================================
# Write your solution in here.
##### ==================================
Zero.eval('0')
Zero.eval('1')
Minus.eval('0')
Minus.eval('1')
~Zero
~One
~Plus
print("< 0 | 0 > =",(~Zero @ Zero).eval())
print("< 1 | 0 > =",(~One @ Zero).eval())
beta = 0.232 + 0.341j
arbitrary_state(beta)
beta = 0.232 + 0.341j
print("< 1 | Ψ > =",(~One @ arbitrary_state(beta)).eval())
print("< 0 | Ψ > =",(~Zero @ arbitrary_state(beta)).eval())
print("< Ψ | Ψ > =", (~arbitrary_state(beta) @ arbitrary_state(beta)).eval())
def normality_check(beta):
##### ==================================
# Write your solution in here.
##### ==================================
# Play with your beta parameter to see if this value changes.
beta = 0.232 + 0.341j
print("|< 1 | Ψ >|^2 + |< 0 | Ψ >|^2 =", normality_check(beta))
def convert_braket_to_Bloch(beta):
if beta == 0: # special case
return [1.0, 0, 0]
##### ==================================
# Write your solution in here.
##### ==================================
return [1.0, theta, phi]
# Check
beta = -1/sqrt(2)*1j
plot_bloch_vector(convert_braket_to_Bloch(beta), coord_type='spherical',
title=r"$|\psi\rangle = \frac{1}{\sqrt{2}}|0\rangle-\frac{1}{\sqrt{2}}i|0\rangle$")
# Play with more values of beta to see if it matches with your expectation
beta = -1/sqrt(10)*1j
plot_bloch_vector(convert_braket_to_Bloch(beta), coord_type='spherical',
title=r"$|\psi\rangle = \sqrt{1-|\beta|^2}|0\rangle+\beta|0\rangle$ in Spherical")
X
Y
Z
def expectation_Z(beta):
##### ==================================
# Write your solution in here. There are more than one solution here...
##### ==================================
print("<Z> =", expectation_Z(beta))
def expectation_X(beta):
##### ==================================
# Write your solution in here. There are more than one solution here...
##### ==================================
def expectation_Y(beta):
##### ==================================
# Write your solution in here. There are more than one solution here...
##### ==================================
def get_cartesian_coordinate(beta):
##### ==================================
# Write your solution in here. There are more than one solution here...
##### ==================================
return [x, y, z]
# Play with more values of beta to see if it matches with your previous Bloch sphere
beta = -1/sqrt(10)*1j
plot_bloch_vector(get_cartesian_coordinate(beta), coord_type='cartesian',
title=r"$|\psi\rangle = \sqrt{1-|\beta|^2}|0\rangle+\beta|0\rangle$ in Cartesian")
# Let's define the quantum simulator
sv_simulator = Aer.get_backend("statevector_simulator")
qasm_simulator = Aer.get_backend("qasm_simulator")
this_circ = QuantumCircuit(1)
this_circ.initialize([1/sqrt(2), -1/sqrt(2)])
this_circ.measure_all()
this_circ.draw('mpl')
shots = 1024
counts = execute(this_circ, backend=qasm_simulator, shots=shots).result().get_counts()
print(counts)
plot_histogram(counts, title=r"Measuring the $|+\rangle$ state")
def contruct_arbitrary_state_on_circuit(beta):
##### ==================================
# Write your solution in here. Here you do not need to append the measurement part in this function
##### ==================================
return circuit
shots = 81920
beta = 0.213
this_circuit = contruct_arbitrary_state_on_circuit(beta)
this_circuit.measure_all()
counts = execute(this_circuit, backend=qasm_simulator, shots=shots).result().get_counts()
print("Probability in |1> basis =", beta**2)
plot_histogram(counts, title=r"Measuring the arbitrary $|\psi(\beta)\rangle$ state")
def expectation_Z_with_QASM(beta, shots):
##### ==================================
# Write your solution in here. Here
##### ==================================
return expectation
beta = -1/sqrt(2)*1j
shots = 81920
print("Expectation <Z> with QASM =", expectation_Z_with_QASM(beta, shots=shots))
print("Expectation <Z> with opflow =", expectation_Z(beta))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/matteoacrossi/oqs-jupyterbook
|
matteoacrossi
|
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource, Slider, CustomJS, Text, DataRange1d, Title
from bokeh.plotting import Figure, show, output_file
from bokeh.io import output_notebook
from amplitude_damping import *
R_values = np.geomspace(start=0.2, stop=500.0, num=100)
R_values_str = [str(i) for i in range(len(R_values))]
R_values_str_R = ['R = {:.2f}'.format(R) for R in R_values] # truncate to two decimals
# make a dictionary of form {'0': 0.0, '1': 0.2, .. }
R_values_dict = {R_values_str[i]:R_values.round(2)[i] for i,_ in enumerate(R_values)} # rounding to two decimals
initial_r = R_values_str[len(R_values)//2]
npoints = 400
ts_cap = np.linspace(0,1.1,200)
ys_cap = {R: np.array([Qa(c1(R_values_dict[R],t)**2) for t in ts_cap]) for R in R_values_str}
rs_cap = {R_values_str[i] : [R_values_str_R[i]] for i,_ in enumerate(R_values)}
# Wrap the data in two ColumnDataSources
#source_visible = ColumnDataSource(data=dict(
# x = ts, y = ys[initial_r]))
#source_available = ColumnDataSource(data=ys)
source_visible = ColumnDataSource(data=dict(
x = ts_cap, y = ys_cap[initial_r]))
source_available = ColumnDataSource(data=ys_cap)
# Define plot elements
plot = Figure(plot_width=400, plot_height=400, x_range = DataRange1d(), y_range=(-.01, 1.01))
plot.line('x', 'y', source=source_visible, legend_label="Q(Φ(t))", line_width=3, line_alpha=0.6)
# Add text
text_source = ColumnDataSource({'r_value': [rs_cap[initial_r]]})
r_available = ColumnDataSource(data=rs_cap)
text = Text(x=0, x_offset=315, y=.8, text='r_value', text_font_size='15pt', text_align='right')
plot.add_glyph(text_source, text)
# Add slider
slider = Slider(value=int(initial_r),
start=np.min([int(i) for i in ys_cap.keys()]),
end=np.max([int(i) for i in ys_cap.keys()]),
step=1,
show_value = False,
title = 'R')
# Define CustomJS callback, which updates the plot based on selected function
# by updating the source_visible ColumnDataSource.
slider.callback = CustomJS(
args=dict(source_visible=source_visible,
source_available=source_available,
text_source = text_source,
r_available = r_available), code="""
var r_idx = cb_obj.value;
// Get the data from the data sources
var data_visible = source_visible.data;
var data_available = source_available.data;
// Change y-axis data according to the selected value
data_visible.y = data_available[r_idx];
// text
text_source.data = {'r_value': [String(r_available.data[r_idx])]};
// Update the plot
source_visible.change.emit();
""")
layout = column(plot,slider)
output_file("channel_cap.html", title="Channel Capacity")
output_notebook()
show(layout)
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
QmlBinaryDataStateCircuitBuilder
=======================================
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state._QmlBinaryDataStateCircuitBuilder
.. autosummary::
:nosignatures:
QmlBinaryDataStateCircuitBuilder
QmlBinaryDataStateCircuitBuilder
#########################################
.. autoclass:: QmlBinaryDataStateCircuitBuilder
:members:
"""
import logging
from math import sqrt
from typing import List
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.dagcircuit import DAGNode
from scipy import sparse
from . import QmlStateCircuitBuilder
from .cnot import CCXFactory
log = logging.getLogger('QubitEncodingClassifierStateCircuit')
class QmlBinaryDataStateCircuitBuilder(QmlStateCircuitBuilder):
"""
From binary training and testing data creates the quantum state vector and applies a quantum algorithm to create a circuit.
"""
def __init__(self, ccx_factory, do_optimizations = True):
# type: (QmlBinaryDataStateCircuitBuilder, CCXFactory, bool) -> None
"""
Creates the uniform amplitude state circuit builder
:param ccx_factory: The multiple-controlled X-gate factory to be used
"""
self.do_optimizations = do_optimizations
self.ccx_factory = ccx_factory # type:CCXFactory
def build_circuit(self, circuit_name, X_train, y_train, X_input):
# type: (QmlBinaryDataStateCircuitBuilder, str, List[sparse.dok_matrix], any, sparse.dok_matrix) -> QuantumCircuit
"""
Build a circuit that encodes the training (samples/labels) and input data sets into a quantum circuit.
Sample data must be given as a binary (sparse) vector, i.e. each vector's entry must be either 0.0 or 1.0.
It may also be given already normed to unit length instead of binary.
:param circuit_name: The name of the quantum circuit
:param X_train: The training data set
:param y_train: the training class label data set
:param X_input: the unclassified input data vector
:return: The circuit containing the gates to encode the input data
"""
log.debug("Preparing state.")
log.debug("Raw Input Vector: %s" % X_input)
# map the training samples and test input to unit length
def normalizer(x):
# type: (sparse.dok_matrix) -> sparse.dok_matrix
norm = sqrt(sum([abs(e)**2 for e in x.values()]))
for k in x.keys():
x[k] = x[k]/norm
return x
X_train = [normalizer(x) for x in X_train]
X_input = normalizer(X_input)
# Calculate dimensions and qubit usage
count_of_samples, sample_space_dimension = len(X_train), max([s.get_shape()[0] for s in X_train + [X_input]])
count_of_distinct_classes = len(set(y_train))
index_of_samples_qubits_needed = (count_of_samples - 1).bit_length()
sample_space_dimensions_qubits_needed = (sample_space_dimension - 1).bit_length()
ancilla_qubits_needed = 1
label_qubits_needed = (count_of_distinct_classes - 1).bit_length() if count_of_distinct_classes > 1 else 1
log.info("Qubit map: index=%d, ancillary=%d, feature=%d, label=%d", index_of_samples_qubits_needed,
ancilla_qubits_needed, sample_space_dimensions_qubits_needed, label_qubits_needed)
# Create Registers
ancilla = QuantumRegister(ancilla_qubits_needed, "a")
index = QuantumRegister(index_of_samples_qubits_needed, "i")
data = QuantumRegister(sample_space_dimensions_qubits_needed, "f^S")
qlabel = QuantumRegister(label_qubits_needed, "l^q")
clabel = ClassicalRegister(label_qubits_needed, "l^c")
branch = ClassicalRegister(1, "b")
# Create the Circuit
qc = QuantumCircuit(ancilla, index, data, qlabel, clabel, branch, name=circuit_name)
# ======================
# Build the circuit now
# ======================
# Superposition on ancilla & index
qc.h(ancilla)
qc.h(index)
# Create multi-CNOTs
# First on the sample, then the input and finally the label
ancilla_and_index_regs = [ancilla[i] for i in range(ancilla.size)] + [index[i] for i in range(index.size)]
for index_sample, (sample, label) in enumerate(zip(X_train, y_train)):
cnot_type_sample = (index_sample << 1) + 0
cnot_type_input = (index_sample << 1) + 1
# The sample will be encoded
for basis_vector_index, _ in sample.keys():
bit_string = "{:b}".format(basis_vector_index)
for i, v in enumerate(reversed(bit_string)):
if v == "1":
self.ccx_factory.ccx(qc,
cnot_type_sample,
ancilla_and_index_regs,
data[i])
# Label will be encoded
bit_string = "{:b}".format(label)
for i, v in enumerate(reversed(bit_string)):
if v == "1":
self.ccx_factory.ccx(qc,
cnot_type_sample,
ancilla_and_index_regs,
qlabel[i])
# The input will be encoded
for basis_vector_index, _ in X_input.keys():
bit_string = "{:b}".format(basis_vector_index)
for i, v in enumerate(reversed(bit_string)):
if v == "1":
self.ccx_factory.ccx(qc, cnot_type_input, ancilla_and_index_regs, data[i])
# Label will be encoded
bit_string = "{:b}".format(label)
for i, v in enumerate(reversed(bit_string)):
if v == "1":
self.ccx_factory.ccx(qc, cnot_type_input, ancilla_and_index_regs, qlabel[i])
stop = False
while not stop and self.do_optimizations:
dag = circuit_to_dag(qc)
dag.remove_all_ops_named("barrier")
gates = dag.named_nodes("ccx", "cx", "x") # type: List[DAGNode]
removable_nodes = []
for ccx_gate in gates:
successor = list(dag.successors(ccx_gate)) # type: List[DAGNode]
if len(successor) == 1:
if successor[0].name == ccx_gate.name:
removable_nodes.append(successor[0])
removable_nodes.append(ccx_gate)
print(end='')
for n in removable_nodes:
dag.remove_op_node(n)
if len(removable_nodes) > 0:
qc = dag_to_circuit(dag)
else:
stop = True
return qc
def is_classifier_branch(self, branch_value):
# type: (QmlBinaryDataStateCircuitBuilder, int) -> bool
"""
The branch of quantum state bearing the classification is defined to be 0.
This functions checks this.
:param branch_value: The measurement of the branch
:return: True is the measured branch is 0, False if not
"""
return branch_value == 0
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# If you introduce a list with less colors than bars, the color of the bars will
# alternate following the sequence from the list.
import numpy as np
from qiskit.quantum_info import DensityMatrix
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_paulivec
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)
matrix = DensityMatrix(qc)
plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
|
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
|
vandnaChaturvedi
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex
from qiskit.extensions import Initialize
from qiskit.ignis.verification import marginal_counts
from qiskit.quantum_info import random_statevector
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
## SETUP
# Protocol uses 3 qubits and 2 classical bits in 2 different registers
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical bits
crx = ClassicalRegister(1, name="crx") # in 2 different registers
teleportation_circuit = QuantumCircuit(qr, crz, crx)
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a,b)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, psi, a):
qc.cx(psi, a)
qc.h(psi)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
"""Measures qubits a & b and 'sends' the results to Bob"""
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
measure_and_send(teleportation_circuit, 0 ,1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1) # Apply gates if the registers
qc.z(qubit).c_if(crz, 1) # are in the state '1'
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
## STEP 3
measure_and_send(teleportation_circuit, 0, 1)
## STEP 4
teleportation_circuit.barrier() # Use barrier to separate steps
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
# Create random 1-qubit state
psi = random_statevector(2)
# Display it nicely
display(array_to_latex(psi, prefix="|\\psi\\rangle ="))
# Show it on a Bloch sphere
plot_bloch_multivector(psi)
init_gate = Initialize(psi)
init_gate.label = "init"
## SETUP
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical registers
crx = ClassicalRegister(1, name="crx")
qc = QuantumCircuit(qr, crz, crx)
## STEP 0
# First, let's initialize Alice's q0
qc.append(init_gate, [0])
qc.barrier()
## STEP 1
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
## STEP 2
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
## STEP 3
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
## STEP 4
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
# Display the circuit
qc.draw()
sim = Aer.get_backend('aer_simulator')
qc.save_statevector()
out_vector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(out_vector)
|
https://github.com/hkhetawat/QArithmetic
|
hkhetawat
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, Aer
from QArithmetic import add
# Registers and circuit.
a = QuantumRegister(4)
b = QuantumRegister(5)
ca = ClassicalRegister(4)
cb = ClassicalRegister(5)
qc = QuantumCircuit(a, b, ca, cb)
# Numbers to add.
qc.x(a[1]) # a = 01110
qc.x(a[2])
qc.x(a[3])
qc.x(b[0]) # b = 01011
qc.x(b[1])
qc.x(b[3])
# Add the numbers, so |a>|b> to |a>|a+b>.
add(qc, a, b, 4)
# Measure the results.
qc.measure(a, ca)
qc.measure(b, cb)
# Simulate the circuit.
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
from QArithmetic import sub
# Registers and circuit.
a = QuantumRegister(5)
b = QuantumRegister(5)
ca = ClassicalRegister(5)
cb = ClassicalRegister(5)
qc = QuantumCircuit(a, b, ca, cb)
# Numbers to subtract.
qc.x(a[1]) # a = 01110
qc.x(a[2])
qc.x(a[3])
qc.x(b[0]) # b = 01011
qc.x(b[1])
qc.x(b[3])
# Add the numbers, so |a>|b> to |a>|a-b>.
sub(qc, a, b, 5)
# Measure the results.
qc.measure(a, ca)
qc.measure(b, cb)
# Simulate the circuit.
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
from QArithmetic import mult
# Registers and circuit.
a = QuantumRegister(2)
b = QuantumRegister(2)
m = QuantumRegister(4)
cm = ClassicalRegister(4)
qc = QuantumCircuit(a, b, m, cm)
# Numbers to multiply.
qc.x(a[1]) # a = 10 = 2
qc.x(b[0]) # b = 11 = 3
qc.x(b[1])
# Multiply the numbers, so |a>|b>|m=0> to |a>|b>|a*b>.
mult(qc, a, b, m, 2)
# Measure the result.
qc.measure(m, cm)
# Simulate the circuit.
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
from QArithmetic import div
# Registers and circuit.
a = QuantumRegister(4)
b = QuantumRegister(4)
c = QuantumRegister(2)
ca = ClassicalRegister(4)
cb = ClassicalRegister(4)
cc = ClassicalRegister(2)
qc = QuantumCircuit(a,b,c,ca,cb,cc)
# Inputs.
qc.x(a[0]) # a = 0011
qc.x(a[1])
qc.x(b[3]) # b = 1000
# Divide a by b.
div(qc, a, b, c, 2)
# Measure.
qc.measure(a, ca)
qc.measure(b, cb)
qc.measure(c, cc)
# Simulate the circuit.
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
from QArithmetic import power
from qiskit.providers.aer import QasmSimulator
# Registers and circuit
a = QuantumRegister(2)
b = QuantumRegister(2)
m = QuantumRegister(6)
ca = ClassicalRegister(2)
cb = ClassicalRegister(2)
cm = ClassicalRegister(6)
qc = QuantumCircuit(a, b, m, ca, cb, cm)
# Inputs.
qc.x(a[1]) # a = 10
qc.x(b[1]) # b = 10
# Raise a to the b power.
power(qc, a, b, m)
# Measure.
qc.measure(a, ca)
qc.measure(b, cb)
qc.measure(m, cm)
#Simulate the circuit.
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
from QArithmetic import bitwise_and
# Registers and circuit.
a = QuantumRegister(4)
b = QuantumRegister(4)
c = QuantumRegister(4)
ca = ClassicalRegister(4)
cb = ClassicalRegister(4)
cc = ClassicalRegister(4)
qc = QuantumCircuit(a, b, c, ca, cb, cc)
# Inputs
qc.x(a[1]) # a =1010
qc.x(a[3])
qc.x(b[0]) # b = 1011
qc.x(b[1])
qc.x(b[3])
# Take the bitwise AND.
bitwise_and(qc, a, b, c, 4)
# Measure.
qc.measure(a, ca)
qc.measure(b, cb)
qc.measure(c, cc)
# Simulate the circuit.
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
from QArithmetic import bitwise_or
# Registers and circuit.
a = QuantumRegister(4)
b = QuantumRegister(4)
c = QuantumRegister(4)
ca = ClassicalRegister(4)
cb = ClassicalRegister(4)
cc = ClassicalRegister(4)
qc = QuantumCircuit(a, b, c, ca, cb, cc)
# Input.
qc.x(a[1]) # a = 1010
qc.x(a[3])
qc.x(b[0]) # b = 1011
qc.x(b[1])
qc.x(b[3])
# Take the bitwise OR.
bitwise_or(qc, a, b, c, 4)
# Measure.
qc.measure(a, ca)
qc.measure(b, cb)
qc.measure(c, cc)
# Simulate the circuit.
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
from QArithmetic import bitwise_xor
# Registers and circuit.
a = QuantumRegister(4)
b = QuantumRegister(4)
c = QuantumRegister(4)
ca = ClassicalRegister(4)
cb = ClassicalRegister(4)
cc = ClassicalRegister(4)
qc = QuantumCircuit(a, b, c, ca, cb, cc)
# Input.
qc.x(a[1]) # a = 1010
qc.x(a[3])
qc.x(b[0]) # b = 1011
qc.x(b[1])
qc.x(b[3])
# Take the bitwise XOR.
bitwise_xor(qc, a, b, c, 4)
# Measure.
qc.measure(a, ca)
qc.measure(b, cb)
qc.measure(c, cc)
# Simulate the circuit.
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
from QArithmetic import bitwise_not
# Registers and circuit.
a = QuantumRegister(4)
b = QuantumRegister(4)
ca = ClassicalRegister(4)
cb = ClassicalRegister(4)
qc = QuantumCircuit(a, b, ca, cb)
# Input.
qc.x(a[1]) # a = 1010
qc.x(a[3])
# Take the bitwise NOT.
bitwise_not(qc, a, b, 4)
# Measure.
qc.measure(a, ca)
qc.measure(b, cb)
# Simulate the circuit.
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a DensityMatrix
state = DensityMatrix(qc)
plot_state_city(state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
dc = pulse.DriveChannel
d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4)
with pulse.build(name='pulse_programming_in') as pulse_prog:
pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3)
pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4)
pulse_prog.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/snow0369/qiskit_tutorial_2021_summerschool
|
snow0369
|
!pip install -r requirements.txt
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
secret_number = '101001'
# here work is happen like buttom to up
for position,value in enumerate(reversed(secret_number)):
if value == '1':
print(position, value)
circuit = QuantumCircuit(6+1, 6)
circuit.h([0,1,2,3,4,5])
circuit.x(6)
circuit.h(6)
circuit.barrier()
circuit.draw(output='mpl')
circuit.cx(5, 6)
circuit.cx(3, 6)
circuit.cx(0, 6)
circuit.barrier()
circuit.draw(output='mpl')
circuit.h([0,1,2,3,4,5])
circuit.draw(output='mpl')
circuit.barrier()
circuit.measure([i for i in range(5)],[i for i in range(5)])
circuit.barrier()
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator, shots=1)
result = job.result()
counts = result.get_counts()
print(counts)
circuit = QuantumCircuit(len(secret_number)+1, len(secret_number))
circuit.h(range(len(secret_number)))
circuit.x(len(secret_number))
circuit.h(len(secret_number))
circuit.barrier()
for position,value in enumerate(reversed(secret_number)):
if value == '1':
circuit.cx(position, len(secret_number))
circuit.barrier()
circuit.h(range(len(secret_number)))
circuit.barrier()
circuit.measure(range(len(secret_number)), range(len(secret_number)))
circuit.barrier()
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator, shots=1)
result = job.result()
counts = result.get_counts()
print(counts)
def find_secret_number(secter_number):
secret_number = str(secter_number)
# Using Bernstein Vazirani Algorithm
circuit = QuantumCircuit(len(secret_number)+1, len(secret_number))
circuit.h(range(len(secret_number)))
circuit.x(len(secret_number))
circuit.h(len(secret_number))
circuit.barrier()
for position,value in enumerate(reversed(secret_number)):
if value == '1':
circuit.cx(position, len(secret_number))
circuit.barrier()
circuit.h(range(len(secret_number)))
circuit.barrier()
circuit.measure(range(len(secret_number)), range(len(secret_number)))
circuit.barrier()
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator, shots=1)
result = job.result()
counts = result.get_counts()
print(counts)
secret_number = int(input("enter number(digits should be 0 or 1): "))
find_secret_number(secret_number)
|
https://github.com/lancecarter03/QiskitLearning
|
lancecarter03
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers.aer import QasmSimulator
from qiskit.visualization import plot_histogram
circuit = QuantumCircuit(2,2)
#Applies Hadamard gate to qubit 0
circuit.h(0)
#Entangles qubit 0 to 1
circuit.cx(0,1)
#When passing entire quantum and classical registers, Ith qubit
#measurement result stored in Ith classical bit
circuit.measure([0,1],[0,1])
circuit.draw()
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.basicaer import QasmSimulatorPy
simulator = QasmSimulator()
compiled_circuit = transpile(circuit,simulator)
job = simulator.run(compiled_circuit,shots=1000)
result = job.result()
counts = result.get_counts(circuit)
print("\nTotal count for 00 and 11 are:",counts)
plot_histogram(counts)
|
https://github.com/abhik-99/Qiskit-Summer-School
|
abhik-99
|
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
excited = Statevector.from_int(1, 2)
plot_bloch_multivector(excited.data)
from qiskit.tools.jupyter import *
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibmq_armonk')
backend_config = backend.configuration()
assert backend_config.open_pulse, "Backend doesn't support Pulse"
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
backend_defaults = backend.defaults()
import numpy as np
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
# We will find the qubit frequency for the following qubit.
qubit = 0
# The Rabi sweep will be at the given qubit frequency.
center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz
# warning: this will change in a future release
print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.")
from qiskit import pulse, assemble # This is where we access all of our Pulse features!
from qiskit.pulse import Play
from qiskit.pulse import pulse_lib # This Pulse module helps us build sampled pulses for common pulse shapes
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure', qubits=[0])
# Rabi experiment parameters
# Drive amplitude values to iterate over: 50 amplitudes evenly spaced from 0 to 0.75
num_rabi_points = 50
drive_amp_min = 0
drive_amp_max = 0.75
drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points)
# drive waveforms mush be in units of 16
drive_sigma = 80 # in dt
drive_samples = 8*drive_sigma # in dt
# Build the Rabi experiments:
# A drive pulse at the qubit frequency, followed by a measurement,
# where we vary the drive amplitude each time.
rabi_schedules = []
for drive_amp in drive_amps:
rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp,
sigma=drive_sigma, name=f"Rabi drive amplitude = {drive_amp}")
this_schedule = pulse.Schedule(name=f"Rabi drive amplitude = {drive_amp}")
this_schedule += Play(rabi_pulse, drive_chan)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
this_schedule += measure << this_schedule.duration
rabi_schedules.append(this_schedule)
rabi_schedules[-1].draw(label=True, scaling=1.0)
# assemble the schedules into a Qobj
num_shots_per_point = 1024
rabi_experiment_program = assemble(rabi_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_point,
schedule_los=[{drive_chan: center_frequency_Hz}]
* num_rabi_points)
# RUN the job on a real device
#job = backend.run(rabi_experiment_program)
#print(job.job_id())
#from qiskit.tools.monitor import job_monitor
#job_monitor(job)
# OR retreive result from previous run
job = backend.retrieve_job("5ef3bf17dc3044001186c011")
rabi_results = job.result()
import matplotlib.pyplot as plt
plt.style.use('dark_background')
scale_factor = 1e-14
# center data around 0
def baseline_remove(values):
return np.array(values) - np.mean(values)
rabi_values = []
for i in range(num_rabi_points):
# Get the results for `qubit` from the ith experiment
rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor)
rabi_values = np.real(baseline_remove(rabi_values))
plt.xlabel("Drive amp [a.u.]")
plt.ylabel("Measured signal [a.u.]")
plt.scatter(drive_amps, rabi_values, color='white') # plot real part of Rabi values
plt.show()
from scipy.optimize import curve_fit
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
fit_params, y_fit = fit_function(drive_amps,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B),
[10, 0.1, 0.6, 0])
plt.scatter(drive_amps, rabi_values, color='white')
plt.plot(drive_amps, y_fit, color='red')
drive_period = fit_params[2] # get period of rabi oscillation
plt.axvline(drive_period/2, color='red', linestyle='--')
plt.axvline(drive_period, color='red', linestyle='--')
plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red'))
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
pi_amp = abs(drive_period / 2)
print(f"Pi Amplitude = {pi_amp}")
# Drive parameters
# The drive amplitude for pi/2 is simply half the amplitude of the pi pulse
drive_amp = pi_amp / 2
# x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees
x90_pulse = pulse_lib.gaussian(duration=drive_samples,
amp=drive_amp,
sigma=drive_sigma,
name='x90_pulse')
# Ramsey experiment parameters
time_max_us = 1.8
time_step_us = 0.025
times_us = np.arange(0.1, time_max_us, time_step_us)
# Convert to units of dt
delay_times_dt = times_us * us / dt
# create schedules for Ramsey experiment
ramsey_schedules = []
for delay in delay_times_dt:
this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us")
this_schedule += Play(x90_pulse, drive_chan)
this_schedule += Play(x90_pulse, drive_chan) << this_schedule.duration + int(delay)
this_schedule += measure << this_schedule.duration
ramsey_schedules.append(this_schedule)
ramsey_schedules[-1].draw(label=True, scaling=1.0)
# Execution settings
num_shots = 256
detuning_MHz = 2
ramsey_frequency = round(center_frequency_Hz + detuning_MHz * MHz, 6) # need ramsey freq in Hz
ramsey_program = assemble(ramsey_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots,
schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules)
)
# RUN the job on a real device
#job = backend.run(ramsey_experiment_program)
#print(job.job_id())
#from qiskit.tools.monitor import job_monitor
#job_monitor(job)
# OR retreive job from previous run
job = backend.retrieve_job('5ef3ed3a84b1b70012374317')
ramsey_results = job.result()
ramsey_values = []
for i in range(len(times_us)):
ramsey_values.append(ramsey_results.get_memory(i)[qubit]*scale_factor)
fit_params, y_fit = fit_function(times_us, np.real(ramsey_values),
lambda x, A, del_f_MHz, C, B: (
A * np.cos(2*np.pi*del_f_MHz*x - C) + B
),
[5, 1./0.4, 0, 0.25]
)
# Off-resonance component
_, del_f_MHz, _, _, = fit_params # freq is MHz since times in us
plt.scatter(times_us, np.real(ramsey_values), color='white')
plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz")
plt.xlim(0, np.max(times_us))
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Ramsey Experiment', fontsize=15)
plt.legend()
plt.show()
|
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
|
SaashaJoshi
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
# our backend is the Pulse Simulator
from resources import helper
from qiskit.providers.aer import PulseSimulator
backend_sim = PulseSimulator()
# sample duration for pulse instructions
dt = 1e-9
# create the model
duffing_model = helper.get_transmon(dt)
# get qubit frequency from Duffing model
qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift()
import numpy as np
# visualization tools
import matplotlib.pyplot as plt
plt.style.use('dark_background')
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
kHz = 1.0e3 # kilohertz
us = 1.0e-6 # microseconds
ns = 1.0e-9 # nanoseconds
from qiskit import pulse
from qiskit.pulse import Play, Acquire
from qiskit.pulse.pulse_lib import GaussianSquare
# qubit to be used throughout the notebook
qubit = 0
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Construct a measurement schedule and add it to an InstructionScheduleMap
meas_samples = 1200
meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150)
measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit))
inst_map = pulse.InstructionScheduleMap()
inst_map.add('measure', [qubit], measure_sched)
# save the measurement/acquire pulse for later
measure = inst_map.get('measure', qubits=[qubit])
from qiskit.pulse import pulse_lib
# the same spect pulse used in every schedule
drive_amp = 0.9
drive_sigma = 16
drive_duration = 128
spec_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp,
sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}")
# Construct an np array of the frequencies for our experiment
spec_freqs_GHz = np.arange(5.0, 5.2, 0.005)
# Create the base schedule
# Start with drive pulse acting on the drive channel
spec_schedules = []
for freq in spec_freqs_GHz:
sb_spec_pulse = helper.apply_sideband(spec_pulse, qubit_lo_freq[0]-freq*GHz, dt)
spec_schedule = pulse.Schedule(name='SB Frequency = {}'.format(freq))
spec_schedule += Play(sb_spec_pulse, drive_chan)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
spec_schedule += measure << spec_schedule.duration
spec_schedules.append(spec_schedule)
spec_schedules[0].draw()
from qiskit import assemble
# assemble the schedules into a Qobj
spec01_qobj = assemble(**helper.get_params('spec01', globals()))
# run the simulation
spec01_result = backend_sim.run(spec01_qobj, duffing_model).result()
# retrieve the data from the experiment
spec01_values = helper.get_values_from_result(spec01_result, qubit)
fit_params, y_fit = helper.fit_lorentzian(spec_freqs_GHz, spec01_values, [5, 5, 1, 0])
f01 = fit_params[1]
plt.scatter(spec_freqs_GHz, np.real(spec01_values), color='white') # plot real part of sweep values
plt.plot(spec_freqs_GHz, y_fit, color='red')
plt.xlim([min(spec_freqs_GHz), max(spec_freqs_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
print("01 Spectroscopy yields %f GHz"%f01)
x180_amp = 0.629070 #from lab 6 Rabi experiment
x_pulse = pulse_lib.gaussian(duration=drive_duration,
amp=x180_amp,
sigma=drive_sigma,
name='x_pulse')
anharmonicity_guess_GHz = -0.3
def build_spec12_pulse_schedule(freq):
sb12_spec_pulse = helper.apply_sideband(spec_pulse, (freq + anharmonicity_guess_GHz)*GHz, dt)
### create a 12 spectroscopy pulse schedule spec12_schedule (already done)
### play an x pulse on the drive channel
### play sidebanded spec pulse on the drive channel
### add measurement pulse to schedule
spec12_schedule = pulse.Schedule()
### WRITE YOUR CODE BETWEEN THESE LINES - START
spec12_schedule += Play(x_pulse, drive_chan)
spec12_schedule += Play(sb12_spec_pulse, drive_chan)
spec12_schedule += measure << spec12_schedule.duration
### WRITE YOUR CODE BETWEEN THESE LINES - STOP
return spec12_schedule
sb_freqs_GHz = np.arange(-.1, .1, 0.005) # sweep +/- 100 MHz around guess
# now vary the sideband frequency for each spec pulse
spec_schedules = []
for freq in sb_freqs_GHz:
spec_schedules.append(build_spec12_pulse_schedule(freq))
spec_schedules[0].draw()
# assemble the schedules into a Qobj
spec12_qobj = assemble(**helper.get_params('spec12', globals()))
answer1 = spec12_qobj
# run the simulation
spec12_result = backend_sim.run(spec12_qobj, duffing_model).result()
# retrieve the data from the experiment
spec12_values = helper.get_values_from_result(spec12_result, qubit)
anharm_offset = qubit_lo_freq[0]/GHz + anharmonicity_guess_GHz
fit_params, y_fit = helper.fit_lorentzian(anharm_offset + sb_freqs_GHz, spec12_values, [5, 4.5, .1, 3])
f12 = fit_params[1]
plt.scatter(anharm_offset + sb_freqs_GHz, np.real(spec12_values), color='white') # plot real part of sweep values
plt.plot(anharm_offset + sb_freqs_GHz, y_fit, color='red')
plt.xlim([anharm_offset + min(sb_freqs_GHz), anharm_offset + max(sb_freqs_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
print("12 Spectroscopy yields %f GHz"%f12)
print("Measured transmon anharmonicity is %f MHz"%((f12-f01)*GHz/MHz))
from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();'));
from grading_tools import send_code;send_code('ex1.ipynb')
|
https://github.com/pochangl/qiskit-experiment
|
pochangl
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Utils for using with Qiskit unit tests."""
import logging
import os
import unittest
from enum import Enum
from qiskit import __path__ as qiskit_path
class Path(Enum):
"""Helper with paths commonly used during the tests."""
# Main SDK path: qiskit/
SDK = qiskit_path[0]
# test.python path: qiskit/test/python/
TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python'))
# Examples path: examples/
EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples'))
# Schemas path: qiskit/schemas
SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas'))
# VCR cassettes path: qiskit/test/cassettes/
CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes'))
# Sample QASMs path: qiskit/test/python/qasm
QASMS = os.path.normpath(os.path.join(TEST, 'qasm'))
def setup_test_logging(logger, log_level, filename):
"""Set logging to file and stdout for a logger.
Args:
logger (Logger): logger object to be updated.
log_level (str): logging level.
filename (str): name of the output file.
"""
# Set up formatter.
log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
' %(message)s'.format(logger.name))
formatter = logging.Formatter(log_fmt)
# Set up the file handler.
file_handler = logging.FileHandler(filename)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Set the logging level from the environment variable, defaulting
# to INFO if it is not a valid level.
level = logging._nameToLevel.get(log_level, logging.INFO)
logger.setLevel(level)
class _AssertNoLogsContext(unittest.case._AssertLogsContext):
"""A context manager used to implement TestCase.assertNoLogs()."""
# pylint: disable=inconsistent-return-statements
def __exit__(self, exc_type, exc_value, tb):
"""
This is a modified version of TestCase._AssertLogsContext.__exit__(...)
"""
self.logger.handlers = self.old_handlers
self.logger.propagate = self.old_propagate
self.logger.setLevel(self.old_level)
if exc_type is not None:
# let unexpected exceptions pass through
return False
if self.watcher.records:
msg = 'logs of level {} or higher triggered on {}:\n'.format(
logging.getLevelName(self.level), self.logger.name)
for record in self.watcher.records:
msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname,
record.lineno,
record.getMessage())
self._raiseFailure(msg)
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
import qiskit
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
import json
import csv
# Gloabal _lambda variable
_LAMBDA = 10
_SHOTS = 10000
_UNIFORM_CONVERGENCE_SAMPLE = []
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def tsp_obj(x, G):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _LAMBDA)
cost = 0
# z term
for index in range(len(x)):
z = (int(x[index]) * 2 ) -1
cost += z_classic_term[index] * z
## zz term
for i in range(len(x)):
z_1 = (int(x[i]) * 2 ) -1
for j in range(len(x)):
z_2 = (int(x[j]) * 2 ) -1
cost += zz_classic_term[i][j] * z_1 * z_1
return cost
# Sample expectation value
def compute_tsp_energy(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj(meas, G)
energy += obj_for_meas*meas_count
total_counts += meas_count
return energy/total_counts
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, _LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_black_box_objective(G,p):
backend = Aer.get_backend('qasm_simulator')
def f(theta):
beta = theta[:p]
gamma = theta[p:]
_lambda = _LAMBDA # get global _lambda
qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
counts = execute(qc, backend, seed_simulator=10, shots=_SHOTS).result().get_counts()
return compute_tsp_energy(invert_counts(counts),G)
return f
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
def f(theta):
beta = theta[:p]
gamma = theta[p:]
#print(beta)
_lambda = _LAMBDA # get global _lambda
qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
#print(beta)
result = execute(qc, backend, seed_simulator=10, shots=_SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
# expected value
#print("prob-dict")
#print(state_vector.probabilities_dict())
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
# get cost from state
cost = tsp_obj_2(state, G, _LAMBDA)
expected_value += cost*probability
#print(probabilities)
counts = result.get_counts()
#qc.save_statevector() # Tell simulator to save statevector
#qobj = assemble(qc) # Create a Qobj from the circuit for the simulator to run
#state_vector = sim.run(qobj).result().get_statevector()
#state_vector = Statevector(state_vector)
#probabilities = state_vector.probabilities()
mean = compute_tsp_energy_2(invert_counts(counts),G)
global _UNIFORM_CONVERGENCE_SAMPLE
_UNIFORM_CONVERGENCE_SAMPLE.append({
"beta" : beta,
"gamma" : gamma,
"counts" : counts,
"mean" : mean,
"probabilities" : probabilities,
"expected_value" : expected_value
})
return mean
return f
def compute_tsp_min_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
min = 1000000000000000000000
index = 0
min_meas = ""
for meas, meas_count in counts.items():
index = index + 1
obj_for_meas = tsp_obj_2(meas, G, _LAMBDA)
if obj_for_meas < min:
min = obj_for_meas
min_meas = meas
return index, min, min_meas
def compute_tsp_min_energy_1(counts, G):
energy = 0
get_counts = 0
total_counts = 0
min = 1000000000000000000000
index = 0
min_meas = ""
for meas, meas_count in counts.items():
index = index + 1
obj_for_meas = tsp_obj(meas, G)
if obj_for_meas < min:
min = obj_for_meas
min_meas = meas
return index, min, min_meas
def test_counts_2(counts, G):
mean_energy2 = compute_tsp_energy_2(invert_counts(counts),G)
cantidad, min, min_meas = compute_tsp_min_energy_2(invert_counts(counts),G)
print("*************************")
print("En el algoritmo 2 (Marina) el valor esperado como resultado es " + str(mean_energy2))
print("El valor minimo de todos los evaluados es " + str(min) + " se evaluaron un total de " + str(cantidad))
print("El vector minimo es " + min_meas)
def test_counts_1(counts, G):
mean_energy1 = compute_tsp_energy(invert_counts(counts),G)
cantidad, min, min_meas = compute_tsp_min_energy_1(invert_counts(counts),G)
print("*************************")
print("En el algoritmo 1 (Pablo) el valor esperado como resultado es " + str(mean_energy1))
print("El valor minimo de todos los evaluados es " + str(min) + " se evaluaron un total de " + str(cantidad))
print("El vector minimo es " + min_meas)
def test_solution(grafo=None, p=7):
global _UNIFORM_CONVERGENCE_SAMPLE
_UNIFORM_CONVERGENCE_SAMPLE = []
if grafo == None:
cantidad_ciudades = 2
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
print(mejor_costo)
print(mejor_camino)
print(G.edges())
print(G.nodes())
else:
G = grafo
# beta [0,pi], gamma [0, 2pi]
# create bounds for beta [0,pi]
bounds = []
intial_random = []
for i in range(p):
bounds.append((0, np.pi))
intial_random.append(np.random.uniform(0,np.pi))
# create bounds for gamma [0,2*pi]
for i in range(p):
bounds.append((0, np.pi * 2))
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
# Pablo Solutions
#obj = get_black_box_objective(G,p)
#res_sample_1 = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
#print(res_sample_1)
# Marina Solutions
obj = get_black_box_objective_2(G,p)
res_sample_2 = minimize(obj, init_point, method="COBYLA", options={"maxiter":2500,"disp":True})
print(res_sample_2)
#theta_1 = res_sample_1.x
theta_2 = res_sample_2.x
#beta = theta_1[:p]
#gamma = theta_1[p:]
#_lambda = _LAMBDA # get global _lambda
#qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
#backend = Aer.get_backend('qasm_simulator')
#job_1 = execute(qc, backend, shots=_SHOTS)
#resutls_1 = job_1.result().get_counts()
#test_counts_1(resutls_1, G)
beta = theta_2[:p]
gamma = theta_2[p:]
_lambda = _LAMBDA # get global _lambda
qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
backend = Aer.get_backend('qasm_simulator')
job_2 = execute(qc, backend, shots=_SHOTS)
resutls_2 = job_2.result().get_counts()
test_counts_2(resutls_2, G)
#print( _UNIFORM_CONVERGENCE_SAMPLE)
return job_2, G, _UNIFORM_CONVERGENCE_SAMPLE
def create_multiple_p_mismo_grafo():
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
UNIFORM_CONVERGENCE_SAMPLE = []
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])
def create_multiple_p_mismo_grafo_multiples_instanncias():
header = ['instance','p','distance', 'mean']
length_p = 4
length_instances = 10
with open('qaoa_multiple_p_distance.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
instance_index = 0
for instance in range(length_instances):
instance_index += 1
first_p = False
UNIFORM_CONVERGENCE_P = []
UNIFORM_CONVERGENCE_SAMPLE = []
for p in range(length_p):
p = p+1
print("p es igual " + str(p))
if first_p == False:
print("Vuelve a llamar a test_solution")
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["expected_value"])
convergence_min = UNIFORM_CONVERGENCE_SAMPLE[0]
UNIFORM_CONVERGENCE_P.append({
"mean":convergence_min["expected_value"],
"probabilities": convergence_min["probabilities"]
})
print("expected value min con p =" + str(p) + " : " + str(convergence_min["expected_value"]))
cauchy_function_nk = UNIFORM_CONVERGENCE_P[len(UNIFORM_CONVERGENCE_P) - 1]
p_index = 0
for p_state in UNIFORM_CONVERGENCE_P:
p_index += 1
print(p_index)
mean = p_state["mean"]
#print(p_state)
print("expected value min")
print(mean)
distance_p_cauchy_function_nk = np.max(np.abs(cauchy_function_nk["probabilities"] - p_state["probabilities"]))
writer.writerow([instance_index, p_index, distance_p_cauchy_function_nk, mean])
if __name__ == '__main__':
#create_multiple_p_mismo_grafo()
create_multiple_p_mismo_grafo_multiples_instanncias()
def defult_init():
cantidad_ciudades = 2
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
print(mejor_costo)
print(mejor_camino)
print(G.edges())
print(G.nodes())
print("labels")
labels = nx.get_edge_attributes(G,'weight')
#z_term, zz_term = get_classical_simplified_hamiltonian(G, 1)
#print("z term")
#print(z_term)
#print("*****************")
#print("zz term")
#print(zz_term)
#print(get_QAOA_circuit(G, beta = [2,3], gamma = [4,5], _lambda = 1))
p = 5
obj = get_black_box_objective(G,p)
init_point = np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1])
#res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
#print(res_sample)
# Marina Solutions
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
theta_2 = [0.72685401, 2.15678239, 0.86389827, 2.19403121, 0.26916675, 2.19832144, 7.06651453, 3.20333137, 3.81301611, 6.08893568]
theta_1 = [0.90644898, 2.15994212, 1.8609325 , 2.14042604, 1.49126214, 2.4127999, 6.10529434, 2.18238732, 3.84056674, 6.07097744]
beta = theta_1[:p]
gamma = theta_1[p:]
_lambda = _LAMBDA # get global _lambda
qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend)
print(plot_histogram(job.result().get_counts(), color='midnightblue', title="New Histogram"))
beta = theta_2[:p]
gamma = theta_2[p:]
_lambda = _LAMBDA # get global _lambda
qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend)
print(plot_histogram(job.result().get_counts(), color='midnightblue', title="New Histogram"))
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Test QuantumCircuit.compose()."""
import unittest
import numpy as np
from qiskit import transpile
from qiskit.pulse import Schedule
from qiskit.circuit import (
QuantumRegister,
ClassicalRegister,
Clbit,
QuantumCircuit,
Qubit,
Parameter,
Gate,
Instruction,
CASE_DEFAULT,
SwitchCaseOp,
)
from qiskit.circuit.library import HGate, RZGate, CXGate, CCXGate, TwoLocal
from qiskit.circuit.classical import expr
from qiskit.test import QiskitTestCase
class TestCircuitCompose(QiskitTestCase):
"""Test composition of two circuits."""
def setUp(self):
super().setUp()
qreg1 = QuantumRegister(3, "lqr_1")
qreg2 = QuantumRegister(2, "lqr_2")
creg = ClassicalRegister(2, "lcr")
self.circuit_left = QuantumCircuit(qreg1, qreg2, creg)
self.circuit_left.h(qreg1[0])
self.circuit_left.x(qreg1[1])
self.circuit_left.p(0.1, qreg1[2])
self.circuit_left.cx(qreg2[0], qreg2[1])
self.left_qubit0 = qreg1[0]
self.left_qubit1 = qreg1[1]
self.left_qubit2 = qreg1[2]
self.left_qubit3 = qreg2[0]
self.left_qubit4 = qreg2[1]
self.left_clbit0 = creg[0]
self.left_clbit1 = creg[1]
self.condition = (creg, 3)
def test_compose_inorder(self):
"""Composing two circuits of the same width, default order.
┌───┐
lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■───────
├───┤ │ ┌───┐
lqr_1_1: |0>──┤ X ├─── rqr_1: |0>──┼──┤ X ├
┌─┴───┴──┐ │ ├───┤
lqr_1_2: |0>┤ P(0.1) ├ + rqr_2: |0>──┼──┤ Y ├ =
└────────┘ ┌─┴─┐└───┘
lqr_2_0: |0>────■───── rqr_3: |0>┤ X ├─────
┌─┴─┐ └───┘┌───┐
lqr_2_1: |0>──┤ X ├─── rqr_4: |0>─────┤ Z ├
└───┘ └───┘
lcr_0: 0 ═══════════
lcr_1: 0 ═══════════
┌───┐
lqr_1_0: |0>──┤ H ├─────■───────
├───┤ │ ┌───┐
lqr_1_1: |0>──┤ X ├─────┼──┤ X ├
┌─┴───┴──┐ │ ├───┤
lqr_1_2: |0>┤ P(0.1) ├──┼──┤ Y ├
└────────┘┌─┴─┐└───┘
lqr_2_0: |0>────■─────┤ X ├─────
┌─┴─┐ └───┘┌───┐
lqr_2_1: |0>──┤ X ├────────┤ Z ├
└───┘ └───┘
lcr_0: 0 ═══════════════════════
lcr_1: 0 ═══════════════════════
"""
qreg = QuantumRegister(5, "rqr")
circuit_right = QuantumCircuit(qreg)
circuit_right.cx(qreg[0], qreg[3])
circuit_right.x(qreg[1])
circuit_right.y(qreg[2])
circuit_right.z(qreg[4])
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit0, self.left_qubit3)
circuit_expected.x(self.left_qubit1)
circuit_expected.y(self.left_qubit2)
circuit_expected.z(self.left_qubit4)
circuit_composed = self.circuit_left.compose(circuit_right, inplace=False)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_inorder_unusual_types(self):
"""Test that composition works in order, using Numpy integer types as well as regular
integer types. In general, it should be permissible to use any of the same `QubitSpecifier`
types (or similar for `Clbit`) that `QuantumCircuit.append` uses."""
qreg = QuantumRegister(5, "rqr")
creg = ClassicalRegister(2, "rcr")
circuit_right = QuantumCircuit(qreg, creg)
circuit_right.cx(qreg[0], qreg[3])
circuit_right.x(qreg[1])
circuit_right.y(qreg[2])
circuit_right.z(qreg[4])
circuit_right.measure([0, 1], [0, 1])
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit0, self.left_qubit3)
circuit_expected.x(self.left_qubit1)
circuit_expected.y(self.left_qubit2)
circuit_expected.z(self.left_qubit4)
circuit_expected.measure(self.left_qubit0, self.left_clbit0)
circuit_expected.measure(self.left_qubit1, self.left_clbit1)
circuit_composed = self.circuit_left.compose(circuit_right, np.arange(5), slice(0, 2))
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_inorder_inplace(self):
"""Composing two circuits of the same width, default order, inplace.
┌───┐
lqr_1_0: |0>───┤ H ├─── rqr_0: |0>──■───────
├───┤ │ ┌───┐
lqr_1_1: |0>───┤ X ├─── rqr_1: |0>──┼──┤ X ├
┌──┴───┴──┐ │ ├───┤
lqr_1_2: |0>┤ U1(0.1) ├ + rqr_2: |0>──┼──┤ Y ├ =
└─────────┘ ┌─┴─┐└───┘
lqr_2_0: |0>─────■───── rqr_3: |0>┤ X ├─────
┌─┴─┐ └───┘┌───┐
lqr_2_1: |0>───┤ X ├─── rqr_4: |0>─────┤ Z ├
└───┘ └───┘
lcr_0: 0 ═══════════
lcr_1: 0 ═══════════
┌───┐
lqr_1_0: |0>───┤ H ├─────■───────
├───┤ │ ┌───┐
lqr_1_1: |0>───┤ X ├─────┼──┤ X ├
┌──┴───┴──┐ │ ├───┤
lqr_1_2: |0>┤ U1(0.1) ├──┼──┤ Y ├
└─────────┘┌─┴─┐└───┘
lqr_2_0: |0>─────■─────┤ X ├─────
┌─┴─┐ └───┘┌───┐
lqr_2_1: |0>───┤ X ├────────┤ Z ├
└───┘ └───┘
lcr_0: 0 ════════════════════════
lcr_1: 0 ════════════════════════
"""
qreg = QuantumRegister(5, "rqr")
circuit_right = QuantumCircuit(qreg)
circuit_right.cx(qreg[0], qreg[3])
circuit_right.x(qreg[1])
circuit_right.y(qreg[2])
circuit_right.z(qreg[4])
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit0, self.left_qubit3)
circuit_expected.x(self.left_qubit1)
circuit_expected.y(self.left_qubit2)
circuit_expected.z(self.left_qubit4)
# inplace
circuit_left = self.circuit_left.copy()
circuit_left.compose(circuit_right, inplace=True)
self.assertEqual(circuit_left, circuit_expected)
def test_compose_inorder_smaller(self):
"""Composing with a smaller RHS dag, default order.
┌───┐ ┌─────┐
lqr_1_0: |0>───┤ H ├─── rqr_0: |0>──■──┤ Tdg ├
├───┤ ┌─┴─┐└─────┘
lqr_1_1: |0>───┤ X ├─── rqr_1: |0>┤ X ├───────
┌──┴───┴──┐ └───┘
lqr_1_2: |0>┤ U1(0.1) ├ + =
└─────────┘
lqr_2_0: |0>─────■─────
┌─┴─┐
lqr_2_1: |0>───┤ X ├───
└───┘
lcr_0: 0 ══════════════
lcr_1: 0 ══════════════
┌───┐ ┌─────┐
lqr_1_0: |0>───┤ H ├─────■──┤ Tdg ├
├───┤ ┌─┴─┐└─────┘
lqr_1_1: |0>───┤ X ├───┤ X ├───────
┌──┴───┴──┐└───┘
lqr_1_2: |0>┤ U1(0.1) ├────────────
└─────────┘
lqr_2_0: |0>─────■─────────────────
┌─┴─┐
lqr_2_1: |0>───┤ X ├───────────────
└───┘
lcr_0: 0 ══════════════════════════
lcr_1: 0 ══════════════════════════
"""
qreg = QuantumRegister(2, "rqr")
circuit_right = QuantumCircuit(qreg)
circuit_right.cx(qreg[0], qreg[1])
circuit_right.tdg(qreg[0])
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit0, self.left_qubit1)
circuit_expected.tdg(self.left_qubit0)
circuit_composed = self.circuit_left.compose(circuit_right)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_permuted(self):
"""Composing two dags of the same width, permuted wires.
┌───┐
lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■───────
├───┤ │ ┌───┐
lqr_1_1: |0>──┤ X ├─── rqr_1: |0>──┼──┤ X ├
┌─┴───┴──┐ │ ├───┤
lqr_1_2: |0>┤ P(0.1) ├ rqr_2: |0>──┼──┤ Y ├
└────────┘ ┌─┴─┐└───┘
lqr_2_0: |0>────■───── + rqr_3: |0>┤ X ├───── =
┌─┴─┐ └───┘┌───┐
lqr_2_1: |0>──┤ X ├─── rqr_4: |0>─────┤ Z ├
└───┘ └───┘
lcr_0: 0 ══════════════
lcr_1: 0 ══════════════
┌───┐ ┌───┐
lqr_1_0: |0>──┤ H ├───┤ Z ├
├───┤ ├───┤
lqr_1_1: |0>──┤ X ├───┤ X ├
┌─┴───┴──┐├───┤
lqr_1_2: |0>┤ P(0.1) ├┤ Y ├
└────────┘└───┘
lqr_2_0: |0>────■───────■──
┌─┴─┐ ┌─┴─┐
lqr_2_1: |0>──┤ X ├───┤ X ├
└───┘ └───┘
lcr_0: 0 ══════════════════
lcr_1: 0 ══════════════════
"""
qreg = QuantumRegister(5, "rqr")
circuit_right = QuantumCircuit(qreg)
circuit_right.cx(qreg[0], qreg[3])
circuit_right.x(qreg[1])
circuit_right.y(qreg[2])
circuit_right.z(qreg[4])
circuit_expected = self.circuit_left.copy()
circuit_expected.z(self.left_qubit0)
circuit_expected.x(self.left_qubit1)
circuit_expected.y(self.left_qubit2)
circuit_expected.cx(self.left_qubit3, self.left_qubit4)
# permuted wiring
circuit_composed = self.circuit_left.compose(
circuit_right,
qubits=[
self.left_qubit3,
self.left_qubit1,
self.left_qubit2,
self.left_qubit4,
self.left_qubit0,
],
inplace=False,
)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_permuted_smaller(self):
"""Composing with a smaller RHS dag, and permuted wires.
Compose using indices.
┌───┐ ┌─────┐
lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■──┤ Tdg ├
├───┤ ┌─┴─┐└─────┘
lqr_1_1: |0>──┤ X ├─── rqr_1: |0>┤ X ├───────
┌─┴───┴──┐ └───┘
lqr_1_2: |0>┤ P(0.1) ├ + =
└────────┘
lqr_2_0: |0>────■─────
┌─┴─┐
lqr_2_1: |0>──┤ X ├───
└───┘
lcr_0: 0 ═════════════
lcr_1: 0 ═════════════
┌───┐
lqr_1_0: |0>──┤ H ├───────────────
├───┤
lqr_1_1: |0>──┤ X ├───────────────
┌─┴───┴──┐┌───┐
lqr_1_2: |0>┤ P(0.1) ├┤ X ├───────
└────────┘└─┬─┘┌─────┐
lqr_2_0: |0>────■───────■──┤ Tdg ├
┌─┴─┐ └─────┘
lqr_2_1: |0>──┤ X ├───────────────
└───┘
lcr_0: 0 ═════════════════════════
lcr_1: 0 ═════════════════════════
"""
qreg = QuantumRegister(2, "rqr")
circuit_right = QuantumCircuit(qreg)
circuit_right.cx(qreg[0], qreg[1])
circuit_right.tdg(qreg[0])
# permuted wiring of subset
circuit_composed = self.circuit_left.compose(circuit_right, qubits=[3, 2])
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit3, self.left_qubit2)
circuit_expected.tdg(self.left_qubit3)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_classical(self):
"""Composing on classical bits.
┌───┐ ┌─────┐┌─┐
lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■──┤ Tdg ├┤M├
├───┤ ┌─┴─┐└─┬─┬─┘└╥┘
lqr_1_1: |0>──┤ X ├─── rqr_1: |0>┤ X ├──┤M├───╫─
┌─┴───┴──┐ └───┘ └╥┘ ║
lqr_1_2: |0>┤ P(0.1) ├ + rcr_0: 0 ════════╬════╩═ =
└────────┘ ║
lqr_2_0: |0>────■───── rcr_1: 0 ════════╩══════
┌─┴─┐
lqr_2_1: |0>──┤ X ├───
└───┘
lcr_0: 0 ══════════════
lcr_1: 0 ══════════════
┌───┐
lqr_1_0: |0>──┤ H ├──────────────────
├───┤ ┌─────┐┌─┐
lqr_1_1: |0>──┤ X ├─────■──┤ Tdg ├┤M├
┌─┴───┴──┐ │ └─────┘└╥┘
lqr_1_2: |0>┤ P(0.1) ├──┼──────────╫─
└────────┘ │ ║
lqr_2_0: |0>────■───────┼──────────╫─
┌─┴─┐ ┌─┴─┐ ┌─┐ ║
lqr_2_1: |0>──┤ X ├───┤ X ├──┤M├───╫─
└───┘ └───┘ └╥┘ ║
lcr_0: 0 ══════════════════╩════╬═
║
lcr_1: 0 ═══════════════════════╩═
"""
qreg = QuantumRegister(2, "rqr")
creg = ClassicalRegister(2, "rcr")
circuit_right = QuantumCircuit(qreg, creg)
circuit_right.cx(qreg[0], qreg[1])
circuit_right.tdg(qreg[0])
circuit_right.measure(qreg, creg)
# permuted subset of qubits and clbits
circuit_composed = self.circuit_left.compose(circuit_right, qubits=[1, 4], clbits=[1, 0])
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit1, self.left_qubit4)
circuit_expected.tdg(self.left_qubit1)
circuit_expected.measure(self.left_qubit4, self.left_clbit0)
circuit_expected.measure(self.left_qubit1, self.left_clbit1)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_conditional(self):
"""Composing on classical bits.
┌───┐ ┌───┐ ┌─┐
lqr_1_0: |0>──┤ H ├─── rqr_0: ────────┤ H ├─┤M├───
├───┤ ┌───┐ └─┬─┘ └╥┘┌─┐
lqr_1_1: |0>──┤ X ├─── rqr_1: ─┤ X ├────┼────╫─┤M├
┌─┴───┴──┐ └─┬─┘ │ ║ └╥┘
lqr_1_2: |0>┤ P(0.1) ├ + ┌──┴──┐┌──┴──┐ ║ ║
└────────┘ rcr_0: ╡ ╞╡ ╞═╩══╬═
lqr_2_0: |0>────■───── │ = 3 ││ = 3 │ ║
┌─┴─┐ rcr_1: ╡ ╞╡ ╞════╩═
lqr_2_1: |0>──┤ X ├─── └─────┘└─────┘
└───┘
lcr_0: 0 ══════════════
lcr_1: 0 ══════════════
┌───┐
lqr_1_0: ──┤ H ├───────────────────────
├───┤ ┌───┐ ┌─┐
lqr_1_1: ──┤ X ├───────────┤ H ├────┤M├
┌─┴───┴──┐ └─┬─┘ └╥┘
lqr_1_2: ┤ P(0.1) ├──────────┼───────╫─
└────────┘ │ ║
lqr_2_0: ────■───────────────┼───────╫─
┌─┴─┐ ┌───┐ │ ┌─┐ ║
lqr_2_1: ──┤ X ├────┤ X ├────┼───┤M├─╫─
└───┘ └─┬─┘ │ └╥┘ ║
┌──┴──┐┌──┴──┐ ║ ║
lcr_0: ════════════╡ ╞╡ ╞═╬══╩═
│ = 3 ││ = 3 │ ║
lcr_1: ════════════╡ ╞╡ ╞═╩════
└─────┘└─────┘
"""
qreg = QuantumRegister(2, "rqr")
creg = ClassicalRegister(2, "rcr")
circuit_right = QuantumCircuit(qreg, creg)
circuit_right.x(qreg[1]).c_if(creg, 3)
circuit_right.h(qreg[0]).c_if(creg, 3)
circuit_right.measure(qreg, creg)
# permuted subset of qubits and clbits
circuit_composed = self.circuit_left.compose(circuit_right, qubits=[1, 4], clbits=[0, 1])
circuit_expected = self.circuit_left.copy()
circuit_expected.x(self.left_qubit4).c_if(*self.condition)
circuit_expected.h(self.left_qubit1).c_if(*self.condition)
circuit_expected.measure(self.left_qubit1, self.left_clbit0)
circuit_expected.measure(self.left_qubit4, self.left_clbit1)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_conditional_no_match(self):
"""Test that compose correctly maps registers in conditions to the new circuit, even when
there are no matching registers in the destination circuit.
Regression test of gh-6583 and gh-6584."""
right = QuantumCircuit(QuantumRegister(3), ClassicalRegister(1), ClassicalRegister(1))
right.h(1)
right.cx(1, 2)
right.cx(0, 1)
right.h(0)
right.measure([0, 1], [0, 1])
right.z(2).c_if(right.cregs[0], 1)
right.x(2).c_if(right.cregs[1], 1)
test = QuantumCircuit(3, 3).compose(right, range(3), range(2))
z = next(ins.operation for ins in test.data[::-1] if ins.operation.name == "z")
x = next(ins.operation for ins in test.data[::-1] if ins.operation.name == "x")
# The registers should have been mapped, including the bits inside them. Unlike the
# previous test, there are no matching registers in the destination circuit, so the
# composition needs to add new registers (bit groupings) over the existing mapped bits.
self.assertIsNot(z.condition, None)
self.assertIsInstance(z.condition[0], ClassicalRegister)
self.assertEqual(len(z.condition[0]), len(right.cregs[0]))
self.assertIs(z.condition[0][0], test.clbits[0])
self.assertEqual(z.condition[1], 1)
self.assertIsNot(x.condition, None)
self.assertIsInstance(x.condition[0], ClassicalRegister)
self.assertEqual(len(x.condition[0]), len(right.cregs[1]))
self.assertEqual(z.condition[1], 1)
self.assertIs(x.condition[0][0], test.clbits[1])
def test_compose_switch_match(self):
"""Test that composition containing a `switch` with a register that matches proceeds
correctly."""
case_0 = QuantumCircuit(1, 2)
case_0.x(0)
case_1 = QuantumCircuit(1, 2)
case_1.z(0)
case_default = QuantumCircuit(1, 2)
cr = ClassicalRegister(2, "target")
right = QuantumCircuit(QuantumRegister(1), cr)
right.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [0], [0, 1])
test = QuantumCircuit(QuantumRegister(3), cr, ClassicalRegister(2)).compose(
right, [1], [0, 1]
)
expected = test.copy_empty_like()
expected.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [1], [0, 1])
self.assertEqual(test, expected)
def test_compose_switch_no_match(self):
"""Test that composition containing a `switch` with a register that matches proceeds
correctly."""
case_0 = QuantumCircuit(1, 2)
case_0.x(0)
case_1 = QuantumCircuit(1, 2)
case_1.z(0)
case_default = QuantumCircuit(1, 2)
cr = ClassicalRegister(2, "target")
right = QuantumCircuit(QuantumRegister(1), cr)
right.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [0], [0, 1])
test = QuantumCircuit(3, 3).compose(right, [1], [0, 1])
self.assertEqual(len(test.data), 1)
self.assertIsInstance(test.data[0].operation, SwitchCaseOp)
target = test.data[0].operation.target
self.assertIn(target, test.cregs)
self.assertEqual(list(target), test.clbits[0:2])
def test_compose_gate(self):
"""Composing with a gate.
┌───┐ ┌───┐ ┌───┐
lqr_1_0: ──┤ H ├─── lqr_1_0: ──┤ H ├────┤ X ├
├───┤ ├───┤ └─┬─┘
lqr_1_1: ──┤ X ├─── lqr_1_1: ──┤ X ├──────┼───
┌─┴───┴──┐ ───■─── ┌─┴───┴──┐ │
lqr_1_2: ┤ P(0.1) ├ + ┌─┴─┐ = lqr_1_2: ┤ P(0.1) ├───┼───
└────────┘ ─┤ X ├─ └────────┘ │
lqr_2_0: ────■───── └───┘ lqr_2_0: ────■────────┼──
┌─┴─┐ ┌─┴─┐ │
lqr_2_1: ──┤ X ├─── lqr_2_1: ──┤ X ├──────■───
└───┘ └───┘
lcr_0: 0 ══════════ lcr_0: 0 ═════════════════
lcr_1: 0 ══════════ lcr_1: 0 ═════════════════
"""
circuit_composed = self.circuit_left.compose(CXGate(), qubits=[4, 0])
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit4, self.left_qubit0)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_calibrations(self):
"""Test that composing two circuits updates calibrations."""
circ_left = QuantumCircuit(1)
circ_left.add_calibration("h", [0], None)
circ_right = QuantumCircuit(1)
circ_right.add_calibration("rx", [0], None)
circ = circ_left.compose(circ_right)
self.assertEqual(len(circ.calibrations), 2)
self.assertEqual(len(circ_left.calibrations), 1)
circ_left = QuantumCircuit(1)
circ_left.add_calibration("h", [0], None)
circ_right = QuantumCircuit(1)
circ_right.add_calibration("h", [1], None)
circ = circ_left.compose(circ_right)
self.assertEqual(len(circ.calibrations), 1)
self.assertEqual(len(circ.calibrations["h"]), 2)
self.assertEqual(len(circ_left.calibrations), 1)
# Ensure that transpiled _calibration is defaultdict
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
qc = transpile(qc, None, basis_gates=["h", "cx"], coupling_map=[[0, 1], [1, 0]])
qc.add_calibration("cx", [0, 1], Schedule())
def test_compose_one_liner(self):
"""Test building a circuit in one line, for fun."""
circ = QuantumCircuit(3)
h = HGate()
rz = RZGate(0.1)
cx = CXGate()
ccx = CCXGate()
circ = circ.compose(h, [0]).compose(cx, [0, 2]).compose(ccx, [2, 1, 0]).compose(rz, [1])
expected = QuantumCircuit(3)
expected.h(0)
expected.cx(0, 2)
expected.ccx(2, 1, 0)
expected.rz(0.1, 1)
self.assertEqual(circ, expected)
def test_compose_global_phase(self):
"""Composing with global phase."""
circ1 = QuantumCircuit(1, global_phase=1)
circ1.rz(0.5, 0)
circ2 = QuantumCircuit(1, global_phase=2)
circ3 = QuantumCircuit(1, global_phase=3)
circ4 = circ1.compose(circ2).compose(circ3)
self.assertEqual(
circ4.global_phase, circ1.global_phase + circ2.global_phase + circ3.global_phase
)
def test_compose_front_circuit(self):
"""Test composing a circuit at the front of a circuit."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
other = QuantumCircuit(2)
other.cz(1, 0)
other.z(1)
output = qc.compose(other, front=True)
expected = QuantumCircuit(2)
expected.cz(1, 0)
expected.z(1)
expected.h(0)
expected.cx(0, 1)
self.assertEqual(output, expected)
def test_compose_front_gate(self):
"""Test composing a gate at the front of a circuit."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
output = qc.compose(CXGate(), [1, 0], front=True)
expected = QuantumCircuit(2)
expected.cx(1, 0)
expected.h(0)
expected.cx(0, 1)
self.assertEqual(output, expected)
def test_compose_adds_parameters(self):
"""Test the composed circuit contains all parameters."""
a, b = Parameter("a"), Parameter("b")
qc_a = QuantumCircuit(1)
qc_a.rx(a, 0)
qc_b = QuantumCircuit(1)
qc_b.rx(b, 0)
with self.subTest("compose with other circuit out-of-place"):
qc_1 = qc_a.compose(qc_b)
self.assertEqual(qc_1.parameters, {a, b})
with self.subTest("compose with other instruction out-of-place"):
instr_b = qc_b.to_instruction()
qc_2 = qc_a.compose(instr_b, [0])
self.assertEqual(qc_2.parameters, {a, b})
with self.subTest("compose with other circuit in-place"):
qc_a.compose(qc_b, inplace=True)
self.assertEqual(qc_a.parameters, {a, b})
def test_wrapped_compose(self):
"""Test wrapping the circuit upon composition works."""
qc_a = QuantumCircuit(1)
qc_a.x(0)
qc_b = QuantumCircuit(1, name="B")
qc_b.h(0)
qc_a.compose(qc_b, wrap=True, inplace=True)
self.assertDictEqual(qc_a.count_ops(), {"B": 1, "x": 1})
self.assertDictEqual(qc_a.decompose().count_ops(), {"h": 1, "u3": 1})
def test_wrapping_unitary_circuit(self):
"""Test a unitary circuit will be wrapped as Gate, else as Instruction."""
qc_init = QuantumCircuit(1)
qc_init.x(0)
qc_unitary = QuantumCircuit(1, name="a")
qc_unitary.ry(0.23, 0)
qc_nonunitary = QuantumCircuit(1)
qc_nonunitary.reset(0)
with self.subTest("wrapping a unitary circuit"):
qc = qc_init.compose(qc_unitary, wrap=True)
self.assertIsInstance(qc.data[1].operation, Gate)
with self.subTest("wrapping a non-unitary circuit"):
qc = qc_init.compose(qc_nonunitary, wrap=True)
self.assertIsInstance(qc.data[1].operation, Instruction)
def test_single_bit_condition(self):
"""Test that compose can correctly handle circuits that contain conditions on single
bits. This is a regression test of the bug that broke qiskit-experiments in gh-7653."""
base = QuantumCircuit(1, 1)
base.x(0).c_if(0, True)
test = QuantumCircuit(1, 1).compose(base)
self.assertIsNot(base.clbits[0], test.clbits[0])
self.assertEqual(base, test)
self.assertIs(test.data[0].operation.condition[0], test.clbits[0])
def test_condition_mapping_ifelseop(self):
"""Test that the condition in an `IfElseOp` is correctly mapped to a new set of bits and
registers."""
base_loose = Clbit()
base_creg = ClassicalRegister(2)
base_qreg = QuantumRegister(1)
base = QuantumCircuit(base_qreg, [base_loose], base_creg)
with base.if_test((base_loose, True)):
base.x(0)
with base.if_test((base_creg, 3)):
base.x(0)
test_loose = Clbit()
test_creg = ClassicalRegister(2)
test_qreg = QuantumRegister(1)
test = QuantumCircuit(test_qreg, [test_loose], test_creg).compose(base)
bit_instruction = test.data[0].operation
reg_instruction = test.data[1].operation
self.assertIs(bit_instruction.condition[0], test_loose)
self.assertEqual(bit_instruction.condition, (test_loose, True))
self.assertIs(reg_instruction.condition[0], test_creg)
self.assertEqual(reg_instruction.condition, (test_creg, 3))
def test_condition_mapping_whileloopop(self):
"""Test that the condition in a `WhileLoopOp` is correctly mapped to a new set of bits and
registers."""
base_loose = Clbit()
base_creg = ClassicalRegister(2)
base_qreg = QuantumRegister(1)
base = QuantumCircuit(base_qreg, [base_loose], base_creg)
with base.while_loop((base_loose, True)):
base.x(0)
with base.while_loop((base_creg, 3)):
base.x(0)
test_loose = Clbit()
test_creg = ClassicalRegister(2)
test_qreg = QuantumRegister(1)
test = QuantumCircuit(test_qreg, [test_loose], test_creg).compose(base)
bit_instruction = test.data[0].operation
reg_instruction = test.data[1].operation
self.assertIs(bit_instruction.condition[0], test_loose)
self.assertEqual(bit_instruction.condition, (test_loose, True))
self.assertIs(reg_instruction.condition[0], test_creg)
self.assertEqual(reg_instruction.condition, (test_creg, 3))
def test_compose_no_clbits_in_one(self):
"""Test combining a circuit with cregs to one without"""
ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx")
qc = QuantumCircuit(2)
qc.measure_all()
out = ansatz.compose(qc)
self.assertEqual(out.clbits, qc.clbits)
def test_compose_no_clbits_in_one_inplace(self):
"""Test combining a circuit with cregs to one without inplace"""
ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx")
qc = QuantumCircuit(2)
qc.measure_all()
ansatz.compose(qc, inplace=True)
self.assertEqual(ansatz.clbits, qc.clbits)
def test_compose_no_clbits_in_one_multireg(self):
"""Test combining a circuit with cregs to one without, multi cregs"""
ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx")
qa = QuantumRegister(2, "q")
ca = ClassicalRegister(2, "a")
cb = ClassicalRegister(2, "b")
qc = QuantumCircuit(qa, ca, cb)
qc.measure(0, cb[1])
out = ansatz.compose(qc)
self.assertEqual(out.clbits, qc.clbits)
self.assertEqual(out.cregs, qc.cregs)
def test_compose_noclbits_registerless(self):
"""Combining a circuit with cregs to one without, registerless case"""
inner = QuantumCircuit([Qubit(), Qubit()], [Clbit(), Clbit()])
inner.measure([0, 1], [0, 1])
outer = QuantumCircuit(2)
outer.compose(inner, inplace=True)
self.assertEqual(outer.clbits, inner.clbits)
self.assertEqual(outer.cregs, [])
def test_expr_condition_is_mapped(self):
"""Test that an expression in a condition involving several registers is mapped correctly to
the destination circuit."""
inner = QuantumCircuit(1)
inner.x(0)
a_src = ClassicalRegister(2, "a_src")
b_src = ClassicalRegister(2, "b_src")
c_src = ClassicalRegister(name="c_src", bits=list(a_src) + list(b_src))
source = QuantumCircuit(QuantumRegister(1), a_src, b_src, c_src)
test_1 = lambda: expr.lift(a_src[0])
test_2 = lambda: expr.logic_not(b_src[1])
test_3 = lambda: expr.logic_and(expr.bit_and(b_src, 2), expr.less(c_src, 7))
source.if_test(test_1(), inner.copy(), [0], [])
source.if_else(test_2(), inner.copy(), inner.copy(), [0], [])
source.while_loop(test_3(), inner.copy(), [0], [])
a_dest = ClassicalRegister(2, "a_dest")
b_dest = ClassicalRegister(2, "b_dest")
dest = QuantumCircuit(QuantumRegister(1), a_dest, b_dest).compose(source)
# Check that the input conditions weren't mutated.
for in_condition, instruction in zip((test_1, test_2, test_3), source.data):
self.assertEqual(in_condition(), instruction.operation.condition)
# Should be `a_dest`, `b_dest` and an added one to account for `c_src`.
self.assertEqual(len(dest.cregs), 3)
mapped_reg = dest.cregs[-1]
expected = QuantumCircuit(dest.qregs[0], a_dest, b_dest, mapped_reg)
expected.if_test(expr.lift(a_dest[0]), inner.copy(), [0], [])
expected.if_else(expr.logic_not(b_dest[1]), inner.copy(), inner.copy(), [0], [])
expected.while_loop(
expr.logic_and(expr.bit_and(b_dest, 2), expr.less(mapped_reg, 7)), inner.copy(), [0], []
)
self.assertEqual(dest, expected)
def test_expr_target_is_mapped(self):
"""Test that an expression in a switch statement's target is mapping correctly to the
destination circuit."""
inner1 = QuantumCircuit(1)
inner1.x(0)
inner2 = QuantumCircuit(1)
inner2.z(0)
a_src = ClassicalRegister(2, "a_src")
b_src = ClassicalRegister(2, "b_src")
c_src = ClassicalRegister(name="c_src", bits=list(a_src) + list(b_src))
source = QuantumCircuit(QuantumRegister(1), a_src, b_src, c_src)
test_1 = lambda: expr.lift(a_src[0])
test_2 = lambda: expr.logic_not(b_src[1])
test_3 = lambda: expr.lift(b_src)
test_4 = lambda: expr.bit_and(c_src, 7)
source.switch(test_1(), [(False, inner1.copy()), (True, inner2.copy())], [0], [])
source.switch(test_2(), [(False, inner1.copy()), (True, inner2.copy())], [0], [])
source.switch(test_3(), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], [])
source.switch(test_4(), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], [])
a_dest = ClassicalRegister(2, "a_dest")
b_dest = ClassicalRegister(2, "b_dest")
dest = QuantumCircuit(QuantumRegister(1), a_dest, b_dest).compose(source)
# Check that the input expressions weren't mutated.
for in_target, instruction in zip((test_1, test_2, test_3, test_4), source.data):
self.assertEqual(in_target(), instruction.operation.target)
# Should be `a_dest`, `b_dest` and an added one to account for `c_src`.
self.assertEqual(len(dest.cregs), 3)
mapped_reg = dest.cregs[-1]
expected = QuantumCircuit(dest.qregs[0], a_dest, b_dest, mapped_reg)
expected.switch(
expr.lift(a_dest[0]), [(False, inner1.copy()), (True, inner2.copy())], [0], []
)
expected.switch(
expr.logic_not(b_dest[1]), [(False, inner1.copy()), (True, inner2.copy())], [0], []
)
expected.switch(
expr.lift(b_dest), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], []
)
expected.switch(
expr.bit_and(mapped_reg, 7),
[(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())],
[0],
[],
)
self.assertEqual(dest, expected)
if __name__ == "__main__":
unittest.main()
|
https://github.com/Q-MAB/Qiskit-FashionMNIST-Case
|
Q-MAB
|
#####################################################################################################
#This code is part of the Medium story 'Hybrid Quantum-Classical Neural Network for classification
#of images in FashionMNIST dataset' case study. Parts of the code may have been imported from Qiskit
#textbook and from the exercises of the Qiskit global summer school on Quantum Machine Learning. The
#case study was a challenge to put insights from the Qiskit summer school into practice and explore
#the hybrid quantum-classical neural network architecture.
#A story on the case study can be found here: medium.com/QMAB
#####################################################################################################
import numpy as np
import torch
from torchvision.transforms import ToTensor
from torch import cat, no_grad, manual_seed
from torchvision import datasets, transforms
import torch.optim as optim
from torch.nn import (Module, Conv2d, Linear, Dropout2d, NLLLoss, MaxPool2d, Flatten, Sequential, ReLU)
from torch.autograd import Function
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torch import Tensor
from torch.optim import LBFGS
from torchviz import make_dot
import torchvision
from torchvision.io import read_image
from torch.autograd import Variable
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 import Parameter
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
import os
import pandas as pd
# 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
self.qnn = TorchConnector(qnn2) # Apply torch connector, weights chosen
self.fc3 = Linear(1, 1) # uniformly at random from interval [-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 = 5
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.barrier()
circuit.h(0)
circuit = RemoveBarriers()(circuit)
circuit.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Necessary imports
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import ZFeatureMap, RealAmplitudes
from qiskit.utils import algorithm_globals
from sklearn.datasets import make_classification
from sklearn.preprocessing import MinMaxScaler
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier
from qiskit_machine_learning.neural_networks import EffectiveDimension, LocalEffectiveDimension
from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN
# set random seed
algorithm_globals.random_seed = 42
num_qubits = 3
# create a feature map
feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1)
# create a variational circuit
ansatz = RealAmplitudes(num_qubits, reps=1)
# combine feature map and ansatz into a single circuit
qc = QuantumCircuit(num_qubits)
qc.append(feature_map, range(num_qubits))
qc.append(ansatz, range(num_qubits))
qc.decompose().draw("mpl")
# parity maps bitstrings to 0 or 1
def parity(x):
return "{:b}".format(x).count("1") % 2
output_shape = 2 # corresponds to the number of classes, possible outcomes of the (parity) mapping.
# construct QNN
qnn = SamplerQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=output_shape,
sparse=False,
)
# we can set the total number of input samples and weight samples for random selection
num_input_samples = 10
num_weight_samples = 10
global_ed = EffectiveDimension(
qnn=qnn, weight_samples=num_weight_samples, input_samples=num_input_samples
)
# we can also provide user-defined samples and parameters
input_samples = algorithm_globals.random.normal(0, 1, size=(10, qnn.num_inputs))
weight_samples = algorithm_globals.random.uniform(0, 1, size=(10, qnn.num_weights))
global_ed = EffectiveDimension(qnn=qnn, weight_samples=weight_samples, input_samples=input_samples)
# finally, we will define ranges to test different numbers of data, n
n = [5000, 8000, 10000, 40000, 60000, 100000, 150000, 200000, 500000, 1000000]
global_eff_dim_0 = global_ed.get_effective_dimension(dataset_size=n[0])
d = qnn.num_weights
print("Data size: {}, global effective dimension: {:.4f}".format(n[0], global_eff_dim_0))
print(
"Number of weights: {}, normalized effective dimension: {:.4f}".format(d, global_eff_dim_0 / d)
)
global_eff_dim_1 = global_ed.get_effective_dimension(dataset_size=n)
print("Effective dimension: {}".format(global_eff_dim_1))
print("Number of weights: {}".format(d))
# plot the normalized effective dimension for the model
plt.plot(n, np.array(global_eff_dim_1) / d)
plt.xlabel("Number of data")
plt.ylabel("Normalized GLOBAL effective dimension")
plt.show()
num_inputs = 3
num_samples = 50
X, y = make_classification(
n_samples=num_samples,
n_features=num_inputs,
n_informative=3,
n_redundant=0,
n_clusters_per_class=1,
class_sep=2.0,
)
X = MinMaxScaler().fit_transform(X)
y = 2 * y - 1 # labels in {-1, 1}
estimator_qnn = EstimatorQNN(
circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters
)
# callback function that draws a live plot when the .fit() method is called
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
# construct classifier
initial_point = algorithm_globals.random.random(estimator_qnn.num_weights)
estimator_classifier = NeuralNetworkClassifier(
neural_network=estimator_qnn,
optimizer=COBYLA(maxiter=80),
initial_point=initial_point,
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function (callback)
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
estimator_classifier.fit(X, y)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
estimator_classifier.score(X, y)
trained_weights = estimator_classifier.weights
# get Local Effective Dimension for set of trained weights
local_ed_trained = LocalEffectiveDimension(
qnn=estimator_qnn, weight_samples=trained_weights, input_samples=X
)
local_eff_dim_trained = local_ed_trained.get_effective_dimension(dataset_size=n)
print(
"normalized local effective dimensions for trained QNN: ",
local_eff_dim_trained / estimator_qnn.num_weights,
)
# get Local Effective Dimension for set of untrained weights
local_ed_untrained = LocalEffectiveDimension(
qnn=estimator_qnn, weight_samples=initial_point, input_samples=X
)
local_eff_dim_untrained = local_ed_untrained.get_effective_dimension(dataset_size=n)
print(
"normalized local effective dimensions for untrained QNN: ",
local_eff_dim_untrained / estimator_qnn.num_weights,
)
# plot the normalized effective dimension for the model
plt.plot(n, np.array(local_eff_dim_trained) / estimator_qnn.num_weights, label="trained weights")
plt.plot(
n, np.array(local_eff_dim_untrained) / estimator_qnn.num_weights, label="untrained weights"
)
plt.xlabel("Number of data")
plt.ylabel("Normalized LOCAL effective dimension")
plt.legend()
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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 BasisTranslator pass"""
import os
from numpy import pi
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import transpile
from qiskit.test import QiskitTestCase
from qiskit.circuit import Gate, Parameter, EquivalenceLibrary, Qubit, Clbit
from qiskit.circuit.library import (
U1Gate,
U2Gate,
U3Gate,
CU1Gate,
CU3Gate,
UGate,
RZGate,
XGate,
SXGate,
CXGate,
)
from qiskit.converters import circuit_to_dag, dag_to_circuit, circuit_to_instruction
from qiskit.exceptions import QiskitError
from qiskit.quantum_info import Operator
from qiskit.transpiler.target import Target, InstructionProperties
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes.basis import BasisTranslator, UnrollCustomDefinitions
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary as std_eqlib,
)
class OneQubitZeroParamGate(Gate):
"""Mock one qubit zero param gate."""
def __init__(self, name="1q0p"):
super().__init__(name, 1, [])
class OneQubitOneParamGate(Gate):
"""Mock one qubit one param gate."""
def __init__(self, theta, name="1q1p"):
super().__init__(name, 1, [theta])
class OneQubitOneParamPrimeGate(Gate):
"""Mock one qubit one param gate."""
def __init__(self, alpha):
super().__init__("1q1p_prime", 1, [alpha])
class OneQubitTwoParamGate(Gate):
"""Mock one qubit two param gate."""
def __init__(self, phi, lam, name="1q2p"):
super().__init__(name, 1, [phi, lam])
class TwoQubitZeroParamGate(Gate):
"""Mock one qubit zero param gate."""
def __init__(self, name="2q0p"):
super().__init__(name, 2, [])
class VariadicZeroParamGate(Gate):
"""Mock variadic zero param gate."""
def __init__(self, num_qubits, name="vq0p"):
super().__init__(name, num_qubits, [])
class TestBasisTranslator(QiskitTestCase):
"""Test the BasisTranslator pass."""
def test_circ_in_basis_no_op(self):
"""Verify we don't change a circuit already in the target basis."""
eq_lib = EquivalenceLibrary()
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = circuit_to_dag(qc)
pass_ = BasisTranslator(eq_lib, ["1q0p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected)
def test_raise_if_target_basis_unreachable(self):
"""Verify we raise if the circuit cannot be transformed to the target."""
eq_lib = EquivalenceLibrary()
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
with self.assertRaises(TranspilerError):
pass_.run(dag)
def test_single_substitution(self):
"""Verify we correctly unroll gates through a single equivalence."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1)
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_double_substitution(self):
"""Verify we correctly unroll gates through multiple equivalences."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
theta = Parameter("theta")
gate = OneQubitOneParamGate(theta)
equiv = QuantumCircuit(1)
equiv.append(OneQubitTwoParamGate(theta, pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1)
expected.append(OneQubitTwoParamGate(pi, pi / 2), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q2p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_single_substitution_with_global_phase(self):
"""Verify we correctly unroll gates through a single equivalence with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 0.2)
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_single_two_gate_substitution_with_global_phase(self):
"""Verify we correctly unroll gates through a single equivalence with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 0.2)
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_two_substitutions_with_global_phase(self):
"""Verify we correctly unroll gates through a single equivalences with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 2 * 0.2)
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_two_single_two_gate_substitutions_with_global_phase(self):
"""Verify we correctly unroll gates through a single equivalence with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 2 * 0.2)
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_double_substitution_with_global_phase(self):
"""Verify we correctly unroll gates through multiple equivalences with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
theta = Parameter("theta")
gate = OneQubitOneParamGate(theta)
equiv = QuantumCircuit(1, global_phase=0.4)
equiv.append(OneQubitTwoParamGate(theta, pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 0.2 + 0.4)
expected.append(OneQubitTwoParamGate(pi, pi / 2), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q2p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_multiple_variadic(self):
"""Verify circuit with multiple instances of variadic gate."""
eq_lib = EquivalenceLibrary()
# e.g. MSGate
oneq_gate = VariadicZeroParamGate(1)
equiv = QuantumCircuit(1)
equiv.append(OneQubitZeroParamGate(), [0])
eq_lib.add_equivalence(oneq_gate, equiv)
twoq_gate = VariadicZeroParamGate(2)
equiv = QuantumCircuit(2)
equiv.append(TwoQubitZeroParamGate(), [0, 1])
eq_lib.add_equivalence(twoq_gate, equiv)
qc = QuantumCircuit(2)
qc.append(VariadicZeroParamGate(1), [0])
qc.append(VariadicZeroParamGate(2), [0, 1])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(2)
expected.append(OneQubitZeroParamGate(), [0])
expected.append(TwoQubitZeroParamGate(), [0, 1])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q0p", "2q0p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_diamond_path(self):
"""Verify we find a path when there are multiple paths to the target basis."""
eq_lib = EquivalenceLibrary()
# Path 1: 1q0p -> 1q1p(pi) -> 1q2p(pi, pi/2)
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
theta = Parameter("theta")
gate = OneQubitOneParamGate(theta)
equiv = QuantumCircuit(1)
equiv.append(OneQubitTwoParamGate(theta, pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
# Path 2: 1q0p -> 1q1p_prime(pi/2) -> 1q2p(2 * pi/2, pi/2)
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1)
equiv.append(OneQubitOneParamPrimeGate(pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
alpha = Parameter("alpha")
gate = OneQubitOneParamPrimeGate(alpha)
equiv = QuantumCircuit(1)
equiv.append(OneQubitTwoParamGate(2 * alpha, pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1)
expected.append(OneQubitTwoParamGate(pi, pi / 2), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q2p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_if_else(self):
"""Test a simple if-else with parameters."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
alpha = Parameter("alpha")
beta = Parameter("beta")
gate = OneQubitOneParamGate(alpha)
equiv = QuantumCircuit([qubits[0]])
equiv.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
equiv.append(OneQubitOneParamGate(alpha, name="1q1p_2"), [qubits[0]])
eq_lib = EquivalenceLibrary()
eq_lib.add_equivalence(gate, equiv)
circ = QuantumCircuit(qubits, clbits)
circ.append(OneQubitOneParamGate(beta), [qubits[0]])
circ.measure(qubits[0], clbits[1])
with circ.if_test((clbits[1], 0)) as else_:
circ.append(OneQubitOneParamGate(alpha), [qubits[0]])
circ.append(TwoQubitZeroParamGate(), qubits)
with else_:
circ.append(TwoQubitZeroParamGate(), [qubits[1], qubits[0]])
dag = circuit_to_dag(circ)
dag_translated = BasisTranslator(eq_lib, ["if_else", "1q0p_2", "1q1p_2", "2q0p"]).run(dag)
expected = QuantumCircuit(qubits, clbits)
expected.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
expected.append(OneQubitOneParamGate(beta, name="1q1p_2"), [qubits[0]])
expected.measure(qubits[0], clbits[1])
with expected.if_test((clbits[1], 0)) as else_:
expected.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
expected.append(OneQubitOneParamGate(alpha, name="1q1p_2"), [qubits[0]])
expected.append(TwoQubitZeroParamGate(), qubits)
with else_:
expected.append(TwoQubitZeroParamGate(), [qubits[1], qubits[0]])
dag_expected = circuit_to_dag(expected)
self.assertEqual(dag_translated, dag_expected)
def test_nested_loop(self):
"""Test a simple if-else with parameters."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
cr = ClassicalRegister(bits=clbits)
index1 = Parameter("index1")
alpha = Parameter("alpha")
gate = OneQubitOneParamGate(alpha)
equiv = QuantumCircuit([qubits[0]])
equiv.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
equiv.append(OneQubitOneParamGate(alpha, name="1q1p_2"), [qubits[0]])
eq_lib = EquivalenceLibrary()
eq_lib.add_equivalence(gate, equiv)
circ = QuantumCircuit(qubits, cr)
with circ.for_loop(range(3), loop_parameter=index1) as ind:
with circ.while_loop((cr, 0)):
circ.append(OneQubitOneParamGate(alpha * ind), [qubits[0]])
dag = circuit_to_dag(circ)
dag_translated = BasisTranslator(
eq_lib, ["if_else", "for_loop", "while_loop", "1q0p_2", "1q1p_2"]
).run(dag)
expected = QuantumCircuit(qubits, cr)
with expected.for_loop(range(3), loop_parameter=index1) as ind:
with expected.while_loop((cr, 0)):
expected.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
expected.append(OneQubitOneParamGate(alpha * ind, name="1q1p_2"), [qubits[0]])
dag_expected = circuit_to_dag(expected)
self.assertEqual(dag_translated, dag_expected)
def test_different_bits(self):
"""Test that the basis translator correctly works when the inner blocks of control-flow
operations are not over the same bits as the outer blocks."""
base = QuantumCircuit([Qubit() for _ in [None] * 4], [Clbit()])
for_body = QuantumCircuit([Qubit(), Qubit()])
for_body.h(0)
for_body.cz(0, 1)
base.for_loop((1,), None, for_body, [1, 2], [])
while_body = QuantumCircuit([Qubit(), Qubit(), Clbit()])
while_body.cz(0, 1)
true_body = QuantumCircuit([Qubit(), Qubit(), Clbit()])
true_body.measure(0, 0)
true_body.while_loop((0, True), while_body, [0, 1], [0])
false_body = QuantumCircuit([Qubit(), Qubit(), Clbit()])
false_body.cz(0, 1)
base.if_else((0, True), true_body, false_body, [0, 3], [0])
basis = {"rz", "sx", "cx", "for_loop", "if_else", "while_loop", "measure"}
out = BasisTranslator(std_eqlib, basis).run(circuit_to_dag(base))
self.assertEqual(set(out.count_ops(recurse=True)), basis)
class TestUnrollerCompatability(QiskitTestCase):
"""Tests backward compatability with the Unroller pass.
Duplicate of TestUnroller from test.python.transpiler.test_unroller with
Unroller replaced by UnrollCustomDefinitions -> BasisTranslator.
"""
def test_basic_unroll(self):
"""Test decompose a single H into u2."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, ["u2"])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, ["u2"])
unrolled_dag = pass_.run(dag)
op_nodes = unrolled_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, "u2")
def test_unroll_toffoli(self):
"""Test unroll toffoli on multi regs to h, t, tdg, cx."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, ["h", "t", "tdg", "cx"])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, ["h", "t", "tdg", "cx"])
unrolled_dag = pass_.run(dag)
op_nodes = unrolled_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_unroll_1q_chain_conditional(self):
"""Test unroll chain of 1-qubit gates interrupted by conditional."""
# ┌───┐┌─────┐┌───┐┌───┐┌─────────┐┌─────────┐┌─────────┐┌─┐ ┌───┐ ┌───┐ »
# qr: ┤ H ├┤ Tdg ├┤ Z ├┤ T ├┤ Ry(0.5) ├┤ Rz(0.3) ├┤ Rx(0.1) ├┤M├─┤ X ├──┤ Y ├─»
# └───┘└─────┘└───┘└───┘└─────────┘└─────────┘└─────────┘└╥┘ └─╥─┘ └─╥─┘ »
# ║ ┌──╨──┐┌──╨──┐»
# cr: 1/══════════════════════════════════════════════════════╩═╡ 0x1 ╞╡ 0x1 ╞»
# 0 └─────┘└─────┘»
# « ┌───┐
# « qr: ─┤ Z ├─
# « └─╥─┘
# « ┌──╨──┐
# «cr: 1/╡ 0x1 ╞
# « └─────┘
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr)
circuit.tdg(qr)
circuit.z(qr)
circuit.t(qr)
circuit.ry(0.5, qr)
circuit.rz(0.3, qr)
circuit.rx(0.1, qr)
circuit.measure(qr, cr)
circuit.x(qr).c_if(cr, 1)
circuit.y(qr).c_if(cr, 1)
circuit.z(qr).c_if(cr, 1)
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, ["u1", "u2", "u3"])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, ["u1", "u2", "u3"])
unrolled_dag = pass_.run(dag)
# Pick up -1 * 0.3 / 2 global phase for one RZ -> U1.
#
# global phase: 6.1332
# ┌─────────┐┌──────────┐┌───────┐┌─────────┐┌─────────────┐┌─────────┐»
# qr: ┤ U2(0,π) ├┤ U1(-π/4) ├┤ U1(π) ├┤ U1(π/4) ├┤ U3(0.5,0,0) ├┤ U1(0.3) ├»
# └─────────┘└──────────┘└───────┘└─────────┘└─────────────┘└─────────┘»
# cr: 1/═══════════════════════════════════════════════════════════════════»
# »
# « ┌──────────────────┐┌─┐┌───────────┐┌───────────────┐┌───────┐
# « qr: ┤ U3(0.1,-π/2,π/2) ├┤M├┤ U3(π,0,π) ├┤ U3(π,π/2,π/2) ├┤ U1(π) ├
# « └──────────────────┘└╥┘└─────╥─────┘└───────╥───────┘└───╥───┘
# « ║ ┌──╨──┐ ┌──╨──┐ ┌──╨──┐
# «cr: 1/═════════════════════╩════╡ 0x1 ╞════════╡ 0x1 ╞══════╡ 0x1 ╞═
# « 0 └─────┘ └─────┘ └─────┘
ref_circuit = QuantumCircuit(qr, cr, global_phase=-0.3 / 2)
ref_circuit.append(U2Gate(0, pi), [qr[0]])
ref_circuit.append(U1Gate(-pi / 4), [qr[0]])
ref_circuit.append(U1Gate(pi), [qr[0]])
ref_circuit.append(U1Gate(pi / 4), [qr[0]])
ref_circuit.append(U3Gate(0.5, 0, 0), [qr[0]])
ref_circuit.append(U1Gate(0.3), [qr[0]])
ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [qr[0]])
ref_circuit.measure(qr[0], cr[0])
ref_circuit.append(U3Gate(pi, 0, pi), [qr[0]]).c_if(cr, 1)
ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [qr[0]]).c_if(cr, 1)
ref_circuit.append(U1Gate(pi), [qr[0]]).c_if(cr, 1)
ref_dag = circuit_to_dag(ref_circuit)
self.assertEqual(unrolled_dag, ref_dag)
def test_unroll_no_basis(self):
"""Test when a given gate has no decompositions."""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr)
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, [])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, [])
with self.assertRaises(QiskitError):
pass_.run(dag)
def test_unroll_all_instructions(self):
"""Test unrolling a circuit containing all standard instructions."""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.crx(0.5, qr[1], qr[2])
circuit.cry(0.5, qr[1], qr[2])
circuit.ccx(qr[0], qr[1], qr[2])
circuit.ch(qr[0], qr[2])
circuit.crz(0.5, qr[1], qr[2])
circuit.cswap(qr[1], qr[0], qr[2])
circuit.append(CU1Gate(0.1), [qr[0], qr[2]])
circuit.append(CU3Gate(0.2, 0.1, 0.0), [qr[1], qr[2]])
circuit.cx(qr[1], qr[0])
circuit.cy(qr[1], qr[2])
circuit.cz(qr[2], qr[0])
circuit.h(qr[1])
circuit.i(qr[0])
circuit.rx(0.1, qr[0])
circuit.ry(0.2, qr[1])
circuit.rz(0.3, qr[2])
circuit.rzz(0.6, qr[1], qr[0])
circuit.s(qr[0])
circuit.sdg(qr[1])
circuit.swap(qr[1], qr[2])
circuit.t(qr[2])
circuit.tdg(qr[0])
circuit.append(U1Gate(0.1), [qr[1]])
circuit.append(U2Gate(0.2, -0.1), [qr[0]])
circuit.append(U3Gate(0.3, 0.0, -0.1), [qr[2]])
circuit.x(qr[2])
circuit.y(qr[1])
circuit.z(qr[0])
# circuit.snapshot('0')
# circuit.measure(qr, cr)
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, ["u3", "cx", "id"])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, ["u3", "cx", "id"])
unrolled_dag = pass_.run(dag)
ref_circuit = QuantumCircuit(qr, cr)
ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(-0.25, 0, 0), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0.25, -pi / 2, 0), [qr[2]])
ref_circuit.append(U3Gate(0.25, 0, 0), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(-0.25, 0, 0), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[1]])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.cx(qr[0], qr[1])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[0]])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[1]])
ref_circuit.cx(qr[0], qr[1])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[2]])
ref_circuit.append(U3Gate(0, 0, 0.25), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, -0.25), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.cx(qr[2], qr[0])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[0]])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[0]])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[1]])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(0, 0, 0.05), [qr[1]])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.cx(qr[2], qr[0])
ref_circuit.append(U3Gate(0, 0, 0.05), [qr[0]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, -0.05), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, 0.05), [qr[2]])
ref_circuit.append(U3Gate(0, 0, -0.05), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(-0.1, 0, -0.05), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[0]])
ref_circuit.append(U3Gate(0.1, 0.1, 0), [qr[2]])
ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[1]])
ref_circuit.append(U3Gate(0.2, 0, 0), [qr[1]])
ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]])
ref_circuit.cx(qr[2], qr[0])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[0]])
ref_circuit.i(qr[0])
ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [qr[0]])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(0, 0, 0.6), [qr[0]])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[0]])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[0]])
ref_circuit.append(U3Gate(pi / 2, 0.2, -0.1), [qr[0]])
ref_circuit.append(U3Gate(0, 0, pi), [qr[0]])
ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[1]])
ref_circuit.append(U3Gate(0, 0, 0.3), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.cx(qr[2], qr[1])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, 0.1), [qr[1]])
ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [qr[1]])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.append(U3Gate(0.3, 0.0, -0.1), [qr[2]])
ref_circuit.append(U3Gate(pi, 0, pi), [qr[2]])
# ref_circuit.snapshot('0')
# ref_circuit.measure(qr, cr)
# ref_dag = circuit_to_dag(ref_circuit)
self.assertTrue(Operator(dag_to_circuit(unrolled_dag)).equiv(ref_circuit))
def test_simple_unroll_parameterized_without_expressions(self):
"""Verify unrolling parameterized gates without expressions."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.rz(theta, qr[0])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(std_eqlib, ["u1", "cx"])
dag = pass_.run(dag)
unrolled_dag = BasisTranslator(std_eqlib, ["u1", "cx"]).run(dag)
expected = QuantumCircuit(qr, global_phase=-theta / 2)
expected.append(U1Gate(theta), [qr[0]])
self.assertEqual(circuit_to_dag(expected), unrolled_dag)
def test_simple_unroll_parameterized_with_expressions(self):
"""Verify unrolling parameterized gates with expressions."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
qc.rz(sum_, qr[0])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(std_eqlib, ["p", "cx"])
dag = pass_.run(dag)
unrolled_dag = BasisTranslator(std_eqlib, ["p", "cx"]).run(dag)
expected = QuantumCircuit(qr, global_phase=-sum_ / 2)
expected.p(sum_, qr[0])
self.assertEqual(circuit_to_dag(expected), unrolled_dag)
def test_definition_unroll_parameterized(self):
"""Verify that unrolling complex gates with parameters does not raise."""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.cp(theta, qr[1], qr[0])
qc.cp(theta * theta, qr[0], qr[1])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(std_eqlib, ["p", "cx"])
dag = pass_.run(dag)
out_dag = BasisTranslator(std_eqlib, ["p", "cx"]).run(dag)
self.assertEqual(out_dag.count_ops(), {"p": 6, "cx": 4})
def test_unrolling_parameterized_composite_gates(self):
"""Verify unrolling circuits with parameterized composite gates."""
mock_sel = EquivalenceLibrary(base=std_eqlib)
qr1 = QuantumRegister(2)
subqc = QuantumCircuit(qr1)
theta = Parameter("theta")
subqc.rz(theta, qr1[0])
subqc.cx(qr1[0], qr1[1])
subqc.rz(theta, qr1[1])
# Expanding across register with shared parameter
qr2 = QuantumRegister(4)
qc = QuantumCircuit(qr2)
sub_instr = circuit_to_instruction(subqc, equivalence_library=mock_sel)
qc.append(sub_instr, [qr2[0], qr2[1]])
qc.append(sub_instr, [qr2[2], qr2[3]])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(mock_sel, ["p", "cx"])
dag = pass_.run(dag)
out_dag = BasisTranslator(mock_sel, ["p", "cx"]).run(dag)
# Pick up -1 * theta / 2 global phase four twice (once for each RZ -> P
# in each of the two sub_instr instructions).
expected = QuantumCircuit(qr2, global_phase=-1 * 4 * theta / 2.0)
expected.p(theta, qr2[0])
expected.p(theta, qr2[2])
expected.cx(qr2[0], qr2[1])
expected.cx(qr2[2], qr2[3])
expected.p(theta, qr2[1])
expected.p(theta, qr2[3])
self.assertEqual(circuit_to_dag(expected), out_dag)
# Expanding across register with shared parameter
qc = QuantumCircuit(qr2)
phi = Parameter("phi")
gamma = Parameter("gamma")
sub_instr = circuit_to_instruction(subqc, {theta: phi}, mock_sel)
qc.append(sub_instr, [qr2[0], qr2[1]])
sub_instr = circuit_to_instruction(subqc, {theta: gamma}, mock_sel)
qc.append(sub_instr, [qr2[2], qr2[3]])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(mock_sel, ["p", "cx"])
dag = pass_.run(dag)
out_dag = BasisTranslator(mock_sel, ["p", "cx"]).run(dag)
expected = QuantumCircuit(qr2, global_phase=-1 * (2 * phi + 2 * gamma) / 2.0)
expected.p(phi, qr2[0])
expected.p(gamma, qr2[2])
expected.cx(qr2[0], qr2[1])
expected.cx(qr2[2], qr2[3])
expected.p(phi, qr2[1])
expected.p(gamma, qr2[3])
self.assertEqual(circuit_to_dag(expected), out_dag)
class TestBasisExamples(QiskitTestCase):
"""Test example circuits targeting example bases over the StandardEquivalenceLibrary."""
def test_cx_bell_to_cz(self):
"""Verify we can translate a CX bell circuit to CZ,RX,RZ."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["cz", "rx", "rz"]).run(in_dag)
self.assertTrue(set(out_dag.count_ops()).issubset(["cz", "rx", "rz"]))
self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag)))
def test_cx_bell_to_iswap(self):
"""Verify we can translate a CX bell to iSwap,U3."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["iswap", "u"]).run(in_dag)
self.assertTrue(set(out_dag.count_ops()).issubset(["iswap", "u"]))
self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag)))
def test_cx_bell_to_ecr(self):
"""Verify we can translate a CX bell to ECR,U."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["ecr", "u"]).run(in_dag)
# ┌────────────┐ ┌─────────────┐┌──────┐┌──────────┐
# q_0: ───┤ U(π/2,0,π) ├───┤ U(0,0,-π/2) ├┤0 ├┤ U(π,0,π) ├
# ┌──┴────────────┴──┐└─────────────┘│ Ecr │└──────────┘
# q_1: ┤ U(-π/2,-π/2,π/2) ├───────────────┤1 ├────────────
# └──────────────────┘ └──────┘
qr = QuantumRegister(2, "q")
expected = QuantumCircuit(2)
expected.u(pi / 2, 0, pi, qr[0])
expected.u(0, 0, -pi / 2, qr[0])
expected.u(-pi / 2, -pi / 2, pi / 2, qr[1])
expected.ecr(0, 1)
expected.u(pi, 0, pi, qr[0])
expected_dag = circuit_to_dag(expected)
self.assertEqual(out_dag, expected_dag)
def test_cx_bell_to_cp(self):
"""Verify we can translate a CX bell to CP,U."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["cp", "u"]).run(in_dag)
self.assertTrue(set(out_dag.count_ops()).issubset(["cp", "u"]))
self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag)))
qr = QuantumRegister(2, "q")
expected = QuantumCircuit(qr)
expected.u(pi / 2, 0, pi, 0)
expected.u(pi / 2, 0, pi, 1)
expected.cp(pi, 0, 1)
expected.u(pi / 2, 0, pi, 1)
expected_dag = circuit_to_dag(expected)
self.assertEqual(out_dag, expected_dag)
def test_cx_bell_to_crz(self):
"""Verify we can translate a CX bell to CRZ,U."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["crz", "u"]).run(in_dag)
self.assertTrue(set(out_dag.count_ops()).issubset(["crz", "u"]))
self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag)))
qr = QuantumRegister(2, "q")
expected = QuantumCircuit(qr)
expected.u(pi / 2, 0, pi, 0)
expected.u(0, 0, pi / 2, 0)
expected.u(pi / 2, 0, pi, 1)
expected.crz(pi, 0, 1)
expected.u(pi / 2, 0, pi, 1)
expected_dag = circuit_to_dag(expected)
self.assertEqual(out_dag, expected_dag)
def test_global_phase(self):
"""Verify global phase preserved in basis translation"""
circ = QuantumCircuit(1)
gate_angle = pi / 5
circ_angle = pi / 3
circ.rz(gate_angle, 0)
circ.global_phase = circ_angle
in_dag = circuit_to_dag(circ)
out_dag = BasisTranslator(std_eqlib, ["p"]).run(in_dag)
qr = QuantumRegister(1, "q")
expected = QuantumCircuit(qr)
expected.p(gate_angle, qr)
expected.global_phase = circ_angle - gate_angle / 2
expected_dag = circuit_to_dag(expected)
self.assertEqual(out_dag, expected_dag)
self.assertAlmostEqual(
float(out_dag.global_phase), float(expected_dag.global_phase), places=14
)
self.assertEqual(Operator(dag_to_circuit(out_dag)), Operator(expected))
def test_condition_set_substitute_node(self):
"""Verify condition is set in BasisTranslator on substitute_node"""
# ┌───┐ ┌───┐
# q_0: ┤ H ├──■──────┤ H ├─
# └───┘┌─┴─┐┌─┐ └─╥─┘
# q_1: ─────┤ X ├┤M├───╫───
# └───┘└╥┘┌──╨──┐
# c: 2/═══════════╩═╡ 0x1 ╞
# 1 └─────┘
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circ = QuantumCircuit(qr, cr)
circ.h(0)
circ.cx(0, 1)
circ.measure(1, 1)
circ.h(0).c_if(cr, 1)
circ_transpiled = transpile(circ, optimization_level=3, basis_gates=["cx", "id", "u"])
# ┌────────────┐ ┌────────────┐
# q_0: ┤ U(π/2,0,π) ├──■─────┤ U(π/2,0,π) ├
# └────────────┘┌─┴─┐┌─┐└─────╥──────┘
# q_1: ──────────────┤ X ├┤M├──────╫───────
# └───┘└╥┘ ┌──╨──┐
# c: 2/════════════════════╩════╡ 0x1 ╞════
# 1 └─────┘
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
expected = QuantumCircuit(qr, cr)
expected.u(pi / 2, 0, pi, 0)
expected.cx(0, 1)
expected.measure(1, 1)
expected.u(pi / 2, 0, pi, 0).c_if(cr, 1)
self.assertEqual(circ_transpiled, expected)
def test_skip_target_basis_equivalences_1(self):
"""Test that BasisTranslator skips gates in the target_basis - #6085"""
circ = QuantumCircuit()
qasm_file = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"qasm",
"TestBasisTranslator_skip_target.qasm",
)
circ = circ.from_qasm_file(qasm_file)
circ_transpiled = transpile(
circ,
basis_gates=["id", "rz", "sx", "x", "cx"],
seed_transpiler=42,
)
self.assertEqual(circ_transpiled.count_ops(), {"cx": 91, "rz": 66, "sx": 22})
class TestBasisTranslatorWithTarget(QiskitTestCase):
"""Test the basis translator when running with a Target."""
def setUp(self):
super().setUp()
self.target = Target()
# U gate in qubit 0.
self.theta = Parameter("theta")
self.phi = Parameter("phi")
self.lam = Parameter("lambda")
u_props = {
(0,): InstructionProperties(duration=5.23e-8, error=0.00038115),
}
self.target.add_instruction(UGate(self.theta, self.phi, self.lam), u_props)
# Rz gate in qubit 1.
rz_props = {
(1,): InstructionProperties(duration=0.0, error=0),
}
self.target.add_instruction(RZGate(self.phi), rz_props)
# X gate in qubit 1.
x_props = {
(1,): InstructionProperties(
duration=3.5555555555555554e-08, error=0.00020056469709026198
),
}
self.target.add_instruction(XGate(), x_props)
# SX gate in qubit 1.
sx_props = {
(1,): InstructionProperties(
duration=3.5555555555555554e-08, error=0.00020056469709026198
),
}
self.target.add_instruction(SXGate(), sx_props)
cx_props = {
(0, 1): InstructionProperties(duration=5.23e-7, error=0.00098115),
(1, 0): InstructionProperties(duration=4.52e-7, error=0.00132115),
}
self.target.add_instruction(CXGate(), cx_props)
def test_2q_with_non_global_1q(self):
"""Test translation works with a 2q gate on an non-global 1q basis."""
qc = QuantumCircuit(2)
qc.cz(0, 1)
bt_pass = BasisTranslator(std_eqlib, target_basis=None, target=self.target)
output = bt_pass(qc)
# We need a second run of BasisTranslator to correct gates outside of
# the target basis. This is a known isssue, see:
# https://qiskit.org/documentation/release_notes.html#release-notes-0-19-0-known-issues
output = bt_pass(output)
expected = QuantumCircuit(2)
expected.rz(pi, 1)
expected.sx(1)
expected.rz(3 * pi / 2, 1)
expected.sx(1)
expected.rz(3 * pi, 1)
expected.cx(0, 1)
expected.rz(pi, 1)
expected.sx(1)
expected.rz(3 * pi / 2, 1)
expected.sx(1)
expected.rz(3 * pi, 1)
self.assertEqual(output, expected)
|
https://github.com/qiskit-community/qiskit-dell-runtime
|
qiskit-community
|
# 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.
# Copyright 2021 Dell (www.dell.com)
#
# 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 unittest
from qiskit import QuantumCircuit, execute, transpile
from dell_runtime import BackendProvider
from qiskit.providers import JobStatus
from time import sleep
class ProviderTest(unittest.TestCase):
def test_job_submission(self):
provider = BackendProvider()
self.assertIsNotNone(provider)
backend = provider.get_backend(name="aer_simulator")
self.assertIsNotNone(backend)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
job = backend.run(qc, shots=1)
self.assertIsNotNone(job)
# self.assertNotEqual(JobStatus.DONE, job.status())
count = 0
# 5 second
max = 50
while count < max and job.status() != JobStatus.DONE:
count += 1
sleep(0.1)
self.assertEqual(JobStatus.DONE, job.status())
job.result()
def test_execute(self):
provider = BackendProvider()
self.assertIsNotNone(provider)
backend = provider.get_backend(name="aer_simulator")
self.assertIsNotNone(backend)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
job = execute(qc, backend, shots=2)
self.assertIsNotNone(job)
count = 0
# 5 second
max = 50
while count < max and job.status() != JobStatus.DONE:
count += 1
sleep(0.1)
self.assertEqual(JobStatus.DONE, job.status())
def test_get_counts(self):
provider = BackendProvider()
self.assertIsNotNone(provider)
backend = provider.get_backend(name="aer_simulator")
self.assertIsNotNone(backend)
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.measure_all()
# Transpile for simulator
circ = transpile(circ, backend)
# Run and get counts
result = backend.run(circ).result()
counts = result.get_counts(circ)
total = counts.get('11') + counts.get('00')
self.assertEqual(total, 1024)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""The n-local circuit class."""
from __future__ import annotations
import typing
from collections.abc import Callable, Mapping, Sequence
from itertools import combinations
import numpy
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.circuit.quantumregister import QuantumRegister
from qiskit.circuit import Instruction, Parameter, ParameterVector, ParameterExpression
from qiskit.exceptions import QiskitError
from ..blueprintcircuit import BlueprintCircuit
if typing.TYPE_CHECKING:
import qiskit # pylint: disable=cyclic-import
class NLocal(BlueprintCircuit):
"""The n-local circuit class.
The structure of the n-local circuit are alternating rotation and entanglement layers.
In both layers, parameterized circuit-blocks act on the circuit in a defined way.
In the rotation layer, the blocks are applied stacked on top of each other, while in the
entanglement layer according to the ``entanglement`` strategy.
The circuit blocks can have arbitrary sizes (smaller equal to the number of qubits in the
circuit). Each layer is repeated ``reps`` times, and by default a final rotation layer is
appended.
For instance, a rotation block on 2 qubits and an entanglement block on 4 qubits using
``'linear'`` entanglement yields the following circuit.
.. parsed-literal::
┌──────┐ ░ ┌──────┐ ░ ┌──────┐
┤0 ├─░─┤0 ├──────────────── ... ─░─┤0 ├
│ Rot │ ░ │ │┌──────┐ ░ │ Rot │
┤1 ├─░─┤1 ├┤0 ├──────── ... ─░─┤1 ├
├──────┤ ░ │ Ent ││ │┌──────┐ ░ ├──────┤
┤0 ├─░─┤2 ├┤1 ├┤0 ├ ... ─░─┤0 ├
│ Rot │ ░ │ ││ Ent ││ │ ░ │ Rot │
┤1 ├─░─┤3 ├┤2 ├┤1 ├ ... ─░─┤1 ├
├──────┤ ░ └──────┘│ ││ Ent │ ░ ├──────┤
┤0 ├─░─────────┤3 ├┤2 ├ ... ─░─┤0 ├
│ Rot │ ░ └──────┘│ │ ░ │ Rot │
┤1 ├─░─────────────────┤3 ├ ... ─░─┤1 ├
└──────┘ ░ └──────┘ ░ └──────┘
| |
+---------------------------------+
repeated reps times
If specified, barriers can be inserted in between every block.
If an initial state object is provided, it is added in front of the NLocal.
"""
def __init__(
self,
num_qubits: int | None = None,
rotation_blocks: QuantumCircuit
| list[QuantumCircuit]
| qiskit.circuit.Instruction
| list[qiskit.circuit.Instruction]
| None = None,
entanglement_blocks: QuantumCircuit
| list[QuantumCircuit]
| qiskit.circuit.Instruction
| list[qiskit.circuit.Instruction]
| None = None,
entanglement: list[int] | list[list[int]] | None = None,
reps: int = 1,
insert_barriers: bool = False,
parameter_prefix: str = "θ",
overwrite_block_parameters: bool | list[list[Parameter]] = True,
skip_final_rotation_layer: bool = False,
skip_unentangled_qubits: bool = False,
initial_state: QuantumCircuit | None = None,
name: str | None = "nlocal",
flatten: bool | None = None,
) -> None:
"""
Args:
num_qubits: The number of qubits of the circuit.
rotation_blocks: The blocks used in the rotation layers. If multiple are passed,
these will be applied one after another (like new sub-layers).
entanglement_blocks: The blocks used in the entanglement layers. If multiple are passed,
these will be applied one after another. To use different entanglements for
the sub-layers, see :meth:`get_entangler_map`.
entanglement: The indices specifying on which qubits the input blocks act. If ``None``, the
entanglement blocks are applied at the top of the circuit.
reps: Specifies how often the rotation blocks and entanglement blocks are repeated.
insert_barriers: If ``True``, barriers are inserted in between each layer. If ``False``,
no barriers are inserted.
parameter_prefix: The prefix used if default parameters are generated.
overwrite_block_parameters: If the parameters in the added blocks should be overwritten.
If ``False``, the parameters in the blocks are not changed.
skip_final_rotation_layer: Whether a final rotation layer is added to the circuit.
skip_unentangled_qubits: If ``True``, the rotation gates act only on qubits that
are entangled. If ``False``, the rotation gates act on all qubits.
initial_state: A :class:`.QuantumCircuit` object which can be used to describe an initial
state prepended to the NLocal circuit.
name: The name of the circuit.
flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple
layers of gate objects. By default currently the contents of
the output circuit will be wrapped in nested objects for
cleaner visualization. However, if you're using this circuit
for anything besides visualization its **strongly** recommended
to set this flag to ``True`` to avoid a large performance
overhead for parameter binding.
Raises:
ValueError: If ``reps`` parameter is less than or equal to 0.
TypeError: If ``reps`` parameter is not an int value.
"""
super().__init__(name=name)
self._num_qubits: int | None = None
self._insert_barriers = insert_barriers
self._reps = reps
self._entanglement_blocks: list[QuantumCircuit] = []
self._rotation_blocks: list[QuantumCircuit] = []
self._prepended_blocks: list[QuantumCircuit] = []
self._prepended_entanglement: list[list[list[int]] | str] = []
self._appended_blocks: list[QuantumCircuit] = []
self._appended_entanglement: list[list[list[int]] | str] = []
self._entanglement = None
self._entangler_maps = None
self._ordered_parameters: ParameterVector | list[Parameter] = ParameterVector(
name=parameter_prefix
)
self._overwrite_block_parameters = overwrite_block_parameters
self._skip_final_rotation_layer = skip_final_rotation_layer
self._skip_unentangled_qubits = skip_unentangled_qubits
self._initial_state: QuantumCircuit | None = None
self._initial_state_circuit: QuantumCircuit | None = None
self._bounds: list[tuple[float | None, float | None]] | None = None
self._flatten = flatten
if int(reps) != reps:
raise TypeError("The value of reps should be int")
if reps < 0:
raise ValueError("The value of reps should be larger than or equal to 0")
if num_qubits is not None:
self.num_qubits = num_qubits
if entanglement_blocks is not None:
self.entanglement_blocks = entanglement_blocks
if rotation_blocks is not None:
self.rotation_blocks = rotation_blocks
if entanglement is not None:
self.entanglement = entanglement
if initial_state is not None:
self.initial_state = initial_state
@property
def num_qubits(self) -> int:
"""Returns the number of qubits in this circuit.
Returns:
The number of qubits.
"""
return self._num_qubits if self._num_qubits is not None else 0
@num_qubits.setter
def num_qubits(self, num_qubits: int) -> None:
"""Set the number of qubits for the n-local circuit.
Args:
The new number of qubits.
"""
if self._num_qubits != num_qubits:
# invalidate the circuit
self._invalidate()
self._num_qubits = num_qubits
self.qregs = [QuantumRegister(num_qubits, name="q")]
@property
def flatten(self) -> bool:
"""Returns whether the circuit is wrapped in nested gates/instructions or flattened."""
return bool(self._flatten)
@flatten.setter
def flatten(self, flatten: bool) -> None:
self._invalidate()
self._flatten = flatten
def _convert_to_block(self, layer: typing.Any) -> QuantumCircuit:
"""Try to convert ``layer`` to a QuantumCircuit.
Args:
layer: The object to be converted to an NLocal block / Instruction.
Returns:
The layer converted to a circuit.
Raises:
TypeError: If the input cannot be converted to a circuit.
"""
if isinstance(layer, QuantumCircuit):
return layer
if isinstance(layer, Instruction):
circuit = QuantumCircuit(layer.num_qubits)
circuit.append(layer, list(range(layer.num_qubits)))
return circuit
try:
circuit = QuantumCircuit(layer.num_qubits)
circuit.append(layer.to_instruction(), list(range(layer.num_qubits)))
return circuit
except AttributeError:
pass
raise TypeError(f"Adding a {type(layer)} to an NLocal is not supported.")
@property
def rotation_blocks(self) -> list[QuantumCircuit]:
"""The blocks in the rotation layers.
Returns:
The blocks in the rotation layers.
"""
return self._rotation_blocks
@rotation_blocks.setter
def rotation_blocks(
self, blocks: QuantumCircuit | list[QuantumCircuit] | Instruction | list[Instruction]
) -> None:
"""Set the blocks in the rotation layers.
Args:
blocks: The new blocks for the rotation layers.
"""
# cannot check for the attribute ``'__len__'`` because a circuit also has this attribute
if not isinstance(blocks, (list, numpy.ndarray)):
blocks = [blocks]
self._invalidate()
self._rotation_blocks = [self._convert_to_block(block) for block in blocks]
@property
def entanglement_blocks(self) -> list[QuantumCircuit]:
"""The blocks in the entanglement layers.
Returns:
The blocks in the entanglement layers.
"""
return self._entanglement_blocks
@entanglement_blocks.setter
def entanglement_blocks(
self, blocks: QuantumCircuit | list[QuantumCircuit] | Instruction | list[Instruction]
) -> None:
"""Set the blocks in the entanglement layers.
Args:
blocks: The new blocks for the entanglement layers.
"""
# cannot check for the attribute ``'__len__'`` because a circuit also has this attribute
if not isinstance(blocks, (list, numpy.ndarray)):
blocks = [blocks]
self._invalidate()
self._entanglement_blocks = [self._convert_to_block(block) for block in blocks]
@property
def entanglement(
self,
) -> str | list[str] | list[list[str]] | list[int] | list[list[int]] | list[
list[list[int]]
] | list[list[list[list[int]]]] | Callable[[int], str] | Callable[[int], list[list[int]]]:
"""Get the entanglement strategy.
Returns:
The entanglement strategy, see :meth:`get_entangler_map` for more detail on how the
format is interpreted.
"""
return self._entanglement
@entanglement.setter
def entanglement(
self,
entanglement: str
| list[str]
| list[list[str]]
| list[int]
| list[list[int]]
| list[list[list[int]]]
| list[list[list[list[int]]]]
| Callable[[int], str]
| Callable[[int], list[list[int]]]
| None,
) -> None:
"""Set the entanglement strategy.
Args:
entanglement: The entanglement strategy. See :meth:`get_entangler_map` for more detail
on the supported formats.
"""
self._invalidate()
self._entanglement = entanglement
@property
def num_layers(self) -> int:
"""Return the number of layers in the n-local circuit.
Returns:
The number of layers in the circuit.
"""
return 2 * self._reps + int(not self._skip_final_rotation_layer)
def _check_configuration(self, raise_on_failure: bool = True) -> bool:
"""Check if the configuration of the NLocal class is valid.
Args:
raise_on_failure: Whether to raise on failure.
Returns:
True, if the configuration is valid and the circuit can be constructed. Otherwise
an ValueError is raised.
Raises:
ValueError: If the blocks are not set.
ValueError: If the number of repetitions is not set.
ValueError: If the qubit indices are not set.
ValueError: If the number of qubit indices does not match the number of blocks.
ValueError: If an index in the repetitions list exceeds the number of blocks.
ValueError: If the number of repetitions does not match the number of block-wise
parameters.
ValueError: If a specified qubit index is larger than the (manually set) number of
qubits.
"""
valid = True
if self.num_qubits is None:
valid = False
if raise_on_failure:
raise ValueError("No number of qubits specified.")
# check no needed parameters are None
if self.entanglement_blocks is None and self.rotation_blocks is None:
valid = False
if raise_on_failure:
raise ValueError("The blocks are not set.")
return valid
@property
def ordered_parameters(self) -> list[Parameter]:
"""The parameters used in the underlying circuit.
This includes float values and duplicates.
Examples:
>>> # prepare circuit ...
>>> print(nlocal)
┌───────┐┌──────────┐┌──────────┐┌──────────┐
q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├
└───────┘└──────────┘└──────────┘└──────────┘
>>> nlocal.parameters
{Parameter(θ[1]), Parameter(θ[3])}
>>> nlocal.ordered_parameters
[1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])]
Returns:
The parameters objects used in the circuit.
"""
if isinstance(self._ordered_parameters, ParameterVector):
self._ordered_parameters.resize(self.num_parameters_settable)
return list(self._ordered_parameters)
return self._ordered_parameters
@ordered_parameters.setter
def ordered_parameters(self, parameters: ParameterVector | list[Parameter]) -> None:
"""Set the parameters used in the underlying circuit.
Args:
The parameters to be used in the underlying circuit.
Raises:
ValueError: If the length of ordered parameters does not match the number of
parameters in the circuit and they are not a ``ParameterVector`` (which could
be resized to fit the number of parameters).
"""
if (
not isinstance(parameters, ParameterVector)
and len(parameters) != self.num_parameters_settable
):
raise ValueError(
"The length of ordered parameters must be equal to the number of "
"settable parameters in the circuit ({}), but is {}".format(
self.num_parameters_settable, len(parameters)
)
)
self._ordered_parameters = parameters
self._invalidate()
@property
def insert_barriers(self) -> bool:
"""If barriers are inserted in between the layers or not.
Returns:
``True``, if barriers are inserted in between the layers, ``False`` if not.
"""
return self._insert_barriers
@insert_barriers.setter
def insert_barriers(self, insert_barriers: bool) -> None:
"""Specify whether barriers should be inserted in between the layers or not.
Args:
insert_barriers: If True, barriers are inserted, if False not.
"""
# if insert_barriers changes, we have to invalidate the circuit definition,
# if it is the same as before we can leave the NLocal instance as it is
if insert_barriers is not self._insert_barriers:
self._invalidate()
self._insert_barriers = insert_barriers
def get_unentangled_qubits(self) -> set[int]:
"""Get the indices of unentangled qubits in a set.
Returns:
The unentangled qubits.
"""
entangled_qubits = set()
for i in range(self._reps):
for j, block in enumerate(self.entanglement_blocks):
entangler_map = self.get_entangler_map(i, j, block.num_qubits)
entangled_qubits.update([idx for indices in entangler_map for idx in indices])
unentangled_qubits = set(range(self.num_qubits)) - entangled_qubits
return unentangled_qubits
@property
def num_parameters_settable(self) -> int:
"""The number of total parameters that can be set to distinct values.
This does not change when the parameters are bound or exchanged for same parameters,
and therefore is different from ``num_parameters`` which counts the number of unique
:class:`~qiskit.circuit.Parameter` objects currently in the circuit.
Returns:
The number of parameters originally available in the circuit.
Note:
This quantity does not require the circuit to be built yet.
"""
num = 0
for i in range(self._reps):
for j, block in enumerate(self.entanglement_blocks):
entangler_map = self.get_entangler_map(i, j, block.num_qubits)
num += len(entangler_map) * len(get_parameters(block))
if self._skip_unentangled_qubits:
unentangled_qubits = self.get_unentangled_qubits()
num_rot = 0
for block in self.rotation_blocks:
block_indices = [
list(range(j * block.num_qubits, (j + 1) * block.num_qubits))
for j in range(self.num_qubits // block.num_qubits)
]
if self._skip_unentangled_qubits:
block_indices = [
indices
for indices in block_indices
if set(indices).isdisjoint(unentangled_qubits)
]
num_rot += len(block_indices) * len(get_parameters(block))
num += num_rot * (self._reps + int(not self._skip_final_rotation_layer))
return num
@property
def reps(self) -> int:
"""The number of times rotation and entanglement block are repeated.
Returns:
The number of repetitions.
"""
return self._reps
@reps.setter
def reps(self, repetitions: int) -> None:
"""Set the repetitions.
If the repetitions are `0`, only one rotation layer with no entanglement
layers is applied (unless ``self.skip_final_rotation_layer`` is set to ``True``).
Args:
repetitions: The new repetitions.
Raises:
ValueError: If reps setter has parameter repetitions < 0.
"""
if repetitions < 0:
raise ValueError("The repetitions should be larger than or equal to 0")
if repetitions != self._reps:
self._invalidate()
self._reps = repetitions
def print_settings(self) -> str:
"""Returns information about the setting.
Returns:
The class name and the attributes/parameters of the instance as ``str``.
"""
ret = f"NLocal: {self.__class__.__name__}\n"
params = ""
for key, value in self.__dict__.items():
if key[0] == "_":
params += f"-- {key[1:]}: {value}\n"
ret += f"{params}"
return ret
@property
def preferred_init_points(self) -> list[float] | None:
"""The initial points for the parameters. Can be stored as initial guess in optimization.
Returns:
The initial values for the parameters, or None, if none have been set.
"""
return None
# pylint: disable=too-many-return-statements
def get_entangler_map(
self, rep_num: int, block_num: int, num_block_qubits: int
) -> Sequence[Sequence[int]]:
"""Get the entangler map for in the repetition ``rep_num`` and the block ``block_num``.
The entangler map for the current block is derived from the value of ``self.entanglement``.
Below the different cases are listed, where ``i`` and ``j`` denote the repetition number
and the block number, respectively, and ``n`` the number of qubits in the block.
=================================== ========================================================
entanglement type entangler map
=================================== ========================================================
``None`` ``[[0, ..., n - 1]]``
``str`` (e.g ``'full'``) the specified connectivity on ``n`` qubits
``List[int]`` [``entanglement``]
``List[List[int]]`` ``entanglement``
``List[List[List[int]]]`` ``entanglement[i]``
``List[List[List[List[int]]]]`` ``entanglement[i][j]``
``List[str]`` the connectivity specified in ``entanglement[i]``
``List[List[str]]`` the connectivity specified in ``entanglement[i][j]``
``Callable[int, str]`` same as ``List[str]``
``Callable[int, List[List[int]]]`` same as ``List[List[List[int]]]``
=================================== ========================================================
Note that all indices are to be taken modulo the length of the array they act on, i.e.
no out-of-bounds index error will be raised but we re-iterate from the beginning of the
list.
Args:
rep_num: The current repetition we are in.
block_num: The block number within the entanglement layers.
num_block_qubits: The number of qubits in the block.
Returns:
The entangler map for the current block in the current repetition.
Raises:
ValueError: If the value of ``entanglement`` could not be cast to a corresponding
entangler map.
"""
i, j, n = rep_num, block_num, num_block_qubits
entanglement = self._entanglement
# entanglement is None
if entanglement is None:
return [list(range(n))]
# entanglement is callable
if callable(entanglement):
entanglement = entanglement(i)
# entanglement is str
if isinstance(entanglement, str):
return get_entangler_map(n, self.num_qubits, entanglement, offset=i)
# check if entanglement is list of something
if not isinstance(entanglement, (tuple, list)):
raise ValueError(f"Invalid value of entanglement: {entanglement}")
num_i = len(entanglement)
# entanglement is List[str]
if all(isinstance(en, str) for en in entanglement):
return get_entangler_map(n, self.num_qubits, entanglement[i % num_i], offset=i)
# entanglement is List[int]
if all(isinstance(en, (int, numpy.integer)) for en in entanglement):
return [[int(en) for en in entanglement]]
# check if entanglement is List[List]
if not all(isinstance(en, (tuple, list)) for en in entanglement):
raise ValueError(f"Invalid value of entanglement: {entanglement}")
num_j = len(entanglement[i % num_i])
# entanglement is List[List[str]]
if all(isinstance(e2, str) for en in entanglement for e2 in en):
return get_entangler_map(
n, self.num_qubits, entanglement[i % num_i][j % num_j], offset=i
)
# entanglement is List[List[int]]
if all(isinstance(e2, (int, numpy.int32, numpy.int64)) for en in entanglement for e2 in en):
for ind, en in enumerate(entanglement):
entanglement[ind] = tuple(map(int, en))
return entanglement
# check if entanglement is List[List[List]]
if not all(isinstance(e2, (tuple, list)) for en in entanglement for e2 in en):
raise ValueError(f"Invalid value of entanglement: {entanglement}")
# entanglement is List[List[List[int]]]
if all(
isinstance(e3, (int, numpy.int32, numpy.int64))
for en in entanglement
for e2 in en
for e3 in e2
):
for en in entanglement:
for ind, e2 in enumerate(en):
en[ind] = tuple(map(int, e2))
return entanglement[i % num_i]
# check if entanglement is List[List[List[List]]]
if not all(isinstance(e3, (tuple, list)) for en in entanglement for e2 in en for e3 in e2):
raise ValueError(f"Invalid value of entanglement: {entanglement}")
# entanglement is List[List[List[List[int]]]]
if all(
isinstance(e4, (int, numpy.int32, numpy.int64))
for en in entanglement
for e2 in en
for e3 in e2
for e4 in e3
):
for en in entanglement:
for e2 in en:
for ind, e3 in enumerate(e2):
e2[ind] = tuple(map(int, e3))
return entanglement[i % num_i][j % num_j]
raise ValueError(f"Invalid value of entanglement: {entanglement}")
@property
def initial_state(self) -> QuantumCircuit:
"""Return the initial state that is added in front of the n-local circuit.
Returns:
The initial state.
"""
return self._initial_state
@initial_state.setter
def initial_state(self, initial_state: QuantumCircuit) -> None:
"""Set the initial state.
Args:
initial_state: The new initial state.
Raises:
ValueError: If the number of qubits has been set before and the initial state
does not match the number of qubits.
"""
self._initial_state = initial_state
self._invalidate()
@property
def parameter_bounds(self) -> list[tuple[float, float]] | None:
"""The parameter bounds for the unbound parameters in the circuit.
Returns:
A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded
parameter in the corresponding direction. If ``None`` is returned, problem is fully
unbounded.
"""
if not self._is_built:
self._build()
return self._bounds
@parameter_bounds.setter
def parameter_bounds(self, bounds: list[tuple[float, float]]) -> None:
"""Set the parameter bounds.
Args:
bounds: The new parameter bounds.
"""
self._bounds = bounds
def add_layer(
self,
other: QuantumCircuit | qiskit.circuit.Instruction,
entanglement: list[int] | str | list[list[int]] | None = None,
front: bool = False,
) -> "NLocal":
"""Append another layer to the NLocal.
Args:
other: The layer to compose, can be another NLocal, an Instruction or Gate,
or a QuantumCircuit.
entanglement: The entanglement or qubit indices.
front: If True, ``other`` is appended to the front, else to the back.
Returns:
self, such that chained composes are possible.
Raises:
TypeError: If `other` is not compatible, i.e. is no Instruction and does not have a
`to_instruction` method.
"""
block = self._convert_to_block(other)
if entanglement is None:
entanglement = [list(range(block.num_qubits))]
elif isinstance(entanglement, list) and not isinstance(entanglement[0], list):
entanglement = [entanglement]
if front:
self._prepended_blocks += [block]
self._prepended_entanglement += [entanglement]
else:
self._appended_blocks += [block]
self._appended_entanglement += [entanglement]
if isinstance(entanglement, list):
num_qubits = 1 + max(max(indices) for indices in entanglement)
if num_qubits > self.num_qubits:
self._invalidate() # rebuild circuit
self.num_qubits = num_qubits
# modify the circuit accordingly
if front is False and self._is_built:
if self._insert_barriers and len(self.data) > 0:
self.barrier()
if isinstance(entanglement, str):
entangler_map: Sequence[Sequence[int]] = get_entangler_map(
block.num_qubits, self.num_qubits, entanglement
)
else:
entangler_map = entanglement
layer = QuantumCircuit(self.num_qubits)
for i in entangler_map:
params = self.ordered_parameters[-len(get_parameters(block)) :]
parameterized_block = self._parameterize_block(block, params=params)
layer.compose(parameterized_block, i, inplace=True)
self.compose(layer, inplace=True)
else:
# cannot prepend a block currently, just rebuild
self._invalidate()
return self
def assign_parameters(
self,
parameters: Mapping[Parameter, ParameterExpression | float]
| Sequence[ParameterExpression | float],
inplace: bool = False,
**kwargs,
) -> QuantumCircuit | None:
"""Assign parameters to the n-local circuit.
This method also supports passing a list instead of a dictionary. If a list
is passed, the list must have the same length as the number of unbound parameters in
the circuit. The parameters are assigned in the order of the parameters in
:meth:`ordered_parameters`.
Returns:
A copy of the NLocal circuit with the specified parameters.
Raises:
AttributeError: If the parameters are given as list and do not match the number
of parameters.
"""
if parameters is None or len(parameters) == 0:
return self
if not self._is_built:
self._build()
return super().assign_parameters(parameters, inplace=inplace, **kwargs)
def _parameterize_block(
self, block, param_iter=None, rep_num=None, block_num=None, indices=None, params=None
):
"""Convert ``block`` to a circuit of correct width and parameterized using the iterator."""
if self._overwrite_block_parameters:
# check if special parameters should be used
# pylint: disable=assignment-from-none
if params is None:
params = self._parameter_generator(rep_num, block_num, indices)
if params is None:
params = [next(param_iter) for _ in range(len(get_parameters(block)))]
update = dict(zip(block.parameters, params))
return block.assign_parameters(update)
return block.copy()
def _build_rotation_layer(self, circuit, param_iter, i):
"""Build a rotation layer."""
# if the unentangled qubits are skipped, compute the set of qubits that are not entangled
if self._skip_unentangled_qubits:
unentangled_qubits = self.get_unentangled_qubits()
# iterate over all rotation blocks
for j, block in enumerate(self.rotation_blocks):
# create a new layer
layer = QuantumCircuit(*self.qregs)
# we apply the rotation gates stacked on top of each other, i.e.
# if we have 4 qubits and a rotation block of width 2, we apply two instances
block_indices = [
list(range(k * block.num_qubits, (k + 1) * block.num_qubits))
for k in range(self.num_qubits // block.num_qubits)
]
# if unentangled qubits should not be acted on, remove all operations that
# touch an unentangled qubit
if self._skip_unentangled_qubits:
block_indices = [
indices
for indices in block_indices
if set(indices).isdisjoint(unentangled_qubits)
]
# apply the operations in the layer
for indices in block_indices:
parameterized_block = self._parameterize_block(block, param_iter, i, j, indices)
layer.compose(parameterized_block, indices, inplace=True)
# add the layer to the circuit
circuit.compose(layer, inplace=True)
def _build_entanglement_layer(self, circuit, param_iter, i):
"""Build an entanglement layer."""
# iterate over all entanglement blocks
for j, block in enumerate(self.entanglement_blocks):
# create a new layer and get the entangler map for this block
layer = QuantumCircuit(*self.qregs)
entangler_map = self.get_entangler_map(i, j, block.num_qubits)
# apply the operations in the layer
for indices in entangler_map:
parameterized_block = self._parameterize_block(block, param_iter, i, j, indices)
layer.compose(parameterized_block, indices, inplace=True)
# add the layer to the circuit
circuit.compose(layer, inplace=True)
def _build_additional_layers(self, circuit, which):
if which == "appended":
blocks = self._appended_blocks
entanglements = self._appended_entanglement
elif which == "prepended":
blocks = reversed(self._prepended_blocks)
entanglements = reversed(self._prepended_entanglement)
else:
raise ValueError("`which` must be either `appended` or `prepended`.")
for block, ent in zip(blocks, entanglements):
layer = QuantumCircuit(*self.qregs)
if isinstance(ent, str):
ent = get_entangler_map(block.num_qubits, self.num_qubits, ent)
for indices in ent:
layer.compose(block, indices, inplace=True)
circuit.compose(layer, inplace=True)
def _build(self) -> None:
"""If not already built, build the circuit."""
if self._is_built:
return
super()._build()
if self.num_qubits == 0:
return
if not self._flatten:
circuit = QuantumCircuit(*self.qregs, name=self.name)
else:
circuit = self
# use the initial state as starting circuit, if it is set
if self.initial_state:
circuit.compose(self.initial_state.copy(), inplace=True)
param_iter = iter(self.ordered_parameters)
# build the prepended layers
self._build_additional_layers(circuit, "prepended")
# main loop to build the entanglement and rotation layers
for i in range(self.reps):
# insert barrier if specified and there is a preceding layer
if self._insert_barriers and (i > 0 or len(self._prepended_blocks) > 0):
circuit.barrier()
# build the rotation layer
self._build_rotation_layer(circuit, param_iter, i)
# barrier in between rotation and entanglement layer
if self._insert_barriers and len(self._rotation_blocks) > 0:
circuit.barrier()
# build the entanglement layer
self._build_entanglement_layer(circuit, param_iter, i)
# add the final rotation layer
if not self._skip_final_rotation_layer:
if self.insert_barriers and self.reps > 0:
circuit.barrier()
self._build_rotation_layer(circuit, param_iter, self.reps)
# add the appended layers
self._build_additional_layers(circuit, "appended")
# cast global phase to float if it has no free parameters
if isinstance(circuit.global_phase, ParameterExpression):
try:
circuit.global_phase = float(circuit.global_phase)
except TypeError:
# expression contains free parameters
pass
if not self._flatten:
try:
block = circuit.to_gate()
except QiskitError:
block = circuit.to_instruction()
self.append(block, self.qubits)
# pylint: disable=unused-argument
def _parameter_generator(self, rep: int, block: int, indices: list[int]) -> Parameter | None:
"""If certain blocks should use certain parameters this method can be overridden."""
return None
def get_parameters(block: QuantumCircuit | Instruction) -> list[Parameter]:
"""Return the list of Parameters objects inside a circuit or instruction.
This is required since, in a standard gate the parameters are not necessarily Parameter
objects (e.g. U3Gate(0.1, 0.2, 0.3).params == [0.1, 0.2, 0.3]) and instructions and
circuits do not have the same interface for parameters.
"""
if isinstance(block, QuantumCircuit):
return list(block.parameters)
else:
return [p for p in block.params if isinstance(p, ParameterExpression)]
def get_entangler_map(
num_block_qubits: int, num_circuit_qubits: int, entanglement: str, offset: int = 0
) -> Sequence[tuple[int, ...]]:
"""Get an entangler map for an arbitrary number of qubits.
Args:
num_block_qubits: The number of qubits of the entangling block.
num_circuit_qubits: The number of qubits of the circuit.
entanglement: The entanglement strategy.
offset: The block offset, can be used if the entanglements differ per block.
See mode ``sca`` for instance.
Returns:
The entangler map using mode ``entanglement`` to scatter a block of ``num_block_qubits``
qubits on ``num_circuit_qubits`` qubits.
Raises:
ValueError: If the entanglement mode ist not supported.
"""
n, m = num_circuit_qubits, num_block_qubits
if m > n:
raise ValueError(
"The number of block qubits must be smaller or equal to the number of "
"qubits in the circuit."
)
if entanglement == "pairwise" and num_block_qubits > 2:
raise ValueError("Pairwise entanglement is not defined for blocks with more than 2 qubits.")
if entanglement == "full":
return list(combinations(list(range(n)), m))
elif entanglement == "reverse_linear":
# reverse linear connectivity. In the case of m=2 and the entanglement_block='cx'
# then it's equivalent to 'full' entanglement
reverse = [tuple(range(n - i - m, n - i)) for i in range(n - m + 1)]
return reverse
elif entanglement in ["linear", "circular", "sca", "pairwise"]:
linear = [tuple(range(i, i + m)) for i in range(n - m + 1)]
# if the number of block qubits is 1, we don't have to add the 'circular' part
if entanglement == "linear" or m == 1:
return linear
if entanglement == "pairwise":
return linear[::2] + linear[1::2]
# circular equals linear plus top-bottom entanglement (if there's space for it)
if n > m:
circular = [tuple(range(n - m + 1, n)) + (0,)] + linear
else:
circular = linear
if entanglement == "circular":
return circular
# sca is circular plus shift and reverse
shifted = circular[-offset:] + circular[:-offset]
if offset % 2 == 1: # if odd, reverse the qubit indices
sca = [ind[::-1] for ind in shifted]
else:
sca = shifted
return sca
else:
raise ValueError(f"Unsupported entanglement type: {entanglement}")
|
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-aqt-provider
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright Alpine Quantum Technologies GmbH 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Trivial minimization example using a variational quantum eigensolver."""
from typing import Final
import qiskit_algorithms
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import SparsePauliOp
from qiskit_algorithms.minimum_eigensolvers import VQE
from qiskit_algorithms.optimizers import COBYLA
from qiskit_aqt_provider import AQTProvider
from qiskit_aqt_provider.aqt_resource import OfflineSimulatorResource
from qiskit_aqt_provider.primitives import AQTEstimator
RANDOM_SEED: Final = 0
if __name__ == "__main__":
backend = AQTProvider("token").get_backend("offline_simulator_no_noise")
assert isinstance(backend, OfflineSimulatorResource) # noqa: S101
estimator = AQTEstimator(backend)
# fix the random seeds such that the example is reproducible
qiskit_algorithms.utils.algorithm_globals.random_seed = RANDOM_SEED
backend.simulator.options.seed_simulator = RANDOM_SEED
# Hamiltonian: Ising model on two spin 1/2 without external field
J = 1.2
hamiltonian = SparsePauliOp.from_list([("XX", J)])
# Find the ground-state energy with VQE
ansatz = TwoLocal(num_qubits=2, rotation_blocks="ry", entanglement_blocks="rxx", reps=1)
optimizer = COBYLA(maxiter=100, tol=0.01)
vqe = VQE(estimator, ansatz, optimizer)
result = vqe.compute_minimum_eigenvalue(operator=hamiltonian)
assert result.eigenvalue is not None # noqa: S101
print(f"Optimizer run time: {result.optimizer_time:.2f} s")
print("Cost function evaluations:", result.cost_function_evals)
print("Deviation from expected ground-state energy:", abs(result.eigenvalue - (-J)))
|
https://github.com/quantum-kittens/quantum-computing-basics
|
quantum-kittens
|
!pip install qiskit
from IPython.display import clear_output
clear_output()
from qiskit import *
import math
import numpy as np
import random
import itertools
teas = ['black', 'green']
mild_spices = ['cardamom (elaichi)', 'fennel seeds (saunf)', 'star anise', 'bay leaves', 'cloves (laung)', 'cinnamon', 'nutmeg', 'saffron (kesar)', 'vanilla bean/extract', 'holy basil (tulsi)']
zesty_spices = [ 'ginger (adrak)', 'black peppercorns', 'white peppercorns', 'cumin seeds (zeera)', 'allspice', 'carom seeds (ajwain)', 'turmeric (haldi)', 'paprika (lal mirch)']
herbs = ['peppermint', 'lemongrass', 'licorice root', 'chamomile', 'spearmint', 'coriander', 'lavender' ]
misc_flavors = ['orange peel', 'rose petals', 'lemon', 'almond shavings/extract', 'cocoa', 'coconut butter', 'jasmine']
def which_tea():
# creates the Bell state (|01> + |10>)/sqrt(2) to choose between black and green tea
circ = QuantumCircuit(2,2) # create a quantum circuit with 2 qubits and 2 classical bits
circ.h(0) # Hadamard gate on qubit 0
circ.cx(0,1) # controlled x with qubit 0 as control and qubit 1 as target
circ.x(0) # x on qubit 0
circ.measure([0,1],[0,1]) # each qubit is measured, and the total outcome is either 01 or 10
job = qiskit.execute(circ, qiskit.BasicAer.get_backend('qasm_simulator') ) # run on qasm_simulator
result = job.result().get_counts() # result is a dict, with key = classical bit outcomes, value = number of counts
max_res = max(result, key=result.get) # find the result with the highest count
return teas[int(max_res,2)-1] #convert to decimal
def run_QuantumCirc(n): # creates and runs a quantum circuit with a Hadamard operating on each qubit
qr = qiskit.QuantumRegister(n) # create quantum register with n qubits
cr = qiskit.ClassicalRegister(n) # create classical register with n bits
circ = qiskit.QuantumCircuit(qr, cr) # create circuit with the two registers
circ.h(qr) # perform Hadamard on each qubit
circ.measure(qr,cr) # each qubit is measured, and the outcome for one qubit is either 0 or 1
job = qiskit.execute(circ, qiskit.BasicAer.get_backend('qasm_simulator') )
result = job.result().get_counts()
return result
def select_ingredients(category): # runs a quantum circuit to select the number of ingredients in a category
num_choices = len(category)
if math.log(num_choices,2)%int(math.log(num_choices,2)) == 0: # checks whether log(num_choices) to the base 2 is a whole number
n = int(math.log(num_choices,2)) # n = number of qubits
result = run_QuantumCirc(n)
max_res = max(result, key=result.get)
else:
n = int(math.log(num_choices,2))+1 # adds 1 to log(N) to the base 2 to get total number of qubits needed
result = run_QuantumCirc(n)
max_res = max(result, key=result.get)
while(int(max_res,2) > num_choices-1): # find max that is less than num_choices
result.pop(str(max_res))
max_res = max(result, key=result.get)
selections = []
random.shuffle(category) # randomly shuffles the category list
for i in range(int(max_res,2)+1): # int(max_res,2)+1 is in decimal; it's the number of ingredients in the category that you will be using
selections.append(category[i]) # returns the first int(max_res,2)+1 entries in the shuffled list
return selections
def ingredient_compatibilities(final_ingredients): # removes what I feel are flavor incomptibilities. This is solely my opinion. comment out any you don't agree with!
if tea == 'green' and 'cocoa' in final_ingredients:
final_ingredients.remove('cocoa')
if tea == 'black' and 'chamomile' in final_ingredients:
final_ingredients.remove('chamomile')
if tea == 'black' and 'jasmine' in final_ingredients:
final_ingredients.remove('jasmine')
if 'paprika' and 'jasmine' in final_ingredients:
final_ingredients.remove('jasmine')
return final_ingredients
def choose_categories(tea): # chooses which ingredient categories your ingredients will come from, we use simple qubit superposition state |0>+|1>
n = 4 #There are 4 ingredient categories
categories_dict = {'0': select_ingredients(mild_spices), '1': select_ingredients(herbs), '2': select_ingredients(misc_flavors), '3': select_ingredients(zesty_spices)}
max_res = '0000'
final_ingredients = []
while len(final_ingredients) == 0: # to make sure we don't return an empty list
while max_res == '0000': # run it until we get SOME ingredients! No one wants 0 ingredients. That'd be utterly boring.
result = run_QuantumCirc(n)
max_res = max(result, key=result.get)
for ind in range(n):
if max_res[ind] == '1':
final_ingredients.append(categories_dict[str(ind)])
final_ingredients = list(itertools.chain.from_iterable(final_ingredients))
final_ingredients = ingredient_compatibilities(final_ingredients)
return final_ingredients
tea = which_tea()
print(f"""
Your quantum chai is {tea} tea with the following ingredients:
{choose_categories(tea)}
Happy drinking!""")
|
https://github.com/CynthiaRios/quantum_orchestra
|
CynthiaRios
|
#pip install music21
#pip install RISE
from qiskit import QuantumCircuit, execute
from qiskit import Aer
from qiskit.visualization import plot_histogram
from qiskit import IBMQ
import qiskit.tools.jupyter
%qiskit_job_watcher
from IPython.display import Audio
import wave
import numpy as np
#start for the project
# import
from music21 import *
#minimum user input will just be for them to fill out the create quantum circuit function inthe backend
n = 1 #insert number of qubits
def CreateQuantumCircuit(n):
cct = QuantumCircuit(n,1)
cct.h(0)
return cct
cct = CreateQuantumCircuit(n)
cct.draw(output="mpl")
def Measurement(cct):
backend = Aer.get_backend('statevector_simulator')
sv = execute(cct, backend).result().get_statevector()
return sv
sv = Measurement(cct)
print(sv)
#from qiskit.visualization import plot_state_city
#plot_state_city(sv)
def MusicalTransformation():
note = 'a';
return note
tune_array = ['c','d'] #collect notes
#for i in range(n+1):
# note = MusicalTransformation()
# tune_array.append(note)
print(tune_array)
def PlayPianoTune(character, song):
if character == 'c':
sound_file = "./Audio/Piano/1-st.wav"
songs.append(sound_file)
if character == 'd':
sound_file = "./Audio/Piano/2-st.wav"
songs.append(sound_file)
if character == 'e':
sound_file = "./Audio/Piano/3-st.wav"
songs.append(sound_file)
if character == 'f':
sound_file = "./Audio/Piano/4-st.wav"
songs.append(sound_file)
if character == 'g':
sound_file = "./Audio/Piano/5-st.wav"
songs.append(sound_file)
def PlayGuitarTune(character, song):
if character == 'c':
sound_file = "./Audio/Guitar/1-ag.wav"
songs.append(sound_file)
if character == 'd':
sound_file = "./Audio/Guitar/2-ag.wav"
songs.append(sound_file)
if character == 'e':
sound_file = "./Audio/Guitar/3-ag.wav"
songs.append(sound_file)
if character == 'f':
sound_file = "./Audio/Guitar/4-ag.wav"
songs.append(sound_file)
if character == 'g':
sound_file = "./Audio/Guitar/5-ag.wav"
songs.append(sound_file)
def PlayBassTune(character, song):
if character == 'c':
sound_file = "./Audio/Bass/1.wav"
songs.append(sound_file)
if character == 'd':
sound_file = "./Audio/Bass/2.wav"
songs.append(sound_file)
if character == 'e':
sound_file = "./Audio/Bass/3.wav"
songs.append(sound_file)
if character == 'f':
sound_file = "./Audio/Bass/4.wav"
songs.append(sound_file)
if character == 'g':
sound_file = "./Audio/Bass/5.wav"
songs.append(sound_file)
def PlayTrumpetTune(character, song):
if character == 'c':
sound_file = "./Audio/Trumpet/1.wav"
songs.append(sound_file)
if character == 'd':
sound_file = "./Audio/Trumpet/2.wav"
songs.append(sound_file)
if character == 'e':
sound_file = "./Audio/Trumpet/3.wav"
songs.append(sound_file)
if character == 'f':
sound_file = "./Audio/Trumpet/4.wav"
songs.append(sound_file)
if character == 'g':
sound_file = "./Audio/Trumpet/5.wav"
songs.append(sound_file)
songs = []
for i in range(n+1):
character = tune_array[i-1]
PlayPianoTune(character, songs)
print(songs)
outfile = "pianosounds.wav"
data= []
for song in songs:
w = wave.open(song, 'rb')
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
output.writeframes(data[0][1])
output.writeframes(data[1][1])
output.close()
songs = []
for i in range(n+1):
character = tune_array[i-1]
PlayGuitarTune(character, songs)
print(songs)
outfile = "guitarsounds.wav"
data= []
for song in songs:
w = wave.open(song, 'rb')
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
output.writeframes(data[0][1])
output.writeframes(data[1][1])
output.close()
songs = []
for i in range(n+1):
character = tune_array[i-1]
PlayTrumpetTune(character, songs)
print(songs)
outfile = "trumpetsounds.wav"
data= []
for song in songs:
w = wave.open(song, 'rb')
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
output.writeframes(data[0][1])
output.writeframes(data[1][1])
output.close()
songs = []
for i in range(n+1):
character = tune_array[i-1]
PlayBassTune(character, songs)
print(songs)
outfile = "basssounds.wav"
data= []
for song in songs:
w = wave.open(song, 'rb')
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
output.writeframes(data[0][1])
output.writeframes(data[1][1])
output.close()
sound_file = "./pianosounds.wav"
Audio(sound_file, autoplay=True)
sound_file = "./guitarsounds.wav"
Audio(sound_file, autoplay=True)
sound_file = "./basssounds.wav"
Audio(sound_file, autoplay=True)
sound_file = "./trumpetsounds.wav"
Audio(sound_file, autoplay=True)
up1 = note.Unpitched()
up1.storedInstrument = instrument.BassDrum()
upUnknownInstrument = note.Unpitched()
up2 = note.Unpitched()
up2.storedInstrument = instrument.Cowbell()
s = stream.Stream()
s.append(up1)
s.append(upUnknownInstrument)
s.append(up2)
s2 = instrument.unbundleInstruments(s)
s3 = instrument.bundleInstruments(s2)
for test in s3:
print(test.storedInstrument)
instrument.ensembleNameBySize(4)
instrument.ensembleNameBySize(1)
instrument.ensembleNameBySize(83)
t1 = instrument.fromString('Clarinet 2 in A')
t1
t1.transposition
t2 = instrument.fromString('Clarinetto 3')
t2
t3 = instrument.fromString('flauto 2')
t3
t4 = instrument.fromString('I <3 music saxofono tenor go beavers')
t4
t5 = instrument.fromString('Bb Clarinet')
t5
t5.transposition
t6 = instrument.fromString('Clarinet in B-flat')
t5.__class__ == t6.__class__
t5.transposition == t6.transposition
t7 = instrument.fromString('B-flat Clarinet.')
t5.__class__ == t7.__class__ and t5.transposition == t7.transposition
t8 = instrument.fromString('Eb Clarinet')
t5.__class__ == t8.__class__
t8.transposition
t9 = instrument.fromString('Klarinette in B.')
t9
t9.transposition
instrument.instrumentFromMidiProgram(0)
instrument.instrumentFromMidiProgram(21)
p1 = converter.parse("tinynotation: 4/4 c4 d e f g a b c' c1")
p2 = converter.parse("tinynotation: 4/4 C#4 D# E# F# G# A# B# c# C#1")
p1.getElementsByClass('Measure')[0].insert(0.0, instrument.Piccolo())
p1.getElementsByClass('Measure')[0].insert(2.0, instrument.AltoSaxophone())
p1.getElementsByClass('Measure')[1].insert(3.0, instrument.Piccolo())
p2.getElementsByClass('Measure')[0].insert(0.0, instrument.Trombone())
p2.getElementsByClass('Measure')[0].insert(3.0, instrument.Piccolo()) # not likely...
p2.getElementsByClass('Measure')[1].insert(1.0, instrument.Trombone())
s = stream.Score()
s.insert(0, p1)
s.insert(0, p2)
s.show('musicxml') #this show on musicscore
s2 = instrument.partitionByInstrument(s)
len(s2.parts)
for p in s2.parts:
unused = p.makeRests(fillGaps=True, inPlace=True)
for p in s2.parts:
p.makeMeasures(inPlace=True)
p.makeTies(inPlace=True)
s2.show('musicxml')
up1 = note.Unpitched()
up1.storedInstrument = instrument.BassDrum()
up2 = note.Unpitched()
up2.storedInstrument = instrument.Cowbell()
s = stream.Stream()
s.append(up1)
s.append(up2)
s2 = instrument.unbundleInstruments(s)
s2.show('musicxml')
instrument1 = 60
instrument2 = 65
instrument3 = 70
instrument4 = 75
instrument1 = converter.parse("tinynotation: 4/4 c4 d e f g a b c' c1")
instrument2 = converter.parse("tinynotation: 4/4 C#4 D# E# F# G# A# B# c# C#1")
instrument3 = converter.parse("tinynotation: 4/4 e f g a b c d e f")
#instrument4 = converter.parse("tinynotation: 4/4 g a b c d e f g a")
note1 = note.Note("C4")
note2 = note.Note("F#4")
note3 = note.Note("F#4")
note4 = note.Note("F#4")
note5 = note.Note("F#4")
note6 = note.Note("F#4")
note7 = note.Note("F#4")
note8 = note.Note("F#4")
note9 = note.Note("F#4")
instrument4 = [note1, note2, note3, note4, note5, note6, note7, note8, note9]
print(instrument4)
stream2 = stream.Stream()
stream2.append(instrument4)
stream2.getElementsByClass('Measure')[0].insert(0.0, instrument.Tuba())
#This creates a stream of a single part
#Add an instrument to the part
instrument1.getElementsByClass('Measure')[0].insert(0.0, instrument.Trumpet())
instrument2.getElementsByClass('Measure')[0].insert(0.0, instrument.EnglishHorn())
instrument3.getElementsByClass('Measure')[0].insert(0.0, instrument.Trombone())
instrument4.getElementsByClass('Measure')[0].insert(0.0, instrument.Tuba())
s = stream.Score()
s.insert(0, instrument1)
s.insert(0, instrument2)
s.insert(0, instrument3)
s.insert(0, instrument4)
s.show()
s.show('midi')
s.show('musicxml') #this show on musicscore
stream1 = stream.Stream()
stream1.addGroupForElements('flute')
stream1.append(midiChordType1)
stream1.append(midiChordType2)
stream1.append(midiChordType3)
stream1.append(midiChordType4)
stream1.show('midi')
stream1.show('musicxml') #this show on musicscore
#c = converter.parse('musicxml')
stream1.show()
midiChordType1 = chord.Chord([instrument1, instrument2, instrument3, instrument4])
midiChordType2 = chord.Chord([55, 60, 65, 70])
midiChordType2.getElementsByClass('Measure')[0].insert(2.0, instrument.Bass())
midiChordType3 = chord.Chord([50, 55, 60, 70])
midiChordType3.getElementsByClass('Measure')[1].insert(3.0, instrument.Guitar())
midiChordType4 = chord.Chord([65, 70, 75, 80])
midiChordType4.getElementsByClass('Measure')[1].insert(3.0, instrument.Trombone())
note1 = note.Note("C4")
note2 = note.Note("F#4")
note3 = note.Note("B-2")
stream1 = stream.Stream()
stream1.append(note1)
stream1.append(note2)
stream1.append(note3)
stream1.show('midi')
note1 = midiChordType
midiChordType1 = chord.Chord([60, 65, 70, 75])
midiChordType2 = chord.Chord([55, 60, 65, 70])
midiChordType3 = chord.Chord([50, 55, 60, 70])
midiChordType4 = chord.Chord([65, 70, 75, 80])
stream1 = stream.Stream()
stream1.append(midiChordType1)
stream1.append(midiChordType2)
stream1.append(midiChordType3)
stream1.append(midiChordType4)
stream1.show('midi')
p1 = converter.parse("tinynotation: 4/4 c4 d e f g a b c' c1")
p2 = converter.parse("tinynotation: 4/4 C#4 D# E# F# G# A# B# c# C#1")
p1.show('midi')
p2.show('midi')
p1.getElementsByClass('Measure')[0].insert(0.0, instrument.Piccolo())
p1.getElementsByClass('Measure')[0].insert(2.0, instrument.AltoSaxophone())
p1.getElementsByClass('Measure')[1].insert(3.0, instrument.Piccolo())
p2.getElementsByClass('Measure')[0].insert(0.0, instrument.Trombone())
p2.getElementsByClass('Measure')[0].insert(3.0, instrument.Piccolo()) # not likely...
p2.getElementsByClass('Measure')[1].insert(1.0, instrument.Trombone())
s.show()
s = corpus.parse('bach/bwv65.2.xml')
|
https://github.com/hkhetawat/QArithmetic
|
hkhetawat
|
# Import the Qiskit SDK
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, Aer
from QArithmetic import add
# Input N
N = 4
a = QuantumRegister(N)
b = QuantumRegister(N+1)
ca = ClassicalRegister(N)
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])
add(qc, a, b, N)
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/AbdulahAmer/PHYS-31415-Summer-2021
|
AbdulahAmer
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
### Creating 3 qubit and 2 classical bits in each separate register
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
teleportation_circuit = QuantumCircuit(qr, crz, crx)
### A third party eve helps to create an entangled state
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a, b)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, a, b):
qc.cx(a, b)
qc.h(a)
teleportation_circuit.barrier()
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
teleportation_circuit.barrier()
measure_and_send(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1)
qc.z(qubit).c_if(crz, 1)
teleportation_circuit.barrier()
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
from qiskit.extensions import Initialize
import math
qc = QuantumCircuit(1)
initial_state = [0,1]
init_gate = Initialize(initial_state)
# qc.append(initialize_qubit, [0])
qr = QuantumRegister(3) # Protocol uses 3 qubits
crz = ClassicalRegister(1) # and 2 classical registers
crx = ClassicalRegister(1)
qc = QuantumCircuit(qr, crz, crx)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
out_vector = execute(qc, backend).result().get_statevector()
plot_bloch_multivector(out_vector)
inverse_init_gate = init_gate.gates_to_uncompute()
qc.append(inverse_init_gate, [2])
qc.draw()
cr_result = ClassicalRegister(1)
qc.add_register(cr_result)
qc.measure(2,2)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1024).result().get_counts()
plot_histogram(counts)
def bob_gates(qc, a, b, c):
qc.cz(a, c)
qc.cx(b, c)
qc = QuantumCircuit(3,1)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
qc.barrier()
# Alice sends classical bits to Bob
bob_gates(qc, 0, 1, 2)
# We undo the initialisation process
qc.append(inverse_init_gate, [2])
# See the results, we only care about the state of qubit 2
qc.measure(2,0)
# View the results:
qc.draw()
from qiskit import IBMQ
IBMQ.save_account('### IMB TOKEN ')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
job_exp = execute(qc, backend=backend, shots=8192)
exp_result = job_exp.result()
exp_measurement_result = exp_result.get_counts(qc)
print(exp_measurement_result)
plot_histogram(exp_measurement_result)
error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \
* 100./ sum(list(exp_measurement_result.values()))
print("The experimental error rate : ", error_rate_percent, "%")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.