repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import IntegerComparator
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
# set problem parameters
n_z = 2
z_max = 2
z_values = np.linspace(-z_max, z_max, 2**n_z)
p_zeros = [0.15, 0.25]
rhos = [0.1, 0.05]
lgd = [1, 2]
K = len(p_zeros)
alpha = 0.05
from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI
u = GCI(n_z, z_max, p_zeros, rhos)
u.draw()
u_measure = u.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(u_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# analyze uncertainty circuit and determine exact solutions
p_z = np.zeros(2**n_z)
p_default = np.zeros(K)
values = []
probabilities = []
num_qubits = u.num_qubits
for i, prob in binary_probabilities.items():
# extract value of Z and corresponding probability
i_normal = int(i[-n_z:], 2)
p_z[i_normal] += prob
# determine overall default probability for k
loss = 0
for k in range(K):
if i[K - k - 1] == "1":
p_default[k] += prob
loss += lgd[k]
values += [loss]
probabilities += [prob]
values = np.array(values)
probabilities = np.array(probabilities)
expected_loss = np.dot(values, probabilities)
losses = np.sort(np.unique(values))
pdf = np.zeros(len(losses))
for i, v in enumerate(losses):
pdf[i] += sum(probabilities[values == v])
cdf = np.cumsum(pdf)
i_var = np.argmax(cdf >= 1 - alpha)
exact_var = losses[i_var]
exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :])
print("Expected Loss E[L]: %.4f" % expected_loss)
print("Value at Risk VaR[L]: %.4f" % exact_var)
print("P[L <= VaR[L]]: %.4f" % cdf[exact_var])
print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar)
# plot loss PDF, expected loss, var, and cvar
plt.bar(losses, pdf)
plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]")
plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)")
plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)")
plt.legend(fontsize=15)
plt.xlabel("Loss L ($)", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Loss Distribution", size=20)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# plot results for Z
plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8)
plt.grid()
plt.xlabel("Z value", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Z Distribution", size=20)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# plot results for default probabilities
plt.bar(range(K), p_default)
plt.xlabel("Asset", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Individual Default Probabilities", size=20)
plt.xticks(range(K), size=15)
plt.yticks(size=15)
plt.grid()
plt.show()
# add Z qubits with weight/loss 0
from qiskit.circuit.library import WeightedAdder
agg = WeightedAdder(n_z + K, [0] * n_z + lgd)
from qiskit.circuit.library import LinearAmplitudeFunction
# define linear objective function
breakpoints = [0]
slopes = [1]
offsets = [0]
f_min = 0
f_max = sum(lgd)
c_approx = 0.25
objective = LinearAmplitudeFunction(
agg.num_sum_qubits,
slope=slopes,
offset=offsets,
# max value that can be reached by the qubit register (will not always be reached)
domain=(0, 2**agg.num_sum_qubits - 1),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A")
# load the random variable
state_preparation.append(u.to_gate(), qr_state)
# aggregate
state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:])
# linear objective function
state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:])
# uncompute aggregation
state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
# draw the circuit
state_preparation.draw()
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
value = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1":
value += prob
print("Exact Expected Loss: %.4f" % expected_loss)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % objective.post_processing(value))
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=state_preparation,
objective_qubits=[len(qr_state)],
post_processing=objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
# print results
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % expected_loss)
print("Estimated value:\t%.4f" % result.estimation_processed)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
# set x value to estimate the CDF
x_eval = 2
comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False)
comparator.draw()
def get_cdf_circuit(x_eval):
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
qr_compare = QuantumRegister(1, "compare")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A")
# load the random variable
state_preparation.append(u, qr_state)
# aggregate
state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:])
# comparator objective function
comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False)
state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:])
# uncompute aggregation
state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
return state_preparation
state_preparation = get_cdf_circuit(x_eval)
state_preparation.draw()
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
var_prob = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1":
var_prob += prob
print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob)
print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval])
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)])
# construct amplitude estimation
ae_cdf = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_cdf = ae_cdf.estimate(problem)
# print results
conf_int = np.array(result_cdf.confidence_interval)
print("Exact value: \t%.4f" % cdf[x_eval])
print("Estimated value:\t%.4f" % result_cdf.estimation)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"):
# construct amplitude estimation
state_preparation = get_cdf_circuit(x_eval)
problem = EstimationProblem(
state_preparation=state_preparation, objective_qubits=[len(qr_state)]
)
ae_var = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_var = ae_var.estimate(problem)
return result_var.estimation
def bisection_search(
objective, target_value, low_level, high_level, low_value=None, high_value=None
):
"""
Determines the smallest level such that the objective value is still larger than the target
:param objective: objective function
:param target: target value
:param low_level: lowest level to be considered
:param high_level: highest level to be considered
:param low_value: value of lowest level (will be evaluated if set to None)
:param high_value: value of highest level (will be evaluated if set to None)
:return: dictionary with level, value, num_eval
"""
# check whether low and high values are given and evaluated them otherwise
print("--------------------------------------------------------------------")
print("start bisection search for target value %.3f" % target_value)
print("--------------------------------------------------------------------")
num_eval = 0
if low_value is None:
low_value = objective(low_level)
num_eval += 1
if high_value is None:
high_value = objective(high_level)
num_eval += 1
# check if low_value already satisfies the condition
if low_value > target_value:
return {
"level": low_level,
"value": low_value,
"num_eval": num_eval,
"comment": "returned low value",
}
elif low_value == target_value:
return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"}
# check if high_value is above target
if high_value < target_value:
return {
"level": high_level,
"value": high_value,
"num_eval": num_eval,
"comment": "returned low value",
}
elif high_value == target_value:
return {
"level": high_level,
"value": high_value,
"num_eval": num_eval,
"comment": "success",
}
# perform bisection search until
print("low_level low_value level value high_level high_value")
print("--------------------------------------------------------------------")
while high_level - low_level > 1:
level = int(np.round((high_level + low_level) / 2.0))
num_eval += 1
value = objective(level)
print(
"%2d %.3f %2d %.3f %2d %.3f"
% (low_level, low_value, level, value, high_level, high_value)
)
if value >= target_value:
high_level = level
high_value = value
else:
low_level = level
low_value = value
# return high value after bisection search
print("--------------------------------------------------------------------")
print("finished bisection search")
print("--------------------------------------------------------------------")
return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"}
# run bisection search to determine VaR
objective = lambda x: run_ae_for_cdf(x)
bisection_result = bisection_search(
objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1
)
var = bisection_result["level"]
print("Estimated Value at Risk: %2d" % var)
print("Exact Value at Risk: %2d" % exact_var)
print("Estimated Probability: %.3f" % bisection_result["value"])
print("Exact Probability: %.3f" % cdf[exact_var])
# define linear objective
breakpoints = [0, var]
slopes = [0, 1]
offsets = [0, 0] # subtract VaR and add it later to the estimate
f_min = 0
f_max = 3 - var
c_approx = 0.25
cvar_objective = LinearAmplitudeFunction(
agg.num_sum_qubits,
slopes,
offsets,
domain=(0, 2**agg.num_sum_qubits - 1),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
cvar_objective.draw()
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A")
# load the random variable
state_preparation.append(u, qr_state)
# aggregate
state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:])
# linear objective function
state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:])
# uncompute aggregation
state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
value = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1":
value += prob
# normalize and add VaR to estimate
value = cvar_objective.post_processing(value)
d = 1.0 - bisection_result["value"]
v = value / d if d != 0 else 0
normalized_value = v + var
print("Estimated CVaR: %.4f" % normalized_value)
print("Exact CVaR: %.4f" % exact_cvar)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=state_preparation,
objective_qubits=[len(qr_state)],
post_processing=cvar_objective.post_processing,
)
# construct amplitude estimation
ae_cvar = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_cvar = ae_cvar.estimate(problem)
# print results
d = 1.0 - bisection_result["value"]
v = result_cvar.estimation_processed / d if d != 0 else 0
print("Exact CVaR: \t%.4f" % exact_cvar)
print("Estimated CVaR:\t%.4f" % (v + var))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure(0, 0)
circ.measure(1, 1)
circ.draw('mpl')
from qiskit import pulse
from qiskit.pulse.library import Gaussian
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration('h', [0], h_q0)
from qiskit import transpile
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
circ = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ.draw('mpl', idle_wires=False)
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
circ = QuantumCircuit(1, 1)
custom_gate = Gate('my_custom_gate', 1, [3.14, 1])
# 3.14 is an arbitrary parameter for demonstration
circ.append(custom_gate, [0])
circ.measure(0, 0)
circ.draw('mpl')
with pulse.build(backend, name='custom') as my_schedule:
pulse.play(Gaussian(duration=64, amp=0.2, sigma=8), pulse.drive_channel(0))
circ.add_calibration('my_custom_gate', [0], my_schedule, [3.14, 1])
# Alternatively: circ.add_calibration(custom_gate, [0], my_schedule)
circ = transpile(circ, backend)
circ.draw('mpl', idle_wires=False)
circ = QuantumCircuit(2, 2)
circ.append(custom_gate, [1])
from qiskit import QiskitError
try:
circ = transpile(circ, backend)
except QiskitError as e:
print(e)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/daimurat/qiskit-implementation
|
daimurat
|
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/JohnBurke4/qaoa_testing_framework
|
JohnBurke4
|
import networkx as nx
import numpy as np
from Helper_Functions import getBestMaxcut, custom_graphs, ry_simulator, greedyMaxcutSolver, customSATSolverCircuit
from qiskit import transpile, Aer
from QAOA_Cost_Function import CostFunction
v = 6
d = 3
for i in range(0, 1):
graph = nx.random_graphs.random_regular_graph(d, v, seed=16)
print(graph.edges())
cost = CostFunction('maxcut', graph)
g = greedyMaxcutSolver(graph, cost)
b = getBestMaxcut(cost, v)
print(g, b)
|
https://github.com/ionq-samples/qiskit-getting-started
|
ionq-samples
|
#imports
from qiskit_ionq import IonQProvider
ionq_provider = IonQProvider(token='API-key-goes-here')
import numpy as np
from qiskit import QuantumCircuit, execute, Aer
from qiskit.tools.visualization import plot_histogram, array_to_latex
from qiskit.extensions import UnitaryGate
swap_gate=QuantumCircuit(2)
swap_gate.cx(0,1)
swap_gate.cx(1,0)
swap_gate.cx(0,1)
swap_gate.draw()
ata = QuantumCircuit(4)
ata.h(0)
ata.cx(0,3)
ata.measure_all()
ata.draw()
backend = ionq_provider.get_backend("ionq_simulator")#choose your backend
job = execute(ata, backend,shots=5000) #get the job object
result = job.result() # get result object
counts = result.get_counts() #get the counts dictionary
fig=plot_histogram(counts) #plot the histogram of the counts
ax = fig.axes[0]
fig
lmt = QuantumCircuit(4)
lmt.h(0)
lmt.cx(1,3)
lmt.cx(3,1)
lmt.cx(1,3)
lmt.cx(0,1)
lmt.cx(1,3)
lmt.cx(3,1)
lmt.cx(1,3)
lmt.measure_all()
lmt.draw()
backend = ionq_provider.get_backend("ionq_simulator")#choose your backend
job = execute(lmt, backend,shots=5000) #get the job object
result = job.result() # get result object
counts = result.get_counts() #get the counts dictionary
fig=plot_histogram(counts) #plot the histogram of the counts
ax = fig.axes[0]
fig
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Width pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import Width
from qiskit.test import QiskitTestCase
class TestWidthPass(QiskitTestCase):
"""Tests for Depth analysis methods."""
def test_empty_dag(self):
"""Empty DAG has 0 depth"""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = Width()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["width"], 0)
def test_just_qubits(self):
"""A dag with 8 operations and no classic bits"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = Width()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["width"], 2)
if __name__ == "__main__":
unittest.main()
|
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 the BasicSwap pass"""
import unittest
from qiskit.transpiler.passes import BasicSwap
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.layout import Layout
from qiskit.transpiler import CouplingMap, Target
from qiskit.circuit.library import CXGate
from qiskit.converters import circuit_to_dag
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
class TestBasicSwap(QiskitTestCase):
"""Tests the BasicSwap pass."""
def test_trivial_case(self):
"""No need to have any swap, the CX are distance 1 to each other
q0:--(+)-[U]-(+)-
| |
q1:---.-------|--
|
q2:-----------.--
CouplingMap map: [1]--[0]--[2]
"""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_trivial_in_same_layer(self):
"""No need to have any swap, two CXs distance 1 to each other, in the same layer
q0:--(+)--
|
q1:---.---
q2:--(+)--
|
q3:---.---
CouplingMap map: [0]--[1]--[2]--[3]
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[2], qr[3])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_a_single_swap(self):
"""Adding a swap
q0:-------
q1:--(+)--
|
q2:---.---
CouplingMap map: [1]--[0]--[2]
q0:--X---.---
| |
q1:--X---|---
|
q2:-----(+)--
"""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[0])
expected.cx(qr[0], qr[2])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_a_single_swap_with_target(self):
"""Adding a swap
q0:-------
q1:--(+)--
|
q2:---.---
CouplingMap map: [1]--[0]--[2]
q0:--X---.---
| |
q1:--X---|---
|
q2:-----(+)--
"""
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (0, 2): None})
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[0])
expected.cx(qr[0], qr[2])
pass_ = BasicSwap(target)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_a_single_swap_bigger_cm(self):
"""Swapper in a bigger coupling map
q0:-------
q1:---.---
|
q2:--(+)--
CouplingMap map: [1]--[0]--[2]--[3]
q0:--X---.---
| |
q1:--X---|---
|
q2:-----(+)--
"""
coupling = CouplingMap([[0, 1], [0, 2], [2, 3]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[0])
expected.cx(qr[0], qr[2])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_keep_layout(self):
"""After a swap, the following gates also change the wires.
qr0:---.---[H]--
|
qr1:---|--------
|
qr2:--(+)-------
CouplingMap map: [0]--[1]--[2]
qr0:--X-----------
|
qr1:--X---.--[H]--
|
qr2:-----(+)------
"""
coupling = CouplingMap([[1, 0], [1, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[1])
expected.cx(qr[1], qr[2])
expected.h(qr[1])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap(self):
"""A far swap that affects coming CXs.
qr0:--(+)---.--
| |
qr1:---|----|--
| |
qr2:---|----|--
| |
qr3:---.---(+)-
CouplingMap map: [0]--[1]--[2]--[3]
qr0:--X--------------
|
qr1:--X--X-----------
|
qr2:-----X--(+)---.--
| |
qr3:---------.---(+)-
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[1])
expected.swap(qr[1], qr[2])
expected.cx(qr[2], qr[3])
expected.cx(qr[3], qr[2])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap_with_gate_the_front(self):
"""A far swap with a gate in the front.
q0:------(+)--
|
q1:-------|---
|
q2:-------|---
|
q3:--[H]--.---
CouplingMap map: [0]--[1]--[2]--[3]
q0:-----------(+)--
|
q1:---------X--.---
|
q2:------X--X------
|
q3:-[H]--X---------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr[3])
circuit.cx(qr[3], qr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[3])
expected.swap(qr[3], qr[2])
expected.swap(qr[2], qr[1])
expected.cx(qr[1], qr[0])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap_with_gate_the_back(self):
"""A far swap with a gate in the back.
q0:--(+)------
|
q1:---|-------
|
q2:---|-------
|
q3:---.--[H]--
CouplingMap map: [0]--[1]--[2]--[3]
q0:-------(+)------
|
q1:-----X--.--[H]--
|
q2:--X--X----------
|
q3:--X-------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[3], qr[2])
expected.swap(qr[2], qr[1])
expected.cx(qr[1], qr[0])
expected.h(qr[1])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap_with_gate_the_middle(self):
"""A far swap with a gate in the middle.
q0:--(+)-------.--
| |
q1:---|--------|--
|
q2:---|--------|--
| |
q3:---.--[H]--(+)-
CouplingMap map: [0]--[1]--[2]--[3]
q0:-------(+)-------.---
| |
q1:-----X--.--[H]--(+)--
|
q2:--X--X---------------
|
q3:--X------------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
circuit.cx(qr[0], qr[3])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[3], qr[2])
expected.swap(qr[2], qr[1])
expected.cx(qr[1], qr[0])
expected.h(qr[1])
expected.cx(qr[0], qr[1])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_fake_run(self):
"""A fake run, doesn't change dag
q0:--(+)-------.--
| |
q1:---|--------|--
|
q2:---|--------|--
| |
q3:---.--[H]--(+)-
CouplingMap map: [0]--[1]--[2]--[3]
q0:-------(+)-------.---
| |
q1:-----X--.--[H]--(+)--
|
q2:--X--X---------------
|
q3:--X------------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
circuit.cx(qr[0], qr[3])
fake_pm = PassManager([BasicSwap(coupling, fake_run=True)])
real_pm = PassManager([BasicSwap(coupling, fake_run=False)])
self.assertEqual(circuit, fake_pm.run(circuit))
self.assertNotEqual(circuit, real_pm.run(circuit))
self.assertIsInstance(fake_pm.property_set["final_layout"], Layout)
self.assertEqual(fake_pm.property_set["final_layout"], real_pm.property_set["final_layout"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Compiler Test."""
import os
import unittest
from qiskit import BasicAer
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit import execute
from qiskit.circuit.library import U1Gate, U2Gate
from qiskit.compiler import transpile, assemble
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeRueschlikon, FakeTenerife
from qiskit.qobj import QasmQobj
class TestCompiler(QiskitTestCase):
"""Qiskit Compiler Tests."""
def setUp(self):
super().setUp()
self.seed_simulator = 42
self.backend = BasicAer.get_backend("qasm_simulator")
def test_example_multiple_compile(self):
"""Test a toy example compiling multiple circuits.
Pass if the results are correct.
"""
backend = BasicAer.get_backend("qasm_simulator")
coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]]
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
bell = QuantumCircuit(qr, cr)
ghz = QuantumCircuit(qr, cr)
# Create a GHZ state
ghz.h(qr[0])
for i in range(4):
ghz.cx(qr[i], qr[i + 1])
# Insert a barrier before measurement
ghz.barrier()
# Measure all of the qubits in the standard basis
for i in range(5):
ghz.measure(qr[i], cr[i])
# Create a Bell state
bell.h(qr[0])
bell.cx(qr[0], qr[1])
bell.barrier()
bell.measure(qr[0], cr[0])
bell.measure(qr[1], cr[1])
shots = 2048
bell_backend = transpile(bell, backend=backend)
ghz_backend = transpile(ghz, backend=backend, coupling_map=coupling_map)
bell_qobj = assemble(bell_backend, shots=shots, seed_simulator=10)
ghz_qobj = assemble(ghz_backend, shots=shots, seed_simulator=10)
bell_result = backend.run(bell_qobj).result()
ghz_result = backend.run(ghz_qobj).result()
threshold = 0.05 * shots
counts_bell = bell_result.get_counts()
target_bell = {"00000": shots / 2, "00011": shots / 2}
self.assertDictAlmostEqual(counts_bell, target_bell, threshold)
counts_ghz = ghz_result.get_counts()
target_ghz = {"00000": shots / 2, "11111": shots / 2}
self.assertDictAlmostEqual(counts_ghz, target_ghz, threshold)
def test_compile_coupling_map(self):
"""Test compile_coupling_map.
If all correct should return data with the same stats. The circuit may
be different.
"""
backend = BasicAer.get_backend("qasm_simulator")
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
qc = QuantumCircuit(qr, cr, name="qccccccc")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.cx(qr[0], qr[2])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
shots = 2048
coupling_map = [[0, 1], [1, 2]]
initial_layout = [0, 1, 2]
qc_b = transpile(
qc, backend=backend, coupling_map=coupling_map, initial_layout=initial_layout
)
qobj = assemble(qc_b, shots=shots, seed_simulator=88)
job = backend.run(qobj)
result = job.result()
qasm_to_check = qc.qasm()
self.assertEqual(len(qasm_to_check), 173)
counts = result.get_counts(qc)
target = {"000": shots / 2, "111": shots / 2}
threshold = 0.05 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_example_swap_bits(self):
"""Test a toy example swapping a set bit around.
Uses the mapper. Pass if results are correct.
"""
backend = BasicAer.get_backend("qasm_simulator")
coupling_map = [
[0, 1],
[0, 8],
[1, 2],
[1, 9],
[2, 3],
[2, 10],
[3, 4],
[3, 11],
[4, 5],
[4, 12],
[5, 6],
[5, 13],
[6, 7],
[6, 14],
[7, 15],
[8, 9],
[9, 10],
[10, 11],
[11, 12],
[12, 13],
[13, 14],
[14, 15],
]
# ┌───┐ ░ ┌─┐
# q0_0: ┤ X ├─X───────────░─┤M├───────────────
# └───┘ │ ░ └╥┘ ┌─┐
# q0_1: ──────┼─────X──X──░──╫────┤M├─────────
# │ │ │ ░ ║ └╥┘ ┌─┐
# q0_2: ──────X──X──┼──┼──░──╫─────╫────┤M├───
# │ │ │ ░ ║ ┌─┐ ║ └╥┘
# q1_0: ─────────┼──┼──┼──░──╫─┤M├─╫─────╫────
# │ │ │ ░ ║ └╥┘ ║ ┌─┐ ║
# q1_1: ─────────┼──┼──X──░──╫──╫──╫─┤M├─╫────
# │ │ ░ ║ ║ ║ └╥┘ ║ ┌─┐
# q1_2: ─────────X──X─────░──╫──╫──╫──╫──╫─┤M├
# ░ ║ ║ ║ ║ ║ └╥┘
# c0: 6/═════════════════════╩══╩══╩══╩══╩══╩═
# 0 3 1 4 2 5
n = 3 # make this at least 3
qr0 = QuantumRegister(n)
qr1 = QuantumRegister(n)
ans = ClassicalRegister(2 * n)
qc = QuantumCircuit(qr0, qr1, ans)
# Set the first bit of qr0
qc.x(qr0[0])
# Swap the set bit
qc.swap(qr0[0], qr0[n - 1])
qc.swap(qr0[n - 1], qr1[n - 1])
qc.swap(qr1[n - 1], qr0[1])
qc.swap(qr0[1], qr1[1])
# Insert a barrier before measurement
qc.barrier()
# Measure all of the qubits in the standard basis
for j in range(n):
qc.measure(qr0[j], ans[j])
qc.measure(qr1[j], ans[j + n])
# First version: no mapping
result = execute(
qc, backend=backend, coupling_map=None, shots=1024, seed_simulator=14
).result()
self.assertEqual(result.get_counts(qc), {"010000": 1024})
# Second version: map to coupling graph
result = execute(
qc, backend=backend, coupling_map=coupling_map, shots=1024, seed_simulator=14
).result()
self.assertEqual(result.get_counts(qc), {"010000": 1024})
def test_parallel_compile(self):
"""Trigger parallel routines in compile."""
backend = FakeRueschlikon()
qr = QuantumRegister(16)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
for k in range(1, 15):
qc.cx(qr[0], qr[k])
qc.measure(qr[5], cr[0])
qlist = [qc for k in range(10)]
qobj = assemble(transpile(qlist, backend=backend))
self.assertEqual(len(qobj.experiments), 10)
def test_no_conflict_backend_passmanager(self):
"""execute(qc, backend=..., passmanager=...)
See: https://github.com/Qiskit/qiskit-terra/issues/5037
"""
backend = BasicAer.get_backend("qasm_simulator")
qc = QuantumCircuit(2)
qc.append(U1Gate(0), [0])
qc.measure_all()
job = execute(qc, backend=backend, pass_manager=PassManager())
result = job.result().get_counts()
self.assertEqual(result, {"00": 1024})
def test_compile_single_qubit(self):
"""Compile a single-qubit circuit in a non-trivial layout"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
layout = {qr[0]: 12}
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
circuit2 = transpile(
circuit, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout
)
qobj = assemble(circuit2)
compiled_instruction = qobj.experiments[0].instructions[0]
self.assertEqual(compiled_instruction.name, "u2")
self.assertEqual(compiled_instruction.qubits, [12])
self.assertEqual(compiled_instruction.params, [0, 3.141592653589793])
def test_compile_pass_manager(self):
"""Test compile with and without an empty pass manager."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.append(U1Gate(3.14), [qr[0]])
qc.append(U2Gate(3.14, 1.57), [qr[0]])
qc.barrier(qr)
qc.measure(qr, cr)
backend = BasicAer.get_backend("qasm_simulator")
qrtrue = assemble(transpile(qc, backend, seed_transpiler=8), seed_simulator=42)
rtrue = backend.run(qrtrue).result()
qrfalse = assemble(PassManager().run(qc), seed_simulator=42)
rfalse = backend.run(qrfalse).result()
self.assertEqual(rtrue.get_counts(), rfalse.get_counts())
def test_mapper_overoptimization(self):
"""Check mapper overoptimization.
The mapper should not change the semantics of the input.
An overoptimization introduced issue #81:
https://github.com/Qiskit/qiskit-terra/issues/81
"""
# ┌───┐ ┌─┐
# q0_0: ┤ X ├──■───────┤M├───────────
# ├───┤┌─┴─┐┌───┐└╥┘ ┌─┐
# q0_1: ┤ Y ├┤ X ├┤ S ├─╫───■──┤M├───
# ├───┤└───┘├───┤ ║ ┌─┴─┐└╥┘┌─┐
# q0_2: ┤ Z ├──■──┤ T ├─╫─┤ X ├─╫─┤M├
# └───┘┌─┴─┐├───┤ ║ └┬─┬┘ ║ └╥┘
# q0_3: ─────┤ X ├┤ H ├─╫──┤M├──╫──╫─
# └───┘└───┘ ║ └╥┘ ║ ║
# c0: 4/════════════════╩═══╩═══╩══╩═
# 0 3 1 2
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
circ = QuantumCircuit(qr, cr)
circ.x(qr[0])
circ.y(qr[1])
circ.z(qr[2])
circ.cx(qr[0], qr[1])
circ.cx(qr[2], qr[3])
circ.s(qr[1])
circ.t(qr[2])
circ.h(qr[3])
circ.cx(qr[1], qr[2])
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
coupling_map = [[0, 2], [1, 2], [2, 3]]
shots = 1000
result1 = execute(
circ,
backend=self.backend,
coupling_map=coupling_map,
seed_simulator=self.seed_simulator,
seed_transpiler=8,
shots=shots,
)
count1 = result1.result().get_counts()
result2 = execute(
circ,
backend=self.backend,
coupling_map=None,
seed_simulator=self.seed_simulator,
seed_transpiler=8,
shots=shots,
)
count2 = result2.result().get_counts()
self.assertDictAlmostEqual(count1, count2, shots * 0.02)
def test_grovers_circuit(self):
"""Testing a circuit originated in the Grover algorithm"""
shots = 1000
coupling_map = None
# 6-qubit grovers
#
# ┌───┐┌───┐ ┌───┐┌───┐ ┌───┐ ┌───┐┌───┐ ░ ┌─┐
# q0_0: ┤ H ├┤ X ├──■──┤ X ├┤ X ├──■──┤ X ├──■──┤ X ├┤ H ├──────░─┤M├───
# ├───┤└───┘ │ └───┘└───┘ │ ├───┤ │ ├───┤├───┤ ░ └╥┘┌─┐
# q0_1: ┤ H ├──■────┼─────────■────┼──┤ X ├──■──┤ X ├┤ H ├──────░──╫─┤M├
# ├───┤ │ ┌─┴─┐ │ ┌─┴─┐└───┘ │ └───┘└───┘ ░ ║ └╥┘
# q0_2: ┤ X ├──┼──┤ X ├──■────┼──┤ X ├───────┼──────────────────░──╫──╫─
# ├───┤┌─┴─┐└───┘ │ ┌─┴─┐└───┘ │ ░ ║ ║
# q0_3: ┤ X ├┤ X ├───────■──┤ X ├────────────┼──────────────────░──╫──╫─
# └───┘└───┘ ┌─┴─┐├───┤┌───┐ ┌─┴─┐┌───┐┌───┐┌───┐ ░ ║ ║
# q0_4: ───────────────┤ X ├┤ X ├┤ H ├─────┤ X ├┤ H ├┤ X ├┤ H ├─░──╫──╫─
# └───┘└───┘└───┘ └───┘└───┘└───┘└───┘ ░ ║ ║
# q0_5: ────────────────────────────────────────────────────────░──╫──╫─
# ░ ║ ║
# c0: 2/═══════════════════════════════════════════════════════════╩══╩═
# 0 1
qr = QuantumRegister(6)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr, name="grovers")
circuit.h(qr[0])
circuit.h(qr[1])
circuit.x(qr[2])
circuit.x(qr[3])
circuit.x(qr[0])
circuit.cx(qr[0], qr[2])
circuit.x(qr[0])
circuit.cx(qr[1], qr[3])
circuit.ccx(qr[2], qr[3], qr[4])
circuit.cx(qr[1], qr[3])
circuit.x(qr[0])
circuit.cx(qr[0], qr[2])
circuit.x(qr[0])
circuit.x(qr[1])
circuit.x(qr[4])
circuit.h(qr[4])
circuit.ccx(qr[0], qr[1], qr[4])
circuit.h(qr[4])
circuit.x(qr[0])
circuit.x(qr[1])
circuit.x(qr[4])
circuit.h(qr[0])
circuit.h(qr[1])
circuit.h(qr[4])
circuit.barrier(qr)
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
result = execute(
circuit,
backend=self.backend,
coupling_map=coupling_map,
seed_simulator=self.seed_simulator,
shots=shots,
)
counts = result.result().get_counts()
expected_probs = {"00": 0.64, "01": 0.117, "10": 0.113, "11": 0.13}
target = {key: shots * val for key, val in expected_probs.items()}
threshold = 0.04 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_math_domain_error(self):
"""Check for floating point errors.
The math library operates over floats and introduces floating point
errors that should be avoided.
See: https://github.com/Qiskit/qiskit-terra/issues/111
"""
# ┌───┐┌───┐ ┌─┐
# q0_0: ┤ Y ├┤ X ├─────┤M├─────────────────────
# └───┘└─┬─┘ └╥┘ ┌─┐
# q0_1: ───────■────────╫─────────────■──┤M├───
# ┌───┐┌───┐┌───┐ ║ ┌───┐┌───┐┌─┴─┐└╥┘┌─┐
# q0_2: ┤ Z ├┤ H ├┤ Y ├─╫─┤ T ├┤ Z ├┤ X ├─╫─┤M├
# └┬─┬┘└───┘└───┘ ║ └───┘└───┘└───┘ ║ └╥┘
# q0_3: ─┤M├────────────╫─────────────────╫──╫─
# └╥┘ ║ ║ ║
# c0: 4/══╩═════════════╩═════════════════╩══╩═
# 3 0 1 2
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
circ = QuantumCircuit(qr, cr)
circ.y(qr[0])
circ.z(qr[2])
circ.h(qr[2])
circ.cx(qr[1], qr[0])
circ.y(qr[2])
circ.t(qr[2])
circ.z(qr[2])
circ.cx(qr[1], qr[2])
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
coupling_map = [[0, 2], [1, 2], [2, 3]]
shots = 2000
job = execute(
circ,
backend=self.backend,
coupling_map=coupling_map,
seed_simulator=self.seed_simulator,
shots=shots,
)
counts = job.result().get_counts()
target = {"0001": shots / 2, "0101": shots / 2}
threshold = 0.04 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_random_parameter_circuit(self):
"""Run a circuit with randomly generated parameters."""
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "random_n5_d5.qasm"))
coupling_map = [[0, 1], [1, 2], [2, 3], [3, 4]]
shots = 1024
qobj = execute(
circ,
backend=self.backend,
coupling_map=coupling_map,
shots=shots,
seed_simulator=self.seed_simulator,
)
counts = qobj.result().get_counts()
expected_probs = {
"00000": 0.079239867254200971,
"00001": 0.032859032998526903,
"00010": 0.10752610993531816,
"00011": 0.018818532050952699,
"00100": 0.054830807251011054,
"00101": 0.0034141983951965164,
"00110": 0.041649309748902276,
"00111": 0.039967731207338125,
"01000": 0.10516937819949743,
"01001": 0.026635620063700002,
"01010": 0.0053475143548793866,
"01011": 0.01940513314416064,
"01100": 0.0044028405481225047,
"01101": 0.057524760052126644,
"01110": 0.010795354134597078,
"01111": 0.026491296821535528,
"10000": 0.094827455395274859,
"10001": 0.0008373965072688836,
"10010": 0.029082297894094441,
"10011": 0.012386622870598416,
"10100": 0.018739140061148799,
"10101": 0.01367656456536896,
"10110": 0.039184170706009248,
"10111": 0.062339335178438288,
"11000": 0.00293674365989009,
"11001": 0.012848433960739968,
"11010": 0.018472497159499782,
"11011": 0.0088903691234912003,
"11100": 0.031305389080034329,
"11101": 0.0004788556283690458,
"11110": 0.002232419390471667,
"11111": 0.017684822659235985,
}
target = {key: shots * val for key, val in expected_probs.items()}
threshold = 0.04 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_yzy_zyz_cases(self):
"""yzy_to_zyz works in previously failed cases.
See: https://github.com/Qiskit/qiskit-terra/issues/607
"""
backend = FakeTenerife()
qr = QuantumRegister(2)
circ1 = QuantumCircuit(qr)
circ1.cx(qr[0], qr[1])
circ1.rz(0.7, qr[1])
circ1.rx(1.570796, qr[1])
qobj1 = assemble(transpile(circ1, backend))
self.assertIsInstance(qobj1, QasmQobj)
circ2 = QuantumCircuit(qr)
circ2.y(qr[0])
circ2.h(qr[0])
circ2.s(qr[0])
circ2.h(qr[0])
qobj2 = assemble(transpile(circ2, backend))
self.assertIsInstance(qobj2, QasmQobj)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
# with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
# with open(filename, "wb") as f:
# pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
# with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump(backend.properties(), f)
retrieved_jobs = jobs
retrieved_cal_job = cal_job
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Tests for Pauli operator class."""
import re
import unittest
import itertools as it
from functools import lru_cache
import numpy as np
from ddt import ddt, data, unpack
from qiskit import QuantumCircuit
from qiskit.exceptions import QiskitError
from qiskit.circuit.library import (
IGate,
XGate,
YGate,
ZGate,
HGate,
SGate,
SdgGate,
CXGate,
CZGate,
CYGate,
SwapGate,
)
from qiskit.circuit.library.generalized_gates import PauliGate
from qiskit.test import QiskitTestCase
from qiskit.quantum_info.random import random_clifford, random_pauli
from qiskit.quantum_info.operators import Pauli, Operator
LABEL_REGEX = re.compile(r"(?P<coeff>[+-]?1?[ij]?)(?P<pauli>[IXYZ]*)")
PHASE_MAP = {"": 0, "-i": 1, "-": 2, "i": 3}
def _split_pauli_label(label):
match_ = LABEL_REGEX.fullmatch(label)
return match_["pauli"], match_["coeff"]
def _phase_from_label(label):
coeff = LABEL_REGEX.fullmatch(label)["coeff"] or ""
return PHASE_MAP[coeff.replace("+", "").replace("1", "").replace("j", "i")]
@lru_cache(maxsize=8)
def pauli_group_labels(nq, full_group=True):
"""Generate list of the N-qubit pauli group string labels"""
labels = ["".join(i) for i in it.product(("I", "X", "Y", "Z"), repeat=nq)]
if full_group:
labels = ["".join(i) for i in it.product(("", "-i", "-", "i"), labels)]
return labels
def operator_from_label(label):
"""Construct operator from full Pauli group label"""
pauli, coeff = _split_pauli_label(label)
coeff = (-1j) ** _phase_from_label(coeff)
return coeff * Operator.from_label(pauli)
@ddt
class TestPauliConversions(QiskitTestCase):
"""Test representation conversions of Pauli"""
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_labels(self, label):
"""Test round trip label conversion"""
pauli = Pauli(label)
self.assertEqual(Pauli(str(pauli)), pauli)
@data("S", "XX-")
def test_invalid_labels(self, label):
"""Test raise if invalid labels are supplied"""
with self.assertRaises(QiskitError):
Pauli(label)
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_to_operator(self, label):
"""Test Pauli operator conversion"""
value = Operator(Pauli(label))
target = operator_from_label(label)
self.assertEqual(value, target)
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_to_matrix_sparse(self, label):
"""Test Pauli operator conversion"""
spmat = Pauli(label).to_matrix(sparse=True)
value = Operator(spmat.todense())
target = operator_from_label(label)
self.assertEqual(value, target)
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_to_instruction(self, label):
"""Test Pauli to instruction"""
pauli = Pauli(label)
value = Operator(pauli.to_instruction())
target = Operator(pauli)
self.assertEqual(value, target)
@data((IGate(), "I"), (XGate(), "X"), (YGate(), "Y"), (ZGate(), "Z"))
@unpack
def test_init_single_pauli_gate(self, gate, label):
"""Test initialization from Pauli basis gates"""
self.assertEqual(str(Pauli(gate)), label)
@data("IXYZ", "XXY", "ZYX", "ZI", "Y")
def test_init_pauli_gate(self, label):
"""Test initialization from Pauli basis gates"""
pauli = Pauli(PauliGate(label))
self.assertEqual(str(pauli), label)
@ddt
class TestPauliProperties(QiskitTestCase):
"""Test Pauli properties"""
@data("I", "XY", "XYZ", "IXYZ", "IXYZX")
def test_len(self, label):
"""Test __len__ method"""
self.assertEqual(len(Pauli(label)), len(label))
@data(*it.product(pauli_group_labels(1, full_group=False), pauli_group_labels(1)))
@unpack
def test_equal(self, label1, label2):
"""Test __eq__ method"""
pauli1 = Pauli(label1)
pauli2 = Pauli(label2)
target = (
np.all(pauli1.z == pauli2.z)
and np.all(pauli1.x == pauli2.x)
and pauli1.phase == pauli2.phase
)
self.assertEqual(pauli1 == pauli2, target)
@data(*it.product(pauli_group_labels(1, full_group=False), pauli_group_labels(1)))
@unpack
def test_equiv(self, label1, label2):
"""Test equiv method"""
pauli1 = Pauli(label1)
pauli2 = Pauli(label2)
target = np.all(pauli1.z == pauli2.z) and np.all(pauli1.x == pauli2.x)
self.assertEqual(pauli1.equiv(pauli2), target)
@data(*pauli_group_labels(1))
def test_phase(self, label):
"""Test phase attribute"""
pauli = Pauli(label)
_, coeff = _split_pauli_label(str(pauli))
target = _phase_from_label(coeff)
self.assertEqual(pauli.phase, target)
@data(*((p, q) for p in ["I", "X", "Y", "Z"] for q in range(4)))
@unpack
def test_phase_setter(self, pauli, phase):
"""Test phase setter"""
pauli = Pauli(pauli)
pauli.phase = phase
_, coeff = _split_pauli_label(str(pauli))
value = _phase_from_label(coeff)
self.assertEqual(value, phase)
def test_x_setter(self):
"""Test phase attribute"""
pauli = Pauli("II")
pauli.x = True
self.assertEqual(pauli, Pauli("XX"))
def test_z_setter(self):
"""Test phase attribute"""
pauli = Pauli("II")
pauli.z = True
self.assertEqual(pauli, Pauli("ZZ"))
@data(
*(
("IXYZ", i)
for i in [0, 1, 2, 3, slice(None, None, None), slice(None, 2, None), [0, 3], [2, 1, 3]]
)
)
@unpack
def test_getitem(self, label, qubits):
"""Test __getitem__"""
pauli = Pauli(label)
value = str(pauli[qubits])
val_array = np.array(list(reversed(label)))[qubits]
target = "".join(reversed(val_array.tolist()))
self.assertEqual(value, target, msg=f"indices = {qubits}")
@data(
(0, "iY", "iIIY"),
([1, 0], "XZ", "IZX"),
(slice(None, None, None), "XYZ", "XYZ"),
(slice(None, None, -1), "XYZ", "ZYX"),
)
@unpack
def test_setitem(self, qubits, value, target):
"""Test __setitem__"""
pauli = Pauli("III")
pauli[qubits] = value
self.assertEqual(str(pauli), target)
def test_insert(self):
"""Test insert method"""
pauli = Pauli("III")
pauli = pauli.insert([2, 0, 4], "XYZ")
self.assertEqual(str(pauli), "IXIZIY")
def test_delete(self):
"""Test delete method"""
pauli = Pauli("IXYZ")
pauli = pauli.delete([0, 2])
self.assertEqual(str(pauli), "IY")
@ddt
class TestPauli(QiskitTestCase):
"""Tests for Pauli operator class."""
@data(*pauli_group_labels(2))
def test_conjugate(self, label):
"""Test conjugate method."""
value = Pauli(label).conjugate()
target = operator_from_label(label).conjugate()
self.assertEqual(Operator(value), target)
@data(*pauli_group_labels(2))
def test_transpose(self, label):
"""Test transpose method."""
value = Pauli(label).transpose()
target = operator_from_label(label).transpose()
self.assertEqual(Operator(value), target)
@data(*pauli_group_labels(2))
def test_adjoint(self, label):
"""Test adjoint method."""
value = Pauli(label).adjoint()
target = operator_from_label(label).adjoint()
self.assertEqual(Operator(value), target)
@data(*pauli_group_labels(2))
def test_inverse(self, label):
"""Test inverse method."""
pauli = Pauli(label)
value = pauli.inverse()
target = pauli.adjoint()
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(2, full_group=False), repeat=2))
@unpack
def test_dot(self, label1, label2):
"""Test dot method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.dot(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.dot(op2)
self.assertEqual(value, target)
target = op1 @ op2
self.assertEqual(value, target)
@data(*pauli_group_labels(1))
def test_dot_qargs(self, label2):
"""Test dot method with qargs."""
label1 = "-iXYZ"
p1 = Pauli(label1)
p2 = Pauli(label2)
qargs = [0]
value = Operator(p1.dot(p2, qargs=qargs))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.dot(op2, qargs=qargs)
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(2, full_group=False), repeat=2))
@unpack
def test_compose(self, label1, label2):
"""Test compose method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.compose(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.compose(op2)
self.assertEqual(value, target)
@data(*pauli_group_labels(1))
def test_compose_qargs(self, label2):
"""Test compose method with qargs."""
label1 = "-XYZ"
p1 = Pauli(label1)
p2 = Pauli(label2)
qargs = [0]
value = Operator(p1.compose(p2, qargs=qargs))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.compose(op2, qargs=qargs)
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(1, full_group=False), repeat=2))
@unpack
def test_tensor(self, label1, label2):
"""Test tensor method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.tensor(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.tensor(op2)
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(1, full_group=False), repeat=2))
@unpack
def test_expand(self, label1, label2):
"""Test expand method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.expand(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.expand(op2)
self.assertEqual(value, target)
@data("II", "XI", "YX", "ZZ", "YZ")
def test_power(self, label):
"""Test power method."""
iden = Pauli("II")
op = Pauli(label)
self.assertTrue(op**2, iden)
@data(1, 1.0, -1, -1.0, 1j, -1j)
def test_multiply(self, val):
"""Test multiply method."""
op = val * Pauli(([True, True], [False, False], 0))
phase = (-1j) ** op.phase
self.assertEqual(phase, val)
op = Pauli(([True, True], [False, False], 0)) * val
phase = (-1j) ** op.phase
self.assertEqual(phase, val)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
op = Pauli("XYZ")
self.assertRaises(QiskitError, op._multiply, 2)
@data(0, 1, 2, 3)
def test_negate(self, phase):
"""Test negate method"""
op = Pauli(([False], [True], phase))
neg = -op
self.assertTrue(op.equiv(neg))
self.assertEqual(neg.phase, (op.phase + 2) % 4)
@data(*it.product(pauli_group_labels(1, False), repeat=2))
@unpack
def test_commutes(self, p1, p2):
"""Test commutes method"""
P1 = Pauli(p1)
P2 = Pauli(p2)
self.assertEqual(P1.commutes(P2), P1.dot(P2) == P2.dot(P1))
@data(*it.product(pauli_group_labels(1, False), repeat=2))
@unpack
def test_anticommutes(self, p1, p2):
"""Test anticommutes method"""
P1 = Pauli(p1)
P2 = Pauli(p2)
self.assertEqual(P1.anticommutes(P2), P1.dot(P2) == -P2.dot(P1))
@data(
*it.product(
(IGate(), XGate(), YGate(), ZGate(), HGate(), SGate(), SdgGate()),
pauli_group_labels(1, False),
)
)
@unpack
def test_evolve_clifford1(self, gate, label):
"""Test evolve method for 1-qubit Clifford gates."""
op = Operator(gate)
pauli = Pauli(label)
value = Operator(pauli.evolve(gate))
value_h = Operator(pauli.evolve(gate, frame="h"))
value_s = Operator(pauli.evolve(gate, frame="s"))
value_inv = Operator(pauli.evolve(gate.inverse()))
target = op.adjoint().dot(pauli).dot(op)
self.assertEqual(value, target)
self.assertEqual(value, value_h)
self.assertEqual(value_inv, value_s)
@data(*it.product((CXGate(), CYGate(), CZGate(), SwapGate()), pauli_group_labels(2, False)))
@unpack
def test_evolve_clifford2(self, gate, label):
"""Test evolve method for 2-qubit Clifford gates."""
op = Operator(gate)
pauli = Pauli(label)
value = Operator(pauli.evolve(gate))
value_h = Operator(pauli.evolve(gate, frame="h"))
value_s = Operator(pauli.evolve(gate, frame="s"))
value_inv = Operator(pauli.evolve(gate.inverse()))
target = op.adjoint().dot(pauli).dot(op)
self.assertEqual(value, target)
self.assertEqual(value, value_h)
self.assertEqual(value_inv, value_s)
@data(
*it.product(
(
IGate(),
XGate(),
YGate(),
ZGate(),
HGate(),
SGate(),
SdgGate(),
CXGate(),
CYGate(),
CZGate(),
SwapGate(),
),
[int, np.int8, np.uint8, np.int16, np.uint16, np.int32, np.uint32, np.int64, np.uint64],
)
)
@unpack
def test_phase_dtype_evolve_clifford(self, gate, dtype):
"""Test phase dtype for evolve method for Clifford gates."""
z = np.ones(gate.num_qubits, dtype=bool)
x = np.ones(gate.num_qubits, dtype=bool)
phase = (np.sum(z & x) % 4).astype(dtype)
paulis = Pauli((z, x, phase))
evo = paulis.evolve(gate)
self.assertEqual(evo.phase.dtype, dtype)
def test_evolve_clifford_qargs(self):
"""Test evolve method for random Clifford"""
cliff = random_clifford(3, seed=10)
op = Operator(cliff)
pauli = random_pauli(5, seed=10)
qargs = [3, 0, 1]
value = Operator(pauli.evolve(cliff, qargs=qargs))
value_h = Operator(pauli.evolve(cliff, qargs=qargs, frame="h"))
value_s = Operator(pauli.evolve(cliff, qargs=qargs, frame="s"))
value_inv = Operator(pauli.evolve(cliff.adjoint(), qargs=qargs))
target = Operator(pauli).compose(op.adjoint(), qargs=qargs).dot(op, qargs=qargs)
self.assertEqual(value, target)
self.assertEqual(value, value_h)
self.assertEqual(value_inv, value_s)
def test_barrier_delay_sim(self):
"""Test barrier and delay instructions can be simulated"""
target_circ = QuantumCircuit(2)
target_circ.x(0)
target_circ.y(1)
target = Pauli(target_circ)
circ = QuantumCircuit(2)
circ.x(0)
circ.delay(100, 0)
circ.barrier([0, 1])
circ.y(1)
value = Pauli(circ)
self.assertEqual(value, target)
@data(("", 0), ("-", 2), ("i", 3), ("-1j", 1))
@unpack
def test_zero_qubit_pauli_construction(self, label, phase):
"""Test that Paulis of zero qubits can be constructed."""
expected = Pauli(label + "X")[0:0] # Empty slice from a 1q Pauli, which becomes phaseless
expected.phase = phase
test = Pauli(label)
self.assertEqual(expected, test)
if __name__ == "__main__":
unittest.main()
|
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
|
gustavomirapalheta
|
import numpy as np
V = np.array([[3+2j],[4-2j]])
modV = np.real(V.T.conjugate().dot(V)[0,0])**0.5
Vn = V/modV; Vn
v0 = np.array([[1,0]]).T
v1 = np.array([[0,1]]).T
Vn[0,0]*v0 + Vn[1,0]*v1
Vn[0,0].conjugate()*Vn[0,0]
Vn[1,0].conjugate()*Vn[1,0]
import numpy as np
CNOT = np.array([[1,0,0,0],
[0,1,0,0],
[0,0,0,1],
[0,0,1,0]])
CNOT.dot(CNOT)
import numpy as np
H = np.array([[1,1],[1,-1]])/2**0.5
H.dot(H)
import numpy as np
X = np.array([[0,1],
[1,0]])
X
X.conj().T.dot(X)
Y = np.array([[0,-1j],
[1j,0]])
Y
Y.conj().T.dot(Y)
Z = np.array([[1,0],
[0,-1]])
Z
Z.conj().T.dot(Z)
H = (X+Z)/np.sqrt(2); H
H.dot(Z).dot(H)
H.dot(X).dot(H)
-H.dot(Y).dot(H)
import numpy as np
S = np.array([[1,0],
[0,1j]])
S
S.conj().T.dot(S)
T = np.array([[1,0],
[0,np.exp(1j*np.pi/4)]])
T
T.conj().T.dot(T)
S = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]]); S
v00 = np.array([[1,0,0,0]]).T
S.dot(v00)
v01 = np.array([[0,1,0,0]]).T
S.dot(v01)
v10 = np.array([[0,0,1,0]]).T
S.dot(v10)
v11 = np.array([[0,0,0,1]]).T
S.dot(v11)
C = np.array([[1,0,0,0],
[0,1,0,0],
[0,0,0,1],
[0,0,1,0]]);C
C_ = np.array([[1,0,0,0],
[0,0,0,1],
[0,0,1,0],
[0,1,0,0]]);C_
C.dot(C_).dot(C)
v = v0 + v1; v
n = np.array([[0,0],[0,1]]); n
n.dot(v)
n_ = np.array([[1,0],[0,0]]);n_
I2 = np.identity(2); I2
I2 - n
n_.dot(v)
n.dot(n)
n_.dot(n_)
n.dot(n_)
n_.dot(n)
n+n_
n.dot(X)
X.dot(n_)
import numpy as np
n = np.array([[0,0],[0,1]]); n
n_ = np.array([[1,0],[0,0]]);n_
# ni nj operam em bits distintos. Como cada operador n atua em um vetor de
# 2 dimensões, ni nj é um operador de 4 dimensões. Sendo assim, fica implícito
# pelos subscritos que ni nj é um produto tensorial.
np.kron(n,n)
# O mesmo vale para n'i n'j
np.kron(n_,n_)
# Para ni n'j
np.kron(n,n_)
# E para n'i nj
np.kron(n_,n)
# Xi Xj são dois operadores 2x2 de inversão, cada um atuando em um bit
# distinto. Sendo assim, fazemos o produto tensorial entre ambos
# para obter XiXj
np.kron(X,X)
# No caso da expressão XiXj(ninj' + ni'nj) temos entre parênteses duas
# matrizes 4x4 (ninj'+ni'nj) e fora dos parênteses uma matriz 4x4 (XiXj)
# Sendo assim fazemos neste caso o produto matricial normal para
# calcular esta expressão.
np.kron(X,X).dot(np.kron(n,n_)+np.kron(n_,n))
# E por último somamos com o resultado inicial de ninj + ni'nj'
# Como pode-se ver, esta expressão gera o operador de SWAP
np.kron(n,n) + np.kron(n_,n_) + np.kron(X,X).dot(np.kron(n,n_)+np.kron(n_,n))
# É importante observar que ninj forma um operador que projeta um vetor de
# 4 dimensões (00, 01, 10, 11) em sua componente 11
np.kron(n,n)
# De maneira similar ni'nj' projeta um vetor de 4 dimensões em sua componente 00
np.kron(n_,n_)
# ni'nj projeta em 01
np.kron(n_,n)
# Assim como ninj' projeta em 10
np.kron(n,n_)
# E por último vemos que ni'nj' + ni'nj + ninj' + ninj = I
nn = np.kron(n,n)
nn_ = np.kron(n,n_)
n_n = np.kron(n_,n)
n_n_ = np.kron(n_,n_)
nn + nn_ + n_n + n_n_
import numpy as np
n = np.array([[0,0],[0,1]]); n
n_ = np.array([[1,0],[0,0]]);n_
# (n x n).(n_ x n_)
np.kron(n,n).dot(np.kron(n_,n_))
# Faz sentido que (ni x nj).(ni_ x nj_) seja o vetor nulo pois:
# ni_ x nj_ é um operador que recebe um vetor de 4 dimensões e
# produz como resultado apenas sua componente |00>. Por sua
# vez ni x nj é um operador que recebe um vetor de 4 dimensões
# e produz como resultado apenas sua componente |11>. Esta
# componente foi zerada pelo primeiro operador, logo o resultado
# será nulo. Isto vai acontecer sempre que a componente não
# zerada do primeiro operador for diferente da do segundo em
# outras palavras sempre que ij do primeiro for diferente de ij
# do segundo.
np.kron(n,n).dot(np.kron(n_,n_))
# Outra forma de entender é transformar (n x n).(n_ x n_) em
# (n.n_) x (n.n_). Como n é ortogonal a n_, a projeção de n
# em n_ dará zero também.
np.kron(n.dot(n_),n.dot(n_))
nn.dot(n_n_)
# (n_ x n).(n x n_)
np.kron(n_,n).dot(np.kron(n,n_))
n_n.dot(nn_)
# (n x n_).(n_ x n)
np.kron(n, n_).dot(np.kron(n_,n))
nn_.dot(n_n)
# (n_ x n_).(n x n)
np.kron(n_, n_).dot(np.kron(n, n))
n_n_.dot(nn)
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import *
qc1=QuantumCircuit(2,2)
qc2=QuantumCircuit(3,3)
#qc=qc1+qc2
#qc.draw()
#Note: circuits are incompatible
qc1=QuantumCircuit(2,2)
qc1.h(0)
qc1.s(1)
qc2=QuantumCircuit(2,2)
qc2.x(1)
qc2.cx(0,1)
qc1.draw(output='mpl')
qc2.draw(output='mpl')
qc=qc1+qc2
qc.draw(output='mpl')
qc1=QuantumCircuit(2,2)
qc1.h(0)
qc1.s(1)
qc1.draw(output='mpl')
qc2=QuantumCircuit(3,3)
qc2.x(1)
qc2.cx(0,2)
qc2.draw(output='mpl')
# rhs added to lhs
qc=qc2.compose(qc1)
qc.draw(output='mpl')
qc.num_qubits
# If inplace attribute is not included , then it returns QuantumCircuit
type(qc2.compose(qc1))
qc1=QuantumCircuit(2,2)
qc1.h(0)
qc1.s(1)
qc2=QuantumCircuit(3,3)
qc2.x(1)
qc2.cx(0,2)
qc2.compose(qc1,inplace=True)
qc2.draw(output='mpl')
type(qc2)
qc2.num_qubits
# If inplace attribute is true , then it returns None
type(qc2.compose(qc1,inplace=True))
qc1=QuantumCircuit(2,2)
qc1.h(0)
qc1.s(1)
qc2=QuantumCircuit(3,3)
qc2.x(1)
qc2.cx(0,2)
qc2.compose(qc1,qubits=[2,1],inplace=True)
qc2.draw(output='mpl')
qc=QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.x(1)
qc.draw(output='mpl')
qc_meas=QuantumCircuit(2)
qc_meas.measure_all()
qc_meas.draw(output='mpl')
qc.compose(qc_meas,inplace=True)
qc.draw(output='mpl')
|
https://github.com/ShabaniLab/q-camp
|
ShabaniLab
|
import numpy as np
# import numpy
# this is a comment
pi_number = np.pi
print(pi_number)
e_number = np.e
print(e_number)
# float with specific number of decimals
print("pie is {0:.5f}, {1}".format(pi_number, " test"))
print(f"pi is {pi_number}")
print("The Euler number is {0:.2f}".format(e_number))
# scientific format with a given number of decimals
x = 3074.1e4
print("x is {0:.2e}".format(x))
# define an array manually
A = np.array([0, 3, 7, -2])
# print(A)
print("A is " + str(A))
# define an array with linearly spaced components
B = np.linspace(0, 1, num=11, endpoint=True)
print("B is " + str(B))
# print the size of the array
print(np.size(A))
print(np.size(B))
# square
x = 2.0
y = np.square(x)
print("y is " + str(y))
# square root
a = 36
b = np.sqrt(a)
print("b is " + str(b))
theta = np.pi/4
f = np.cos(theta)
print(f)
print(np.sqrt(2)/2)
# custom functions
def my_function(x):
return x**3
print(my_function(2))
print(my_function(3))
print(my_function(A))
B = np.array([[1, -2, 3, -4], [0, -1.5, 3, 7 + 1j]])
print(B*2)
print(type(B))
C = [1, 2, "test", my_function]
print(C)
M = np.ones((4, 7))
N = np.ones((7, 3))
print(np.matmul(M, N))
def another_function(x):
return x**3 -3*x**2 + 2
x = np.linspace(-2, 2, num=101)
y = another_function(x)
print(np.size(x))
print(np.size(y))
import matplotlib.pyplot as plt
# make figure
fig = plt.figure()
# get the axes
ax = plt.axes()
# plot y array versus x array
# ax.plot(x, y)
ax.scatter(x, y, s=1)
# labels
ax.set_xlabel('the x axis')
ax.set_ylabel('y = f(x)')
# show the plot
plt.show()
|
https://github.com/Qiskit/feedback
|
Qiskit
|
%load_ext autoreload
%autoreload 2
import qiskit_metal as metal
from qiskit_metal import designs, draw
from qiskit_metal import MetalGUI, Dict, open_docs
%metal_heading Welcome to Qiskit Metal!
from qiskit_metal.qlibrary.qubits.transmon_pocket_6 import TransmonPocket6
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
from qiskit_metal.qlibrary.tlines.pathfinder import RoutePathfinder
from qiskit_metal.qlibrary.tlines.straight_path import RouteStraight
from qiskit_metal.qlibrary.lumped.cap_n_interdigital import CapNInterdigital
from qiskit_metal.qlibrary.couplers.cap_n_interdigital_tee import CapNInterdigitalTee
from qiskit_metal.qlibrary.terminations.launchpad_wb import LaunchpadWirebond
design = metal.designs.DesignPlanar()
gui = metal.MetalGUI(design)
design.overwrite_enabled = True
design.chips.main
design.chips.main.size.size_x = '6mm'
design.chips.main.size.size_y = '6mm'
TransmonPocket6.get_template_options(design)
q_0 = TransmonPocket6(design,'Q_0', options = dict(
pos_x='-1.25mm',
pos_y='0.5mm',
gds_cell_name ='FakeJunction_01',
hfss_inductance ='14nH',
pad_width = '425 um',
pocket_height = '650um',
connection_pads=dict(
readout = dict(loc_W=0, loc_H=1, pad_width = '80um', pad_gap = '50um'),
bus_01 = dict(loc_W=1, loc_H=-1, pad_width = '60um', pad_gap = '10um'),
bus_02 = dict(loc_W=-1, loc_H=-1, pad_width = '60um', pad_gap = '10um')
)))
q_1 = TransmonPocket6(design,'Q_1', options = dict(
pos_x='1.25mm',
pos_y='0.5mm',
gds_cell_name ='FakeJunction_01',
hfss_inductance ='14nH',
pad_width = '425 um',
pocket_height = '650um',
connection_pads=dict(
readout = dict(loc_W=0, loc_H=1, pad_width = '80um', pad_gap = '50um'),
bus_01 = dict(loc_W=-1, loc_H=-1, pad_width = '60um', pad_gap = '10um'),
bus_12 = dict(loc_W=1, loc_H=-1, pad_width = '60um', pad_gap = '10um')
)))
q_2 = TransmonPocket6(design,'Q_2', options = dict(
pos_x='0mm',
pos_y='-1.35mm',
gds_cell_name ='FakeJunction_01',
hfss_inductance ='14nH',
pad_width = '425 um',
pocket_height = '650um',
connection_pads=dict(
readout = dict(loc_W=0, loc_H=-1, pad_width = '80um', pad_gap = '50um'),
bus_02 = dict(loc_W=-1, loc_H=1, pad_width = '60um', pad_gap = '10um'),
bus_12 = dict(loc_W=1, loc_H=1, pad_width = '60um', pad_gap = '10um')
)))
gui.rebuild()
gui.autoscale()
from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength
def find_resonator_length(frequency, line_width, line_gap, N):
#frequency in GHz
#line_width/line_gap in um
#N -> 2 for lambda/2, 4 for lambda/4
#substrate dimensions and properties already set
[lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6,
line_gap*10**-6, 750*10**-6, 200*10**-9, 11.9)
return str(lambdaG/N*10**3)+" mm"
?guided_wavelength
q_0.pins.keys()
find_resonator_length(5.8,10,6,2) #Note: What might be wrong with this length?
bus_01 = RouteMeander(design,'Bus_01', options = dict(hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component='Q_0',
pin='bus_01'),
end_pin=Dict(
component='Q_1',
pin='bus_01')
),
lead=Dict(
start_straight='125um',
end_straight = '125um'
),
meander=Dict(
asymmetry = '50um'),
fillet = "99um",
total_length = '10.3mm'))
gui.rebuild()
gui.autoscale()
bus_02 = RouteMeander(design,'Bus_02', options = dict(hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component='Q_0',
pin='bus_02'),
end_pin=Dict(
component='Q_2',
pin='bus_02')
),
lead=Dict(
start_straight='125um',
end_straight = '125um'
),
meander=Dict(
asymmetry = '50um'),
fillet = "99um",
total_length = '10mm'))
bus_12 = RouteMeander(design,'Bus_12', options = dict(hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component='Q_1',
pin='bus_12'),
end_pin=Dict(
component='Q_2',
pin='bus_12')
),
lead=Dict(
start_straight='125um',
end_straight = '125um'
),
meander=Dict(
asymmetry = '50um'),
fillet = "99um",
total_length = '9.7mm'))
gui.rebuild()
gui.autoscale()
from collections import OrderedDict
bus_01 = RouteMeander(design,'Bus_01', options = dict(hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component='Q_0',
pin='bus_01'),
end_pin=Dict(
component='Q_1',
pin='bus_01')
),
lead=Dict(
start_straight='125um',
end_straight = '125um'
),
meander=Dict(
asymmetry = '-350um'),
fillet = "99um",
total_length = '10.3mm'))
jogs_start = OrderedDict()
jogs_start[0] = ["L", '350um']
jogs_start[1] = ["L", '500um']
bus_02 = RouteMeander(design,'Bus_02', options = dict(hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component='Q_0',
pin='bus_02'),
end_pin=Dict(
component='Q_2',
pin='bus_02')
),
lead=Dict(
start_straight='125um',
end_straight = '225um',
start_jogged_extension=jogs_start,
#end_jogged_extension = jogs_end
),
meander=Dict(
asymmetry = '-50um'),
fillet = "99um",
total_length = '10mm'))
jogs_start = OrderedDict()
jogs_start[0] = ["R", '350um']
jogs_start[1] = ["R", '700um']
bus_12 = RouteMeander(design,'Bus_12', options = dict(hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component='Q_1',
pin='bus_12'),
end_pin=Dict(
component='Q_2',
pin='bus_12')
),
lead=Dict(
start_straight='325um',
end_straight = '25um',
start_jogged_extension=jogs_start
),
meander=Dict(
asymmetry = '50um'),
fillet = "99um",
total_length = '9.7mm'))
gui.rebuild()
gui.autoscale()
launch_readout_q_0 = LaunchpadWirebond(design, 'Launch_Readout_Q_0',
options = dict(pos_x = '-2mm',
pos_y ='2.5mm',
orientation = '-90'))
launch_readout_q_1 = LaunchpadWirebond(design, 'Launch_Readout_Q_1',
options = dict(pos_x = '2mm',
pos_y ='2.5mm',
orientation = '-90'))
launch_readout_q_2 = LaunchpadWirebond(design, 'Launch_Readout_Q_2',
options = dict(pos_x = '-2mm',
pos_y ='-2.5mm',
orientation = '90'))
gui.rebuild()
gui.autoscale()
cap_readout_q_2 = CapNInterdigital(design,'Cap_Readout_Q_2', options = dict(pos_x = '-2mm', pos_y ='-2.25mm', orientation = '0'))
cap_readout_q_0 = CapNInterdigitalTee(design,'Cap_Readout_Q_0', options=dict(pos_x = '-1.5mm', pos_y = '2.25mm',
orientation = '0'))
cap_readout_q_1 = CapNInterdigitalTee(design,'Cap_Readout_Q_1', options=dict(pos_x = '1.5mm', pos_y = '2.25mm',
orientation = '0'))
gui.rebuild()
gui.autoscale()
find_resonator_length(7.2,10,6,2)
jogs_start = OrderedDict()
jogs_start[0] = ["L", '350um']
#jogs_start[1] = ["R", '700um']
readout_0 = RouteMeander(design,'Readout_0', options = dict(hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component='Q_0',
pin='readout'),
end_pin=Dict(
component='Cap_Readout_Q_0',
pin='second_end')
),
lead=Dict(
start_straight='125um',
end_straight = '25um',
start_jogged_extension=jogs_start,
#end_jogged_extension = jogs_end
),
meander=Dict(
asymmetry = '50um'),
fillet = "99um",
total_length = '8.8mm'))
jogs_start = OrderedDict()
jogs_start[0] = ["R", '350um']
readout_1 = RouteMeander(design,'Readout_1', options = dict(hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component='Q_1',
pin='readout'),
end_pin=Dict(
component='Cap_Readout_Q_1',
pin='second_end')
),
lead=Dict(
start_straight='125um',
end_straight = '25um',
start_jogged_extension=jogs_start,
#end_jogged_extension = jogs_end
),
meander=Dict(
asymmetry = '50um'),
fillet = "99um",
total_length = '8.5mm'))
readout_2 = RouteMeander(design,'Readout_2', options = dict(hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component='Q_2',
pin='readout'),
end_pin=Dict(
component='Cap_Readout_Q_2',
pin='north_end')
),
lead=Dict(
start_straight='125um',
end_straight = '25um',
),
meander=Dict(
asymmetry = '200um'),
fillet = "99um",
total_length = '8.3mm'))
gui.rebuild()
gui.autoscale()
tl_readout_q_2= RouteStraight(design,'TL_Readout_Q_2', options = dict(hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component='Cap_Readout_Q_2',
pin='south_end'),
end_pin=Dict(
component='Launch_Readout_Q_2',
pin='tie')),
trace_width = '10um',
trace_gap = '6um'
))
tl_readout_q_0 = RoutePathfinder(design,'TL_Readout_Q_0', options = dict(hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component='Cap_Readout_Q_0',
pin='prime_start'),
end_pin=Dict(
component='Launch_Readout_Q_0',
pin='tie')),
fillet = '99um',
trace_width = '10um',
trace_gap = '6um'
))
tl_readout_q_1 = RoutePathfinder(design,'TL_Readout_Q_1', options = dict(hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component='Cap_Readout_Q_1',
pin='prime_end'),
end_pin=Dict(
component='Launch_Readout_Q_1',
pin='tie')),
fillet = '99um',
trace_width = '10um',
trace_gap = '6um'
))
tl_readout_q_01= RouteStraight(design,'TL_Readout_Q_01', options = dict(hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component='Cap_Readout_Q_0',
pin='prime_end'),
end_pin=Dict(
component='Cap_Readout_Q_1',
pin='prime_start')),
trace_width = '10um',
trace_gap = '6um'
))
gui.rebuild()
gui.autoscale()
from qiskit_metal.analyses.quantization import LOManalysis
q_0_LOM = LOManalysis(design, "q3d")
q_0_LOM.sim.setup
q_0_LOM.setup
q_0_LOM.setup.freq_readout = 6.8
q_0_LOM.setup.freq_bus = [5.8,6.0]
q_0_LOM.setup
q_0.pins.keys()
q_0_LOM.run(components=['Q_0'], open_terminations=[('Q_0', 'readout'), ('Q_0', 'bus_01'), ('Q_0', 'bus_02')])
q_0_LOM.plot_convergence();
q_0_LOM.plot_convergence_chi()
q_0_LOM.sim.setup.percent_error = 0.1
q_0_LOM.sim.setup.max_passes = 20
q_0_LOM.run()
q_0_LOM.plot_convergence();
q_0_LOM.plot_convergence_chi()
q_0_LOM.sim.capacitance_matrix
q_0_LOM.lumped_oscillator
q_0.options.pad_gap = '28um'
q_0.options.connection_pads.readout.pad_gap = '22um'
q_0.options.connection_pads.readout.pad_width = '100um'
q_0.options.connection_pads.bus_01.pad_width = '135um'
q_0.options.connection_pads.bus_02.pad_width = '135um'
q_0_LOM.setup.junctions.Lj = 14.9
gui.rebuild()
q_0_LOM.run(name="Q_0_LOM_2",components=['Q_0'], open_terminations=[('Q_0', 'readout'), ('Q_0', 'bus_01'), ('Q_0', 'bus_02')])
q_0_LOM.lumped_oscillator
q_0.options.hfss_inductance = '14.9nH'
gui.rebuild()
q_0_LOM.sim.close()
from qiskit_metal.analyses.quantization import EPRanalysis
bus_02_EPR = EPRanalysis(design, "hfss")
bus_02_EPR.sim.setup
bus_02_EPR.sim.setup.n_modes = 2
bus_02_EPR.sim.run_sim(name="Bus_02_Sim", components=['Q_0','Q_2','Bus_02'],
ignored_jjs = [('Q_0','rect_jj'),('Q_2','rect_jj')],
box_plus_buffer = False)
bus_02_EPR.sim.plot_convergences()
bus_02_EPR.get_frequencies()
bus_02_EPR.sim.plot_fields('main')
#bus_02_EPR.sim.save_screenshot()
from qiskit_metal.analyses.sweep_and_optimize.sweeping import Sweeping
sweep = Sweeping(design)
?sweep.sweep_one_option_get_eigenmode_solution_data
em_setup_args = Dict(min_freq_ghz=3,
n_modes=1,
max_passes=12,
max_delta_f = 0.1)
all_sweeps, return_code = sweep.sweep_one_option_get_eigenmode_solution_data(
'Bus_02',
'total_length',
['9.4mm', '9.3mm', '9.2mm'],
['Bus_02','Q_0','Q_2'],
[],
[('Q_0','rect_jj'),('Q_2','rect_jj')],
design_name="GetEigenModeSolution",
setup_args=em_setup_args)
frequency = {}
for key in all_sweeps.keys():
frequency[key] = all_sweeps[key]['frequency']
frequency
bus_02.options.total_length = '9.35mm'
bus_02_EPR.sim.close()
q_1.options.pad_gap = '28um'
q_1.options.connection_pads.readout.pad_gap = '20um'
q_1.options.connection_pads.readout.pad_width = '100um'
q_1.options.connection_pads.bus_12.pad_width = '130um'
q_1.options.hfss_inductance = '13.9nH'
bus_01.options.total_length = '9.55mm'
gui.rebuild()
three_mode_EPR = EPRanalysis(design, "hfss")
three_mode_EPR.sim.setup.max_passes = 18
three_mode_EPR.sim.setup.max_delta_f = 0.025
three_mode_EPR.sim.setup.n_modes = 3
three_mode_EPR.sim.setup.vars = Dict(Lj0= '14.9 nH', Cj0= '0 fF',
Lj1= '13.9 nH', Cj1= '0 fF')
three_mode_EPR.sim.run_sim(name="Three_Mode",
components=['Q_0', 'Q_1', 'Bus_01'])
three_mode_EPR.sim.plot_convergences()
del three_mode_EPR.setup.junctions['jj']
three_mode_EPR.setup.junctions.jj0 = Dict(rect='JJ_rect_Lj_Q_0_rect_jj', line='JJ_Lj_Q_0_rect_jj_',
Lj_variable='Lj0', Cj_variable='Cj0')
three_mode_EPR.setup.junctions.jj1 = Dict(rect='JJ_rect_Lj_Q_1_rect_jj', line='JJ_Lj_Q_1_rect_jj_',
Lj_variable='Lj1', Cj_variable='Cj1')
three_mode_EPR.setup.sweep_variable = 'Lj0'
three_mode_EPR.setup
three_mode_EPR.setup
three_mode_EPR.run_epr()
three_mode_EPR.sim.close()
mt_gds = design.renderers.gds
mt_gds.options
mt_gds.options.path_filename = '../resources/Fake_Junctions.GDS'
mt_gds.options.no_cheese.buffer = '40um'
mt_gds.options.max_points = 2555
mt_gds.options.cheese.cheese_0_x = '3um'
mt_gds.options.cheese.cheese_0_y = '3um'
mt_gds.options.cheese.delta_x = '50um'
mt_gds.options.cheese.delta_y = '50um'
mt_gds.options.cheese.view_in_file= {'main': {1: True}}
mt_gds.options.fabricate = True
mt_gds.export_to_gds("MetalTutorial.gds")
|
https://github.com/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
import logging
import random
from abc import ABC
from sys import maxsize
from qiskit import QuantumCircuit
from qiskit.circuit.gate import Gate
from qiskit.quantum_info import Operator, random_clifford, random_unitary
from qiskit.transpiler.passes import Collect2qBlocks, ConsolidateBlocks, CountOps
from qiskit.transpiler.passmanager import PassManager
from slam.utils.gates.custom_gates import RiSwapGate
from slam.utils.transpiler_pass.weyl_decompose import RootiSwapWeylDecomposition
logger = logging.getLogger()
"""Define functions which act as distributions for a template to train
against."""
class SampleFunction(ABC):
def __init__(self, n_qubits=2, n_samples=1):
self.n_qubits = n_qubits
self.n_samples = n_samples
def __iter__(self):
for _ in range(self.n_samples):
yield self._get_unitary()
def _get_unitary(self):
raise NotImplementedError
class GateSample(SampleFunction):
def __init__(self, gate: Gate, n_samples=1):
self.gate = gate
super().__init__(gate.num_qubits, n_samples)
def _get_unitary(self):
return Operator(self.gate).data
class CircuitSample(SampleFunction):
def __init__(self, circuit: QuantumCircuit):
pm = PassManager([Collect2qBlocks(), ConsolidateBlocks(force_consolidate=True)])
self.transpiled_circuit = pm.run(circuit)
super().__init__(n_qubits=2, n_samples=len(self.transpiled_circuit))
logging.info(f"Created sampler with {self.n_samples} 2Q gates")
def __iter__(self):
for instruction in self.transpiled_circuit:
yield self._get_unitary(instruction)
def _get_unitary(self, instruction):
return instruction[0].to_matrix()
class Clifford(SampleFunction):
def _get_unitary(self):
return Operator(random_clifford(num_qubits=self.n_qubits)).data
class HaarSample(SampleFunction):
def __init__(self, seed=None, n_samples=1, n_qubits=2):
self.seed = seed
super().__init__(n_samples=n_samples, n_qubits=n_qubits)
def _get_unitary(self):
random.seed(self.seed)
return random_unitary(
dims=2**self.n_qubits, seed=random.randint(0, maxsize)
).data
def _haar_ground_truth(self, haar_exact=2):
"""When using sqrt[2] iswap, we might want to do a haar sample where we
know ahead of time if it will take 2 or 3 uses this is used for
establishing the effectiveness of our optimizer, but won't work for any
other basis gate."""
logging.warning("This sampler only works for \sqrt[2]iSwap")
pm0 = PassManager()
pm0.append(RootiSwapWeylDecomposition(basis_gate=RiSwapGate(0.5)))
pm0.append(CountOps())
logger.setLevel(
logging.CRITICAL
) # turn off logging here so we don't see lots of irrelevant things
while True:
qc = QuantumCircuit(2)
qc.append(random_unitary(dims=4), [0, 1])
pm0.run(qc)
if haar_exact == pm0.property_set["count_ops"]["riswap"]:
logger.setLevel(logging.INFO)
return qc
class Haar2Sample(HaarSample):
def __init__(self, seed=None, n_samples=1):
super().__init__(seed=seed, n_samples=n_samples)
def _get_unitary(self):
return Operator(self._haar_ground_truth(2)).data
class Haar3Sample(HaarSample):
def __init__(self, seed=None, n_samples=1):
super().__init__(seed=seed, n_samples=n_samples)
def _get_unitary(self):
return Operator(self._haar_ground_truth(3)).data
|
https://github.com/Axect/QuantumAlgorithms
|
Axect
|
import qiskit
qiskit.__qiskit_version__
# useful additional packages
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# importing Qiskit
from qiskit import BasicAer, IBMQ
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.monitor import job_monitor
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Load our saved IBMQ accounts
IBMQ.load_account()
n = 13 # the length of the first register for querying the oracle
# Choose a type of oracle at random. With probability half it is constant,
# and with the same probability it is balanced
oracleType, oracleValue = np.random.randint(2), np.random.randint(2)
if oracleType == 0:
print("The oracle returns a constant value ", oracleValue)
else:
print("The oracle returns a balanced function")
a = np.random.randint(1,2**n) # this is a hidden parameter for balanced oracle.
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(n+1) #all qubits are initialized to zero
# for recording the measurement on the first register
cr = ClassicalRegister(n)
circuitName = "DeutschJozsa"
djCircuit = QuantumCircuit(qr, cr)
# Create the superposition of all input queries in the first register by applying the Hadamard gate to each qubit.
for i in range(n):
djCircuit.h(qr[i])
# Flip the second register and apply the Hadamard gate.
djCircuit.x(qr[n])
djCircuit.h(qr[n])
# Apply barrier to mark the beginning of the oracle
djCircuit.barrier()
if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue for all input.
if oracleValue == 1:
djCircuit.x(qr[n])
else:
djCircuit.iden(qr[n])
else: # Otherwise, it returns the inner product of the input with a (non-zero bitstring)
for i in range(n):
if (a & (1 << i)):
djCircuit.cx(qr[i], qr[n])
# Apply barrier to mark the end of the oracle
djCircuit.barrier()
# Apply Hadamard gates after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
# Measurement
djCircuit.barrier()
for i in range(n):
djCircuit.measure(qr[i], cr[i])
#draw the circuit
djCircuit.draw(output='mpl',scale=0.5)
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
job = execute(djCircuit, backend=backend, shots=shots)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
backend = IBMQ.get_backend('ibmq_16_melbourne')
djCompiled = transpile(djCircuit, backend=backend, optimization_level=1)
djCompiled.draw(output='mpl',scale=0.5)
job = execute(djCompiled, backend=backend, shots=1024)
job_monitor(job)
results = job.result()
answer = results.get_counts()
threshold = int(0.01 * shots) # the threshold of plotting significant measurements
filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} # filter the answer for better view of plots
removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) # number of counts removed
filteredAnswer['other_bitstrings'] = removedCounts # the removed counts are assigned to a new index
plot_histogram(filteredAnswer)
print(filteredAnswer)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# =============================================================================
"""Test Estimator Gradients"""
import unittest
import numpy as np
from ddt import ddt, data, unpack
from qiskit import QuantumCircuit
from qiskit_algorithms.gradients import (
FiniteDiffEstimatorGradient,
LinCombEstimatorGradient,
ParamShiftEstimatorGradient,
SPSAEstimatorGradient,
ReverseEstimatorGradient,
DerivativeType,
)
from qiskit.circuit import Parameter
from qiskit.circuit.library import EfficientSU2, RealAmplitudes
from qiskit.circuit.library.standard_gates import RXXGate, RYYGate, RZXGate, RZZGate
from qiskit.primitives import Estimator
from qiskit.quantum_info import Operator, SparsePauliOp, Pauli
from qiskit.quantum_info.random import random_pauli_list
from qiskit.test import QiskitTestCase
from .logging_primitives import LoggingEstimator
gradient_factories = [
lambda estimator: FiniteDiffEstimatorGradient(estimator, epsilon=1e-6, method="central"),
lambda estimator: FiniteDiffEstimatorGradient(estimator, epsilon=1e-6, method="forward"),
lambda estimator: FiniteDiffEstimatorGradient(estimator, epsilon=1e-6, method="backward"),
ParamShiftEstimatorGradient,
LinCombEstimatorGradient,
lambda estimator: ReverseEstimatorGradient(), # does not take an estimator!
]
@ddt
class TestEstimatorGradient(QiskitTestCase):
"""Test Estimator Gradient"""
@data(*gradient_factories)
def test_gradient_operators(self, grad):
"""Test the estimator gradient for different operators"""
estimator = Estimator()
a = Parameter("a")
qc = QuantumCircuit(1)
qc.h(0)
qc.p(a, 0)
qc.h(0)
gradient = grad(estimator)
op = SparsePauliOp.from_list([("Z", 1)])
correct_result = -1 / np.sqrt(2)
param = [np.pi / 4]
value = gradient.run([qc], [op], [param]).result().gradients[0]
self.assertAlmostEqual(value[0], correct_result, 3)
op = SparsePauliOp.from_list([("Z", 1)])
value = gradient.run([qc], [op], [param]).result().gradients[0]
self.assertAlmostEqual(value[0], correct_result, 3)
op = Operator.from_label("Z")
value = gradient.run([qc], [op], [param]).result().gradients[0]
self.assertAlmostEqual(value[0], correct_result, 3)
@data(*gradient_factories)
def test_single_circuit_observable(self, grad):
"""Test the estimator gradient for a single circuit and observable"""
estimator = Estimator()
a = Parameter("a")
qc = QuantumCircuit(1)
qc.h(0)
qc.p(a, 0)
qc.h(0)
gradient = grad(estimator)
op = SparsePauliOp.from_list([("Z", 1)])
correct_result = -1 / np.sqrt(2)
param = [np.pi / 4]
value = gradient.run(qc, op, [param]).result().gradients[0]
self.assertAlmostEqual(value[0], correct_result, 3)
@data(*gradient_factories)
def test_gradient_p(self, grad):
"""Test the estimator gradient for p"""
estimator = Estimator()
a = Parameter("a")
qc = QuantumCircuit(1)
qc.h(0)
qc.p(a, 0)
qc.h(0)
gradient = grad(estimator)
op = SparsePauliOp.from_list([("Z", 1)])
param_list = [[np.pi / 4], [0], [np.pi / 2]]
correct_results = [[-1 / np.sqrt(2)], [0], [-1]]
for i, param in enumerate(param_list):
gradients = gradient.run([qc], [op], [param]).result().gradients[0]
for j, value in enumerate(gradients):
self.assertAlmostEqual(value, correct_results[i][j], 3)
@data(*gradient_factories)
def test_gradient_u(self, grad):
"""Test the estimator gradient for u"""
estimator = Estimator()
a = Parameter("a")
b = Parameter("b")
c = Parameter("c")
qc = QuantumCircuit(1)
qc.h(0)
qc.u(a, b, c, 0)
qc.h(0)
gradient = grad(estimator)
op = SparsePauliOp.from_list([("Z", 1)])
param_list = [[np.pi / 4, 0, 0], [np.pi / 4, np.pi / 4, np.pi / 4]]
correct_results = [[-0.70710678, 0.0, 0.0], [-0.35355339, -0.85355339, -0.85355339]]
for i, param in enumerate(param_list):
gradients = gradient.run([qc], [op], [param]).result().gradients[0]
for j, value in enumerate(gradients):
self.assertAlmostEqual(value, correct_results[i][j], 3)
@data(*gradient_factories)
def test_gradient_efficient_su2(self, grad):
"""Test the estimator gradient for EfficientSU2"""
estimator = Estimator()
qc = EfficientSU2(2, reps=1)
op = SparsePauliOp.from_list([("ZI", 1)])
gradient = grad(estimator)
param_list = [
[np.pi / 4 for param in qc.parameters],
[np.pi / 2 for param in qc.parameters],
]
correct_results = [
[
-0.35355339,
-0.70710678,
0,
0.35355339,
0,
-0.70710678,
0,
0,
],
[0, 0, 0, 1, 0, 0, 0, 0],
]
for i, param in enumerate(param_list):
gradients = gradient.run([qc], [op], [param]).result().gradients[0]
np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3)
@data(*gradient_factories)
def test_gradient_2qubit_gate(self, grad):
"""Test the estimator gradient for 2 qubit gates"""
estimator = Estimator()
for gate in [RXXGate, RYYGate, RZZGate, RZXGate]:
param_list = [[np.pi / 4], [np.pi / 2]]
correct_results = [
[-0.70710678],
[-1],
]
op = SparsePauliOp.from_list([("ZI", 1)])
for i, param in enumerate(param_list):
a = Parameter("a")
qc = QuantumCircuit(2)
gradient = grad(estimator)
if gate is RZZGate:
qc.h([0, 1])
qc.append(gate(a), [qc.qubits[0], qc.qubits[1]], [])
qc.h([0, 1])
else:
qc.append(gate(a), [qc.qubits[0], qc.qubits[1]], [])
gradients = gradient.run([qc], [op], [param]).result().gradients[0]
np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3)
@data(*gradient_factories)
def test_gradient_parameter_coefficient(self, grad):
"""Test the estimator gradient for parameter variables with coefficients"""
estimator = Estimator()
qc = RealAmplitudes(num_qubits=2, reps=1)
qc.rz(qc.parameters[0].exp() + 2 * qc.parameters[1], 0)
qc.rx(3.0 * qc.parameters[0] + qc.parameters[1].sin(), 1)
qc.u(qc.parameters[0], qc.parameters[1], qc.parameters[3], 1)
qc.p(2 * qc.parameters[0] + 1, 0)
qc.rxx(qc.parameters[0] + 2, 0, 1)
gradient = grad(estimator)
param_list = [[np.pi / 4 for _ in qc.parameters], [np.pi / 2 for _ in qc.parameters]]
correct_results = [
[-0.7266653, -0.4905135, -0.0068606, -0.9228880],
[-3.5972095, 0.10237173, -0.3117748, 0],
]
op = SparsePauliOp.from_list([("ZI", 1)])
for i, param in enumerate(param_list):
gradients = gradient.run([qc], [op], [param]).result().gradients[0]
np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3)
@data(*gradient_factories)
def test_gradient_parameters(self, grad):
"""Test the estimator gradient for parameters"""
estimator = Estimator()
a = Parameter("a")
b = Parameter("b")
qc = QuantumCircuit(1)
qc.rx(a, 0)
qc.rx(b, 0)
gradient = grad(estimator)
param_list = [[np.pi / 4, np.pi / 2]]
correct_results = [
[-0.70710678],
]
op = SparsePauliOp.from_list([("Z", 1)])
for i, param in enumerate(param_list):
gradients = gradient.run([qc], [op], [param], parameters=[[a]]).result().gradients[0]
np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3)
# parameter order
with self.subTest(msg="The order of gradients"):
c = Parameter("c")
qc = QuantumCircuit(1)
qc.rx(a, 0)
qc.rz(b, 0)
qc.rx(c, 0)
param_list = [[np.pi / 4, np.pi / 2, np.pi / 3]]
correct_results = [
[-0.35355339, 0.61237244, -0.61237244],
[-0.61237244, 0.61237244, -0.35355339],
[-0.35355339, -0.61237244],
[-0.61237244, -0.35355339],
]
param = [[a, b, c], [c, b, a], [a, c], [c, a]]
op = SparsePauliOp.from_list([("Z", 1)])
for i, p in enumerate(param):
gradient = grad(estimator)
gradients = (
gradient.run([qc], [op], param_list, parameters=[p]).result().gradients[0]
)
np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3)
@data(*gradient_factories)
def test_gradient_multi_arguments(self, grad):
"""Test the estimator gradient for multiple arguments"""
estimator = Estimator()
a = Parameter("a")
b = Parameter("b")
qc = QuantumCircuit(1)
qc.rx(a, 0)
qc2 = QuantumCircuit(1)
qc2.rx(b, 0)
gradient = grad(estimator)
param_list = [[np.pi / 4], [np.pi / 2]]
correct_results = [
[-0.70710678],
[-1],
]
op = SparsePauliOp.from_list([("Z", 1)])
gradients = gradient.run([qc, qc2], [op] * 2, param_list).result().gradients
np.testing.assert_allclose(gradients, correct_results, atol=1e-3)
c = Parameter("c")
qc3 = QuantumCircuit(1)
qc3.rx(c, 0)
qc3.ry(a, 0)
param_list2 = [[np.pi / 4], [np.pi / 4, np.pi / 4], [np.pi / 4, np.pi / 4]]
correct_results2 = [
[-0.70710678],
[-0.5],
[-0.5, -0.5],
]
gradients2 = (
gradient.run([qc, qc3, qc3], [op] * 3, param_list2, parameters=[[a], [c], None])
.result()
.gradients
)
np.testing.assert_allclose(gradients2[0], correct_results2[0], atol=1e-3)
np.testing.assert_allclose(gradients2[1], correct_results2[1], atol=1e-3)
np.testing.assert_allclose(gradients2[2], correct_results2[2], atol=1e-3)
@data(*gradient_factories)
def test_gradient_validation(self, grad):
"""Test estimator gradient's validation"""
estimator = Estimator()
a = Parameter("a")
qc = QuantumCircuit(1)
qc.rx(a, 0)
gradient = grad(estimator)
param_list = [[np.pi / 4], [np.pi / 2]]
op = SparsePauliOp.from_list([("Z", 1)])
with self.assertRaises(ValueError):
gradient.run([qc], [op], param_list)
with self.assertRaises(ValueError):
gradient.run([qc, qc], [op, op], param_list, parameters=[[a]])
with self.assertRaises(ValueError):
gradient.run([qc, qc], [op], param_list, parameters=[[a]])
with self.assertRaises(ValueError):
gradient.run([qc], [op], [[np.pi / 4, np.pi / 4]])
def test_spsa_gradient(self):
"""Test the SPSA estimator gradient"""
estimator = Estimator()
with self.assertRaises(ValueError):
_ = SPSAEstimatorGradient(estimator, epsilon=-0.1)
a = Parameter("a")
b = Parameter("b")
qc = QuantumCircuit(2)
qc.rx(b, 0)
qc.rx(a, 1)
param_list = [[1, 1]]
correct_results = [[-0.84147098, 0.84147098]]
op = SparsePauliOp.from_list([("ZI", 1)])
gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, seed=123)
gradients = gradient.run([qc], [op], param_list).result().gradients
np.testing.assert_allclose(gradients, correct_results, atol=1e-3)
# multi parameters
with self.subTest(msg="Multiple parameters"):
gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, seed=123)
param_list2 = [[1, 1], [1, 1], [3, 3]]
gradients2 = (
gradient.run([qc] * 3, [op] * 3, param_list2, parameters=[None, [b], None])
.result()
.gradients
)
correct_results2 = [[-0.84147098, 0.84147098], [0.84147098], [-0.14112001, 0.14112001]]
for grad, correct in zip(gradients2, correct_results2):
np.testing.assert_allclose(grad, correct, atol=1e-3)
# batch size
with self.subTest(msg="Batch size"):
correct_results = [[-0.84147098, 0.1682942]]
gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, batch_size=5, seed=123)
gradients = gradient.run([qc], [op], param_list).result().gradients
np.testing.assert_allclose(gradients, correct_results, atol=1e-3)
# parameter order
with self.subTest(msg="The order of gradients"):
gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, seed=123)
c = Parameter("c")
qc = QuantumCircuit(1)
qc.rx(a, 0)
qc.rz(b, 0)
qc.rx(c, 0)
op = SparsePauliOp.from_list([("Z", 1)])
param_list3 = [[np.pi / 4, np.pi / 2, np.pi / 3]]
param = [[a, b, c], [c, b, a], [a, c], [c, a]]
expected = [
[-0.3535525, 0.3535525, 0.3535525],
[0.3535525, 0.3535525, -0.3535525],
[-0.3535525, 0.3535525],
[0.3535525, -0.3535525],
]
for i, p in enumerate(param):
gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, seed=123)
gradients = (
gradient.run([qc], [op], param_list3, parameters=[p]).result().gradients[0]
)
np.testing.assert_allclose(gradients, expected[i], atol=1e-3)
@data(ParamShiftEstimatorGradient, LinCombEstimatorGradient)
def test_gradient_random_parameters(self, grad):
"""Test param shift and lin comb w/ random parameters"""
rng = np.random.default_rng(123)
qc = RealAmplitudes(num_qubits=3, reps=1)
params = qc.parameters
qc.rx(3.0 * params[0] + params[1].sin(), 0)
qc.ry(params[0].exp() + 2 * params[1], 1)
qc.rz(params[0] * params[1] - params[2], 2)
qc.p(2 * params[0] + 1, 0)
qc.u(params[0].sin(), params[1] - 2, params[2] * params[3], 1)
qc.sx(2)
qc.rxx(params[0].sin(), 1, 2)
qc.ryy(params[1].cos(), 2, 0)
qc.rzz(params[2] * 2, 0, 1)
qc.crx(params[0].exp(), 1, 2)
qc.cry(params[1].arctan(), 2, 0)
qc.crz(params[2] * -2, 0, 1)
qc.dcx(0, 1)
qc.csdg(0, 1)
qc.toffoli(0, 1, 2)
qc.iswap(0, 2)
qc.swap(1, 2)
qc.global_phase = params[0] * params[1] + params[2].cos().exp()
size = 10
op = SparsePauliOp(random_pauli_list(num_qubits=qc.num_qubits, size=size, seed=rng))
op.coeffs = rng.normal(0, 10, size)
estimator = Estimator()
findiff = FiniteDiffEstimatorGradient(estimator, 1e-6)
gradient = grad(estimator)
num_tries = 10
param_values = rng.normal(0, 2, (num_tries, qc.num_parameters)).tolist()
np.testing.assert_allclose(
findiff.run([qc] * num_tries, [op] * num_tries, param_values).result().gradients,
gradient.run([qc] * num_tries, [op] * num_tries, param_values).result().gradients,
rtol=1e-4,
)
@data((DerivativeType.IMAG, -1.0), (DerivativeType.COMPLEX, -1.0j))
@unpack
def test_complex_gradient(self, derivative_type, expected_gradient_value):
"""Tests if the ``LinCombEstimatorGradient`` has the correct value."""
estimator = Estimator()
lcu = LinCombEstimatorGradient(estimator, derivative_type=derivative_type)
reverse = ReverseEstimatorGradient(derivative_type=derivative_type)
for gradient in [lcu, reverse]:
with self.subTest(gradient=gradient):
c = QuantumCircuit(1)
c.rz(Parameter("p"), 0)
result = gradient.run([c], [Pauli("I")], [[0.0]]).result()
self.assertAlmostEqual(result.gradients[0][0], expected_gradient_value)
@data(
FiniteDiffEstimatorGradient,
ParamShiftEstimatorGradient,
LinCombEstimatorGradient,
SPSAEstimatorGradient,
)
def test_options(self, grad):
"""Test estimator gradient's run options"""
a = Parameter("a")
qc = QuantumCircuit(1)
qc.rx(a, 0)
op = SparsePauliOp.from_list([("Z", 1)])
estimator = Estimator(options={"shots": 100})
with self.subTest("estimator"):
if grad is FiniteDiffEstimatorGradient or grad is SPSAEstimatorGradient:
gradient = grad(estimator, epsilon=1e-6)
else:
gradient = grad(estimator)
options = gradient.options
result = gradient.run([qc], [op], [[1]]).result()
self.assertEqual(result.options.get("shots"), 100)
self.assertEqual(options.get("shots"), 100)
with self.subTest("gradient init"):
if grad is FiniteDiffEstimatorGradient or grad is SPSAEstimatorGradient:
gradient = grad(estimator, epsilon=1e-6, options={"shots": 200})
else:
gradient = grad(estimator, options={"shots": 200})
options = gradient.options
result = gradient.run([qc], [op], [[1]]).result()
self.assertEqual(result.options.get("shots"), 200)
self.assertEqual(options.get("shots"), 200)
with self.subTest("gradient update"):
if grad is FiniteDiffEstimatorGradient or grad is SPSAEstimatorGradient:
gradient = grad(estimator, epsilon=1e-6, options={"shots": 200})
else:
gradient = grad(estimator, options={"shots": 200})
gradient.update_default_options(shots=100)
options = gradient.options
result = gradient.run([qc], [op], [[1]]).result()
self.assertEqual(result.options.get("shots"), 100)
self.assertEqual(options.get("shots"), 100)
with self.subTest("gradient run"):
if grad is FiniteDiffEstimatorGradient or grad is SPSAEstimatorGradient:
gradient = grad(estimator, epsilon=1e-6, options={"shots": 200})
else:
gradient = grad(estimator, options={"shots": 200})
options = gradient.options
result = gradient.run([qc], [op], [[1]], shots=300).result()
self.assertEqual(result.options.get("shots"), 300)
# Only default + estimator options. Not run.
self.assertEqual(options.get("shots"), 200)
@data(
FiniteDiffEstimatorGradient,
ParamShiftEstimatorGradient,
LinCombEstimatorGradient,
SPSAEstimatorGradient,
)
def test_operations_preserved(self, gradient_cls):
"""Test non-parameterized instructions are preserved and not unrolled."""
x = Parameter("x")
circuit = QuantumCircuit(2)
circuit.initialize([0.5, 0.5, 0.5, 0.5]) # this should remain as initialize
circuit.crx(x, 0, 1) # this should get unrolled
values = [np.pi / 2]
expect = -1 / (2 * np.sqrt(2))
observable = SparsePauliOp(["XX"])
ops = []
def operations_callback(op):
ops.append(op)
estimator = LoggingEstimator(operations_callback=operations_callback)
if gradient_cls in [SPSAEstimatorGradient, FiniteDiffEstimatorGradient]:
gradient = gradient_cls(estimator, epsilon=0.01)
else:
gradient = gradient_cls(estimator)
job = gradient.run([circuit], [observable], [values])
result = job.result()
with self.subTest(msg="assert initialize is preserved"):
self.assertTrue(all("initialize" in ops_i[0].keys() for ops_i in ops))
with self.subTest(msg="assert result is correct"):
self.assertAlmostEqual(result.gradients[0].item(), expect, places=5)
if __name__ == "__main__":
unittest.main()
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
"""
Shor's Order Finding Algorithm Benchmark - QSim
"""
import math
import sys
import time
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
sys.path[1:1] = ["_common", "_common/qsim", "shors/_common", "quantum-fourier-transform/qsim"]
sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../shors/_common", "../../quantum-fourier-transform/qsim"]
import execute as ex
import metrics as metrics
from shors_utils import getAngles, getAngle, modinv, generate_base, verify_order
from qft_benchmark import inv_qft_gate
from qft_benchmark import qft_gate
from execute import BenchmarkResult
# Benchmark Name
benchmark_name = "Shor's Order Finding"
np.random.seed(0)
verbose = False
QC_ = None
PHIADD_ = None
CCPHIADDMODN_ = None
CMULTAMODN_ = None
CUA_ = None
QFT_ = None
############### Circuit Definition
#Creation of the circuit that performs addition by a in Fourier Space
#Can also be used for subtraction by setting the parameter inv to a value different from 0
def phiADD(num_qubits, a):
qc = QuantumCircuit(num_qubits, name = "\u03C6ADD")
angle = getAngles(a, num_qubits)
for i in range(0, num_qubits):
# addition
qc.p(angle[i], i)
global PHIADD_
if PHIADD_ == None or num_qubits <= 3:
if num_qubits < 4: PHIADD_ = qc
return qc
#Single controlled version of the phiADD circuit
def cphiADD(num_qubits, a):
phiadd_gate = phiADD(num_qubits,a).to_gate()
cphiadd_gate = phiadd_gate.control(1)
return cphiadd_gate
#Doubly controlled version of the phiADD circuit
def ccphiADD(num_qubits, a):
phiadd_gate = phiADD(num_qubits,a).to_gate()
ccphiadd_gate = phiadd_gate.control(2)
return ccphiadd_gate
# Circuit that implements doubly controlled modular addition by a (num qubits should be bit count for number N)
def ccphiADDmodN(num_qubits, a, N):
qr_ctl = QuantumRegister(2)
qr_main = QuantumRegister(num_qubits+1)
qr_ancilla = QuantumRegister(1)
qc = QuantumCircuit(qr_ctl, qr_main,qr_ancilla, name = "cc\u03C6ADDmodN")
# Generate relevant gates for circuit
ccphiadda_gate = ccphiADD(num_qubits+1, a)
ccphiadda_inv_gate = ccphiADD(num_qubits+1, a).inverse()
phiaddN_inv_gate = phiADD(num_qubits+1, N).inverse(); phiaddN_inv_gate.name = "inv_\u03C6ADD"
cphiaddN_gate = cphiADD(num_qubits+1, N)
# Create relevant temporary qubit lists
ctl_main_qubits = [i for i in qr_ctl]; ctl_main_qubits.extend([i for i in qr_main])
anc_main_qubits = [qr_ancilla[0]]; anc_main_qubits.extend([i for i in qr_main])
#Create circuit
qc.append(ccphiadda_gate, ctl_main_qubits)
qc.append(phiaddN_inv_gate, qr_main)
qc.append(inv_qft_gate(num_qubits+1), qr_main)
qc.cx(qr_main[-1], qr_ancilla[0])
qc.append(qft_gate(num_qubits+1), qr_main)
qc.append(cphiaddN_gate, anc_main_qubits)
qc.append(ccphiadda_inv_gate, ctl_main_qubits)
qc.append(inv_qft_gate(num_qubits+1), qr_main)
qc.x(qr_main[-1])
qc.cx(qr_main[-1], qr_ancilla[0])
qc.x(qr_main[-1])
qc.append(qft_gate(num_qubits+1), qr_main)
qc.append(ccphiadda_gate, ctl_main_qubits)
global CCPHIADDMODN_
if CCPHIADDMODN_ == None or num_qubits <= 2:
if num_qubits < 3: CCPHIADDMODN_ = qc
return qc
# Circuit that implements the inverse of doubly controlled modular addition by a
def ccphiADDmodN_inv(num_qubits, a, N):
cchpiAddmodN_circ = ccphiADDmodN(num_qubits, a, N)
cchpiAddmodN_inv_circ = cchpiAddmodN_circ.inverse()
cchpiAddmodN_inv_circ.name = "inv_cchpiAddmodN"
return cchpiAddmodN_inv_circ
# Creates circuit that implements single controlled modular multiplication by a. n represents the number of bits
# needed to represent the integer number N
def cMULTamodN(n, a, N):
qr_ctl = QuantumRegister(1)
qr_x = QuantumRegister(n)
qr_main = QuantumRegister(n+1)
qr_ancilla = QuantumRegister(1)
qc = QuantumCircuit(qr_ctl, qr_x, qr_main,qr_ancilla, name = "cMULTamodN")
# quantum Fourier transform only on auxillary qubits
qc.append(qft_gate(n+1), qr_main)
for i in range(n):
ccphiADDmodN_gate = ccphiADDmodN(n, (2**i)*a % N, N)
# Create relevant temporary qubit list
qubits = [qr_ctl[0]]; qubits.extend([qr_x[i]])
qubits.extend([i for i in qr_main]); qubits.extend([qr_ancilla[0]])
qc.append(ccphiADDmodN_gate, qubits)
# inverse quantum Fourier transform only on auxillary qubits
qc.append(inv_qft_gate(n+1), qr_main)
global CMULTAMODN_
if CMULTAMODN_ == None or n <= 2:
if n < 3: CMULTAMODN_ = qc
return qc
# Creates circuit that implements single controlled Ua gate. n represents the number of bits
# needed to represent the integer number N
def controlled_Ua(n,a,exponent,N):
qr_ctl = QuantumRegister(1)
qr_x = QuantumRegister(n)
qr_main = QuantumRegister(n)
qr_ancilla = QuantumRegister(2)
qc = QuantumCircuit(qr_ctl, qr_x, qr_main,qr_ancilla, name = f"C-U^{a**exponent}")
# Generate Gates
a_inv = modinv(a**exponent,N)
cMULTamodN_gate = cMULTamodN(n, a**exponent, N)
cMULTamodN_inv_gate = cMULTamodN(n, a_inv, N).inverse(); cMULTamodN_inv_gate.name = "inv_cMULTamodN"
# Create relevant temporary qubit list
qubits = [i for i in qr_ctl]; qubits.extend([i for i in qr_x]); qubits.extend([i for i in qr_main])
qubits.extend([i for i in qr_ancilla])
qc.append(cMULTamodN_gate, qubits)
for i in range(n):
qc.cswap(qr_ctl, qr_x[i], qr_main[i])
qc.append(cMULTamodN_inv_gate, qubits)
global CUA_
if CUA_ == None or n <= 2:
if n < 3: CUA_ = qc
return qc
# Execute Shor's Order Finding Algorithm given a 'number' to factor,
# the 'base' of exponentiation, and the number of qubits required 'input_size'
def ShorsAlgorithm(number, base, method, verbose=verbose):
# Create count of qubits to use to represent the number to factor
# NOTE: this should match the number of bits required to represent (number)
n = int(math.ceil(math.log(number, 2)))
# Standard Shors Algorithm
if method == 1:
num_qubits = 4*n + 2
if verbose:
print(f"... running Shors to find order of [ {base}^x mod {number} ] using num_qubits={num_qubits}")
# Create a circuit and allocate necessary qubits
qr_counting = QuantumRegister(2*n) # Register for sequential QFT
qr_mult = QuantumRegister(n) # Register for multiplications
qr_aux = QuantumRegister(n+2) # Register for addition and multiplication
cr_data = ClassicalRegister(2*n) # Register for measured values of QFT
qc = QuantumCircuit(qr_counting, qr_mult, qr_aux, cr_data,
name=f"qmc({method})-{num_qubits}-{number}")
# Initialize multiplication register to 1 and counting register to superposition state
qc.h(qr_counting)
qc.x(qr_mult[0])
qc.barrier()
# Apply Multiplication Gates for exponentiation
for i in reversed(range(2*n)):
cUa_gate = controlled_Ua(n,int(base),2**(2*n-1-i),number)
# Create relevant temporary qubit list
qubits = [qr_counting[i]]; qubits.extend([i for i in qr_mult]);qubits.extend([i for i in qr_aux])
qc.append(cUa_gate, qubits)
qc.barrier()
qc.append(inv_qft_gate(2*n),qr_counting)
# Measure counting register
qc.measure(qr_counting, cr_data)
elif method == 2:
# Create a circuit and allocate necessary qubits
num_qubits = 2*n + 3
if verbose:
print(f"... running Shors to find order of [ {base}^x mod {number} ] using num_qubits={num_qubits}")
qr_counting = QuantumRegister(1) # Single qubit for sequential QFT
qr_mult = QuantumRegister(n) # Register for multiplications
qr_aux = QuantumRegister(n+2) # Register for addition and multiplication
cr_data = ClassicalRegister(2*n) # Register for measured values of QFT
cr_aux = ClassicalRegister(1) # Register to reset the state of the up register based on previous measurements
qc = QuantumCircuit(qr_counting, qr_mult, qr_aux, cr_data, cr_aux, name="main")
# Initialize mult register to 1
qc.x(qr_mult[0])
# perform modular exponentiation 2*n times
for k in range(2*n):
qc.barrier()
# Reset the counting qubit to 0 if the previous measurement was 1
qc.x(qr_counting).c_if(cr_aux,1)
qc.h(qr_counting)
cUa_gate = controlled_Ua(n, base,2**(2*n-1-k), number)
# Create relevant temporary qubit list
qubits = [qr_counting[0]]; qubits.extend([i for i in qr_mult]);qubits.extend([i for i in qr_aux])
qc.append(cUa_gate, qubits)
# perform inverse QFT --> Rotations conditioned on previous outcomes
for i in range(2**k):
qc.p(getAngle(i, k), qr_counting[0]).c_if(cr_data, i)
qc.h(qr_counting)
qc.measure(qr_counting[0], cr_data[k])
qc.measure(qr_counting[0], cr_aux[0])
global QC_, QFT_
if QC_ == None or n <= 2:
if n < 3: QC_ = qc
if QFT_ == None or n <= 2:
if n < 3: QFT_ = qft_gate(n+1)
return qc
############### Circuit end
def expected_shor_dist(num_bits, order, num_shots):
# num_bits represent the number of bits to represent the number N in question
# Qubits measureed always 2 * num_bits for the three methods implemented in this benchmark
qubits_measured = 2 * num_bits
dist = {}
#Conver float to int
r = int(order)
#Generate expected distribution
q = int(2 ** (qubits_measured))
for i in range(r):
key = bin(int(q*(i/r)))[2:].zfill(qubits_measured)
dist[key] = num_shots/r
'''
for c in range(2 ** qubits_measured):
key = bin(c)[2:].zfill(qubits_measured)
amp = 0
for i in range(int(q/r) - 1):
amp += np.exp(2*math.pi* 1j * i * (r * c % q)/q )
amp = amp * np.sqrt(r) / q
dist[key] = abs(amp) ** 2
'''
return dist
# Print analyzed results
# Analyze and print measured results
# Expected result is always the order r, so fidelity calc is simple
def analyze_and_print_result(qc, result, num_qubits, order, num_shots, method):
if method == 1:
num_bits = int((num_qubits - 2) / 4)
elif method == 2:
num_bits = int((num_qubits - 3) / 2)
elif method == 3:
num_bits = int((num_qubits - 2) / 2)
if result.backend_name == 'dm_simulator':
benchmark_result = BenchmarkResult(result, num_shots)
probs = benchmark_result.get_probs(num_shots) # get results as measured probability
else:
probs = result.get_counts(qc) # get results as measured counts
# Only classical data qubits are important and removing first auxiliary qubit from count
if method == 2:
temp_probs = {}
for key, item in probs.items():
temp_probs[key[2:]] = item
probs = temp_probs
# generate correct distribution
correct_dist = expected_shor_dist(num_bits, order, num_shots)
if verbose:
print(f"For order value {order}, measured: {probs}")
print(f"For order value {order}, correct_dist: {correct_dist}")
# use our polarization fidelity rescaling
fidelity = metrics.polarization_fidelity(probs, correct_dist)
return probs, fidelity
#################### Benchmark Loop
# Execute program with default parameters
def run (min_qubits=3, max_circuits=1, max_qubits=10, num_shots=100, method = 1,
verbose=verbose, backend_id='dm_simulator', provider_backend=None,
#hub="ibm-q", group="open", project="main",
exec_options=None,
context=None):
print(f"{benchmark_name} ({method}) Benchmark - QSim")
# Each method has a different minimum amount of qubits to run and a certain multiple of qubits that can be run
qubit_multiple = 2 #Standard for Method 2 and 3
max_qubits = max(max_qubits, min_qubits) # max must be >= min
if method == 1:
min_qubits = max(min_qubits, 10) # need min of 10
qubit_multiple = 4
elif method ==2:
min_qubits = max(min_qubits, 7) # need min of 7
elif method == 3:
min_qubits = max(min_qubits,6) # need min of 6
#skip_qubits = max(1, skip_qubits)
if max_qubits < min_qubits:
print(f"Max number of qubits {max_qubits} is too low to run method {method} of {benchmark_name}")
return
# create context identifier
if context is None: context = f"{benchmark_name} ({method}) Benchmark"
##########
# Initialize metrics module
metrics.init_metrics()
# Define custom result handler # number_order contains an array of length 2 with the number and order
def execution_handler(qc, result, num_qubits, number_order, num_shots):
# determine fidelity of result set
num_qubits = int(num_qubits)
#Must convert number_order from string to array
order = eval(number_order)[1]
probs, fidelity = analyze_and_print_result(qc, result, num_qubits, order, num_shots, method)
metrics.store_metric(num_qubits, number_order, 'fidelity', fidelity)
# Initialize execution module using the execution result handler above and specified backend_id
ex.init_execution(execution_handler)
ex.set_execution_target(backend_id, provider_backend=provider_backend,
# hub=hub, group=group, project=project,
exec_options=exec_options,
context=context)
##########
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
for num_qubits in range(min_qubits, max_qubits + 1, qubit_multiple):
input_size = num_qubits - 1
if method == 1: num_bits = int((num_qubits -2)/4)
elif method == 2: num_bits = int((num_qubits -3)/2)
elif method == 3: num_bits = int((num_qubits -2)/2)
# determine number of circuits to execute for this group
num_circuits = min(2 ** (input_size), max_circuits)
print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}")
for _ in range(num_circuits):
base = 1
while base == 1:
# Ensure N is a number using the greatest bit
number = np.random.randint(2 ** (num_bits - 1) + 1, 2 ** num_bits)
order = np.random.randint(2, number)
base = generate_base(number, order)
# Checking if generated order can be reduced. Can also run through prime list in shors utils
if order % 2 == 0: order = 2
if order % 3 == 0: order = 3
number_order = (number, order)
if verbose: print(f"Generated {number=}, {base=}, {order=}")
# create the circuit for given qubit size and order, store time metric
ts = time.time()
qc = ShorsAlgorithm(number, base, method=method, verbose=verbose).reverse_bits() # reverse_bits() is applying to handle the change in endianness
metrics.store_metric(num_qubits, number_order, 'create_time', time.time()-ts)
# collapse the 4 sub-circuit levels used in this benchmark (for qiskit)
qc = qc.decompose().decompose().decompose().decompose()
# submit circuit for execution on target (simulator, cloud simulator, or hardware)
ex.submit_circuit(qc, num_qubits, number_order, num_shots)
# Wait for some active circuits to complete; report metrics when groups complete
ex.throttle_execution(metrics.finalize_group)
# Wait for all active circuits to complete; report metrics when groups complete
ex.finalize_execution(metrics.finalize_group)
##########
# print the last circuit created
print("***************************************************************************************************************************************")
# print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
# print("\nControlled Ua Operator 'cUa' ="); print(CUA_ if CUA_ != None else " ... too large!")
# print("\nControlled Multiplier Operator 'cMULTamodN' ="); print(CMULTAMODN_ if CMULTAMODN_!= None else " ... too large!")
# print("\nControlled Modular Adder Operator 'ccphiamodN' ="); print(CCPHIADDMODN_ if CCPHIADDMODN_ != None else " ... too large!")
# print("\nPhi Adder Operator '\u03C6ADD' ="); print(PHIADD_ if PHIADD_ != None else " ... too large!")
# print("\nQFT Circuit ="); print(QFT_ if QFT_ != None else " ... too large!")
# Plot metrics for all circuit sizes
metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim")
# if main, execute method
if __name__ == '__main__': run()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
circ.draw('mpl')
from qiskit.quantum_info import Statevector
# Set the intial state of the simulator to the ground state using from_int
state = Statevector.from_int(0, 2**3)
# Evolve the state by the quantum circuit
state = state.evolve(circ)
#draw using latex
state.draw('latex')
from qiskit.visualization import array_to_latex
#Alternative way of representing in latex
array_to_latex(state)
state.draw('qsphere')
state.draw('hinton')
from qiskit.quantum_info import Operator
U = Operator(circ)
# Show the results
U.data
# Create a Quantum Circuit
meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
# map the quantum measurement to the classical bits
meas.measure(range(3), range(3))
# The Qiskit circuit object supports composition.
# Here the meas has to be first and front=True (putting it before)
# as compose must put a smaller circuit into a larger one.
qc = meas.compose(circ, range(3), front=True)
#drawing the circuit
qc.draw('mpl')
# Adding the transpiler to reduce the circuit to QASM instructions
# supported by the backend
from qiskit import transpile
# Use AerSimulator
from qiskit_aer import AerSimulator
backend = AerSimulator()
# First we have to transpile the quantum circuit
# to the low-level QASM instructions used by the
# backend
qc_compiled = transpile(qc, backend)
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = backend.run(qc_compiled, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc_compiled)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibm_nairobi')
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
qr = QuantumRegister(4); cr = ClassicalRegister(4); qc = QuantumCircuit(qr,cr)
qc.h([0,1])
qc.barrier()
qc.cx(0,2); qc.cx(0,3); qc.cx(1,2); qc.cx(1,3) # oraculo
qc.barrier()
qc.measure([2,3],[2,3])
qc.barrier()
qc.h([0,1]); qc.measure([0,1],[0,1])
qc.draw(output='mpl')
jobS = execute(qc, backend = simulator, shots = nshots)
jobE = execute(qc, backend = device, shots = nshots)
job_monitor(jobE)
plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)],
bar_labels = False, legend = ['sim', 'exp'])
|
https://github.com/tigerjack/qiskit_grover
|
tigerjack
|
from math import sqrt, pi
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import oracle_simple
import composed_gates
def get_circuit(n, oracles):
"""
Build the circuit composed by the oracle black box and the other quantum gates.
:param n: The number of qubits (not including the ancillas)
:param oracles: A list of black box (quantum) oracles; each of them selects a specific state
:returns: The proper quantum circuit
:rtype: qiskit.QuantumCircuit
"""
cr = ClassicalRegister(n)
## Testing
if n > 3:
#anc = QuantumRegister(n - 1, 'anc')
# n qubits for the real number
# n - 1 qubits for the ancillas
qr = QuantumRegister(n + n - 1)
qc = QuantumCircuit(qr, cr)
else:
# We don't need ancillas
qr = QuantumRegister(n)
qc = QuantumCircuit(qr, cr)
## /Testing
print("Number of qubits is {0}".format(len(qr)))
print(qr)
# Initial superposition
for j in range(n):
qc.h(qr[j])
# The length of the oracles list, or, in other words, how many roots of the function do we have
m = len(oracles)
# Grover's algorithm is a repetition of an oracle box and a diffusion box.
# The number of repetitions is given by the following formula.
print("n is ", n)
r = int(round((pi / 2 * sqrt((2**n) / m) - 1) / 2))
print("Repetition of ORACLE+DIFFUSION boxes required: {0}".format(r))
oracle_t1 = oracle_simple.OracleSimple(n, 5)
oracle_t2 = oracle_simple.OracleSimple(n, 0)
for j in range(r):
for i in range(len(oracles)):
oracles[i].get_circuit(qr, qc)
diffusion(n, qr, qc)
for j in range(n):
qc.measure(qr[j], cr[j])
return qc, len(qr)
def diffusion(n, qr, qc):
"""
The Grover diffusion operator.
Given the arry of qiskit QuantumRegister qr and the qiskit QuantumCircuit qc, it adds the diffusion operator to the appropriate qubits in the circuit.
"""
for j in range(n):
qc.h(qr[j])
# D matrix, flips state |000> only (instead of flipping all the others)
for j in range(n):
qc.x(qr[j])
# 0..n-2 control bits, n-1 target, n..
if n > 3:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1],
[qr[j] for j in range(n, n + n - 1)])
else:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1], None)
for j in range(n):
qc.x(qr[j])
for j in range(n):
qc.h(qr[j])
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-3*np.pi,3*np.pi,0.1) # start,stop,step
y = np.sin(x)
yaxis = 0
plt.axes()
plt.plot(x,y,xaxis)
plt.show()
|
https://github.com/weiT1993/qiskit_helper_functions
|
weiT1993
|
from qiskit import QuantumCircuit, QuantumRegister
import sys
import math
import numpy as np
class Dynamics:
"""
Class to implement the simulation of quantum dynamics as described
in Section 4.7 of Nielsen & Chuang (Quantum computation and quantum
information (10th anniv. version), 2010.)
A circuit implementing the quantum simulation can be generated for a given
problem Hamiltonian parameterized by calling the gen_circuit() method.
Attributes
----------
H : ??
The given Hamiltonian whose dynamics we want to simulate
barriers : bool
should barriers be included in the generated circuit
measure : bool
should a ClassicalRegister and measurements be added to the circuit
regname : str
optional string to name the quantum and classical registers. This
allows for the easy concatenation of multiple QuantumCircuits.
qr : QuantumRegister
Qiskit QuantumRegister holding all of the quantum bits
circ : QuantumCircuit
Qiskit QuantumCircuit that represents the uccsd circuit
"""
def __init__(self, H, barriers=False, measure=False, regname=None):
# Hamiltonian
self.H = H
# set flags for circuit generation
self.barriers = barriers
self.nq = self.get_num_qubits()
# create a QuantumCircuit object
if regname is None:
self.qr = QuantumRegister(self.nq)
else:
self.qr = QuantumRegister(self.nq, name=regname)
self.circ = QuantumCircuit(self.qr)
# Create and add an ancilla register to the circuit
self.ancQ = QuantumRegister(1, "ancQ")
self.circ.add_register(self.ancQ)
def get_num_qubits(self):
"""
Given the problem Hamiltonian, return the appropriate number of qubits
needed to simulate its dynamics.
This number does not include the single ancilla qubit that is added
to the circuit.
"""
numq = 0
for term in self.H:
if len(term) > numq:
numq = len(term)
return numq
def compute_to_Z_basis(self, pauli_str):
"""
Take the given pauli_str of the form ABCD and apply operations to the
circuit which will take it from the ABCD basis to the ZZZZ basis
Parameters
----------
pauli_str : str
string of the form 'p1p2p3...pN' where pK is a Pauli matrix
"""
for i, pauli in enumerate(pauli_str):
if pauli == "X":
self.circ.h(self.qr[i])
elif pauli == "Y":
self.circ.h(self.qr[i])
self.circ.s(self.qr[i])
def uncompute_to_Z_basis(self, pauli_str):
"""
Take the given pauli_str of the form ABCD and apply operations to the
circuit which will take it from the ZZZZ basis to the ABCD basis
Parameters
----------
pauli_str : str
string of the form 'p1p2p3...pN' where pK is a Pauli matrix
"""
for i, pauli in enumerate(pauli_str):
if pauli == "X":
self.circ.h(self.qr[i])
elif pauli == "Y":
self.circ.sdg(self.qr[i])
self.circ.h(self.qr[i])
def apply_phase_shift(self, delta_t):
"""
Simulate the evolution of exp(-i(dt)Z)
"""
# apply CNOT ladder -> compute parity
for i in range(self.nq):
self.circ.cx(self.qr[i], self.ancQ[0])
# apply phase shift to the ancilla
# rz applies the unitary: exp(-i*theta*Z/2)
self.circ.rz(2 * delta_t, self.ancQ[0])
# apply CNOT ladder -> uncompute parity
for i in range(self.nq - 1, -1, -1):
self.circ.cx(self.qr[i], self.ancQ[0])
def gen_circuit(self):
"""
Create a circuit implementing the quantum dynamics simulation
Returns
-------
QuantumCircuit
QuantumCircuit object of size nq with no ClassicalRegister and
no measurements
"""
# generate a naive version of a simulation circuit
for term in self.H:
self.compute_to_Z_basis(term)
if self.barriers:
self.circ.barrier()
self.apply_phase_shift(1)
if self.barriers:
self.circ.barrier()
self.uncompute_to_Z_basis(term)
if self.barriers:
self.circ.barrier()
# generate a commutation aware version of a simulation circuit
# simulate all commuting terms simulataneously by using 1 ancilla per
# term that will encode the phase shift based on the parity of the term.
return self.circ
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# 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.
"""
Initializes a mixed quantum state.
"""
from math import log2, ceil, isclose
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qclib.gates.initialize import Initialize
from qclib.gates.initialize_mixed import InitializeMixed
from qclib.gates.initialize_sparse import InitializeSparse
from qclib.state_preparation import LowRankInitialize
# pylint: disable=maybe-no-member
class MixedInitialize(InitializeMixed):
"""
This class implements a mixed state preparation gate.
"""
def __init__(
self,
params,
initializer=LowRankInitialize,
opt_params=None,
probabilities=None,
label=None,
reset=True,
classical = True
):
"""
Parameters
----------
params: list of list of complex
A list of unit vectors, each representing a quantum state.
Values are amplitudes.
initializer: Initialize or InitializeSparse
Type of the class that will be applied to prepare pure states.
Default is ``LowRankInitialize``.
opt_params: dictionary
Optional parameters of the class of type ``initializer``.
reset: bool
Indicates whether the auxiliary qubits should be reset or not.
Default is ``True``.
classical: bool
Indicates whether the purification is done classically or
in-circuit (quantically). Default is ``True``.
"""
if (
not issubclass(initializer, Initialize) and
not issubclass(initializer, InitializeSparse)
):
raise TypeError("The value of initializer should be Initialize or InitializeSparse.")
if probabilities is None:
probabilities = [1/len(params)] * len(params)
elif any(i < 0.0 for i in probabilities):
raise ValueError("All probabilities must greater than or equal to 0.")
elif any(i > 1.0 for i in probabilities):
raise ValueError("All probabilities must less than or equal to 1.")
elif not isclose(sum(probabilities), 1.0):
raise ValueError("The sum of the probabilities must be 1.0.")
self._name = "mixed"
self._get_num_qubits(params)
self._initializer = initializer
self._reset = reset
self._opt_params = opt_params
self._probabilities = probabilities
self._classical = classical
self._num_ctrl_qubits = int(ceil(log2(len(params))))
self._num_data_qubits = initializer(params[0]).num_qubits
self._list_params = params
if label is None:
label = "Mixed"
super().__init__(self._name, self.num_qubits, np.array(params).reshape(-1), label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
purified_circuit = QuantumCircuit(self.num_qubits)
if self._classical:
# Calculates the pure state classically.
pure_state = np.zeros(2**(self._num_qubits), dtype=complex)
for index, (state_vector, prob) in enumerate(
zip(self._list_params, self._probabilities)
):
basis = np.zeros(2**self._num_ctrl_qubits)
basis[index] = 1
pure_state += np.kron(np.sqrt(prob) * state_vector, basis)
purified_circuit = self._initializer(
pure_state,
opt_params=self._opt_params
).definition
else:
# Calculates the pure state quantically.
aux_state = np.concatenate((
np.sqrt(self._probabilities),
[0] * (2**(self._num_ctrl_qubits) - len(self._probabilities))
))
sub_circuit = self._initializer(
aux_state,
opt_params=self._opt_params
).definition
sub_circuit.name = 'aux. space'
purified_circuit.append(sub_circuit, range(self._num_ctrl_qubits))
for index, state in enumerate(self._list_params):
sub_circuit = self._initializer(
state,
opt_params=self._opt_params
).definition
sub_circuit.name = f'state {index}'
sub_circuit = sub_circuit.control(
num_ctrl_qubits=self._num_ctrl_qubits,
ctrl_state = f"{index:0{self._num_ctrl_qubits}b}"
)
purified_circuit.compose(sub_circuit, purified_circuit.qubits, inplace=True)
purified_circuit.name = 'purified state'
circuit = QuantumCircuit()
circuit.add_register(QuantumRegister(self._num_ctrl_qubits, 'aux'))
circuit.add_register(QuantumRegister(self._num_data_qubits, 'rho'))
circuit.append(purified_circuit, circuit.qubits)
if self._reset:
circuit.reset(range(self._num_ctrl_qubits))
return circuit
@staticmethod
def initialize(q_circuit, ensemble, qubits=None, opt_params=None, probabilities=None):
"""
Appends a MixedInitialize gate into the q_circuit
"""
if qubits is None:
q_circuit.append(
MixedInitialize(
ensemble,
opt_params=opt_params,
probabilities=probabilities
)
, q_circuit.qubits
)
else:
q_circuit.append(
MixedInitialize(
ensemble,
opt_params=opt_params,
probabilities=probabilities
)
, qubits
)
|
https://github.com/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import json
from typing import Any, Callable, Optional, Tuple, Union
from urllib.parse import urljoin
from qiskit import QuantumCircuit, execute
from qiskit.providers import JobStatus
from qiskit.providers.ibmq.job import IBMQJob
from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint
from .exercises import get_question_id
from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate
def _circuit_criteria(
circuit: QuantumCircuit,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[int], Optional[int]]:
if max_qubits is not None and circuit.num_qubits > max_qubits:
print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.')
print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.')
return None, None
try:
if check_gates and not uses_multiqubit_gate(circuit):
print('Your circuit appears to not use any multi-quibit gates.')
print('Please review your circuit and try again.')
return None, None
cost = compute_cost(circuit)
if min_cost is not None and cost < min_cost:
print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n'
'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.')
return None, None
return circuit.num_qubits, cost
except Exception as err:
print(f'Unable to compute cost: {err}')
return None, None
def _circuit_grading(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
payload = None
server = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or '
'the grading servers are down right now.')
return None, None
else:
server = None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
payload = {
'answer': circuit_to_json(circuit)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _job_grading(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str):
print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}')
print(f'Please submit a job as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading '
'servers are down right now.')
return None, None
else:
server = None
job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id
if not job:
print('An invalid or non-existent job was specified.')
return None, None
job_status = job.status()
if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]:
print(f'Job did not successfully complete: {job_status.value}.')
return None, None
elif job_status is not JobStatus.DONE:
print(f'Job has not yet completed: {job_status.value}.')
print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.')
return None, None
header = job.result().header.to_dict()
if 'qc_cost' not in header:
if is_submit:
print('An unprepared answer was specified. '
'Please prepare() and grade() answer before submitting.')
else:
print('An unprepared answer was specified. Please prepare() answer before grading.')
return None, None
download_url, result_url = get_job_urls(job)
if not download_url or not result_url:
print('Unable to obtain job URLs')
return None, None
payload = {
'answer': json.dumps({
'download_url': download_url,
'result_url': result_url
})
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _number_grading(
answer: int,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(answer, int):
print(f'Expected a integer, but was given {type(answer)}')
print(f'Please provide a number as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server '
'or the grading servers are down right now.')
return None, None
else:
server = None
payload = {
'answer': str(answer)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def prepare_circuit(
circuit: QuantumCircuit,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit.')
return None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiment. Please wait...')
job = execute(
circuit,
qobj_header={
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def prepare_solver(
solver_func: Callable,
lab_id: str,
ex_id: str,
problem_set: Optional[Any] = None,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not callable(solver_func):
print(f'Expected a function, but was given {type(solver_func)}')
print(f'Please provide a function that returns a QuantumCircuit.')
return None
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading servers are down right now.')
return
endpoint = server + 'problem-set'
index, value = get_problem_set(lab_id, ex_id, endpoint)
print(f'Running {solver_func.__name__}...')
qc_1 = solver_func(problem_set)
_, cost = _circuit_criteria(
qc_1,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if value and index is not None and index >= 0 and cost is not None:
qc_2 = solver_func(value)
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiments. Please wait...')
job = execute(
[qc_1, qc_2],
qobj_header={
'qc_index': [None, index],
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def grade_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, server = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=False,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_job(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str
) -> bool:
payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def submit_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, _ = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=True,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_job(
job_or_id: IBMQJob,
lab_id: str,
ex_id: str,
) -> bool:
payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def get_problem_set(
lab_id: str, ex_id: str, endpoint: str
) -> Tuple[Optional[int], Optional[Any]]:
problem_set_response = None
try:
payload = {'question_id': get_question_id(lab_id, ex_id)}
problem_set_response = send_request(endpoint, query=payload, method='GET')
except Exception as err:
print('Unable to obtain the problem set')
if problem_set_response:
status = problem_set_response.get('status')
if status == 'valid':
try:
index = problem_set_response.get('index')
value = json.loads(problem_set_response.get('value'))
return index, value
except Exception as err:
print(f'Problem set could not be processed: {err}')
else:
cause = problem_set_response.get('cause')
print(f'Problem set failed: {cause}')
return None, None
def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool:
try:
answer_response = send_request(endpoint, body=payload)
status = answer_response.get('status', None)
cause = answer_response.get('cause', None)
score = cost if cost else answer_response.get('score', None)
handle_grade_response(status, score=score, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def submit_answer(payload: dict) -> bool:
try:
access_token = get_access_token()
baseurl = get_submission_endpoint()
endpoint = urljoin(baseurl, './challenges/answers')
submit_response = send_request(
endpoint,
body=payload,
query={'access_token': access_token}
)
status = submit_response.get('status', None)
if status is None:
status = submit_response.get('valid', None)
cause = submit_response.get('cause', None)
handle_submit_response(status, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def handle_grade_response(
status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None
) -> None:
if status == 'valid':
print('\nCongratulations 🎉! Your answer is correct.')
if score is not None:
print(f'Your score is {score}.')
elif status == 'invalid':
print(f'\nOops 😕! {cause}')
print('Please review your answer and try again.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete then try again.')
else:
print(f'Failed: {cause}')
print('Unable to grade your answer.')
def handle_submit_response(
status: Union[str, bool], cause: Optional[str] = None
) -> None:
if status == 'valid' or status is True:
print('\nSuccess 🎉! Your answer has been submitted.')
elif status == 'invalid' or status is False:
print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}')
print('Make sure your answer is correct and successfully graded before submitting.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete, grade it, and then try to submit again.')
else:
print(f'Failed: {cause}')
print('Unable to submit your answer at this time.')
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
import numpy as np
import random
from qiskit import QuantumCircuit, Aer, execute
from math import log2, ceil, pi, sin
from numpy import savetxt, save, savez_compressed
import sys
#=====================================================================================================================
simulator = Aer.get_backend('statevector_simulator')
def disp_isv(circ, msg="", all=True, precision=1e-8):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
qb = int(log2(len(statevector)))
print("\n============ State Vector ============", msg)
s = 0
for i in statevector:
if (all == True): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
else:
if (abs(i) > precision): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
s = s+1
print("============..............============")
return
#=====================================================================================================================
tape = [0,1,2,3]
ancilla = [4]
count = [5,6,7,8]
# searchbits = 5
# for j in range(4,7):
# print("\nDetectable solutions with %d count bits:",j)
# countbits = j
# for i in range(0,countbits**2):
# theta = (i/(2**countbits))*pi*2
# counter = 2**searchbits * (1 - sin(theta/2)**2)
# print(round(counter),"|",end='')
# sys.exit(0)
qcirc_width = len(tape) + len(ancilla) + len(count)
qcirc = QuantumCircuit(qcirc_width, len(count))
# U_qpulba121
# qcirc.h(fsm)
# qcirc.cx(fsm[1], ancilla[0])
# qcirc.cx(fsm[0],tape[0])
# qcirc.cx(fsm[0],tape[1])
# qcirc.cx(fsm[0],tape[2])
# qcirc.cx(fsm[0],tape[3])
# qcirc.h(tape)
# qcirc.h(tape[0:3])
qcirc.h(tape[0])
# qcirc.cx(tape[1], ancilla[0]) # Gives 32 solns: wrong
# qcirc.h(ancilla[0]) # Gives 2 solns: correct
disp_isv(qcirc, "Step: Run QPULBA 121", all=False, precision=1e-4)
# sys.exit(0)
#=====================================================================================================================
def condition_fsm(qcirc, fsm, tape):
# Finding specific programs-output characteristics (fsm|tape)
# e.g. Self-replication
for q in fsm:
qcirc.cx(q,tape[q])
qcirc.barrier()
return
#=====================================================================================================================
# search = tape
# condition_fsm(qcirc, fsm, tape)
# disp_isv(qcirc, "Step: Find self-replicating programs", all=False, precision=1e-4)
# sys.exit(0)
#=====================================================================================================================
def U_oracle(sz):
# Mark fsm/tape/state with all zero Hamming distance (matches applied condition perfectly)
tgt_reg = list(range(0,sz))
oracle = QuantumCircuit(len(tgt_reg))
oracle.x(tgt_reg)
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x(tgt_reg)
return oracle
def U_diffuser(sz):
# https://qiskit.org/textbook/ch-algorithms/quantum-counting.html
tgt_reg = list(range(0,sz))
diffuser = QuantumCircuit(len(tgt_reg))
diffuser.h(tgt_reg[1:])
diffuser.x(tgt_reg[1:])
diffuser.z(tgt_reg[0])
diffuser.mct(tgt_reg[1:],tgt_reg[0])
diffuser.x(tgt_reg[1:])
diffuser.h(tgt_reg[1:])
diffuser.z(tgt_reg[0])
return diffuser
def U_QFT(n):
# n-qubit QFT circuit
qft = QuantumCircuit(n)
def swap_registers(qft, n):
for qubit in range(n//2):
qft.swap(qubit, n-qubit-1)
return qft
def qft_rotations(qft, n):
# Performs qft on the first n qubits in circuit (without swaps)
if n == 0:
return qft
n -= 1
qft.h(n)
for qubit in range(n):
qft.cu1(np.pi/2**(n-qubit), qubit, n)
qft_rotations(qft, n)
qft_rotations(qft, n)
swap_registers(qft, n)
return qft
#=====================================================================================================================
selregs = [0,1,2,3]
# selregs = [4,5,6,7]
# selregs = [0,1,2,3,4,5,6,7,8]
# Create controlled Grover oracle circuit
# oracle = U_oracle(len(search)).to_gate()
oracle = U_oracle(len(selregs)).to_gate()
c_oracle = oracle.control()
c_oracle.label = "cGO"
# Create controlled Grover diffuser circuit
diffuser = U_diffuser(len(selregs)).to_gate()
c_diffuser = diffuser.control()
c_diffuser.label = "cGD"
# Create inverse QFT circuit
iqft = U_QFT(len(count)).to_gate().inverse()
iqft.label = "iQFT"
#=====================================================================================================================
qcirc.h(count)
qcirc.barrier()
# Begin controlled Grover iterations
iterations = 1
for qb in count:
for i in range(iterations):
# qcirc.append(c_oracle, [qb] + search)
qcirc.append(c_oracle, [qb] + selregs)
# disp_isv(qcirc, "Step", all=False, precision=1e-4)
qcirc.append(c_diffuser, [qb] + selregs)
iterations *= 2
qcirc.barrier()
# Inverse QFT
qcirc.append(iqft, count)
qcirc.barrier()
# Measure counting qubits
qcirc.measure(count, range(len(count)))
# print(qcirc.draw())
# sys.exit(0)
#=====================================================================================================================
emulator = Aer.get_backend('qasm_simulator')
job = execute(qcirc, emulator, shots=1024)
hist = job.result().get_counts()
# print(hist)
measured_int = int(max(hist, key=hist.get),2)
theta = (measured_int/(2**len(count)))*pi*2
# counter = 2**3 * (1 - sin(theta/2)**2)
# print("Number of solutions = %.1f" % counter)
counter = 2**len(selregs) * sin(theta/2)**2
print("Number of non-solutions =",counter)
counter = 2**len(selregs) * (1 - sin(theta/2)**2)
print("Number of solutions = %.1f" % counter)
#=====================================================================================================================
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import warnings
import numpy as np
from numpy import pi
from matplotlib import MatplotlibDeprecationWarning
from qiskit import QuantumRegister, QuantumCircuit, execute, BasicAer
from qiskit_optimization import QuadraticProgram
from qiskit.visualization import plot_state_qsphere
from qiskit.quantum_info.operators import Operator
qreg_q = QuantumRegister(3, 'q')
qc_init = QuantumCircuit(qreg_q)
qc_init.h(qreg_q[0])
qc_init.h(qreg_q[1])
qc_init.h(qreg_q[2])
qc_init.barrier()
psi_0 = execute(qc_init, BasicAer.get_backend('statevector_simulator')).result().get_statevector(qc_init, \
decimals=3)
superpos_state = np.ones(8, dtype=complex) / np.sqrt(8)
print("Superposition state: ",np.allclose(psi_0, superpos_state, rtol=0.01))
warnings.filterwarnings("ignore", category=MatplotlibDeprecationWarning)
plot_state_qsphere(psi_0)
def pretty_print(x):
""" print with 1 decimal only """
with np.printoptions(precision=1, suppress=True):
print(x)
qc_evol = QuantumCircuit(qreg_q)
qc_evol.cx(qreg_q[1], qreg_q[0])
qc_evol.rz(-0.06942544294642758, qreg_q[0])
qc_evol.cx(qreg_q[1], qreg_q[0])
qc_evol.rz(-0.20827632883928274, qreg_q[0])
qc_evol.cx(qreg_q[2], qreg_q[1])
qc_evol.rz(1.2496579730356965, qreg_q[1])
qc_evol.cx(qreg_q[2], qreg_q[1])
qc_evol.rz(-0.20827632883928274, qreg_q[1])
qc_evol.barrier()
qc_evol.rx(0.7530122052855767, qreg_q[0])
qc_evol.rx(0.7530122052855767, qreg_q[1])
qc_evol.rx(0.7530122052855767, qreg_q[2])
U = execute(qc_evol, BasicAer.get_backend('unitary_simulator')).result().get_unitary(qc_evol, decimals=3)
pretty_print(U)
op = Operator(qc_evol) # to make it easy to multiply
psi_g = op.data.dot(psi_0)
pretty_print(psi_g)
warnings.filterwarnings("ignore", category=MatplotlibDeprecationWarning)
plot_state_qsphere(psi_g, figsize=(10,10))
qc_qaoa = qc_init.compose(qc_evol)
qc_qaoa.measure_all()
qc_qaoa.draw(output='latex') # ref to fig:circuit_ideal
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw
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, backend=FakeBoeblingen())
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
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
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
# unused for this file
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../../solutions/utils/")
import circuit_utils, zne_utils, tomography_utils
importlib.reload(circuit_utils)
importlib.reload(zne_utils) # unused for this file
importlib.reload(tomography_utils) # unused for this file
from circuit_utils import *
from zne_utils import zne_wrapper, zne_decoder
from tomography_utils import expvals_to_valid_rho
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
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_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100]
print("trotter step list: ", num_steps_list)
scale_factors = [1.0, 2.0, 3.0] # unused for this file
shots = 1 << 13
reps = 8 # unused
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
# 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())
retrieved_cal_job = cal_job
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
raw_fid_list = []
raw_stddev_list = []
qrem_fid_list = []
qrem_stddev_list = []
for num_steps in num_steps_list:
print("trotter steps: ", num_steps)
t1 = time.perf_counter()
# 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(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 = t3_st_qcs
# zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False)
# 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), ")")
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)
retrieved_jobs = jobs
raw_fids = []
qrem_fids = []
for job in retrieved_jobs:
raw_results = job.result()
mit_results = meas_fitter.filter.apply(raw_results)
raw_rho = StateTomographyFitter(raw_results, t3_zne_qcs).fit(method='lstsq')
qrem_rho = StateTomographyFitter(mit_results, t3_zne_qcs).fit(method='lstsq')
raw_fids.append(state_fidelity(raw_rho, target_state))
qrem_fids.append(state_fidelity(qrem_rho, target_state))
raw_fid_list.append(np.mean(raw_fids))
raw_stddev_list.append(np.std(raw_fids))
qrem_fid_list.append(np.mean(qrem_fids))
qrem_stddev_list.append(np.std(qrem_fids))
t2 = time.perf_counter()
print('raw state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(raw_fids), np.std(raw_fids)))
print('qrem state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(qrem_fids), np.std(qrem_fids)))
print("time:", t2 - t1)
print()
with open("e2d1_raw.pkl", "wb") as f:
pickle.dump({"num_steps_list": num_steps_list, "fid": raw_fid_list, "stddev": raw_stddev_list}, f)
with open("e2d1_qrem.pkl", "wb") as f:
pickle.dump({"num_steps_list": num_steps_list, "fid": qrem_fid_list, "stddev": qrem_stddev_list}, f)
import qiskit.tools.jupyter
%qiskit_version_table
plt.plot(num_steps_list, raw_fid_list)
plt.plot(num_steps_list, qrem_fid_list)
|
https://github.com/clausia/qiskit-fall-fest-peru-2022
|
clausia
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
A = QuantumRegister(1, 'a')
B = QuantumRegister(1, 'b')
CarryIn = QuantumRegister(1, 'cin-sum')
cero = QuantumRegister(1, 'aux-cout')
adder = QuantumCircuit(A, B, CarryIn, cero)
adder.ccx(0, 1, 3)
adder.cx(0, 1)
adder.ccx(1, 2, 3)
adder.cx(1, 2)
adder.cx(0, 1)
adder.draw('mpl')
inicializacion = QuantumCircuit(4)
inicializacion.x(0) # a = 1
inicializacion.x(2) # cin = 1
inicializacion.barrier()
inicializacion.draw('mpl')
suma = inicializacion.compose(adder)
suma.barrier()
suma.add_register(ClassicalRegister(2, 'res'))
suma.measure([2, 3], [0, 1])
suma.draw('mpl')
from qiskit import execute, Aer
from qiskit.tools.visualization import plot_histogram
job = execute(suma, Aer.get_backend('aer_simulator'), shots=1000)
counts = job.result().get_counts(suma)
print(counts)
plot_histogram(counts, title='Conteos del resultado de la suma')
inicializacion2 = QuantumCircuit(4)
inicializacion2.x(0) # a = 1
inicializacion2.x(1) # b = 1
inicializacion2.x(2) # cin = 1
inicializacion2.barrier()
suma2 = inicializacion2.compose(adder)
suma2.barrier()
suma2.add_register(ClassicalRegister(2, 'res'))
suma2.measure([2, 3], [0, 1])
display(suma2.draw('mpl'))
job = execute(suma2, Aer.get_backend('aer_simulator'), shots=1) # con una sola ejecución es suficiente
counts2 = job.result().get_counts(suma2)
print(counts2)
plot_histogram(counts2, title='Conteos del resultado de la suma2')
inicializacion3 = QuantumCircuit(4)
inicializacion3.h(0) # a y b en estado de Bell
inicializacion3.cx(0, 1)
inicializacion3.h(2) # estado en superposión: ( |0> + |1> ) / sqrt(2)
inicializacion3.barrier()
suma3 = inicializacion3.compose(adder) # el 'adder' es el mismo
suma3.barrier()
suma3.add_register(ClassicalRegister(2, 'res'))
suma3.measure([2, 3], [0, 1])
display(suma3.draw('mpl'))
job = execute(suma3, Aer.get_backend('aer_simulator'), shots=1000) # en este caso si necesitamos multiples shots
counts3 = job.result().get_counts(suma3)
print(counts3)
plot_histogram(counts3, title='Conteos del resultado de la suma3')
from qiskit.circuit.library.arithmetic.adders import CDKMRippleCarryAdder
qiskit_adder = CDKMRippleCarryAdder(3, 'full', 'Sumador completo')
operando1 = QuantumRegister(3, 'o1') # primer número a sumar
operando2 = QuantumRegister(3, 'o2') # segundo número a sumar
aux = QuantumRegister(2, 'a') # acarreo de entrada y de salida
cr = ClassicalRegister(4) # para almacenar el resultado en bits clásicos
circ = QuantumCircuit(operando1, operando2, aux, cr)
circ.x([operando1[0], operando1[1]]) # 3 en binario: 011
circ.x([operando2[0], operando2[2]]) # 5 en binario: 101
# El orden esperado por la clase 'CDKMRippleCarryAdder' es: carry_in - 1er operando - 2do operando - carry_out
circ.append(qiskit_adder, [aux[0]] + operando1[0:3] + operando2[0:3] + [aux[1]])
circ.measure(operando2[0:3] + [aux[1]], cr) # esta clase escribe el resultado en el 2do operando y en el carry_out
display(circ.draw('mpl'))
job = execute(circ, Aer.get_backend('aer_simulator'), shots=1000)
counts = job.result().get_counts(circ)
print(counts) # resultado es 8 en binario: 1000
plot_histogram(counts, title='Conteos del ejemplo con CDKMRippleCarryAdder')
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
qr_alice = QuantumRegister(2, name="alicia") # dos qubits de Alicia
qr_bob = QuantumRegister(1, name="bob") # un qubit de Bob
crz = ClassicalRegister(1, name="crz") # 2 bits clasicos
crx = ClassicalRegister(1, name="crx") # en 2 diferentes registros
circuito_teleportacion = QuantumCircuit(qr_alice, qr_bob, crz, crx)
circuito_teleportacion.draw('mpl')
def crear_estado_bell(circ, a, b):
circ.h(a) # poner el qubit a en el estado |+>
circ.cx(a, b) # CNOT con control el qubit a y objetivo el qubit b
crear_estado_bell(circuito_teleportacion, 1, 2) # circuito, qubit a, qubit b
circuito_teleportacion.draw('mpl')
def compuertas_alicia(circ, psi, a):
circ.barrier()
circ.cx(psi, a)
circ.h(psi)
compuertas_alicia(circuito_teleportacion, 0, 1)
circuito_teleportacion.draw('mpl')
def mediciones_y_envio(circ, psi, a):
circ.barrier()
circ.measure(psi, 0)
circ.measure(a, 1)
mediciones_y_envio(circuito_teleportacion, 0, 1)
circuito_teleportacion.draw('mpl')
def compuertas_bob(circ, b, crz, crx):
circ.barrier()
circ.x(b).c_if(crx, 1)
circ.z(b).c_if(crz, 1)
compuertas_bob(circuito_teleportacion, 2, crz, crx)
circuito_teleportacion.draw('mpl')
from qiskit.quantum_info import random_statevector
from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex
# generamos un estado aleatorio (el que enviará Alicia Bob y al ser aleatorio ella no lo conoce)
psi = random_statevector(2)
# veamos que de que estado se trata
display(array_to_latex(psi, prefix="|\\psi\\rangle ="))
plot_bloch_multivector(psi)
from qiskit.extensions import Initialize
# crear una instruccion de inicializacion que coloque al qubit en el estado que generamos aleatoriamente
instruccion_inicializacion = Initialize(psi)
instruccion_inicializacion.label = "init"
# El protocolo completo:
# Configuración inicial
qr_alice = QuantumRegister(2, name="alicia") # dos qubits de Alicia
qr_bob = QuantumRegister(1, name="bob") # un qubit de Bob
crz = ClassicalRegister(1, name="crz") # 2 bits clasicos
crx = ClassicalRegister(1, name="crx") # en 2 diferentes registros
circuito_teleportacion = QuantumCircuit(qr_alice, qr_bob, crz, crx)
# Paso 0
# Iniciar el qubit a enviar
circuito_teleportacion.append(instruccion_inicializacion, [0])
circuito_teleportacion.barrier()
# Paso 1
# Crear el par entrelazado
crear_estado_bell(circuito_teleportacion, 1, 2) # circuito, qubit a, qubit b
# Paso 2
# "Enviar" q1 a Alicia y q2 a Bob
compuertas_alicia(circuito_teleportacion, 0, 1)
# Paso 3
# Alicia envia sus bits clásicos a Bob
mediciones_y_envio(circuito_teleportacion, 0, 1)
# Paso 4
# Bob decodifica su qubit
compuertas_bob(circuito_teleportacion, 2, crz, crx)
circuito_teleportacion.draw('mpl')
sim = Aer.get_backend('aer_simulator')
circuito_teleportacion.save_statevector()
out_vector = sim.run(circuito_teleportacion).result().get_statevector()
display(plot_bloch_multivector(out_vector))
out_vector.draw('latex')
reverso_instruccion_inicializacion = instruccion_inicializacion.gates_to_uncompute()
qr_alice = QuantumRegister(2, name="alicia") # dos qubits de Alicia
qr_bob = QuantumRegister(1, name="bob") # un qubit de Bob
crz = ClassicalRegister(1, name="crz") # 2 bits clasicos
crx = ClassicalRegister(1, name="crx") # en 2 diferentes registros
circuito_teleportacion = QuantumCircuit(qr_alice, qr_bob, crz, crx)
# Paso 0
# Iniciar el qubit a enviar
circuito_teleportacion.append(instruccion_inicializacion, [0])
circuito_teleportacion.barrier()
# Paso 1
# Crear el par entrelazado
crear_estado_bell(circuito_teleportacion, 1, 2) # circuito, qubit a, qubit b
# Paso 2
# "Enviar" q1 a Alicia y q2 a Bob
compuertas_alicia(circuito_teleportacion, 0, 1)
# Paso 3
# Alicia envia sus bits clásicos a Bob
mediciones_y_envio(circuito_teleportacion, 0, 1)
# Paso 4
# Bob decodifica su qubit
compuertas_bob(circuito_teleportacion, 2, crz, crx)
circuito_teleportacion.append(reverso_instruccion_inicializacion, [2])
circuito_teleportacion.draw('mpl')
cr_result = ClassicalRegister(1)
circuito_teleportacion.add_register(cr_result)
circuito_teleportacion.measure(2, 2)
circuito_teleportacion.draw('mpl')
from qiskit.result import marginal_counts
from qiskit import transpile
t_qc = transpile(circuito_teleportacion, sim)
t_qc.save_statevector()
counts = sim.run(t_qc).result().get_counts()
qubit_counts = [marginal_counts(counts, [qubit]) for qubit in range(3)]
plot_histogram(qubit_counts)
n = 3 # cantidad de bits para la función f
from qiskit import QuantumCircuit
import numpy as np
#---------------------
## Oráculo Constante
#---------------------
const_oraculo = QuantumCircuit(n+1) # +1 qubit que corresponde al segundo registro
# en este caso, la entrada no tiene efecto en la salida, por lo que simplemente
# configuramos aleatoriamente el qubit de salida en 0 o 1:
output = np.random.randint(2)
if output == 1:
const_oraculo.x(n) # aplicar X al qubits de salida (un solo resultado para todas las entradas)
const_oraculo.draw('mpl')
#---------------------
## Oráculo Balanceado
#---------------------
balan_oraculo = QuantumCircuit(n+1)
# podemos crear un oráculo balanceado usando CNOTs con cada qubit de entrada como control
# y el bit de salida como objetivo. Podemos variar los estados de entrada que dan 0 o 1
# encerrando algunos de los controles con compuertas X. Primero elijamos una cadena binaria de
# longitud n que dicte qué controles ajustar:
b_str = "101"
# agregar las compuertas X en la posción donde hay un 1
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balan_oraculo.x(qubit)
balan_oraculo.barrier()
# ahora, aplicamos las compuertas CNOT, usando cada qubit de entrada como control y el
# qubit de salida como objetivo:
for qubit in range(n):
balan_oraculo.cx(qubit, n)
balan_oraculo.barrier()
# finalmente, aplicamos compuertas X para terminar de envolver los controles:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balan_oraculo.x(qubit)
balan_oraculo.draw('mpl')
dj_circuit = QuantumCircuit(n+1, n) # n+1=4 qubits, n=3 bits clásicos
dj_circuit.x(n) # colocar el último qubits (segundo registro) en el estado |1>
dj_circuit.barrier()
dj_circuit.draw('mpl')
# Aplicar las compuertas H al primer registro
for qubit in range(n):
dj_circuit.h(qubit)
# Aplicar H al segundo registro, H|1> = |->
dj_circuit.h(n)
dj_circuit.barrier()
dj_circuit.draw('mpl')
def dj_oraculo(dj_circuit, caso):
if caso == 'balanceado':
circuit_return = dj_circuit.compose(balan_oraculo)
else:
circuit_return = dj_circuit.compose(const_oraculo)
circuit_return.barrier()
return circuit_return
# generemos un circuito con el oráculo constante
dj_circ_constante = dj_oraculo(dj_circuit, 'constante')
# generemos un circuito con el oráculo balanceado
dj_circ_balanceado = dj_oraculo(dj_circuit, 'balanceado')
dj_circ_balanceado.draw('mpl')
#---------------------
## Oráculo Balanceado
#---------------------
# Aplicar nuevaente compuertas H al primer registro (en el circuito que ya tienen el oráculo)
for qubit in range(n):
dj_circ_balanceado.h(qubit)
dj_circ_balanceado.barrier()
dj_circ_balanceado.draw('mpl')
#---------------------
## Oráculo Constante
#---------------------
# Aplicar nuevaente compuertas H al primer registro (en el circuito que ya tienen el oráculo)
for qubit in range(n):
dj_circ_constante.h(qubit)
dj_circ_constante.barrier()
dj_circ_constante.draw('mpl')
#---------------------
## Oráculo Balanceado
#---------------------
# agregamos mediciones al primer registro
for i in range(n):
dj_circ_balanceado.measure(i, i)
dj_circ_balanceado.draw('mpl')
#---------------------
## Oráculo Constante
#---------------------
# agregamos mediciones al primer registro
for i in range(n):
dj_circ_constante.measure(i, i)
dj_circ_constante.draw('mpl')
from qiskit import Aer
aer_sim = Aer.get_backend('aer_simulator')
#---------------------
## Oráculo Constante
#---------------------
results = aer_sim.run(dj_circ_constante).result()
respuesta = results.get_counts()
plot_histogram(respuesta)
#---------------------
## Oráculo Balanceado
#---------------------
results = aer_sim.run(dj_circ_balanceado).result()
respuesta = results.get_counts()
plot_histogram(respuesta)
from qiskit import QuantumCircuit
n = 2
grover_circuit = QuantumCircuit(n)
def initialize_s(qc, qubits):
# Aplicar una compuerta H a los 'qubits' in qc
for q in qubits:
#
return qc
grover_circuit = initialize_s(grover_circuit, [0,1])
grover_circuit.draw('mpl')
grover_circuit.barrier()
grover_circuit.cz(0,1) # oráculo
grover_circuit.barrier()
grover_circuit.draw('mpl')
# operador de difusión (U_s)
grover_circuit.h([0,1])
grover_circuit.z([0,1])
grover_circuit.cz(0,1)
grover_circuit.h([0,1])
grover_circuit.draw('mpl')
from qiskit import Aer
from qiskit.visualization import array_to_latex
# revisamos el estado al final del circuito
sv_sim = Aer.get_backend('statevector_simulator')
result = sv_sim.run(grover_circuit).result()
statevec = result.get_statevector()
array_to_latex(statevec, prefix="|\\psi\\rangle =")
# agregamos las mediciones a todos los qubits
grover_circuit.measure_all()
grover_circuit.draw('mpl')
# simulamos la ejecución del circuito
qasm_sim = Aer.get_backend('qasm_simulator')
result = qasm_sim.run(grover_circuit).result()
counts = result.get_counts()
plot_histogram(counts)
# crear el oráculo
qc = QuantumCircuit(3)
qc.cz(0, 2)
qc.cz(1, 2)
oracle_ex3 = qc.to_gate()
oracle_ex3.name = "U$_\omega$"
# función para un difusor general
def diffuser(nqubits):
qc = QuantumCircuit(nqubits)
# Aplicar la transformación |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qc.h(qubit)
# Aplicar la transformación |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qc.x(qubit)
# Aplicar múltiples compuertas Z controladas
qc.h(nqubits-1)
qc.mct(list(range(nqubits-1)), nqubits-1) # toffoli con multicontrol
qc.h(nqubits-1)
# Aplicar la transformación |11..1> -> |00..0>
for qubit in range(nqubits):
qc.x(qubit)
# Aplicar la transformación |00..0> -> |s>
for qubit in range(nqubits):
qc.h(qubit)
# Regresar el difusor como compuerta
U_s = qc.to_gate()
U_s.name = "U$_s$"
return U_s
# Ejemplo para circuito de 3 qubits
n = 3
grover_circuit = QuantumCircuit(n)
grover_circuit = initialize_s(grover_circuit, [0, 1, 2])
grover_circuit.append(oracle_ex3, [0, 1, 2])
grover_circuit.append(diffuser(n), [0, 1, 2])
grover_circuit.measure_all()
grover_circuit.draw('mpl')
# simulamos la ejecución del circuito
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_grover_circuit = transpile(grover_circuit, qasm_sim) # necesario para transpilar las compuertas Uw y Us
results = qasm_sim.run(transpiled_grover_circuit).result()
counts = results.get_counts()
plot_histogram(counts)
from qiskit.algorithms import AmplificationProblem
# el estado que se desea encontrar '11'
good_state = ['11']
# especificar el oráculo que marca el estado '11' como la solución correcta
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
# definir el algorito de Grover
problem = AmplificationProblem(oracle, is_good_state=good_state)
# veamos el operador Grover que será usado para resolver el problema
problem.grover_operator.decompose().draw(output='mpl')
from qiskit.algorithms import Grover
aer_simulator = Aer.get_backend('aer_simulator')
grover = Grover(quantum_instance=aer_simulator) # definir una instancia de `Grover` con el problema
result = grover.amplify(problem)
print('tipo del resultado:', type(result))
print()
print('¡Éxito!' if result.oracle_evaluation else '¡Falló!')
print()
print('Medición más grande:', result.top_measurement)
plot_histogram(result.circuit_results)
import matplotlib.pyplot as plt
N = 35
a = 3
xvals = range(35)
yvals = [np.mod(a**x, N) for x in xvals]
fig, ax = plt.subplots()
ax.plot(xvals, yvals, linewidth=1, linestyle='dotted', marker='x')
ax.set(xlabel='$x$', ylabel='$%i^x$ mod $%i$' % (a, N), title="Ejemplo de función periódica")
try: # graficar 'r'
r = yvals[1:].index(1) + 1
plt.annotate('', xy=(0, 1), xytext=(r, 1), arrowprops=dict(arrowstyle='<->'))
plt.annotate('$r=%i$' % r, xy=(r/3, 1.5))
except ValueError:
print('No se pudo encontrar el período, revisa que a < N y no tengan factores comunes')
ax.set(xlabel='Cantidad de aplicaciones de U', ylabel='Estado final del registro',
title="Efecto de aplicaciones sucesivas de U")
fig
def c_amod15(a, power):
# Multiplicación conrolada por a mod 15
if a not in [2,4,7,8,11,13]:
raise ValueError("'a' debe ser 2,4,7,8,11 o 13")
U = QuantumCircuit(4)
for iteration in range(power):
if a in [2,13]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
if a in [7,8]:
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
if a in [4, 11]:
U.swap(1,3)
U.swap(0,2)
if a in [7,11,13]:
for q in range(4):
U.x(q)
U = U.to_gate()
U.name = "%i^%i mod 15" % (a, power)
c_U = U.control()
return c_U
n_count = 8 # número de qubits de conteo
a = 7
def qft_dagger(n):
# QFT daga de n qubits, los prmero n qubits en circ
qc = QuantumCircuit(n)
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-np.pi/float(2**(j-m)), m, j)
qc.h(j)
qc.name = "QFT†"
return qc
# Crear el circuito final
# circuito con n_count qubits de conteo
# más 4 qubits para que U actúe sobre ellos
qc = QuantumCircuit(n_count + 4, n_count)
# inicializar los qubits de conteo
# en el estado |+>
for q in range(n_count):
qc.h(q)
# y un registro auxiliar en el estado |1>
qc.x(3+n_count)
# aplicar las U controladas
for q in range(n_count):
qc.append(c_amod15(a, 2**q),
[q] + [i+n_count for i in range(4)])
# aplicar QFT daga
qc.append(qft_dagger(n_count), range(n_count))
# medir el circuito
qc.measure(range(n_count), range(n_count))
qc.draw('mpl', fold=-1) # -1 significa 'no separar'
aer_sim = Aer.get_backend('aer_simulator')
t_qc = transpile(qc, aer_sim)
results = aer_sim.run(t_qc).result()
counts = results.get_counts()
plot_histogram(counts)
import pandas as pd
rows, measured_phases = [], []
for output in counts:
decimal = int(output, 2) # Convert (base 2) string to decimal
phase = decimal/(2**n_count) # Find corresponding eigenvalue
measured_phases.append(phase)
# Add these values to the rows in our table:
rows.append([f"{output}(bin) = {decimal:>3}(dec)",
f"{decimal}/{2**n_count} = {phase:.2f}"])
# Print the rows in a table
headers=["Salida del registro", "Fase"]
df = pd.DataFrame(rows, columns=headers)
print(df)
from fractions import Fraction
Fraction(0.666)
# Obtener la fracción que más se asemeje a 0.666
# con denominador < 15
Fraction(0.666).limit_denominator(15)
rows = []
for phase in measured_phases:
frac = Fraction(phase).limit_denominator(15)
rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator])
# Print as a table
headers=["Fase", "Fracción", "Suposición para r"]
df = pd.DataFrame(rows, columns=headers)
print(df)
def a2jmodN(a, j, N):
# Calcular a^{2^j} (mod N) con 'repeated squaring'
for i in range(j):
a = np.mod(a**2, N)
return a
a2jmodN(7, 2049, 53)
N = 15
from numpy.random import randint
np.random.seed(1) # Para hacer reproducibles los resultados
a = randint(2, 15)
print(a)
# ahora, comprobamos que no es ya un factor no trivial de N
from math import gcd # máximo común divisor b(greatest common divisor)
gcd(a, N)
def qpe_amod15(a):
n_count = 8
qc = QuantumCircuit(4+n_count, n_count)
for q in range(n_count):
qc.h(q) # Inicializar qubits en el estado |+>
qc.x(3+n_count) # un registro auxiliar en el estado |1>
for q in range(n_count): # aplicar operaciones U controladas
qc.append(c_amod15(a, 2**q),
[q] + [i+n_count for i in range(4)])
qc.append(qft_dagger(n_count), range(n_count)) # aplicar la QFT inversa
qc.measure(range(n_count), range(n_count))
# simular los resultados
aer_sim = Aer.get_backend('aer_simulator')
# Configurar 'memory=True' permite ver una lista de cada lectura secuencial
t_qc = transpile(qc, aer_sim)
result = aer_sim.run(t_qc, shots=1, memory=True).result()
readings = result.get_memory()
print("Lectura del registro: " + readings[0])
phase = int(readings[0],2)/(2**n_count)
print("Fase correspondiente: %f" % phase)
return phase
# a partir de esta fase, podemos encontrar fácilmente una suposición para r:
phase = qpe_amod15(a) # fase = s/r
Fraction(phase).limit_denominator(15) # el denominador debería decirnos r (eso esperamos)
frac = Fraction(phase).limit_denominator(15)
s, r = frac.numerator, frac.denominator
print(r)
guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)]
print(guesses)
a = 7
factor_found = False
attempt = 0
while not factor_found:
attempt += 1
print("Intento %i:" % attempt)
phase = qpe_amod15(a) # fase = s/r
frac = Fraction(phase).limit_denominator(N) # el denominador debería decirnos r (eso esperamos)
r = frac.denominator
print("Resultado: r = %i" % r)
if phase != 0:
# las suposiciones para los factores son gcd(x^{r/2} ±1 , 15)
guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)]
print("Factores supuestos: %i and %i" % (guesses[0], guesses[1]))
for guess in guesses:
if guess not in [1,N] and (N % guess) == 0: # Check to see if guess is a factor
print("*** Factor encontrado no trivial: %i ***" % guess)
factor_found = True
from qiskit.utils import QuantumInstance
from qiskit.algorithms import Shor
N = 15
backend = Aer.get_backend('aer_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
shor = Shor(quantum_instance=quantum_instance)
result = shor.factor(N)
print(f"La lista de factores de {N} calculada por el algoritmo de Shor es {result.factors[0]}.")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc, style=IQXDebugging())
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Example showing how to use Qiskit-Terra at level 0 (novice).
This example shows the most basic way to user Terra. It builds some circuits
and runs them on both the BasicAer (local Qiskit provider) or IBMQ (remote IBMQ provider).
To control the compile parameters we have provided a transpile function which can be used
as a level 1 user.
"""
# Import the Qiskit modules
from qiskit import QuantumCircuit
from qiskit import execute, BasicAer
# making first circuit: bell state
qc1 = QuantumCircuit(2, 2)
qc1.h(0)
qc1.cx(0, 1)
qc1.measure([0, 1], [0, 1])
# making another circuit: superpositions
qc2 = QuantumCircuit(2, 2)
qc2.h([0, 1])
qc2.measure([0, 1], [0, 1])
# setting up the backend
print("(BasicAER Backends)")
print(BasicAer.backends())
# running the job
job_sim = execute([qc1, qc2], BasicAer.get_backend("qasm_simulator"))
sim_result = job_sim.result()
# Show the results
print(sim_result.get_counts(qc1))
print(sim_result.get_counts(qc2))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for circuit MPL drawer"""
import unittest
import os
import math
from test.visual import VisualTestUtilities
from pathlib import Path
import numpy as np
from numpy import pi
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.providers.fake_provider import FakeTenerife
from qiskit.visualization.circuit.circuit_visualization import _matplotlib_circuit_drawer
from qiskit.circuit.library import (
XGate,
MCXGate,
HGate,
RZZGate,
SwapGate,
DCXGate,
ZGate,
SGate,
U1Gate,
CPhaseGate,
)
from qiskit.circuit.library import MCXVChain
from qiskit.extensions import HamiltonianGate
from qiskit.circuit import Parameter, Qubit, Clbit
from qiskit.circuit.library import IQP
from qiskit.quantum_info.random import random_unitary
from qiskit.utils import optionals
if optionals.HAS_MATPLOTLIB:
from matplotlib.pyplot import close as mpl_close
else:
raise ImportError('Must have Matplotlib installed. To install, run "pip install matplotlib".')
BASE_DIR = Path(__file__).parent
RESULT_DIR = Path(BASE_DIR) / "circuit_results"
TEST_REFERENCE_DIR = Path(BASE_DIR) / "references"
FAILURE_DIFF_DIR = Path(BASE_DIR).parent / "visual_test_failures"
FAILURE_PREFIX = "circuit_failure_"
class TestCircuitMatplotlibDrawer(QiskitTestCase):
"""Circuit MPL visualization"""
def setUp(self):
super().setUp()
self.circuit_drawer = VisualTestUtilities.save_data_wrap(
_matplotlib_circuit_drawer, str(self), RESULT_DIR
)
if not os.path.exists(FAILURE_DIFF_DIR):
os.makedirs(FAILURE_DIFF_DIR)
if not os.path.exists(RESULT_DIR):
os.makedirs(RESULT_DIR)
def tearDown(self):
super().tearDown()
mpl_close("all")
@staticmethod
def _image_path(image_name):
return os.path.join(RESULT_DIR, image_name)
@staticmethod
def _reference_path(image_name):
return os.path.join(TEST_REFERENCE_DIR, image_name)
def test_empty_circuit(self):
"""Test empty circuit"""
circuit = QuantumCircuit()
fname = "empty_circut.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.h(0)
from qiskit import pulse
with pulse.build(name="hadamard") as h_q0:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(0)
)
circuit.add_calibration("h", [0], h_q0)
fname = "calibrations.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations_with_control_gates(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.cx(0, 1)
circuit.ch(0, 1)
from qiskit import pulse
with pulse.build(name="cnot") as cx_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("cx", [0, 1], cx_q01)
with pulse.build(name="ch") as ch_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("ch", [0, 1], ch_q01)
fname = "calibrations_with_control_gates.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations_with_swap_and_reset(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.swap(0, 1)
circuit.reset(0)
from qiskit import pulse
with pulse.build(name="swap") as swap_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("swap", [0, 1], swap_q01)
with pulse.build(name="reset") as reset_q0:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("reset", [0], reset_q0)
fname = "calibrations_with_swap_and_reset.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations_with_rzz_and_rxx(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.rzz(pi, 0, 1)
circuit.rxx(pi, 0, 1)
from qiskit import pulse
with pulse.build(name="rzz") as rzz_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("rzz", [0, 1], rzz_q01)
with pulse.build(name="rxx") as rxx_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("rxx", [0, 1], rxx_q01)
fname = "calibrations_with_rzz_and_rxx.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_no_ops(self):
"""Test circuit with no ops.
See https://github.com/Qiskit/qiskit-terra/issues/5393"""
circuit = QuantumCircuit(2, 3)
fname = "no_op_circut.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_long_name(self):
"""Test to see that long register names can be seen completely
As reported in #2605
"""
# add a register with a very long name
qr = QuantumRegister(4, "veryLongQuantumRegisterName")
# add another to make sure adjustments are made based on longest
qrr = QuantumRegister(1, "q0")
circuit = QuantumCircuit(qr, qrr)
# check gates are shifted over accordingly
circuit.h(qr)
circuit.h(qr)
circuit.h(qr)
fname = "long_name.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_multi_underscore_reg_names(self):
"""Test that multi-underscores in register names display properly"""
q_reg1 = QuantumRegister(1, "q1_re__g__g")
q_reg3 = QuantumRegister(3, "q3_re_g__g")
c_reg1 = ClassicalRegister(1, "c1_re_g__g")
c_reg3 = ClassicalRegister(3, "c3_re_g__g")
circuit = QuantumCircuit(q_reg1, q_reg3, c_reg1, c_reg3)
fname = "multi_underscore_true.png"
self.circuit_drawer(circuit, cregbundle=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "multi_underscore_false.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_conditional(self):
"""Test that circuits with conditionals draw correctly"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
# check gates are shifted over accordingly
circuit.h(qr)
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr, 2)
fname = "reg_conditional.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_bit_conditional_with_cregbundle(self):
"""Test that circuits with single bit conditionals draw correctly
with cregbundle=True."""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.x(qr[1]).c_if(cr[1], 0)
fname = "bit_conditional_bundle.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_bit_conditional_no_cregbundle(self):
"""Test that circuits with single bit conditionals draw correctly
with cregbundle=False."""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.x(qr[1]).c_if(cr[1], 0)
fname = "bit_conditional_no_bundle.png"
self.circuit_drawer(circuit, filename=fname, cregbundle=False)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_plot_partial_barrier(self):
"""Test plotting of partial barriers."""
# generate a circuit with barrier and other barrier like instructions in
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q, c)
# check for barriers
circuit.h(q[0])
circuit.barrier(0)
circuit.h(q[0])
fname = "plot_partial_barrier.png"
self.circuit_drawer(circuit, filename=fname, plot_barriers=True)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_plot_barriers(self):
"""Test to see that plotting barriers works.
If it is set to False, no blank columns are introduced"""
# generate a circuit with barriers and other barrier like instructions in
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q, c)
# check for barriers
circuit.h(q[0])
circuit.barrier()
# check for other barrier like commands
circuit.h(q[1])
# this import appears to be unused, but is actually needed to get snapshot instruction
import qiskit.extensions.simulator # pylint: disable=unused-import
circuit.snapshot("1")
# check the barriers plot properly when plot_barriers= True
fname = "plot_barriers_true.png"
self.circuit_drawer(circuit, filename=fname, plot_barriers=True)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "plot_barriers_false.png"
self.circuit_drawer(circuit, filename=fname2, plot_barriers=False)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_no_barriers_false(self):
"""Generate the same circuit as test_plot_barriers but without the barrier commands
as this is what the circuit should look like when displayed with plot barriers false"""
q1 = QuantumRegister(2, "q")
c1 = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q1, c1)
circuit.h(q1[0])
circuit.h(q1[1])
fname = "no_barriers.png"
self.circuit_drawer(circuit, filename=fname, plot_barriers=False)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_fold_minus1(self):
"""Test to see that fold=-1 is no folding"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
for _ in range(3):
circuit.h(0)
circuit.x(0)
fname = "fold_minus1.png"
self.circuit_drawer(circuit, fold=-1, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_fold_4(self):
"""Test to see that fold=4 is folding"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
for _ in range(3):
circuit.h(0)
circuit.x(0)
fname = "fold_4.png"
self.circuit_drawer(circuit, fold=4, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_big_gates(self):
"""Test large gates with params"""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2])
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0,
]
circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]])
circuit.unitary([[1, 0], [0, 1]], [qr[0]])
matrix = np.zeros((4, 4))
theta = Parameter("theta")
circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]])
circuit = circuit.bind_parameters({theta: 1})
circuit.isometry(np.eye(4, 4), list(range(3, 5)), [])
fname = "big_gates.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_cnot(self):
"""Test different cnot gates (ccnot, mcx, etc)"""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.append(XGate().control(3, ctrl_state="010"), [qr[2], qr[3], qr[0], qr[1]])
circuit.append(MCXGate(num_ctrl_qubits=3, ctrl_state="101"), [qr[0], qr[1], qr[2], qr[4]])
circuit.append(MCXVChain(3, dirty_ancillas=True), [qr[0], qr[1], qr[2], qr[3], qr[5]])
fname = "cnot.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_cz(self):
"""Test Z and Controlled-Z Gates"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.z(0)
circuit.cz(0, 1)
circuit.append(ZGate().control(3, ctrl_state="101"), [0, 1, 2, 3])
circuit.append(ZGate().control(2), [1, 2, 3])
circuit.append(ZGate().control(1, ctrl_state="0", label="CZ Gate"), [2, 3])
fname = "cz.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_pauli_clifford(self):
"""Test Pauli(green) and Clifford(blue) gates"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.y(0)
circuit.z(0)
circuit.id(0)
circuit.h(1)
circuit.cx(1, 2)
circuit.cy(1, 2)
circuit.cz(1, 2)
circuit.swap(3, 4)
circuit.s(3)
circuit.sdg(3)
circuit.iswap(3, 4)
circuit.dcx(3, 4)
fname = "pauli_clifford.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_creg_initial(self):
"""Test cregbundle and initial state options"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(0)
circuit.h(0)
circuit.x(1)
fname = "creg_initial_true.png"
self.circuit_drawer(circuit, filename=fname, cregbundle=True, initial_state=True)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "creg_initial_false.png"
self.circuit_drawer(circuit, filename=fname2, cregbundle=False, initial_state=False)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_r_gates(self):
"""Test all R gates"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.r(3 * pi / 4, 3 * pi / 8, 0)
circuit.rx(pi / 2, 1)
circuit.ry(-pi / 2, 2)
circuit.rz(3 * pi / 4, 3)
circuit.rxx(pi / 2, 0, 1)
circuit.ryy(3 * pi / 4, 2, 3)
circuit.rzx(-pi / 2, 0, 1)
circuit.rzz(pi / 2, 2, 3)
fname = "r_gates.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_ctrl_labels(self):
"""Test control labels"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cy(1, 0, label="Bottom Y label")
circuit.cu(pi / 2, pi / 2, pi / 2, 0, 2, 3, label="Top U label")
circuit.ch(0, 1, label="Top H label")
circuit.append(
HGate(label="H gate label").control(3, label="H control label", ctrl_state="010"),
[qr[1], qr[2], qr[3], qr[0]],
)
fname = "ctrl_labels.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_cswap_rzz(self):
"""Test controlled swap and rzz gates"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cswap(0, 1, 2)
circuit.append(RZZGate(3 * pi / 4).control(3, ctrl_state="010"), [2, 1, 4, 3, 0])
fname = "cswap_rzz.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_ghz_to_gate(self):
"""Test controlled GHZ to_gate circuit"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
ghz_circuit = QuantumCircuit(3, name="this is a WWWWWWWWWWWide name Ctrl-GHZ Circuit")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2, ctrl_state="10")
circuit.append(ccghz, [4, 0, 1, 3, 2])
fname = "ghz_to_gate.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_scale(self):
"""Tests scale
See: https://github.com/Qiskit/qiskit-terra/issues/4179"""
circuit = QuantumCircuit(5)
circuit.unitary(random_unitary(2**5), circuit.qubits)
fname = "scale_default.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "scale_half.png"
self.circuit_drawer(circuit, filename=fname2, scale=0.5)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname3 = "scale_double.png"
self.circuit_drawer(circuit, filename=fname3, scale=2)
ratio3 = VisualTestUtilities._save_diff(
self._image_path(fname3),
self._reference_path(fname3),
fname3,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
self.assertGreaterEqual(ratio3, 0.9999)
def test_pi_param_expr(self):
"""Test pi in circuit with parameter expression."""
x, y = Parameter("x"), Parameter("y")
circuit = QuantumCircuit(1)
circuit.rx((pi - x) * (pi - y), 0)
fname = "pi_in_param_expr.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_partial_layout(self):
"""Tests partial_layout
See: https://github.com/Qiskit/qiskit-terra/issues/4757"""
circuit = QuantumCircuit(3)
circuit.h(1)
transpiled = transpile(
circuit,
backend=FakeTenerife(),
basis_gates=["id", "cx", "rz", "sx", "x"],
optimization_level=0,
initial_layout=[1, 2, 0],
seed_transpiler=0,
)
fname = "partial_layout.png"
self.circuit_drawer(transpiled, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_init_reset(self):
"""Test reset and initialize with 1 and 2 qubits"""
circuit = QuantumCircuit(2)
circuit.initialize([0, 1], 0)
circuit.reset(1)
circuit.initialize([0, 1, 0, 0], [0, 1])
fname = "init_reset.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_with_global_phase(self):
"""Tests with global phase"""
circuit = QuantumCircuit(3, global_phase=1.57079632679)
circuit.h(range(3))
fname = "global_phase.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_alternative_colors(self):
"""Tests alternative color schemes"""
ratios = []
for style in ["iqx", "iqx-dark", "textbook"]:
with self.subTest(style=style):
circuit = QuantumCircuit(7)
circuit.h(0)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.swap(0, 1)
circuit.cswap(0, 1, 2)
circuit.append(SwapGate().control(2), [0, 1, 2, 3])
circuit.dcx(0, 1)
circuit.append(DCXGate().control(1), [0, 1, 2])
circuit.append(DCXGate().control(2), [0, 1, 2, 3])
circuit.z(4)
circuit.s(4)
circuit.sdg(4)
circuit.t(4)
circuit.tdg(4)
circuit.p(pi / 2, 4)
circuit.cz(5, 6)
circuit.cp(pi / 2, 5, 6)
circuit.y(5)
circuit.rx(pi / 3, 5)
circuit.rzx(pi / 2, 5, 6)
circuit.u(pi / 2, pi / 2, pi / 2, 5)
circuit.barrier(5, 6)
circuit.reset(5)
fname = f"{style}_color.png"
self.circuit_drawer(circuit, style={"name": style}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
ratios.append(ratio)
for ratio in ratios:
self.assertGreaterEqual(ratio, 0.9999)
def test_reverse_bits(self):
"""Tests reverse_bits parameter"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0, 1)
circuit.ccx(2, 1, 0)
fname = "reverse_bits.png"
self.circuit_drawer(circuit, reverse_bits=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_bw(self):
"""Tests black and white style parameter"""
circuit = QuantumCircuit(3, 3)
circuit.h(0)
circuit.x(1)
circuit.sdg(2)
circuit.cx(0, 1)
circuit.ccx(2, 1, 0)
circuit.swap(1, 2)
circuit.measure_all()
fname = "bw.png"
self.circuit_drawer(circuit, style={"name": "bw"}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_user_style(self):
"""Tests loading a user style"""
circuit = QuantumCircuit(7)
circuit.h(0)
circuit.append(HGate(label="H2"), [1])
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.swap(0, 1)
circuit.cswap(0, 1, 2)
circuit.append(SwapGate().control(2), [0, 1, 2, 3])
circuit.dcx(0, 1)
circuit.append(DCXGate().control(1), [0, 1, 2])
circuit.append(DCXGate().control(2), [0, 1, 2, 3])
circuit.z(4)
circuit.append(SGate(label="S1"), [4])
circuit.sdg(4)
circuit.t(4)
circuit.tdg(4)
circuit.p(pi / 2, 4)
circuit.cz(5, 6)
circuit.cp(pi / 2, 5, 6)
circuit.y(5)
circuit.rx(pi / 3, 5)
circuit.rzx(pi / 2, 5, 6)
circuit.u(pi / 2, pi / 2, pi / 2, 5)
circuit.barrier(5, 6)
circuit.reset(5)
fname = "user_style.png"
self.circuit_drawer(
circuit,
style={
"name": "user_style",
"displaytext": {"H2": "H_2"},
"displaycolor": {"H2": ("#EEDD00", "#FF0000")},
},
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_subfont_change(self):
"""Tests changing the subfont size"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(0)
circuit.u(pi / 2, pi / 2, pi / 2, 1)
circuit.p(pi / 2, 2)
style = {"name": "iqx", "subfontsize": 11}
fname = "subfont.png"
self.circuit_drawer(circuit, style=style, filename=fname)
self.assertEqual(style, {"name": "iqx", "subfontsize": 11}) # check does not change style
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_meas_condition(self):
"""Tests measure with a condition"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
fname = "meas_condition.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_reverse_bits_condition(self):
"""Tests reverse_bits with a condition and gate above"""
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.x(0)
circuit.x(0)
circuit.measure(2, 1)
circuit.x(2).c_if(cr, 2)
fname = "reverse_bits_cond_true.png"
self.circuit_drawer(circuit, cregbundle=False, reverse_bits=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "reverse_bits_cond_false.png"
self.circuit_drawer(circuit, cregbundle=False, reverse_bits=False, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_style_custom_gates(self):
"""Tests style for custom gates"""
def cnotnot(gate_label):
gate_circuit = QuantumCircuit(3, name=gate_label)
gate_circuit.cnot(0, 1)
gate_circuit.cnot(0, 2)
gate = gate_circuit.to_gate()
return gate
q = QuantumRegister(3, name="q")
circuit = QuantumCircuit(q)
circuit.append(cnotnot("CNOTNOT"), [q[0], q[1], q[2]])
circuit.append(cnotnot("CNOTNOT_PRIME"), [q[0], q[1], q[2]])
circuit.h(q[0])
fname = "style_custom_gates.png"
self.circuit_drawer(
circuit,
style={
"displaycolor": {"CNOTNOT": ("#000000", "#FFFFFF"), "h": ("#A1A1A1", "#043812")},
"displaytext": {"CNOTNOT_PRIME": "$\\mathrm{CNOTNOT}'$"},
},
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_6095(self):
"""Tests controlled-phase gate style
See https://github.com/Qiskit/qiskit-terra/issues/6095"""
circuit = QuantumCircuit(2)
circuit.cp(1.0, 0, 1)
circuit.h(1)
fname = "6095.png"
self.circuit_drawer(
circuit,
style={"displaycolor": {"cp": ("#A27486", "#000000"), "h": ("#A27486", "#000000")}},
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_1q_1c(self):
"""Tests q0-cr0 instruction on a circuit"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
inst = QuantumCircuit(1, 1, name="Inst").to_instruction()
circuit.append(inst, [qr[0]], [cr[0]])
fname = "instruction_1q_1c.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_3q_3c_circ1(self):
"""Tests q0-q1-q2-cr_20-cr0-cr1 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr, cr2)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1], qr[2]], [cr2[0], cr[0], cr[1]])
fname = "instruction_3q_3c_circ1.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_3q_3c_circ2(self):
"""Tests q3-q0-q2-cr0-cr1-cr_20 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr, cr2)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[3], qr[0], qr[2]], [cr[0], cr[1], cr2[0]])
fname = "instruction_3q_3c_circ2.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_3q_3c_circ3(self):
"""Tests q3-q1-q2-cr_31-cr1-cr_30 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
cr3 = ClassicalRegister(2, "cr3")
circuit = QuantumCircuit(qr, cr, cr2, cr3)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[3], qr[1], qr[2]], [cr3[1], cr[1], cr3[0]])
fname = "instruction_3q_3c_circ3.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_overwide_gates(self):
"""Test gates don't exceed width of default fold"""
circuit = QuantumCircuit(5)
initial_state = np.zeros(2**5)
initial_state[5] = 1
circuit.initialize(initial_state)
fname = "wide_params.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_one_bit_regs(self):
"""Test registers with only one bit display without number"""
qr1 = QuantumRegister(1, "qr1")
qr2 = QuantumRegister(2, "qr2")
cr1 = ClassicalRegister(1, "cr1")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.h(0)
circuit.measure(0, 0)
fname = "one_bit_regs.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_user_ax_subplot(self):
"""Test for when user supplies ax for a subplot"""
import matplotlib.pyplot as plt
fig = plt.figure(1, figsize=(6, 4))
fig.patch.set_facecolor("white")
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
ax1.plot([1, 2, 3])
circuit = QuantumCircuit(4)
circuit.h(0)
circuit.cx(0, 1)
circuit.h(1)
circuit.cx(1, 2)
plt.close(fig)
fname = "user_ax.png"
self.circuit_drawer(circuit, ax=ax2, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_figwidth(self):
"""Test style dict 'figwidth'"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0, 1)
circuit.x(1)
circuit.cx(1, 2)
circuit.x(2)
fname = "figwidth.png"
self.circuit_drawer(circuit, style={"figwidth": 5}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_registerless_one_bit(self):
"""Test circuit with one-bit registers and registerless bits."""
qrx = QuantumRegister(2, "qrx")
qry = QuantumRegister(1, "qry")
crx = ClassicalRegister(2, "crx")
circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx)
fname = "registerless_one_bit.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_measures_with_conditions(self):
"""Test that a measure containing a condition displays"""
qr = QuantumRegister(2, "qr")
cr1 = ClassicalRegister(2, "cr1")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr1, cr2)
circuit.h(0)
circuit.h(1)
circuit.measure(0, cr1[1])
circuit.measure(1, cr2[0]).c_if(cr1, 1)
circuit.h(0).c_if(cr2, 3)
fname = "measure_cond_false.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "measure_cond_true.png"
self.circuit_drawer(circuit, cregbundle=True, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_conditions_measures_with_bits(self):
"""Test that gates with conditions and measures work with bits"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(crx[1], 0)
circuit.measure(0, bits[3])
fname = "measure_cond_bits_false.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "measure_cond_bits_true.png"
self.circuit_drawer(circuit, cregbundle=True, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_conditional_gates_right_of_measures_with_bits(self):
"""Test that gates with conditions draw to right of measures when same bit"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[1])
circuit.h(qr[1]).c_if(cr[1], 0)
circuit.h(qr[2]).c_if(cr[0], 0)
fname = "measure_cond_bits_right.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_conditions_with_bits_reverse(self):
"""Test that gates with conditions work with bits reversed"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(2, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(bits[3], 0)
fname = "cond_bits_reverse.png"
self.circuit_drawer(circuit, cregbundle=False, reverse_bits=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_sidetext_with_condition(self):
"""Test that sidetext gates align properly with conditions"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
fname = "sidetext_condition.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_fold_with_conditions(self):
"""Test that gates with conditions draw correctly when folding"""
qr = QuantumRegister(3)
cr = ClassicalRegister(5)
circuit = QuantumCircuit(qr, cr)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 1)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 3)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 5)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 7)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 9)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 11)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 13)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 15)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 17)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 19)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 21)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 23)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 25)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 27)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 29)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 31)
fname = "fold_with_conditions.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_idle_wires_barrier(self):
"""Test that idle_wires False works with barrier"""
circuit = QuantumCircuit(4, 4)
circuit.x(2)
circuit.barrier()
fname = "idle_wires_barrier.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_wire_order(self):
"""Test the wire_order option"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "cx")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 10)
fname = "wire_order.png"
self.circuit_drawer(
circuit,
cregbundle=False,
wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7],
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_barrier_label(self):
"""Test the barrier label"""
circuit = QuantumCircuit(2)
circuit.x(0)
circuit.y(1)
circuit.barrier()
circuit.y(0)
circuit.x(1)
circuit.barrier(label="End Y/X")
fname = "barrier_label.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_op(self):
"""Test the IfElseOp with if only"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.cx(0, 1)
fname = "if_op.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op(self):
"""Test the IfElseOp with else"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)) as _else:
circuit.h(0)
circuit.cx(0, 1)
with _else:
circuit.cx(0, 1)
fname = "if_else_op.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_textbook_style(self):
"""Test the IfElseOp with else in textbook style"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)) as _else:
circuit.h(0)
circuit.cx(0, 1)
with _else:
circuit.cx(0, 1)
fname = "if_else_op_textbook.png"
self.circuit_drawer(circuit, style="textbook", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_with_body(self):
"""Test the IfElseOp with adding a body manually"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
circuit.h(1)
circuit.measure(0, 1)
circuit.measure(1, 2)
circuit.x(2)
circuit.x(2, label="XLabel").c_if(cr, 2)
qr2 = QuantumRegister(3, "qr2")
qc2 = QuantumCircuit(qr2, cr)
qc2.x(1)
qc2.y(1)
qc2.z(0)
qc2.x(0, label="X1i").c_if(cr, 4)
circuit.if_else((cr[1], 1), qc2, None, [0, 1, 2], [0, 1, 2])
circuit.x(0, label="X1i")
fname = "if_else_body.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_nested(self):
"""Test the IfElseOp with complex nested if/else"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_nested.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_wire_order(self):
"""Test the IfElseOp with complex nested if/else and wire_order"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_wire_order.png"
self.circuit_drawer(circuit, wire_order=[2, 0, 3, 1, 4, 5, 6], filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_fold(self):
"""Test the IfElseOp with complex nested if/else and fold"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_fold.png"
self.circuit_drawer(circuit, fold=7, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_while_loop_op(self):
"""Test the WhileLoopOp"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
circuit.measure(0, 2)
with circuit.while_loop((cr[0], 0)):
circuit.h(0)
circuit.cx(0, 1)
circuit.measure(0, 0)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
fname = "while_loop.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_for_loop_op(self):
"""Test the ForLoopOp"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
a = Parameter("a")
circuit.h(0)
circuit.measure(0, 2)
with circuit.for_loop((2, 4, 8, 16), loop_parameter=a):
circuit.h(0)
circuit.cx(0, 1)
circuit.rx(pi / a, 1)
circuit.measure(0, 0)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
fname = "for_loop.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_switch_case_op(self):
"""Test the SwitchCaseOp"""
qreg = QuantumRegister(3, "q")
creg = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qreg, creg)
circuit.h([0, 1, 2])
circuit.measure([0, 1, 2], [0, 1, 2])
with circuit.switch(creg) as case:
with case(0, 1, 2):
circuit.x(0)
with case(3, 4, 5):
circuit.y(1)
circuit.y(0)
circuit.y(0)
with case(case.DEFAULT):
circuit.cx(0, 1)
circuit.h(0)
fname = "switch_case.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
if __name__ == "__main__":
unittest.main(verbosity=1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
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')
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Testing module for transpiling."""
import numpy as np
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.test import QiskitTestCase
from qiskit_cold_atom.transpiler import Optimize1SpinGates
# pylint: disable=no-member
class TestSpinTranspilation(QiskitTestCase):
"""Test class for spin-based transpilation."""
def test_optimize_1s_gates(self):
"""Test the single-spin gate transpilation."""
circ = QuantumCircuit(1)
circ.rlx(np.pi / 2, 0)
circ.rlx(np.pi / 2, 0)
circ.rlx(np.pi / 2, 0)
circ.rly(np.pi / 2, 0)
circ.rly(np.pi / 2, 0)
circ.rlz2(np.pi / 4, 0)
circ.rlz2(np.pi / 4, 0)
circ.rlz2(np.pi / 4, 0)
circ.rlx(np.pi / 2, 0)
pass_manager = PassManager(Optimize1SpinGates())
circ_new = pass_manager.run(circ)
self.assertEqual(circ_new.count_ops()["rlx"], 2)
self.assertEqual(circ_new.count_ops()["rly"], 1)
self.assertEqual(circ_new.count_ops()["rlz2"], 1)
self.assertTrue(np.allclose(circ_new.data[0][0].params[0], 3 * np.pi / 2))
self.assertTrue(np.allclose(circ_new.data[1][0].params[0], np.pi))
self.assertTrue(np.allclose(circ_new.data[2][0].params[0], 3 * np.pi / 4))
self.assertTrue(np.allclose(circ_new.data[3][0].params[0], np.pi / 2))
def test_optimize_1s_gates_multi_spin(self):
"""Test the single-spin gate transpilation."""
circ = QuantumCircuit(2)
circ.rlx(np.pi / 3, 0)
circ.rlx(np.pi / 3, 0)
circ.rlx(np.pi / 3, 0)
circ.rly(np.pi / 4, 1)
circ.rly(np.pi / 4, 1)
pass_manager = PassManager(Optimize1SpinGates())
circ_new = pass_manager.run(circ)
self.assertEqual(circ_new.count_ops()["rlx"], 1)
self.assertEqual(circ_new.count_ops()["rly"], 1)
self.assertTrue(np.allclose(circ_new.data[0][0].params[0], np.pi))
self.assertTrue(np.allclose(circ_new.data[1][0].params[0], np.pi / 2))
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
# Importing everything
from qiskit import *
from qiskit.visualization import plot_histogram
# For Jupyter Notebooks, change the settings to get nicer images
%config InlineBackend.figure_format = 'svg'
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a, b)
def encode_message(qc, qubit, message):
if message == "00":
pass
elif message == "01":
qc.z(qubit)
elif message == "10":
qc.x(qubit)
elif message == "11":
qc.z(qubit)
qz.x(qubit)
else:
print("Enter Valid message please")
def decode_message(qc, a, b):
qc.cx(a, b)
qc.h(a)
# Create the quantum circuit with 2 qubits
qc = QuantumCircuit(2)
# First, Eve creates the entangled pair between Alice and Bob
create_bell_pair(qc, 0, 1)
qc.barrier() # This adds a barrier to our circuit. A barrier
# separates the gates in our diagram and makes it
# clear which part of the circuit is which
# At this point, qubit 0 goes to Alice and qubit 1 goes to Bob
# Next, Alice encodes her message onto qubit 0. In this case,
# we want to send the message '10'. You can try changing this
# value and see how it affects the circuit
message = "10"
encode_message(qc, 0, message)
qc.barrier()
# Alice then sends her qubit to Bob.
# After recieving qubit 0, Bob applies the recovery protocol:
decode_message(qc, 0, 1)
# Finally, Bob measures his qubits to read Alice's message
qc.measure_all()
# Draw our output
qc.draw(output = "mpl")
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend, shots=1024)
sim_result = job_sim.result()
measurement_result = sim_result.get_counts(qc)
print(measurement_result)
plot_histogram(measurement_result)
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
shots = 256
# Load local account information
IBMQ.load_account()
# Get the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit
job = execute(qc, backend=backend, shots=shots)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(qc))
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test 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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import MCXGate
gate = MCXGate(4)
from qiskit import QuantumCircuit
circuit = QuantumCircuit(5)
circuit.append(gate, [0, 1, 4, 2, 3])
circuit.draw('mpl')
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for core modules of timeline drawer."""
from qiskit import QuantumCircuit, transpile
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import core, stylesheet, generators, layouts
class TestCanvas(QiskitTestCase):
"""Test for canvas."""
def setUp(self):
super().setUp()
self.style = stylesheet.QiskitTimelineStyle()
circ = QuantumCircuit(4)
circ.h(0)
circ.barrier()
circ.cx(0, 2)
circ.cx(1, 3)
self.circ = transpile(
circ,
scheduling_method="alap",
basis_gates=["h", "cx"],
instruction_durations=[("h", 0, 200), ("cx", [0, 2], 1000), ("cx", [1, 3], 1000)],
optimization_level=0,
)
def test_time_range(self):
"""Test calculating time range."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter = {"margin.left_percent": 0.1, "margin.right_percent": 0.1}
canvas.time_range = (0, 100)
ref_range = [-10.0, 110.0]
self.assertListEqual(list(canvas.time_range), ref_range)
def test_load_program(self):
"""Test loading program."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [],
"barriers": [],
"gate_links": [],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 8)
ref_coord = {
self.circ.qregs[0][0]: -1.0,
self.circ.qregs[0][1]: -2.0,
self.circ.qregs[0][2]: -3.0,
self.circ.qregs[0][3]: -4.0,
}
self.assertDictEqual(canvas.assigned_coordinates, ref_coord)
def test_gate_link_overlap(self):
"""Test shifting gate link overlap."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update(
{
"margin.link_interval_percent": 0.01,
"margin.left_percent": 0,
"margin.right_percent": 0,
}
)
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 2)
self.assertListEqual(drawings_tested[0][1].xvals, [706.0])
self.assertListEqual(drawings_tested[1][1].xvals, [694.0])
ref_keys = list(canvas._collections.keys())
self.assertEqual(drawings_tested[0][0], ref_keys[0])
self.assertEqual(drawings_tested[1][0], ref_keys[1])
def test_object_outside_xlimit(self):
"""Test eliminating drawings outside the horizontal limit."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [generators.gen_bit_name, generators.gen_timeslot],
"barriers": [],
"gate_links": [],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.set_time_range(t_start=400, t_end=600)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 12)
def test_non_transpiled_delay_circuit(self):
"""Test non-transpiled circuit containing instruction which is trivial on duration."""
circ = QuantumCircuit(1)
circ.delay(10, 0)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [],
"barriers": [],
"gate_links": [],
}
with self.assertWarns(DeprecationWarning):
canvas.load_program(circ)
self.assertEqual(len(canvas._collections), 1)
def test_multi_measurement_with_clbit_not_shown(self):
"""Test generating bit link drawings of measurements when clbits is disabled."""
circ = QuantumCircuit(2, 2)
circ.measure(0, 0)
circ.measure(1, 1)
circ = transpile(
circ,
scheduling_method="alap",
basis_gates=[],
instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)],
optimization_level=0,
)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({"control.show_clbits": False})
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.load_program(circ)
canvas.update()
self.assertEqual(len(canvas._output_dataset), 0)
def test_multi_measurement_with_clbit_shown(self):
"""Test generating bit link drawings of measurements when clbits is enabled."""
circ = QuantumCircuit(2, 2)
circ.measure(0, 0)
circ.measure(1, 1)
circ = transpile(
circ,
scheduling_method="alap",
basis_gates=[],
instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)],
optimization_level=0,
)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({"control.show_clbits": True})
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.load_program(circ)
canvas.update()
self.assertEqual(len(canvas._output_dataset), 2)
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
#Program 3.1a Apply X-gate to qubit
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.x(1)
qc.draw('mpl')
#Program 3.1b Show Bloch sphere of qubit w/wo X-gate
from qiskit.quantum_info import Statevector
state = Statevector.from_instruction(qc)
state.draw('bloch')
#Program 3.2a Measure state of qubit w/o X-gate
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
import math
qc = QuantumCircuit(1,1)
qc.initialize([math.sqrt(1/3), math.sqrt(2/3)],0)
qc.measure([0],[0])
print(qc)
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
#Program 3.2b Measure state of qubit w/ X-gate
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
import math
qc = QuantumCircuit(1,1)
qc.initialize([math.sqrt(1/3), math.sqrt(2/3)],0)
qc.x(0)
qc.measure([0],[0])
print(qc)
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
#Program 3.3a Apply X-gate and H-gate to qubit
from qiskit import QuantumCircuit
import math
qc = QuantumCircuit(4)
qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)],0)
qc.initialize([1/math.sqrt(2), -1/math.sqrt(2)],1)
qc.h(2)
qc.x(3)
qc.h(3)
qc.draw('mpl')
#Program 3.3b Show Bloch sphere of qubit w/ X-gate and H-gate
from qiskit.quantum_info import Statevector
state = Statevector.from_instruction(qc)
state.draw('bloch')
#Program 3.4 Measure state of qubit w/ H-gate
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
qc = QuantumCircuit(1,1)
qc.h(0)
qc.measure([0],[0])
print("This is |+>:")
print(qc)
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
#Program 3.5 Measure state of qubit w/ X-gate and H-gate
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
qc = QuantumCircuit(1,1)
qc.x(0)
qc.h(0)
qc.measure([0],[0])
print("This is |->:")
print(qc)
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
#Program 3.6 Measure state of qubit w/ H-gate
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
qc = QuantumCircuit(2,2)
qc.h(0)
qc.h(1)
qc.measure([0,1],[0,1])
print("This is |++>:")
print(qc)
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
#Program 3.7a Apply X-, Y-, and Z-gate to qubit
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
qc.x(0)
qc.y(1)
qc.z(2)
qc.draw('mpl')
#Program 3.7b Show Bloch sphere of qubit w/ X-, Y-, and Z-gate
from qiskit.quantum_info import Statevector
state = Statevector.from_instruction(qc)
state.draw('bloch')
#Program 3.8a Apply RX-, RY-, and RZ-gate to qubit
from qiskit import QuantumCircuit
import math
qc = QuantumCircuit(3)
qc.rx(math.pi/2, 0)
qc.ry(math.pi/2, 1)
qc.rz(math.pi/2, 2)
qc.draw('mpl')
#Program 3.8b Show Bloch sphere of qubit w/ RX-, RY-, and RZ-gate
from qiskit.quantum_info import Statevector
state = Statevector.from_instruction(qc)
state.draw('bloch')
#Program 3.9a Apply RX-, P-, S-, T-gate to qubit
from qiskit import QuantumCircuit
import math
qc = QuantumCircuit(4)
qc.rx(math.pi/2, [0,1,2,3])
qc.p(math.pi/8, 1)
qc.s(2)
qc.t(3)
qc.draw('mpl')
#Program 3.9b Show Bloch sphere of qubit w/ RX-, P-, S-, and T-gate
from qiskit.quantum_info import Statevector
state = Statevector.from_instruction(qc)
state.draw('bloch')
#Program 3.10a Apply RX-, I-, and U-gate to qubit
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')
#Program 3.10b Show Bloch sphere of qubit w/ RX-, I-, and U-gate
from qiskit.quantum_info import Statevector
state = Statevector.from_instruction(qc)
state.draw('bloch')
|
https://github.com/qiskit-community/qiskit-aqt-provider
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) 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.
import json
import os
import re
import uuid
from pathlib import Path
from typing import NamedTuple, Optional
import httpx
import pytest
import qiskit
from pytest_httpx import HTTPXMock
from pytest_mock import MockerFixture
from qiskit.providers import JobStatus
from qiskit_aqt_provider import api_models, api_models_generated, persistence
from qiskit_aqt_provider.aqt_job import AQTJob
from qiskit_aqt_provider.aqt_options import AQTOptions
from qiskit_aqt_provider.aqt_provider import AQTProvider
from qiskit_aqt_provider.aqt_resource import AQTResource, OfflineSimulatorResource
from qiskit_aqt_provider.test.circuits import random_circuit
from qiskit_aqt_provider.test.fixtures import MockSimulator
@pytest.mark.parametrize(
"backend_name",
[
"offline_simulator_no_noise",
pytest.param(
"offline_simulator_noise",
marks=pytest.mark.xfail(reason="Job persistence on noisy simulator not supported."),
),
],
)
@pytest.mark.parametrize("remove_from_store", [True, False])
def test_job_persistence_transaction_offline_simulator(
backend_name: str, remove_from_store: bool, tmp_path: Path
) -> None:
"""Persist and restore a job on offline simulators."""
token = str(uuid.uuid4())
provider = AQTProvider(token)
backend = provider.get_backend(backend_name)
assert isinstance(backend, OfflineSimulatorResource)
circuits = [random_circuit(2), random_circuit(3)]
job = backend.run(qiskit.transpile(circuits, backend))
path = job.persist(store_path=tmp_path)
# sanity check
assert str(path).startswith(str(tmp_path))
restored_job = AQTJob.restore(
job.job_id(), access_token=token, store_path=tmp_path, remove_from_store=remove_from_store
)
assert path.exists() is not remove_from_store
assert isinstance(restored_job.backend(), OfflineSimulatorResource)
restored_backend: OfflineSimulatorResource = restored_job.backend()
assert restored_backend.provider.access_token == backend.provider.access_token
assert restored_backend.with_noise_model == backend.with_noise_model
assert restored_job.options == job.options
assert restored_job.circuits == job.circuits
assert restored_job.api_submit_payload == job.api_submit_payload
# for offline simulators, the backend state is fully lost so the restored_job
# is actually a new one
assert restored_job.job_id()
assert restored_job.job_id() != job.job_id()
# we get a result for both jobs, but they in principle differ because the job was re-submitted
assert restored_job.result().success
assert len(restored_job.result().get_counts()) == len(circuits)
assert job.result().success
assert len(job.result().get_counts()) == len(circuits)
def test_job_persistence_transaction_online_backend(httpx_mock: HTTPXMock, tmp_path: Path) -> None:
"""Persist and restore a job on mocked online resources."""
# Set up a fake online resource
token = str(uuid.uuid4())
provider = AQTProvider(token)
resource_id = api_models.ResourceId(
workspace_id=str(uuid.uuid4()),
resource_id=str(uuid.uuid4()),
resource_name=str(uuid.uuid4()),
resource_type="device",
)
backend = AQTResource(provider, resource_id)
class PortalJob(NamedTuple):
"""Mocked portal state: holds details of the submitted jobs."""
circuits: list[api_models_generated.QuantumCircuit]
workspace_id: str
resource_id: str
error_msg: str
portal_state: dict[uuid.UUID, PortalJob] = {}
def handle_submit(request: httpx.Request) -> httpx.Response:
"""Mocked circuit submission endpoint.
Create a job ID and a unique error message for the submitted job.
Store the details in `portal_state`.
"""
assert request.headers["authorization"] == f"Bearer {token}"
_, workspace_id, resource_id = request.url.path.rsplit("/", maxsplit=2)
data = api_models.SubmitJobRequest.model_validate_json(request.content.decode("utf-8"))
circuits = data.payload.circuits
job_id = uuid.uuid4()
assert job_id not in portal_state
portal_state[job_id] = PortalJob(
circuits=circuits,
workspace_id=workspace_id,
resource_id=resource_id,
error_msg=str(uuid.uuid4()),
)
return httpx.Response(
status_code=httpx.codes.OK,
json=json.loads(
api_models.Response.queued(
job_id=job_id, resource_id=resource_id, workspace_id=workspace_id
).model_dump_json()
),
)
def handle_result(request: httpx.Request) -> httpx.Response:
"""Mocked circuit result endpoint.
Check that the access token is valid.
Return an error response, with the unique error message for the
requested job ID.
"""
assert request.headers["authorization"] == f"Bearer {token}"
_, job_id = request.url.path.rsplit("/", maxsplit=1)
job = portal_state[uuid.UUID(job_id)]
return httpx.Response(
status_code=httpx.codes.OK,
json=json.loads(
api_models.Response.error(
job_id=uuid.UUID(job_id),
workspace_id=job.workspace_id,
resource_id=job.resource_id,
message=job.error_msg,
).model_dump_json()
),
)
httpx_mock.add_callback(
handle_submit, url=re.compile(r".+/submit/[0-9a-f-]+/[0-9a-f-]+$"), method="POST"
)
httpx_mock.add_callback(handle_result, url=re.compile(r".+/result/[0-9a-f-]+$"), method="GET")
# ----------
circuits = [random_circuit(2), random_circuit(3), random_circuit(4)]
job = backend.run(qiskit.transpile(circuits, backend), shots=123)
# sanity checks
assert uuid.UUID(job.job_id()) in portal_state
assert job.options != AQTOptions() # non-default options because shots=123
path = job.persist(store_path=tmp_path)
restored_job = AQTJob.restore(job.job_id(), access_token=token, store_path=tmp_path)
assert not path.exists() # remove_from_store is True by default
assert restored_job.job_id() == job.job_id()
assert restored_job.circuits == job.circuits
assert restored_job.options == job.options
# the mocked GET /result route always returns an error response with a unique error message
assert job.status() is JobStatus.ERROR
assert restored_job.status() is JobStatus.ERROR
assert job.error_message
assert job.error_message == restored_job.error_message
assert job.result().success is False
assert restored_job.result().success is False
# both job and restored_job have already been submitted, so they can't be submitted again
with pytest.raises(RuntimeError, match="Job already submitted"):
job.submit()
with pytest.raises(RuntimeError, match="Job already submitted"):
restored_job.submit()
def test_can_only_persist_submitted_jobs(
offline_simulator_no_noise: MockSimulator, tmp_path: Path
) -> None:
"""Check that only jobs with a valid job_id can be persisted."""
circuit = qiskit.transpile(random_circuit(2), offline_simulator_no_noise)
job = AQTJob(offline_simulator_no_noise, [circuit], AQTOptions())
assert not job.job_id()
with pytest.raises(RuntimeError, match=r"Can only persist submitted jobs."):
job.persist(store_path=tmp_path)
def test_restore_unknown_job(tmp_path: Path) -> None:
"""Check that an attempt at restoring an unknown job raises JobNotFoundError."""
with pytest.raises(persistence.JobNotFoundError):
AQTJob.restore(job_id="invalid", store_path=tmp_path)
@pytest.mark.parametrize("override", [None, Path("foo/bar")])
def test_store_path_resolver(
override: Optional[Path], tmp_path: Path, mocker: MockerFixture
) -> None:
"""Test the persistence store path resolver.
The returned path must:
- be the override, if passed
- exist
- be a directory.
"""
# do not pollute the test user's environment
# this only works on unix
mocker.patch.dict(os.environ, {"XDG_CACHE_HOME": str(tmp_path)})
if override is not None:
override = tmp_path / override
store_path = persistence.get_store_path(override)
# sanity check: make sure the mock works
assert str(store_path).startswith(str(tmp_path))
assert store_path.exists()
assert store_path.is_dir()
if override is not None:
assert store_path == override
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=unused-argument
"""A module for monitoring backends."""
import time
from sys import modules
from IPython.display import HTML, display
from IPython.core.magic import line_magic, Magics, magics_class
import qiskit
from qiskit.utils import local_hardware_info
@magics_class
class VersionTable(Magics):
"""A class of status magic functions."""
@line_magic
def qiskit_version_table(self, line="", cell=None):
"""
Print an HTML-formatted table with version numbers for Qiskit and its
dependencies. This should make it possible to reproduce the environment
and the calculation later on.
"""
html = "<h3>Version Information</h3>"
html += "<table>"
html += "<tr><th>Software</th><th>Version</th></tr>"
packages = {"qiskit": None}
packages["qiskit-terra"] = qiskit.__version__
qiskit_modules = {module.split(".")[0] for module in modules.keys() if "qiskit" in module}
for qiskit_module in qiskit_modules:
packages[qiskit_module] = getattr(modules[qiskit_module], "__version__", None)
from importlib.metadata import metadata, PackageNotFoundError
try:
packages["qiskit"] = metadata("qiskit")["Version"]
except PackageNotFoundError:
packages["qiskit"] = None
for name, version in packages.items():
if name == "qiskit" or version:
html += f"<tr><td><code>{name}</code></td><td>{version}</td></tr>"
html += "<tr><th colspan='2'>System information</th></tr>"
local_hw_info = local_hardware_info()
sys_info = [
("Python version", local_hw_info["python_version"]),
("Python compiler", local_hw_info["python_compiler"]),
("Python build", local_hw_info["python_build"]),
("OS", "%s" % local_hw_info["os"]),
("CPUs", "%s" % local_hw_info["cpus"]),
("Memory (Gb)", "%s" % local_hw_info["memory"]),
]
for name, version in sys_info:
html += f"<tr><td>{name}</td><td>{version}</td></tr>"
html += "<tr><td colspan='2'>%s</td></tr>" % time.strftime("%a %b %d %H:%M:%S %Y %Z")
html += "</table>"
return display(HTML(html))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
ghz.draw(output='mpl')
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
import logging
from qiskit import QuantumRegister, QuantumCircuit
from qiskit import execute as q_execute
from qiskit import BasicAer
from qiskit.aqua import AquaError, aqua_globals
from qiskit.aqua.components.initial_states import InitialState
from qiskit.aqua.circuits import StateVectorCircuit
from qiskit.aqua.utils.arithmetic import normalize_vector
from qiskit.aqua.utils.circuit_utils import convert_to_basis_gates
logger = logging.getLogger(__name__)
class Custom(InitialState):
"""A custom initial state."""
CONFIGURATION = {
'name': 'CUSTOM',
'description': 'Custom initial state',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'custom_state_schema',
'type': 'object',
'properties': {
'state': {
'type': 'string',
'default': 'zero',
'oneOf': [
{'enum': ['zero', 'uniform', 'random']}
]
},
'state_vector': {
'type': ['array', 'null'],
"items": {
"type": "number"
},
'default': None
}
},
'additionalProperties': False
}
}
def __init__(self, num_qubits, state="zero", state_vector=None, circuit=None):
"""Constructor.
Args:
num_qubits (int): number of qubits
state (str): `zero`, `uniform` or `random`
state_vector: customized vector
circuit (QuantumCircuit): the actual custom circuit for the desired initial state
"""
loc = locals().copy()
# since state_vector is a numpy array of complex numbers which aren't json valid,
# remove it from validation
del loc['state_vector']
self.validate(loc)
super().__init__()
self._num_qubits = num_qubits
self._state = state
size = np.power(2, self._num_qubits)
self._circuit = None
if circuit is not None:
if circuit.width() != num_qubits:
logger.warning('The specified num_qubits and the provided custom circuit do not match.')
self._circuit = convert_to_basis_gates(circuit)
if state_vector is not None:
self._state = None
self._state_vector = None
logger.warning('The provided state_vector is ignored in favor of the provided custom circuit.')
else:
if state_vector is None:
if self._state == 'zero':
self._state_vector = np.array([1.0] + [0.0] * (size - 1))
elif self._state == 'uniform':
self._state_vector = np.array([1.0 / np.sqrt(size)] * size)
elif self._state == 'random':
self._state_vector = normalize_vector(aqua_globals.random.rand(size))
else:
raise AquaError('Unknown state {}'.format(self._state))
else:
if len(state_vector) != np.power(2, self._num_qubits):
raise AquaError('The state vector length {} is incompatible with the number of qubits {}'.format(
len(state_vector), self._num_qubits
))
self._state_vector = normalize_vector(state_vector)
self._state = None
def construct_circuit(self, mode, register=None):
"""
Construct the statevector of desired initial state.
Args:
mode (string): `vector` or `circuit`. The `vector` mode produces the vector.
While the `circuit` constructs the quantum circuit corresponding that
vector.
register (QuantumRegister): register for circuit construction.
Returns:
QuantumCircuit or numpy.ndarray: statevector.
Raises:
AquaError: when mode is not 'vector' or 'circuit'.
"""
if mode == 'vector':
if self._state_vector is None:
if self._circuit is not None:
self._state_vector = np.asarray(q_execute(self._circuit, BasicAer.get_backend(
'statevector_simulator')).result().get_statevector(self._circuit))
return self._state_vector
elif mode == 'circuit':
if self._circuit is None:
if register is None:
register = QuantumRegister(self._num_qubits, name='q')
# create emtpy quantum circuit
circuit = QuantumCircuit()
# if register is actually a list of qubits
if type(register) is list:
# loop over all qubits and add the required registers
for q in register:
if not circuit.has_register(q[0]):
circuit.add_register(q[0])
else:
# if an actual register is given, add it
circuit.add_register(register)
if self._state is None or self._state == 'random':
svc = StateVectorCircuit(self._state_vector)
svc.construct_circuit(circuit, register)
elif self._state == 'zero':
pass
elif self._state == 'uniform':
for i in range(self._num_qubits):
circuit.u2(0.0, np.pi, register[i])
else:
pass
self._circuit = circuit
return self._circuit.copy()
else:
raise AquaError('Mode should be either "vector" or "circuit"')
|
https://github.com/snow0369/qiskit_tutorial_2021_summerschool
|
snow0369
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.providers.aer import AerProvider
from qiskit import execute
qr = QuantumRegister(2) # 2 qubits
cr = ClassicalRegister(2) # 2 classical bits
qc = QuantumCircuit(qr, cr) # a quantum circuit with 2 qubits and 2 bits
qc.draw()
qc.h(qr[0]) # 0번째 qubit에 hadamard 연산을 취합니다.
qc.cx(qr[0], qr[1]) # 0번째 qubit을 control, 1번째 qubit를 target으로 하는 CNOT 연산을 취합니다.
qc.measure(qr, cr) # qr을 측정하여 cr에 저장하는 측정 연산을 취합니다.
qc.draw('mpl') # 완성된 회로를 출력합니다.
qasm_simulator = AerProvider().get_backend('qasm_simulator')
job_qasm = execute(qc, backend=qasm_simulator, shots=2048)
# 다른 방법
# job_qasm = qasm_simulator.run(qc, shots=2048)
#
# 또는
#
# from qiskit.utils import QuantumInstance
# qi = QuantumInstance(qasm_simulator, shots=2048)
# result = qi.execute(qc)
# counts = result.get_counts()
counts = job_qasm.result().get_counts()
print("Bell measurement result")
for k, v in counts.items():
print(k, v)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
# Benchmark qiskit_alt peforming the Jordan-Wigner transform on a Fermi operator.
import qiskit_alt
qiskit_alt.project.ensure_init()
import timeit
def make_setup_code(basis, geometry):
return f"""
import qiskit_alt.electronic_structure
h2_geometry = [['H', [0., 0., 0.]], ['H', [0., 0., 0.7414]]]
h2o_geometry = [['O', [0., 0., 0.]],
['H', [0.757, 0.586, 0.]],
['H', [-0.757, 0.586, 0.]]]
basis = {basis}
fermi_op = qiskit_alt.electronic_structure.fermionic_hamiltonian({geometry}, basis)
qiskit_alt.electronic_structure.jordan_wigner(fermi_op);
"""
def run_one_basis(basis, geometry, num_repetitions):
setup_code = make_setup_code(basis, geometry)
bench_code = "qiskit_alt.electronic_structure.jordan_wigner(fermi_op)"
time = timeit.timeit(stmt=bench_code, setup=setup_code, number=num_repetitions)
t = 1000 * time / num_repetitions
print(f"geometry={geometry}, basis={basis} {t:0.2f}", "ms")
return t
def run_benchmarks():
alt_times = []
for basis, geometry, num_repetitions in (("'sto3g'", "h2_geometry", 10), ("'631g'", "h2_geometry", 10),
("'631++g'", "h2_geometry", 10),
("'sto3g'", "h2o_geometry", 10), ("'631g'", "h2o_geometry", 5)):
t = run_one_basis(basis, geometry, num_repetitions)
alt_times.append(t)
return alt_times
if __name__ == '__main__':
alt_times = run_benchmarks()
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/0sophy1/Qiskit-Dev-Cert-lectures
|
0sophy1
|
a = 2 + 3j
b = 5 - 2j
print("a + b=", a+b)
print("a * b=", a*b)
a = 2 + 3j
a_bar = 2 - 3j
print("a + a_bar = ", a + a_bar)
print("a * a_bar = ", a * a_bar)
import matplotlib.pyplot as plt
import numpy as np
import math
z1 = 3 + 4j
x_min = 0
x_max = 5.0
y_min = 0
y_max = 5.0
def plot_complex_number_geometric_representation(z,x_min,x_max,y_min,y_max):
fig = plt.figure()
ax = plt.gca()
a = [0.0,0.0]
b = [z.real,z.imag]
head_length = 0.2
dx = b[0] - a[0]
dy = b[1] - a[1]
vec_ab = [dx,dy]
vec_ab_magnitude = math.sqrt(dx**2+dy**2)
dx = dx / vec_ab_magnitude
dy = dy / vec_ab_magnitude
vec_ab_magnitude = vec_ab_magnitude - head_length
ax.arrow(a[0], a[1], vec_ab_magnitude*dx, vec_ab_magnitude*dy, head_width=head_length, head_length=head_length, fc='black', ec='black')
plt.xlim(x_min,x_max)
plt.ylim(y_min,y_max)
plt.grid(True,linestyle='-')
plt.show()
plot_complex_number_geometric_representation(z1,x_min,x_max,y_min,y_max)
import numpy as np
A = np.array([[1,2,3]])
B = np.array([[7], [10], [9]])
A+B
A = np.array([[7], [10], [9]])
B = np.array([[1,2,3]])
C = np.array([[1, 2, 3], [5, 6, 7], [8,9,10]])
print("AB = ", np.matmul(A,B))
print("BA = ", np.matmul(B,A))
print("CA = ", np.matmul(C, A))
print("AC = ", np.matmul(A, C))
A = np.array([[1, 2], [3,4]])
B = np.array([[5, 6], [7,8]])
print("AB = \n", np.matmul(A,B))
print("BA = \n", np.matmul(B,A))
from scipy.linalg import orth
from numpy import linalg as LA
A = np.array([[1 + 3j, 2 - 1j], [3, 4 - 2j]])
data =orth(A)
x, y = data[:, 0], data[:, 1]
print("norm of x = %f" % LA.norm(x))
print("norm of y = %f" % LA.norm(y))
print("x dot y = ", np.vdot(x,y))
|
https://github.com/rigetti/qiskit-rigetti
|
rigetti
|
from typing import Callable
PreCompilationHook = Callable[[str], str]
"""Represents a function that can transform a QASM program string just before compilation."""
def set_rewiring(rewiring: str) -> PreCompilationHook:
"""
Create a hook which will apply rewiring before compilation.
See: https://pyquil-docs.rigetti.com/en/stable/compiler.html#initial-rewiring for more information.
Args:
rewiring: Rewiring directive to apply.
Returns:
PreCompilationHook: A hook to apply rewiring.
Examples:
Applying rewiring to a program::
>>> from qiskit import execute
>>> from qiskit_rigetti import RigettiQCSProvider, QuilCircuit
>>> from qiskit_rigetti.hooks.pre_compilation import set_rewiring
>>> p = RigettiQCSProvider()
>>> backend = p.get_simulator(num_qubits=2, noisy=True)
>>> circuit = QuilCircuit(2, 2)
>>> _ = circuit.measure([0, 1], [0, 1])
>>> job = execute(circuit, backend, shots=10, before_compile=[set_rewiring("NAIVE")])
"""
def fn(qasm: str) -> str:
return qasm.replace("OPENQASM 2.0;", f'OPENQASM 2.0;\n#pragma INITIAL_REWIRING "{rewiring}";')
return fn
|
https://github.com/Cryoris/surfer
|
Cryoris
|
"""The Gradient interface.
Avoids using the plain name Gradient since that exists in Qiskit and I want to avoid conflicts.
"""
from abc import ABC, abstractmethod
import qiskit
import qiskit.opflow
import numpy as np
class GradientCalculator(ABC):
"""The Gradient interface."""
def __init__(self, do_checks: bool = True):
"""
Args:
do_checks: Do some sanity checks on the inputs. Can be disabled for performance.
"""
self.do_checks = do_checks
@abstractmethod
def compute(
self,
operator: qiskit.opflow.OperatorBase,
circuit: qiskit.QuantumCircuit,
values: np.ndarray,
) -> np.ndarray:
"""Compute the Gradient for the given circuit.
The initial state is assumed to be the all-zero state.
Args:
operator: The operator for the expectation value.
circuit: A parameterized unitary circuit preparing the quantum state of which we compute
the Gradient.
values: The parameter values.
"""
raise NotImplementedError
@staticmethod
def check_inputs(circuit: qiskit.QuantumCircuit, values: np.ndarray) -> None:
"""Check the circuit and values.
Args:
circuit: A parameterized unitary circuit preparing the quantum state of which we compute
the Gradient.
values: The parameter values.
Raises:
ValueError: If the circuit is invalid (non unitary or gates with more than 1 parameter).
ValueError: If the number of values doesn't match the parameters.
"""
_check_circuit_is_unitay(circuit)
_check_1_parameter_per_gate(circuit)
# check the number of parameters
if circuit.num_parameters != values.size:
raise ValueError(
f"Mismatching number of parameters ({circuit.num_parameters}) "
f"and values ({values.size})."
)
def _check_circuit_is_unitay(circuit):
try:
_ = circuit.to_gate()
except qiskit.circuit.exceptions.CircuitError:
# pylint: disable=raise-missing-from
raise ValueError("The circuit is not unitary.")
def _check_1_parameter_per_gate(circuit):
for inst, _, _ in circuit.data:
params = inst.params
if (
any(isinstance(params, qiskit.circuit.ParameterExpression))
and len(params) > 1
):
raise ValueError(
"If a gate is parameterized, it can only have 1 parameter."
)
|
https://github.com/adlantz/QiskitSG
|
adlantz
|
# initialization
import itertools as it
import os
from typing import List
# importing Qiskit
from qiskit import (
Aer,
QuantumCircuit,
ClassicalRegister,
QuantumRegister,
transpile,
)
# import basic plot tools
from qiskit.visualization import plot_histogram
import pprint
LOOP_DICT = {3: 6, 4: 6, 5: 24}
def main():
# Get number of spins
while True:
N = int(input("Number of spins/qubits: "))
if N in LOOP_DICT:
break
print(
f"Unable to calculate for this size. Possible sizes: {list(LOOP_DICT.keys())}"
)
bond_list = bond_list_maker(N)
num_of_bonds = len(bond_list)
# Build requisite quantum and classical registers
spin_qubits = QuantumRegister(N, name="spin")
bond_qubits = QuantumRegister(num_of_bonds, name="bond")
multi_control_qubit = QuantumRegister(1, name="multi")
cbits = ClassicalRegister(num_of_bonds, name="cbit")
qc = QuantumCircuit(spin_qubits, bond_qubits, multi_control_qubit, cbits)
# Initialize multi control qubit to |-> state
qc.x(multi_control_qubit)
qc.h(multi_control_qubit)
qc.barrier() # for visual separation
# Initialise spin and bond qubits in state |++...+> (equal superposition)
qc.h(spin_qubits)
qc.h(bond_qubits)
qc.barrier()
# We don't know how many solutions there are so we can't calculate the optimal number of loops
# TODO: Implement quantum counting to find number of solutions
# Until we implement the above, we just use the LOOP_DICT dictionary I made from trial and error
loop_number = LOOP_DICT[N]
for _ in range(loop_number):
# Add the oracle - this adds a negative phase only to solutions
SG_oracle(qc, bond_list, bond_qubits, multi_control_qubit)
qc.barrier()
# Add the diffuser, this "reflects" the state vector around the equal superposition vector
# We make this a gate for legibility
qc.append(diffuser(num_of_bonds), bond_qubits)
# print(qc.draw())
# Measure the variable qubits
# qc.measure(bond_qubits, cbits)
# Print/Save circuit interface
while True:
prntqc = input("Print Circuit? (y/n)")
if prntqc == "y" or prntqc == "yes":
print(qc.draw())
break
elif prntqc.lower() in ("n", "no"):
break
else:
print("invalid input")
while True:
sveqc = input("Save circuit as png? (y/n)")
if sveqc == "y" or sveqc == "yes":
print("saving to " + str(os.getcwd()))
qc.draw(output="mpl", filename="N" + str(N) + "_frust_qc.png", style="iqp")
break
elif sveqc.lower() in ("n", "no"):
break
else:
print("invalid input")
print("Simulating quantum circuit...")
# Send circuit to backend to get exact mathematical state of circuit before measuring
backend = Aer.get_backend("aer_simulator_statevector")
qc.save_statevector()
result = backend.run(transpile(qc, backend)).result()
final_state_vector = result.get_statevector(qc)
# Get probabilities of each bond + spin state combo
probabilities_dict = final_state_vector.probabilities_dict(
[i for i in range(N + num_of_bonds)]
)
# Consolidate most probable bonds and their solution spin states
output_obj = {}
for key in probabilities_dict:
if probabilities_dict[key] > 0.0001:
bond_state = key[:num_of_bonds]
spin_sate = key[0 - N :]
if bond_state not in output_obj:
output_obj[bond_state] = {
"probability": probabilities_dict[key],
"spin_states": [spin_sate],
}
else:
output_obj[bond_state]["probability"] += probabilities_dict[key]
output_obj[bond_state]["spin_states"].append(spin_sate)
print(
"Here are the bond states with no frustration and the spin states that solve them"
)
pprint.PrettyPrinter(indent=4).pprint(output_obj)
# Give the option to visualize bond configurations using SGViz.py
while True:
bond_config = input(
f"Input bond configuration from keys of object above (Example: {list(output_obj.keys())[0]}) to visualize (q to to quit): "
)
if bond_config.lower() in ("q", "quit"):
print("Goodbye!")
break
if bond_config in output_obj:
os.system("python3 SGViz.py -loadBC -BC " + bond_config + " -N " + str(N))
else:
print("not a valid input")
def bond_list_maker(N: int) -> List[List[int]]:
# Given a set of spins, an ordered list of the form [ [a,b], [a,c], ...] where
# the ith element is a list of the two spins connected by the ith bond
return [list(c) for c in it.combinations([i for i in range(N)], 2)]
def diffuser(nqubits: int):
qc = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qc.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qc.x(qubit)
# Do multi-controlled-Z gate
qc.h(nqubits - 1)
qc.mcx(list(range(nqubits - 1)), nqubits - 1) # multi-controlled-toffoli
qc.h(nqubits - 1)
# Apply transformation |11..1> -> |00..0>
for qubit in range(nqubits):
qc.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qc.h(qubit)
# Return the diffuser as a gate
U_s = qc.to_gate()
U_s.name = "$U_s$"
return U_s
def XOR(qc, a, b, output):
qc.cx(a, output)
qc.cx(b, output)
qc.barrier()
def SG_oracle(
qc: QuantumCircuit,
bond_list: List[List[int]],
bond_qubits: QuantumRegister,
multi_control_qubit: QuantumRegister,
):
# Add an XOR to each bond qubit such that if bond_i connects spin_a
# and spin_b, the bond_i qubit will become spin_a XOR spin_b
for i, clause in enumerate(bond_list):
XOR(qc, clause[0], clause[1], bond_qubits[i])
# Apply X gate to 'multicontrol' qubit if all clauses are satisfied
# This adds a negative phase to solution items only
qc.mcx(bond_qubits, multi_control_qubit)
# Add the exact same XOR gates to "uncompute" and return bonds to original state
for i, clause in enumerate(bond_list):
XOR(qc, clause[0], clause[1], bond_qubits[i])
i += 1
if __name__ == "__main__":
main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import NormalDistribution
# can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example.
A = np.eye(2)
b = np.zeros(2)
# specify the number of qubits that are used to represent the different dimenions of the uncertainty model
num_qubits = [2, 2]
# specify the lower and upper bounds for the different dimension
low = [0, 0]
high = [0.12, 0.24]
mu = [0.12, 0.24]
sigma = 0.01 * np.eye(2)
# construct corresponding distribution
bounds = list(zip(low, high))
u = NormalDistribution(num_qubits, mu, sigma, bounds)
# plot contour of probability density function
x = np.linspace(low[0], high[0], 2 ** num_qubits[0])
y = np.linspace(low[1], high[1], 2 ** num_qubits[1])
z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1])
plt.contourf(x, y, z)
plt.xticks(x, size=15)
plt.yticks(y, size=15)
plt.grid()
plt.xlabel("$r_1$ (%)", size=15)
plt.ylabel("$r_2$ (%)", size=15)
plt.colorbar()
plt.show()
# specify cash flow
cf = [1.0, 2.0]
periods = range(1, len(cf) + 1)
# plot cash flow
plt.bar(periods, cf)
plt.xticks(periods, size=15)
plt.yticks(size=15)
plt.grid()
plt.xlabel("periods", size=15)
plt.ylabel("cashflow ($)", size=15)
plt.show()
# estimate real value
cnt = 0
exact_value = 0.0
for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])):
for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])):
prob = u.probabilities[cnt]
for t in range(len(cf)):
# evaluate linear approximation of real value w.r.t. interest rates
exact_value += prob * (
cf[t] / pow(1 + b[t], t + 1)
- (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2)
)
cnt += 1
print("Exact value: \t%.4f" % exact_value)
# specify approximation factor
c_approx = 0.125
# create fixed income pricing application
from qiskit_finance.applications.estimation import FixedIncomePricing
fixed_income = FixedIncomePricing(
num_qubits=num_qubits,
pca_matrix=A,
initial_interests=b,
cash_flow=cf,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=u,
)
fixed_income._objective.draw()
fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits)
# load probability distribution
fixed_income_circ.append(u, range(u.num_qubits))
# apply function
fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits))
fixed_income_circ.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
# construct amplitude estimation
problem = fixed_income.to_estimation_problem()
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (fixed_income.interpret(result)))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
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 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests preset pass managers with 1Q backend"""
from test import combine
from ddt import ddt
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import Fake1Q
from qiskit.transpiler import TranspilerError
def emptycircuit():
"""Empty circuit"""
return QuantumCircuit()
def circuit_3516():
"""Circuit from https://github.com/Qiskit/qiskit-terra/issues/3516 should fail"""
circuit = QuantumCircuit(2, 1)
circuit.h(0)
circuit.ry(0.11, 1)
circuit.measure([0], [0])
return circuit
@ddt
class Test1QFailing(QiskitTestCase):
"""1Q tests that should fail."""
@combine(
circuit=[circuit_3516],
level=[0, 1, 2, 3],
dsc="Transpiling {circuit.__name__} at level {level} should fail",
name="{circuit.__name__}_level{level}_fail",
)
def test(self, circuit, level):
"""All the levels with all the 1Q backend"""
with self.assertRaises(TranspilerError):
transpile(circuit(), backend=Fake1Q(), optimization_level=level, seed_transpiler=42)
@ddt
class Test1QWorking(QiskitTestCase):
"""1Q tests that should work."""
@combine(
circuit=[emptycircuit],
level=[0, 1, 2, 3],
dsc="Transpiling {circuit.__name__} at level {level} should work",
name="{circuit.__name__}_level{level}_valid",
)
def test_device(self, circuit, level):
"""All the levels with all the 1Q backend"""
result = transpile(
circuit(), backend=Fake1Q(), optimization_level=level, seed_transpiler=42
)
self.assertIsInstance(result, QuantumCircuit)
@combine(
circuit=[circuit_3516],
level=[0, 1, 2, 3],
dsc="Transpiling {circuit.__name__} at level {level} should work for simulator",
name="{circuit.__name__}_level{level}_valid",
)
def test_simulator(self, circuit, level):
"""All the levels with all the 1Q simulator backend"""
# Set fake backend config to simulator
backend = Fake1Q()
backend._configuration.simulator = True
result = transpile(circuit(), backend=backend, optimization_level=level, seed_transpiler=42)
self.assertIsInstance(result, QuantumCircuit)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# -*- 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.
# TODO: Remove after 0.7 and the deprecated methods are removed
# pylint: disable=unused-argument
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import errno
import logging
import os
import subprocess
import tempfile
from PIL import Image
from qiskit import user_config
from qiskit.visualization import exceptions
from qiskit.visualization import latex as _latex
from qiskit.visualization import text as _text
from qiskit.visualization import utils
from qiskit.visualization import matplotlib as _matplotlib
logger = logging.getLogger(__name__)
def circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Args:
circuit (QuantumCircuit): the quantum circuit to draw
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (str): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. By
default the 'text' drawer is used unless a user config file has
an alternative backend set as the default. If the output is passed
in that backend will always be used.
interactive (bool): when set true show the circuit in a new window
(for `mpl` this depends on the matplotlib backend being used
supporting this). Note when used with either the `text` or the
`latex_source` output type this has no effect and will be silently
ignored.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). However, if you're running in
jupyter the default line length is set to 80 characters. If you
don't want pagination at all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (string): Options are `left`, `right` or `none`, if anything
else is supplied it defaults to left justified. It refers to where
gates should be placed in the output circuit if there is an option.
`none` results in each gate being placed in its own column. Currently
only supported by text drawer.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
ImportError: when the output methods requieres non-installed libraries.
.. _style-dict-doc:
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'id': 'id',
'u0': 'U_0',
'u1': 'U_1',
'u2': 'U_2',
'u3': 'U_3',
'x': 'X',
'y': 'Y',
'z': 'Z',
'h': 'H',
's': 'S',
'sdg': 'S^\\dagger',
't': 'T',
'tdg': 'T^\\dagger',
'rx': 'R_x',
'ry': 'R_y',
'rz': 'R_z',
'reset': '\\left|0\\right\\rangle'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
"""
image = None
config = user_config.get_config()
# Get default from config file else use text
default_output = 'text'
if config:
default_output = config.get('circuit_drawer', 'text')
if output is None:
output = default_output
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename,
line_length=line_length,
reverse_bits=reverse_bits,
plotbarriers=plot_barriers,
justify=justify)
elif output == 'latex':
image = _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits,
justify=justify)
elif output == 'latex_source':
return _generate_latex_source(circuit,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits,
justify=justify)
elif output == 'mpl':
image = _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits,
justify=justify)
else:
raise exceptions.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if image and interactive:
image.show()
return image
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
"""Return default style for matplotlib_circuit_drawer (IBM QX style)."""
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"id": "id",
"u0": "U_0",
"u1": "U_1",
"u2": "U_2",
"u3": "U_3",
"x": "X",
"y": "Y",
"z": "Z",
"h": "H",
"s": "S",
"sdg": "S^\\dagger",
"t": "T",
"tdg": "T^\\dagger",
"rx": "R_x",
"ry": "R_y",
"rz": "R_z",
"reset": "\\left|0\\right\\rangle"
},
"displaycolor": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None, line_length=None, reverse_bits=False,
plotbarriers=True, justify=None, vertically_compressed=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reverse_bits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
vertically_compressed (bool): Default is `True`. It merges the lines so the
drawing will take less vertical room.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
qregs, cregs, ops = utils._get_layered_instructions(circuit,
reverse_bits=reverse_bits,
justify=justify)
text_drawing = _text.TextDrawing(qregs, cregs, ops)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
text_drawing.vertically_compressed = vertically_compressed
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def _latex_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits, justify=justify)
image = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as ex:
with open('latex_error.log', 'wb') as error_file:
error_file.write(ex.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
image = Image.open(base + '.png')
image = utils._trim(image)
os.remove(base + '.png')
if filename:
image.save(filename, 'PNG')
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return image
def _generate_latex_source(circuit, filename=None,
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True, justify=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
str: Latex string appropriate for writing to file.
"""
qregs, cregs, ops = utils._get_layered_instructions(circuit,
reverse_bits=reverse_bits,
justify=justify)
qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
qregs, cregs, ops = utils._get_layered_instructions(circuit,
reverse_bits=reverse_bits,
justify=justify)
qcd = _matplotlib.MatplotlibDrawer(qregs, cregs, ops, scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
return qcd.draw(filename)
|
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
|
alejomonbar
|
# !pip install --upgrade pip
# !pip uninstall tensorflow --y
# !pip install tensorflow
#import os
#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
#os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
# load csv file
import pandas as pd
# numpy to the seed
import numpy as np
# load csv fileframework to neural networks
import tensorflow as tf
#Method forthe neural network
from keras.regularizers import l2
from keras.models import Sequential
from keras.layers import Dense, Dropout
#save as image the model summary
from keras.utils.vis_utils import plot_model
# librariesto plot
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
from sklearn.metrics import confusion_matrix, roc_curve, auc
from sklearn.preprocessing import StandardScaler
# demonstration of calculating metrics for a neural network model using sklearn
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import roc_auc_score
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
data_train = pd.read_csv("classic_train.csv")
X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values
data_test = pd.read_csv("classic_test.csv")
X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values
(X_train.shape, y_train.shape),(X_test.shape, y_test.shape)
np.random.seed(123)
tf.random.set_seed(123)
scale = StandardScaler()
scale.fit(X_train)
X_train_std = scale.transform(X_train)
X_test_std = scale.transform(X_test)
X_train_std[1], y_train[1]
model = Sequential()
model.add(Dense(25, input_dim=16, activation='relu', kernel_regularizer=l2(1e-6),kernel_initializer="glorot_normal"))
model.add(Dropout(0.5))
model.add(Dense(8, activation='relu',kernel_regularizer=l2(1e-6), kernel_initializer="glorot_normal"))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid',kernel_regularizer=l2(1e-6), kernel_initializer="glorot_normal"))
plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)
# Compile model
auc = tf.keras.metrics.AUC()
model.compile(loss='binary_crossentropy', optimizer="Adam", metrics=['accuracy',auc])
model_history = model.fit(X_train_std, y_train, epochs=100,
batch_size=32,
validation_split=0.2, shuffle=True)
train_pred = model.predict(X_train_std)
test_pred = model.predict(X_test_std)
y_train_pred = (model.predict(X_train_std) > 0.5).astype("int32")
y_test_pred = (model.predict(X_test_std) > 0.5).astype("int32")
accuracy = accuracy_score(y_train, y_train_pred)
print('Accuracy: %f' % accuracy)
# precision tp / (tp + fp)
precision = precision_score(y_train, y_train_pred)
print('Precision: %f' % precision)
# recall: tp / (tp + fn)
recall = recall_score(y_train, y_train_pred)
print('Recall: %f' % recall)
# f1: 2 tp / (2 tp + fp + fn)
f1 = f1_score(y_train, y_train_pred)
print('F1 score: %f' % f1)
# kappa
kappa = cohen_kappa_score(y_train, y_train_pred)
print('Cohens kappa: %f' % kappa)
# ROC AUC
auc = roc_auc_score(y_train, y_train_pred)
print('ROC AUC: %f' % auc)
# confusion matrix
train_matrix = confusion_matrix(y_train, y_train_pred)
print(train_matrix)
ax = sns.heatmap(train_matrix, annot=True, cmap='Blues', fmt='g')
ax.set_title('Seaborn Confusion Matrix with labels\n\n');
ax.set_xlabel('\nPredicted Values')
ax.set_ylabel('Actual Values ');
ax.xaxis.set_ticklabels(['0','1'])
ax.yaxis.set_ticklabels(['0','1'])
## Display the visualization of the Confusion Matrix.
plt.show()
accuracy = accuracy_score(y_test, y_test_pred)
print('Accuracy: %f' % accuracy)
# precision tp / (tp + fp)
precision = precision_score(y_test, y_test_pred)
print('Precision: %f' % precision)
# recall: tp / (tp + fn)
recall = recall_score(y_test, y_test_pred)
print('Recall: %f' % recall)
# f1: 2 tp / (2 tp + fp + fn)
f1 = f1_score(y_test, y_test_pred)
print('F1 score: %f' % f1)
# kappa
kappa = cohen_kappa_score(y_test, y_test_pred)
print('Cohens kappa: %f' % kappa)
# ROC AUC
auc = roc_auc_score(y_test, y_test_pred)
print('ROC AUC: %f' % auc)
# confusion matrix
test_matrix = confusion_matrix(y_test, y_test_pred)
print(test_matrix)
ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g')
ax.set_title('Seaborn Confusion Matrix with labels\n\n');
ax.set_xlabel('\nPredicted Values')
ax.set_ylabel('Actual Values ');
ax.xaxis.set_ticklabels(['0','1'])
ax.yaxis.set_ticklabels(['0','1'])
## Display the visualization of the Confusion Matrix.
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()
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/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
from typing import List
import numpy as np
import weylchamber
from qiskit.circuit.gate import Gate
from qiskit.circuit.parameterexpression import ParameterValueType
from qiskit.extensions import UnitaryGate
from slam.hamiltonian import (
CirculatorHamiltonian,
ConversionGainPhaseHamiltonian,
ConversionGainSmush,
ConversionGainSmush1QPhase,
)
"""
Library of useful gates that aren't defined natively in qiskit
Example Usage:
from custom_gates import *
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.append(RiSwapGate(1/4), [0,1])
qc.draw(output='mpl')
"""
class CustomCostGate(Gate):
# want to build a gate progamatically from a unitary
# cost value used in expected haar calcuation
def __init__(self, unitary, str, cost=1, duration=1, num_qubits=2):
self.unitary = unitary
self.str = str
self.c = cost
# self.global_phase = 0 #idk why the dag method requires this
super().__init__(str, num_qubits=num_qubits, params=[], label=str)
self.duration = duration # duration is attribution not duration
@classmethod
def from_gate(cls, gate: Gate, cost: float):
return cls(gate.to_matrix(), str(gate), cost=cost)
# we use this duration property in the speed limit pass sub
# we build a dummy gate that sets duration such that fooanalysis counts correctly
# the fam substitution messes up our custom scaled gates but this is a nice work around
# def duration(self):
# return self.d
def cost(self):
return self.c
def __str__(self):
return self.str
def __array__(self, dtype=None):
return np.array(self.unitary, dtype)
# class VSwap(Gate):
# def __init__(self, t_el: ParameterValueType = 1):
# super().__init__("vswap", 3, [t_el], "VSWAP")
# # v_nn = np.sqrt(2) * np.pi / np.arccos(1 / np.sqrt(3))
# # self.v_params = [np.pi / 2, np.pi / 2, 0, np.pi / v_nn, np.pi / v_nn, 0]
# #use a more standardized normalization
# v_nn = 4/np.sqrt(2) #1.5iswap
# self.v_params = [np.pi / 2, np.pi / 2, 0, np.pi / v_nn, np.pi / v_nn, 0] #V-swap
# #self._array = CirculatorHamiltonian.construct_U(*v_params,t=t_el)
# def __array__(self, dtype=None):
# # v_nn = np.sqrt(2)*np.pi/np.arccos(1/np.sqrt(3))
# # params = [np.pi/2,np.pi/2,0, np.pi/v_nn, np.pi/v_nn, 0]
# self._array = CirculatorHamiltonian.construct_U(*self.v_params,t=self.params[0])
# return self._array.full()
# def inverse(self):
# return UnitaryGate(np.matrix.getH(self.__array__()))
# class DeltaSwap(Gate):
# def __init__(self, t_el: ParameterValueType = 1):
# super().__init__("Δswap", 3, [t_el], "ΔSWAP")
# nn = 3 * np.sqrt(3) / 2
# self.v_params = [np.pi / 2, -np.pi / 2, np.pi / 2, np.pi / nn, np.pi / nn, np.pi / nn] #smiley
# def __array__(self, dtype=None):
# self._array = CirculatorHamiltonian.construct_U(*self.v_params,t=self.params[0])
# return self._array.full()
# def inverse(self):
# return UnitaryGate(np.matrix.getH(self.__array__()))
class CirculatorSNAILGate(Gate):
def __init__(
self,
p1: ParameterValueType,
p2: ParameterValueType,
p3: ParameterValueType,
g1: ParameterValueType,
g2: ParameterValueType,
g3: ParameterValueType,
t_el: ParameterValueType = 1,
):
super().__init__("3QGate", 3, [p1, p2, p3, g1, g2, g3, t_el], "3QGate")
# XXX can only assign duration after init with real values
if all([isinstance(p, (int, float)) for p in self.params]):
self.duration = self.cost()
# NOTE: we don't want this param in the constr ctor, it messes len(signature(gate).parameters) in template construction
def set_str(self, str):
self._label = str
self._name = str
def __array__(self, dtype=None):
self._array = CirculatorHamiltonian.construct_U(
*[float(el) for el in self.params[0:-1]], t=float(self.params[-1])
)
return self._array.full()
def cost(self):
# #something to prevent infinitely small/negative values
# if all([float(el) <= (1/20) for el in self.params[3:-1]]):
# return 0
norm = np.pi / 2
# abs because g can be negative, just consider its absolute strength
c = (sum(abs(np.array(self.params[3:-1]))) * self.params[-1]) / norm
return c
def fidelity(self):
c = self.cost()
base = 0.999
return np.max(1 - (1 - base) * float(c), 0)
def inverse(self):
return UnitaryGate(np.matrix.getH(self.__array__()))
class VSwap(CirculatorSNAILGate):
def __init__(
self,
t_el: ParameterValueType = 1,
) -> None:
v_nn = 4 / np.sqrt(2) # 1.5iswap
super().__init__(
*[np.pi / 2, np.pi / 2, 0, np.pi / v_nn, np.pi / v_nn, 0], t_el=t_el
)
self.set_str("VSWAP")
class DeltaSwap(CirculatorSNAILGate):
def __init__(self, t_el: ParameterValueType = 1) -> None:
nn = 3 * np.sqrt(3) / 2
super().__init__(
*[np.pi / 2, -np.pi / 2, np.pi / 2, np.pi / nn, np.pi / nn, np.pi / nn],
t_el=t_el,
)
self.set_str("Δ-iSWAP")
class ConversionGainGate(Gate):
def __init__(
self,
p1: ParameterValueType,
p2: ParameterValueType,
g1: ParameterValueType,
g2: ParameterValueType,
t_el: ParameterValueType = 1,
):
super().__init__("2QGate", 2, [p1, p2, g1, g2, t_el], "2QGate")
# XXX can only assign duration after init with real values
if all([isinstance(p, (int, float)) for p in self.params]):
self.duration = (
self.cost()
) # XXX not really duration since always normalized to norm=1
self.name = str(self)
def __array__(self, dtype=None):
self._array = ConversionGainPhaseHamiltonian.construct_U(
*[float(el) for el in self.params[0:-1]], t=float(self.params[-1])
)
return self._array.full()
# overwrite string representation
def __str__(self):
g1 = self.params[2]
g2 = self.params[3]
t = self.params[4]
# truncate to 8 decimal places
s = f"2QGate({g1:.8f}, {g2:.8f}, {t:.8f})"
return s
def normalize_duration(self, new_duration):
# scales g terms such that t is new_duration
# this is useful for loading gates from a file, matching file hashes
# save the old duration
old_duration = self.duration
t = self.params[-1]
self.params[2] = self.params[2] * t / new_duration
self.params[3] = self.params[3] * t / new_duration
self.params[-1] = new_duration
# assert the duration has not hcnaged
assert self.duration == old_duration
self = ConversionGainGate(*self.params)
def cost(self):
norm = np.pi / 2
# sum the g terms
c = (sum(abs(np.array(self.params[2:4]))) * self.params[-1]) / norm
return c
class ConversionGainSmushGate(Gate):
def __init__(
self,
pc: ParameterValueType,
pg: ParameterValueType,
gc: ParameterValueType,
gg: ParameterValueType,
gx: List[ParameterValueType],
gy: List[ParameterValueType],
t_el: ParameterValueType = 1,
):
self.xy_len = len(gx)
assert len(gx) == len(gy)
self.t_el = t_el
super().__init__(
"2QSmushGate", 2, [pc, pg, gc, gg, *gx, *gy, t_el], "2QSmushGate"
)
# XXX can only assign duration after init with real values
# XXX vectors will break this type checking
# XXX not checking if time is real valued!!
if all([isinstance(p, (int, float)) for p in self.params[0:4]]):
self.duration = self.cost()
def __array__(self, dtype=None):
self._array = ConversionGainSmush.construct_U(
float(self.params[0]),
float(self.params[1]),
float(self.params[2]),
float(self.params[3]),
[float(el) for el in self.params[4 : 4 + self.xy_len]],
[float(el) for el in self.params[4 + self.xy_len : -1]],
t=float(self.params[-1]),
)
return (
self._array
) # don't need full() since multiplication happens inside the construct_U function
def cost(self):
norm = np.pi / 2
# sum the g terms, ignore the x and y terms
# idea is that 1Q gates drive qubits not SNAIL so don't contribute to speed limit
c = (sum(abs(np.array(self.params[2:4]))) * self.params[-1]) / norm
return c
class ConversionGainSmush1QPhaseGate(Gate):
def __init__(
self,
pa: ParameterValueType,
pb: ParameterValueType,
pc: ParameterValueType,
pg: ParameterValueType,
gc: ParameterValueType,
gg: ParameterValueType,
gz1: ParameterValueType,
gz2: ParameterValueType,
gx: List[ParameterValueType],
gy: List[ParameterValueType],
t_el: ParameterValueType = 1,
):
self.xy_len = len(gx)
assert len(gx) == len(gy)
self.t_el = t_el
super().__init__(
"2QSmushGate1QPhase",
2,
[pa, pb, pc, pg, gc, gg, gz1, gz2, *gx, *gy, t_el],
"2QSmushGate1QPhase",
)
# XXX can only assign duration after init with real values
# XXX vectors will break this type checking
# XXX not checking if time is real valued!!
if all([isinstance(p, (int, float)) for p in self.params[:8]]):
self.duration = self.cost()
def __array__(self, dtype=None):
self._array = ConversionGainSmush1QPhase.construct_U(
float(self.params[0]),
float(self.params[1]),
float(self.params[2]),
float(self.params[3]),
float(self.params[4]),
float(self.params[5]),
float(self.params[6]),
float(self.params[7]),
[float(el) for el in self.params[8 : 8 + self.xy_len]],
[float(el) for el in self.params[8 + self.xy_len : -1]],
t=float(self.params[-1]),
)
return (
self._array
) # don't need full() since multiplication happens inside the construct_U function
def cost(self):
norm = np.pi / 2
# sum the g terms, ignore the x and y terms
# idea is that 1Q gates drive qubits not SNAIL so don't contribute to speed limit
c = (sum(abs(np.array(self.params[4:6]))) * self.params[-1]) / norm
return c
class CParitySwap(Gate):
def __init__(self, _: ParameterValueType = None):
super().__init__("cpswap", 3, [], "CParitySwap")
# an alternative defintion using hamiltonian
# we just have it hardcoded instead
# nn = 3 * np.sqrt(3) / 2
# params = [-np.pi / 2, np.pi / 2, -np.pi / 2, np.pi / nn, np.pi / nn, np.pi / nn] #frowny
# params = [np.pi / 2, -np.pi / 2, np.pi / 2, np.pi / nn, np.pi / nn, np.pi / nn] #smiley
# from hamiltonian import CirculatorHamiltonian
# self._array = CirculatorHamiltonian.construct_U(*params)
def __array__(self, dtype=None):
return np.array(
[
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
],
dtype=dtype,
)
def _define(self):
"""Gate ccx a,b,c { h c; cx b,c; tdg c; cx a,c; t c; cx b,c; tdg c; cx
a,c; t b; t c; h c; cx a,b; t a; tdg b; cx a,b;}"""
# pylint: disable=cyclic-import
from qiskit.circuit.quantumcircuit import QuantumCircuit
# q_0: ─X──X──X──X─
# │ │ │ │
# q_1: ─X──■──X──┼─
# │ │ │
# q_2: ─■──X─────X─
qc = QuantumCircuit(3, name=self.name)
qc.cswap(2, 0, 1)
qc.cswap(1, 0, 2)
qc.swap(0, 1)
qc.swap(0, 2)
self.definition = qc
class Margolus(Gate):
def __init__(self, _: ParameterValueType = None):
super().__init__("margolus", 3, [], "Margolus")
def __array__(Self, dtype=None):
return np.array(
[
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, -1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0],
],
dtype=dtype,
)
class CanonicalGate(Gate):
def __init__(self, alpha, beta, gamma, name="can"):
super().__init__(name, 2, [alpha, beta, gamma], name)
# normalize to convention
alpha, beta, gamma = [2 * x / np.pi for x in (alpha, beta, gamma)]
self.data = weylchamber.canonical_gate(alpha, beta, gamma).full()
def __array__(self, dtype=None):
return np.array(self.data, dtype=dtype)
class BerkeleyGate(CanonicalGate):
def __init__(self):
super().__init__(np.pi / 4, np.pi / 8, 0, name="B")
def __str__(self):
return "B"
# alternative definition
# def __init__(self):
# from hamiltonian import ConversionGainHamiltonian
# ConversionGainHamiltonian.construct_U(3*np.pi/8, np.pi/8)
# ...
class CCZGate(Gate):
def __init__(self, _: ParameterValueType = None):
super().__init__("ccz", 3, [], "CCZGate")
def __array__(self, dtype=None):
return np.array(
[
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, -1],
],
dtype=dtype,
)
class CCiXGate(Gate):
def __init__(self, _: ParameterValueType = None):
super().__init__("ccix", 3, [], "CCiXGate")
def __array__(Self, dtype=None):
return np.array(
[
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1j],
[0, 0, 0, 0, 0, 0, 1j, 0],
],
dtype=dtype,
)
class CiSwap(Gate):
def __init__(self, _: ParameterValueType = None):
super().__init__("ciswap", 3, [], "CiSwap")
def __array__(Self, dtype=None):
return np.array(
[
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1j, 0],
[0, 0, 0, 0, 0, 1j, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
],
dtype=dtype,
)
class Peres(Gate):
def __init__(self, _: ParameterValueType = None):
super().__init__("peres", 3, [], "PERES")
def __array__(Self, dtype=None):
return np.array(
[
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
],
dtype=dtype,
)
class FSim(Gate):
def __init__(self, theta: ParameterValueType, phi: ParameterValueType):
"""SYC: FSim(theta=np.pi/2, phi=np.pi/6)"""
super().__init__("fsim", 2, [theta, phi])
def __array__(self, dtype=None):
return np.array(
[
[1, 0, 0, 0],
[0, np.cos(self.params[0]), -1j * np.sin(self.params[0]), 0],
[0, -1j * np.sin(self.params[0]), np.cos(self.params[0]), 0],
[0, 0, 0, np.exp(1j * self.params[1])],
],
dtype=dtype,
)
from slam.hamiltonian import FSimHamiltonian
class FSimHamiltonianGate(Gate):
def __init__(
self, g: ParameterValueType, eta: ParameterValueType, t: ParameterValueType
):
super().__init__("fsim", 2, [g, eta, t])
def __array__(self, dtype=None):
self._array = FSimHamiltonian.construct_U(
*[float(el) for el in self.params[0:-1]], t=float(self.params[-1])
)
return self._array.full()
class SYC(FSim):
def __init__(self):
super().__init__(np.pi / 2, np.pi / 6)
def __str__(self):
return self.latex_string(self.params)
@staticmethod
def latex_string(gate_params):
return "SYC"
class RiSwapGate(Gate):
# turns out you can also do qiskit.iSwapGate().power(1/n)
# but I didnt know about the power fucntion until recently :(
r"""RiSWAP gate.
**Circuit Symbol:**
.. parsed-literal::
q_0: ─⨂─
R(alpha)
q_1: ─⨂─
"""
def __init__(self, alpha: ParameterValueType):
"""Create new iSwap gate."""
# super().__init__(
# "riswap", 2, [alpha], label=r"$\sqrt[" + str(int(1 / alpha)) + r"]{iSwap}$"
# )
super().__init__("riswap", 2, [alpha], label="riswap")
# XXX can only assign duration after init with real values
if all([isinstance(p, (int, float)) for p in self.params]):
self.duration = self.cost()
# including this seems to break the decompose method
# we don't want to define riswap in terms of other gates, leave it as riswap primitives
# def _define(self):
# from qiskit import QuantumCircuit
# qc = QuantumCircuit(2)
# from qiskit.circuit.library.standard_gates import iSwapGate
# qc.append(iSwapGate().power(1/self.params[0]), [0, 1])
# self.definition = qc
def cost(self):
# norm = np.pi/2
# I don't need to use nrom bc already considered in parameter definition
# e.g. sqisw has params[0] := 1/2
return float(self.params[0])
def fidelity(self):
if float(self.params[0]) <= (
1 / 20
): # something to prevent infinitely small/negative values
return 0
base = 0.999
return np.max(1 - (1 - base) * float(self.params[0]), 0)
def __array__(self, dtype=None):
"""Return a numpy.array for the RiSWAP gate."""
alpha = float(self.params[0]) / 2
cos = np.cos(np.pi * alpha)
isin = 1j * np.sin(np.pi * alpha)
return np.array(
[
[1, 0, 0, 0],
[0, cos, isin, 0],
[0, isin, cos, 0],
[0, 0, 0, 1],
],
dtype=dtype,
)
def __str__(self):
return RiSwapGate.latex_string(self.params)
@staticmethod
def latex_string(gate_params=None):
if gate_params is None:
return r"$\sqrt[n]{iSwap}$"
else:
n = 1 / gate_params[0]
return r"$\sqrt[" + str(int(n)) + r"]{iSwap}$"
|
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
|
PavanCyborg
|
#Assign these values as per your requirements.
global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion
method = 2
min_qubits=4 # must be at least (MIN_STATE_QUBITS=1) + 3 = 4
## for method-1 min_qubits = 5 (MIN_STATE_QUBITS = 2)+3 = 5
max_qubits=10 # Because circuit size grows significantly with num_qubits limit the max_qubits here ...
skip_qubits=1
max_circuits=3
num_shots=1000
epsilon=0.05
degree=2
Noise_Inclusion = False
saveplots = False
Memory_utilization_plot = True
gate_counts_plots = True
Type_of_Simulator = "FAKEV2" #Inputs are "built_in" or "FAKE" or "FAKEV2"
backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends
#Change your Specification of Simulator in Declaring Backend Section
#By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2()
import numpy as np
import copy
import functools
import mc_utils as mc_utils
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute
import time
import matplotlib.pyplot as plt
from numpy.polynomial.polynomial import Polynomial
from numpy.polynomial.polynomial import polyfit
from qiskit.circuit.library.standard_gates.ry import RYGate
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error)
# Benchmark Name
benchmark_name = "Monte Carlo Sampling"
# Selection of basis gate set for transpilation
# Note: selector 1 is a hardware agnostic gate set
basis_selector = 1
basis_gates_array = [
[],
['rx', 'ry', 'rz', 'cx'], # a common basis set, default
['cx', 'rz', 'sx', 'x'], # IBM default basis set
['rx', 'ry', 'rxx'], # IonQ default basis set
['h', 'p', 'cx'], # another common basis set
['u', 'cx'] # general unitaries basis gates
]
np.random.seed(0)
num_gates = 0
depth = 0
QV_=0
def get_QV(backend):
import json
# Assuming backend.conf_filename is the filename and backend.dirname is the directory path
conf_filename = backend.dirname + "/" + backend.conf_filename
# Open the JSON file
with open(conf_filename, 'r') as file:
# Load the JSON data
data = json.load(file)
# Extract the quantum_volume parameter
QV = data.get('quantum_volume', None)
return QV
def checkbackend(backend_name,Type_of_Simulator):
if Type_of_Simulator == "built_in":
available_backends = []
for i in Aer.backends():
available_backends.append(i.name)
if backend_name in available_backends:
platform = backend_name
return platform
else:
print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!")
print(f"available backends are : {available_backends}")
platform = "qasm_simulator"
return platform
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2":
import qiskit.providers.fake_provider as fake_backends
if hasattr(fake_backends,backend_name) is True:
print(f"Backend {backend_name} is available for type {Type_of_Simulator}.")
backend_class = getattr(fake_backends,backend_name)
backend_instance = backend_class()
return backend_instance
else:
print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!")
if Type_of_Simulator == "FAKEV2":
backend_class = getattr(fake_backends,"FakeSantiagoV2")
else:
backend_class = getattr(fake_backends,"FakeSantiago")
backend_instance = backend_class()
return backend_instance
if Type_of_Simulator == "built_in":
platform = checkbackend(backend_name,Type_of_Simulator)
#By default using "Qasm Simulator"
backend = Aer.get_backend(platform)
QV_=None
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"backend version is {backend.backend_version}")
elif Type_of_Simulator == "FAKE":
basis_selector = 0
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting.
max_qubits=backend.configuration().n_qubits
print(f"{platform} device is capable of running {backend.configuration().n_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
elif Type_of_Simulator == "FAKEV2":
basis_selector = 0
if "V2" not in backend_name:
backend_name = backend_name+"V2"
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.name +"-" +backend.backend_version
max_qubits=backend.num_qubits
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
else:
print("Enter valid Simulator.....")
# saved circuits and subcircuits for display
A_ = None
Q_ = None
cQ_ = None
QC_ = None
R_ = None
F_ = None
QFTI_ = None
# default function is f(x) = x^2
f_of_X = functools.partial(mc_utils.power_f, power=2)
# default distribution is gaussian distribution
p_distribution = mc_utils.gaussian_dist
############### Circuit Definition
def MonteCarloSampling(target_dist, f, num_state_qubits, num_counting_qubits, epsilon=0.05, degree=2, method=2):
A_qr = QuantumRegister(num_state_qubits+1)
A = QuantumCircuit(A_qr, name=f"A_ckt")
num_qubits = num_state_qubits + 1 + num_counting_qubits
# initialize R and F circuits
R_qr = QuantumRegister(num_state_qubits+1)
F_qr = QuantumRegister(num_state_qubits+1)
R = QuantumCircuit(R_qr, name=f"R")
F = QuantumCircuit(F_qr, name=f"F")
# method 1 takes in the abitrary function f and arbitrary dist
if method == 1:
state_prep(R, R_qr, target_dist, num_state_qubits)
f_on_objective(F, F_qr, f, epsilon=epsilon, degree=degree)
# method 2 chooses to have lower circuit depth by choosing specific f and dist
elif method == 2:
uniform_prep(R, R_qr, num_state_qubits)
square_on_objective(F, F_qr)
# append R and F circuits to A
A.append(R.to_gate(), A_qr)
A.append(F.to_gate(), A_qr)
# run AE subroutine given our A composed of R and F
qc = AE_Subroutine(num_state_qubits, num_counting_qubits, A, method)
# save smaller circuit example for display
global QC_, R_, F_
if QC_ == None or num_qubits <= 5:
if num_qubits < 9: QC_ = qc
if (R_ and F_) == None or num_state_qubits <= 3:
if num_state_qubits < 5: R_ = R; F_ = F
return qc
###############
def f_on_objective(qc, qr, f, epsilon=0.05, degree=2):
"""
Assume last qubit is the objective. Function f is evaluated on first n-1 qubits
"""
num_state_qubits = qc.num_qubits - 1
c_star = (2*epsilon)**(1/(degree+1))
f_ = functools.partial(f, num_state_qubits=num_state_qubits)
zeta_ = functools.partial(mc_utils.zeta_from_f, func=f_, epsilon=epsilon, degree=degree, c=c_star)
x_eval = np.linspace(0.0, 2**(num_state_qubits) - 1, num= degree+1)
poly = Polynomial(polyfit(x_eval, zeta_(x_eval), degree))
b_exp = mc_utils.binary_expansion(num_state_qubits, poly)
for controls in b_exp.keys():
theta = 2*b_exp[controls]
controls = list(controls)
if len(controls)==0:
qc.ry(-theta, qr[num_state_qubits])
else:
# define a MCRY gate:
# this does the same thing as qc.mcry, but is clearer in the circuit printing
MCRY = RYGate(-theta).control(len(controls))
qc.append(MCRY, [*(qr[i] for i in controls), qr[num_state_qubits]])
def square_on_objective(qc, qr):
"""
Assume last qubit is the objective.
Shifted square wave function: if x is even, f(x) = 0; if x i s odd, f(x) = 1
"""
num_state_qubits = qc.num_qubits - 1
for control in range(num_state_qubits):
qc.cx(control, num_state_qubits)
def state_prep(qc, qr, target_dist, num_state_qubits):
"""
Use controlled Ry gates to construct the superposition Sum \sqrt{p_i} |i>
"""
r_probs = mc_utils.region_probs(target_dist, num_state_qubits)
regions = r_probs.keys()
r_norm = {}
for r in regions:
num_controls = len(r) - 1
super_key = r[:num_controls]
if super_key=='':
r_norm[super_key] = 1
elif super_key == '1':
r_norm[super_key] = r_probs[super_key]
r_norm['0'] = 1-r_probs[super_key]
else:
try:
r_norm[super_key] = r_probs[super_key]
except KeyError:
r_norm[super_key] = r_norm[super_key[:num_controls-1]] - r_probs[super_key[:num_controls-1] + '1']
norm = r_norm[super_key]
p = 0
if norm != 0:
p = r_probs[r] / norm
theta = 2*np.arcsin(np.sqrt(p))
if r == '1':
qc.ry(-theta, num_state_qubits-1)
else:
controls = [qr[num_state_qubits-1 - i] for i in range(num_controls)]
# define a MCRY gate:
# this does the same thing as qc.mcry, but is clearer in the circuit printing
MCRY = RYGate(-theta).control(num_controls, ctrl_state=r[:-1])
qc.append(MCRY, [*controls, qr[num_state_qubits-1 - num_controls]])
def uniform_prep(qc, qr, num_state_qubits):
"""
Generates a uniform distribution over all states
"""
for i in range(num_state_qubits):
qc.h(i)
def AE_Subroutine(num_state_qubits, num_counting_qubits, A_circuit, method):
num_qubits = num_state_qubits + num_counting_qubits
qr_state = QuantumRegister(num_state_qubits+1)
qr_counting = QuantumRegister(num_counting_qubits)
cr = ClassicalRegister(num_counting_qubits)
qc = QuantumCircuit(qr_state, qr_counting, cr, name=f"qmc({method})-{num_qubits}-{0}")
A = A_circuit
cQ, Q = Ctrl_Q(num_state_qubits, A)
# save small example subcircuits for visualization
global A_, Q_, cQ_, QFTI_
if (cQ_ and Q_) == None or num_state_qubits <= 6:
if num_state_qubits < 9: cQ_ = cQ; Q_ = Q
if A_ == None or num_state_qubits <= 3:
if num_state_qubits < 5: A_ = A
if QFTI_ == None or num_counting_qubits <= 3:
if num_counting_qubits < 4: QFTI_ = inv_qft_gate(num_counting_qubits)
# Prepare state from A, and counting qubits with H transform
qc.append(A, qr_state)
for i in range(num_counting_qubits):
qc.h(qr_counting[i])
repeat = 1
for j in reversed(range(num_counting_qubits)):
for _ in range(repeat):
qc.append(cQ, [qr_counting[j]] + [qr_state[l] for l in range(num_state_qubits+1)])
repeat *= 2
qc.barrier()
# inverse quantum Fourier transform only on counting qubits
qc.append(inv_qft_gate(num_counting_qubits), qr_counting)
print(inv_qft_gate(num_counting_qubits))
qc.barrier()
qc.measure([qr_counting[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits)))
return qc
###############################
# Construct the grover-like operator and a controlled version of it
def Ctrl_Q(num_state_qubits, A_circ):
# index n is the objective qubit, and indexes 0 through n-1 are state qubits
qc = QuantumCircuit(num_state_qubits+1, name=f"Q")
temp_A = copy.copy(A_circ)
A_gate = temp_A.to_gate()
A_gate_inv = temp_A.inverse().to_gate()
### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ
# -S_chi
qc.x(num_state_qubits)
qc.z(num_state_qubits)
qc.x(num_state_qubits)
# A_circ_inverse
qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)])
# S_0
for i in range(num_state_qubits+1):
qc.x(i)
qc.h(num_state_qubits)
qc.mcx([x for x in range(num_state_qubits)], num_state_qubits)
qc.h(num_state_qubits)
for i in range(num_state_qubits+1):
qc.x(i)
# A_circ
qc.append(A_gate, [i for i in range(num_state_qubits+1)])
# Create a gate out of the Q operator
qc.to_gate(label='Q')
# and also a controlled version of it
Ctrl_Q_ = qc.control(1)
# and return both
return Ctrl_Q_, qc
############### Inverse QFT Circuit
def inv_qft_gate(input_size):
global QFTI_, num_gates, depth
qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="inv_qft")
# Generate multiple groups of diminishing angle CRZs and H gate
for i_qubit in reversed(range(0, input_size)):
# start laying out gates from highest order qubit (the hidx)
hidx = input_size - i_qubit - 1
# precede with an H gate (applied to all qubits)
qc.h(qr[hidx])
num_gates += 1
depth += 1
# if not the highest order qubit, add multiple controlled RZs of decreasing angle
if hidx < input_size - 1:
num_crzs = i_qubit
for j in reversed(range(0, num_crzs)):
divisor = 2 ** (num_crzs - j)
qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1])
num_gates += 1
depth += 1
qc.barrier()
if QFTI_ == None or input_size <= 5:
if input_size < 9: QFTI_= qc
return qc
# Create an empty noise model
noise_parameters = NoiseModel()
if Type_of_Simulator == "built_in":
# Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5%
depol_one_qb_error = 0.05
depol_two_qb_error = 0.005
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx'])
# Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0%
amp_damp_one_qb_error = 0.0
amp_damp_two_qb_error = 0.0
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx'])
# Add reset noise to all single qubit resets
reset_to_zero_error = 0.005
reset_to_one_error = 0.005
noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"])
# Add readout error
p0given1_error = 0.000
p1given0_error = 0.000
error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]])
noise_parameters.add_all_qubit_readout_error(error_meas)
#print(noise_parameters)
elif Type_of_Simulator == "FAKE"or"FAKEV2":
noise_parameters = NoiseModel.from_backend(backend)
#print(noise_parameters)
### Analysis methods to be expanded and eventually compiled into a separate analysis.py file
import math, functools
def hellinger_fidelity_with_expected(p, q):
""" p: result distribution, may be passed as a counts distribution
q: the expected distribution to be compared against
References:
`Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_
Qiskit Hellinger Fidelity Function
"""
p_sum = sum(p.values())
q_sum = sum(q.values())
if q_sum == 0:
print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0")
return 0
p_normed = {}
for key, val in p.items():
p_normed[key] = val/p_sum
# if p_sum != 0:
# p_normed[key] = val/p_sum
# else:
# p_normed[key] = 0
q_normed = {}
for key, val in q.items():
q_normed[key] = val/q_sum
total = 0
for key, val in p_normed.items():
if key in q_normed.keys():
total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2
del q_normed[key]
else:
total += val
total += sum(q_normed.values())
# in some situations (error mitigation) this can go negative, use abs value
if total < 0:
print(f"WARNING: using absolute value in fidelity calculation")
total = abs(total)
dist = np.sqrt(total)/np.sqrt(2)
fidelity = (1-dist**2)**2
return fidelity
def polarization_fidelity(counts, correct_dist, thermal_dist=None):
"""
Combines Hellinger fidelity and polarization rescaling into fidelity calculation
used in every benchmark
counts: the measurement outcomes after `num_shots` algorithm runs
correct_dist: the distribution we expect to get for the algorithm running perfectly
thermal_dist: optional distribution to pass in distribution from a uniform
superposition over all states. If `None`: generated as
`uniform_dist` with the same qubits as in `counts`
returns both polarization fidelity and the hellinger fidelity
Polarization from: `https://arxiv.org/abs/2008.11294v1`
"""
num_measured_qubits = len(list(correct_dist.keys())[0])
#print(num_measured_qubits)
counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()}
# calculate hellinger fidelity between measured expectation values and correct distribution
hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist)
# to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits
if num_measured_qubits > 16:
return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity }
# if not provided, generate thermal dist based on number of qubits
if thermal_dist == None:
thermal_dist = uniform_dist(num_measured_qubits)
# set our fidelity rescaling value as the hellinger fidelity for a depolarized state
floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist)
# rescale fidelity result so uniform superposition (random guessing) returns fidelity
# rescaled to 0 to provide a better measure of success of the algorithm (polarization)
new_floor_fidelity = 0
fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity)
return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity }
## Uniform distribution function commonly used
def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity):
"""
Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks
fidelity: raw fidelity to rescale
floor_fidelity: threshold fidelity which is equivalent to random guessing
new_floor_fidelity: what we rescale the floor_fidelity to
Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0:
1 -> 1;
0.25 -> 0;
0.5 -> 0.3333;
"""
rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1
# ensure fidelity is within bounds (0, 1)
if rescaled_fidelity < 0:
rescaled_fidelity = 0.0
if rescaled_fidelity > 1:
rescaled_fidelity = 1.0
return rescaled_fidelity
def uniform_dist(num_state_qubits):
dist = {}
for i in range(2**num_state_qubits):
key = bin(i)[2:].zfill(num_state_qubits)
dist[key] = 1/(2**num_state_qubits)
return dist
from matplotlib.patches import Rectangle
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize
from matplotlib.patches import Circle
############### Color Map functions
# Create a selection of colormaps from which to choose; default to custom_spectral
cmap_spectral = plt.get_cmap('Spectral')
cmap_greys = plt.get_cmap('Greys')
cmap_blues = plt.get_cmap('Blues')
cmap_custom_spectral = None
# the default colormap is the spectral map
cmap = cmap_spectral
cmap_orig = cmap_spectral
# current cmap normalization function (default None)
cmap_norm = None
default_fade_low_fidelity_level = 0.16
default_fade_rate = 0.7
# Specify a normalization function here (default None)
def set_custom_cmap_norm(vmin, vmax):
global cmap_norm
if vmin == vmax or (vmin == 0.0 and vmax == 1.0):
print("... setting cmap norm to None")
cmap_norm = None
else:
print(f"... setting cmap norm to [{vmin}, {vmax}]")
cmap_norm = Normalize(vmin=vmin, vmax=vmax)
# Remake the custom spectral colormap with user settings
def set_custom_cmap_style(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
#print("... set custom map style")
global cmap, cmap_custom_spectral, cmap_orig
cmap_custom_spectral = create_custom_spectral_cmap(
fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate)
cmap = cmap_custom_spectral
cmap_orig = cmap_custom_spectral
# Create the custom spectral colormap from the base spectral
def create_custom_spectral_cmap(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
# determine the breakpoint from the fade level
num_colors = 100
breakpoint = round(fade_low_fidelity_level * num_colors)
# get color list for spectral map
spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)]
#print(fade_rate)
# create a list of colors to replace those below the breakpoint
# and fill with "faded" color entries (in reverse)
low_colors = [0] * breakpoint
#for i in reversed(range(breakpoint)):
for i in range(breakpoint):
# x is index of low colors, normalized 0 -> 1
x = i / breakpoint
# get color at this index
bc = spectral_colors[i]
r0 = bc[0]
g0 = bc[1]
b0 = bc[2]
z0 = bc[3]
r_delta = 0.92 - r0
#print(f"{x} {bc} {r_delta}")
# compute saturation and greyness ratio
sat_ratio = 1 - x
#grey_ratio = 1 - x
''' attempt at a reflective gradient
if i >= breakpoint/2:
xf = 2*(x - 0.5)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (yf + 0.5)
else:
xf = 2*(0.5 - x)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (0.5 - yf)
'''
grey_ratio = 1 - math.pow(x, 1/fade_rate)
#print(f" {xf} {yf} ")
#print(f" {sat_ratio} {grey_ratio}")
r = r0 + r_delta * sat_ratio
g_delta = r - g0
b_delta = r - b0
g = g0 + g_delta * grey_ratio
b = b0 + b_delta * grey_ratio
#print(f"{r} {g} {b}\n")
low_colors[i] = (r,g,b,z0)
#print(low_colors)
# combine the faded low colors with the regular spectral cmap to make a custom version
cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:])
#spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)]
#for i in range(10): print(spectral_colors[i])
#print("")
return cmap_custom_spectral
# Make the custom spectral color map the default on module init
set_custom_cmap_style()
# Arrange the stored annotations optimally and add to plot
def anno_volumetric_data(ax, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True):
# sort all arrays by the x point of the text (anno_offs)
global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos
all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos))
x_anno_offs = [a for a,b,c,d,e in all_annos]
y_anno_offs = [b for a,b,c,d,e in all_annos]
anno_labels = [c for a,b,c,d,e in all_annos]
x_annos = [d for a,b,c,d,e in all_annos]
y_annos = [e for a,b,c,d,e in all_annos]
#print(f"{x_anno_offs}")
#print(f"{y_anno_offs}")
#print(f"{anno_labels}")
for i in range(len(anno_labels)):
x_anno = x_annos[i]
y_anno = y_annos[i]
x_anno_off = x_anno_offs[i]
y_anno_off = y_anno_offs[i]
label = anno_labels[i]
if i > 0:
x_delta = abs(x_anno_off - x_anno_offs[i - 1])
y_delta = abs(y_anno_off - y_anno_offs[i - 1])
if y_delta < 0.7 and x_delta < 2:
y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6
#x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1
ax.annotate(label,
xy=(x_anno+0.0, y_anno+0.1),
arrowprops=dict(facecolor='black', shrink=0.0,
width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)),
xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]),
rotation=labelrot,
horizontalalignment='left', verticalalignment='baseline',
color=(0.2,0.2,0.2),
clip_on=True)
if saveplots == True:
plt.savefig("VolumetricPlotSample.jpg")
# Plot one group of data for volumetric presentation
def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True,
x_size=1.0, y_size=1.0, zorder=1, offset_flag=False,
max_depth=0, suppress_low_fidelity=False):
# since data may come back out of order, save point at max y for annotation
i_anno = 0
x_anno = 0
y_anno = 0
# plot data rectangles
low_fidelity_count = True
last_y = -1
k = 0
# determine y-axis dimension for one pixel to use for offset of bars that start at 0
(_, dy) = get_pixel_dims(ax)
# do this loop in reverse to handle the case where earlier cells are overlapped by later cells
for i in reversed(range(len(d_data))):
x = depth_index(d_data[i], depth_base)
y = float(w_data[i])
f = f_data[i]
# each time we star a new row, reset the offset counter
# DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars
# that represent time starting from 0 secs. We offset by one pixel each and center the group
if y != last_y:
last_y = y;
k = 3 # hardcoded for 8 cells, offset by 3
#print(f"{i = } {x = } {y = }")
if max_depth > 0 and d_data[i] > max_depth:
#print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}")
break;
# reject cells with low fidelity
if suppress_low_fidelity and f < suppress_low_fidelity_level:
if low_fidelity_count: break
else: low_fidelity_count = True
# the only time this is False is when doing merged gradation plots
if do_border == True:
# this case is for an array of x_sizes, i.e. each box has different width
if isinstance(x_size, list):
# draw each of the cells, with no offset
if not offset_flag:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder))
# use an offset for y value, AND account for x and width to draw starting at 0
else:
ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder))
# this case is for only a single cell
else:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size))
# save the annotation point with the largest y value
if y >= y_anno:
x_anno = x
y_anno = y
i_anno = i
# move the next bar down (if using offset)
k -= 1
# if no data rectangles plotted, no need for a label
if x_anno == 0 or y_anno == 0:
return
x_annos.append(x_anno)
y_annos.append(y_anno)
anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 )
# adjust radius of annotation circle based on maximum width of apps
anno_max = 10
if w_max > 10:
anno_max = 14
if w_max > 14:
anno_max = 18
scale = anno_max / anno_dist
# offset of text from end of arrow
if scale > 1:
x_anno_off = scale * x_anno - x_anno - 0.5
y_anno_off = scale * y_anno - y_anno
else:
x_anno_off = 0.7
y_anno_off = 0.5
x_anno_off += x_anno
y_anno_off += y_anno
# print(f"... {xx} {yy} {anno_dist}")
x_anno_offs.append(x_anno_off)
y_anno_offs.append(y_anno_off)
anno_labels.append(label)
if do_label:
ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot,
horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2))
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# init arrays to hold annotation points for label spreading
def vplot_anno_init ():
global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# Number of ticks on volumetric depth axis
max_depth_log = 22
# average transpile factor between base QV depth and our depth based on results from QV notebook
QV_transpile_factor = 12.7
# format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1
# (sign handling may be incorrect)
def format_number(num, digits=0):
if isinstance(num, str): num = float(num)
num = float('{:.3g}'.format(abs(num)))
sign = ''
metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1}
for index in metric:
num_check = num / metric[index]
if num_check >= 1:
num = round(num_check, digits)
sign = index
break
numstr = f"{str(num)}"
if '.' in numstr:
numstr = numstr.rstrip('0').rstrip('.')
return f"{numstr}{sign}"
# Return the color associated with the spcific value, using color map norm
def get_color(value):
# if there is a normalize function installed, scale the data
if cmap_norm:
value = float(cmap_norm(value))
if cmap == cmap_spectral:
value = 0.05 + value*0.9
elif cmap == cmap_blues:
value = 0.00 + value*1.0
else:
value = 0.0 + value*0.95
return cmap(value)
# Return the x and y equivalent to a single pixel for the given plot axis
def get_pixel_dims(ax):
# transform 0 -> 1 to pixel dimensions
pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0))
xpix = pixdims[1][0]
ypix = pixdims[0][1]
#determine x- and y-axis dimension for one pixel
dx = (1 / xpix)
dy = (1 / ypix)
return (dx, dy)
############### Helper functions
# return the base index for a circuit depth value
# take the log in the depth base, and add 1
def depth_index(d, depth_base):
if depth_base <= 1:
return d
if d == 0:
return 0
return math.log(d, depth_base) + 1
# draw a box at x,y with various attributes
def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1):
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5*y_size,
zorder=zorder)
# draw a circle at x,y with various attributes
def circle_at(x, y, value, type=1, fill=True):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Circle((x, y), size/2,
alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5)
def box4_at(x, y, value, type=1, fill=True, alpha=1.0):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.3,0.3,0.3)
ec = fc
return Rectangle((x - size/8, y - size/2), size/4, size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.1)
# Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value
def qv_box_at(x, y, qv_width, qv_depth, value, depth_base):
#print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}")
return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width,
edgecolor = (value,value,value),
facecolor = (value,value,value),
fill=True,
lw=1)
def bkg_box_at(x, y, value=0.9):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (value,value,value),
fill=True,
lw=0.5)
def bkg_empty_box_at(x, y):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (1.0,1.0,1.0),
fill=True,
lw=0.5)
# Plot the background for the volumetric analysis
def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"):
if suptitle == None:
suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}"
QV0 = QV
qv_estimate = False
est_str = ""
if QV == 0: # QV = 0 indicates "do not draw QV background or label"
QV = 2048
elif QV < 0: # QV < 0 indicates "add est. to label"
QV = -QV
qv_estimate = True
est_str = " (est.)"
if avail_qubits > 0 and max_qubits > avail_qubits:
max_qubits = avail_qubits
max_width = 13
if max_qubits > 11: max_width = 18
if max_qubits > 14: max_width = 20
if max_qubits > 16: max_width = 24
if max_qubits > 24: max_width = 33
#print(f"... {avail_qubits} {max_qubits} {max_width}")
plot_width = 6.8
plot_height = 0.5 + plot_width * (max_width / max_depth_log)
#print(f"... {plot_width} {plot_height}")
# define matplotlib figure and axis; use constrained layout to fit colorbar to right
fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True)
plt.suptitle(suptitle)
plt.xlim(0, max_depth_log)
plt.ylim(0, max_width)
# circuit depth axis (x axis)
xbasis = [x for x in range(1,max_depth_log)]
xround = [depth_base**(x-1) for x in xbasis]
xlabels = [format_number(x) for x in xround]
ax.set_xlabel('Circuit Depth')
ax.set_xticks(xbasis)
plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor")
# other label options
#plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left')
#plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor")
# circuit width axis (y axis)
ybasis = [y for y in range(1,max_width)]
yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now
ylabels = [str(y) for y in yround] # not used now
#ax.set_ylabel('Circuit Width (Number of Qubits)')
ax.set_ylabel('Circuit Width')
ax.set_yticks(ybasis)
#create simple line plot (not used right now)
#ax.plot([0, 10],[0, 10])
log2QV = math.log2(QV)
QV_width = log2QV
QV_depth = log2QV * QV_transpile_factor
# show a quantum volume rectangle of QV = 64 e.g. (6 x 6)
if QV0 != 0:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base))
else:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base))
# the untranspiled version is commented out - we do not show this by default
# also show a quantum volume rectangle un-transpiled
# ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base))
# show 2D array of volumetric cells based on this QV_transpiled
# DEVNOTE: we use +1 only to make the visuals work; s/b without
# Also, the second arg of the min( below seems incorrect, needs correction
maxprod = (QV_width + 1) * (QV_depth + 1)
for w in range(1, min(max_width, round(QV) + 1)):
# don't show VB squares if width greater than known available qubits
if avail_qubits != 0 and w > avail_qubits:
continue
i_success = 0
for d in xround:
# polarization factor for low circuit widths
maxtest = maxprod / ( 1 - 1 / (2**w) )
# if circuit would fail here, don't draw box
if d > maxtest: continue
if w * d > maxtest: continue
# guess for how to capture how hardware decays with width, not entirely correct
# # reduce maxtext by a factor of number of qubits > QV_width
# # just an approximation to account for qubit distances
# if w > QV_width:
# over = w - QV_width
# maxtest = maxtest / (1 + (over/QV_width))
# draw a box at this width and depth
id = depth_index(d, depth_base)
# show vb rectangles; if not showing QV, make all hollow (or less dark)
if QV0 == 0:
#ax.add_patch(bkg_empty_box_at(id, w))
ax.add_patch(bkg_box_at(id, w, 0.95))
else:
ax.add_patch(bkg_box_at(id, w, 0.9))
# save index of last successful depth
i_success += 1
# plot empty rectangle after others
d = xround[i_success]
id = depth_index(d, depth_base)
ax.add_patch(bkg_empty_box_at(id, w))
# Add annotation showing quantum volume
if QV0 != 0:
t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12,
horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2),
bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1))
# add colorbar to right of plot
plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax,
shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7))
return ax
# Function to calculate circuit depth
def calculate_circuit_depth(qc):
# Calculate the depth of the circuit
depth = qc.depth()
return depth
def calculate_transpiled_depth(qc,basis_selector):
# use either the backend or one of the basis gate sets
if basis_selector == 0:
qc = transpile(qc, backend)
else:
basis_gates = basis_gates_array[basis_selector]
qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0)
transpiled_depth = qc.depth()
return transpiled_depth,qc
def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title):
avg_fidelity_means = []
avg_Hf_fidelity_means = []
avg_num_qubits_values = list(fidelity_data.keys())
# Calculate the average fidelity and Hamming fidelity for each unique number of qubits
for num_qubits in avg_num_qubits_values:
avg_fidelity = np.average(fidelity_data[num_qubits])
avg_fidelity_means.append(avg_fidelity)
avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits])
avg_Hf_fidelity_means.append(avg_Hf_fidelity)
return avg_fidelity_means,avg_Hf_fidelity_means
list_of_gates = []
def list_of_standardgates():
import qiskit.circuit.library as lib
from qiskit.circuit import Gate
import inspect
# List all the attributes of the library module
gate_list = dir(lib)
# Filter out non-gate classes (like functions, variables, etc.)
gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)]
# Get method names from QuantumCircuit
circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction)
method_names = [name for name, _ in circuit_methods]
# Map gate class names to method names
gate_to_method = {}
for gate in gates:
gate_class = getattr(lib, gate)
class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name
for method in method_names:
if method == class_name or method == class_name.replace('cr', 'c-r'):
gate_to_method[gate] = method
break
# Add common operations that are not strictly gates
additional_operations = {
'Measure': 'measure',
'Barrier': 'barrier',
}
gate_to_method.update(additional_operations)
for k,v in gate_to_method.items():
list_of_gates.append(v)
def update_counts(gates,custom_gates):
operations = {}
for key, value in gates.items():
operations[key] = value
for key, value in custom_gates.items():
if key in operations:
operations[key] += value
else:
operations[key] = value
return operations
def get_gate_counts(gates,custom_gate_defs):
result = gates.copy()
# Iterate over the gate counts in the quantum circuit
for gate, count in gates.items():
if gate in custom_gate_defs:
custom_gate_ops = custom_gate_defs[gate]
# Multiply custom gate operations by the count of the custom gate in the circuit
for _ in range(count):
result = update_counts(result, custom_gate_ops)
# Remove the custom gate entry as we have expanded it
del result[gate]
return result
dict_of_qc = dict()
custom_gates_defs = dict()
# Function to count operations recursively
def count_operations(qc):
dict_of_qc.clear()
circuit_traverser(qc)
operations = dict()
operations = dict_of_qc[qc.name]
del dict_of_qc[qc.name]
# print("operations :",operations)
# print("dict_of_qc :",dict_of_qc)
for keys in operations.keys():
if keys not in list_of_gates:
for k,v in dict_of_qc.items():
if k in operations.keys():
custom_gates_defs[k] = v
operations=get_gate_counts(operations,custom_gates_defs)
custom_gates_defs.clear()
return operations
def circuit_traverser(qc):
dict_of_qc[qc.name]=dict(qc.count_ops())
for i in qc.data:
if str(i.operation.name) not in list_of_gates:
qc_1 = i.operation.definition
circuit_traverser(qc_1)
def get_memory():
import resource
usage = resource.getrusage(resource.RUSAGE_SELF)
max_mem = usage.ru_maxrss/1024 #in MB
return max_mem
def analyzer(num_counting_qubits,num_state_qubits,mu,f_of_X):
# generate exact value for the expectation value given our function and dist
target_dist = p_distribution(num_state_qubits, mu)
f = functools.partial(f_of_X, num_state_qubits=num_state_qubits)
if method == 1:
exact = mc_utils.estimated_value(target_dist, f)
elif method == 2:
exact = 0.5 # hard coded exact value from uniform dist and square function
# calculate the expected output histogram
correct_dist = a_to_bitstring(exact, num_counting_qubits)
# generate thermal_dist with amplitudes instead, to be comparable to correct_dist
thermal_dist = uniform_dist(num_counting_qubits)
# # convert counts, expectation, and thermal_dist to app form for visibility
# # app form of correct distribution is measuring the input a 100% of the time
# # convert bit_counts into expectation values counts according to Quantum Risk Analysis paper
# app_counts = expectation_from_bits(counts, num_counting_qubits, num_shots, method)
# app_correct_dist = mc_utils.mc_dist(num_counting_qubits, exact, c_star, method)
# app_thermal_dist = expectation_from_bits(thermal_dist, num_counting_qubits, num_shots, method)
return correct_dist,thermal_dist
def a_to_bitstring(a, num_counting_qubits):
m = num_counting_qubits
# solution 1
num1 = round(np.arcsin(np.sqrt(a)) / np.pi * 2**m)
num2 = round( (np.pi - np.arcsin(np.sqrt(a))) / np.pi * 2**m)
if num1 != num2 and num2 < 2**m and num1 < 2**m:
counts = {format(num1, "0"+str(m)+"b"): 0.5, format(num2, "0"+str(m)+"b"): 0.5}
else:
counts = {format(num1, "0"+str(m)+"b"): 1}
return counts
def expectation_from_bits(bits, num_qubits, num_shots, method):
amplitudes = {}
for b in bits.keys():
precision = int(num_qubits / (np.log2(10))) + 2
r = bits[b]
a_meas = pow(np.sin(np.pi*int(b,2)/pow(2,num_qubits)),2)
if method == 1:
a = ((a_meas - 0.5)/c_star) + 0.5
if method == 2:
a = a_meas
a = round(a, precision)
if a not in amplitudes.keys():
amplitudes[a] = 0
amplitudes[a] += r
return amplitudes
if method == 1:
MIN_STATE_QUBITS = 2
elif method == 2:
MIN_STATE_QUBITS = 1
def run (min_qubits=min_qubits, max_qubits=5, skip_qubits=skip_qubits,
max_circuits=max_circuits, num_shots=num_shots, epsilon=epsilon, degree=degree,
num_state_qubits = MIN_STATE_QUBITS, method=2 #(default)
):
creation_times = []
elapsed_times = []
quantum_times = []
circuit_depths = []
transpiled_depths = []
fidelity_data = {}
Hf_fidelity_data = {}
numckts = []
mem_usage = []
algorithmic_1Q_gate_counts = []
algorithmic_2Q_gate_counts = []
transpiled_1Q_gate_counts = []
transpiled_2Q_gate_counts = []
print(f"{benchmark_name} Benchmark Program - {platform}")
#defining all the standard gates supported by qiskit in a list
if gate_counts_plots == True:
list_of_standardgates()
skip_qubits = max(1, skip_qubits)
print(f"min, max qubits = {min_qubits} {max_qubits}")
global c_star
c_star = (2*epsilon)**(1/(degree+1))
global max_ckts
max_ckts = max_circuits
global min_qbits,max_qbits,skp_qubits
min_qbits = min_qubits
max_qbits = max_qubits
skp_qubits = skip_qubits
print(f"min, max qubits = {min_qubits} {max_qubits}")
# Execute Benchmark Program N times for multiple circuit sizes
for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits):
fidelity_data[num_qubits] = []
Hf_fidelity_data[num_qubits] = []
# reset random seed
np.random.seed(0)
input_size = num_qubits - 1 # TODO: keep using inputsize? only used in num_circuits
# as circuit width grows, the number of counting qubits is increased
num_counting_qubits = num_qubits - num_state_qubits - 1
# determine number of circuits to execute for this group
num_circuits = min(2 ** (input_size), max_circuits)
print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}")
numckts.append(num_circuits)
# determine range of circuits to loop over for method 1
if 2**(input_size) <= max_circuits:
mu_range = [i/2**(input_size) for i in range(num_circuits)]
else:
mu_range = [i/2**(input_size) for i in np.random.choice(2**(input_size), num_circuits, False)]
for mu in mu_range:
print("*********************************************")
print(f"qc of {num_qubits} qubits for mu value {mu}")
target_dist = p_distribution(num_state_qubits, mu)
f_to_estimate = functools.partial(f_of_X, num_state_qubits=num_state_qubits)
#creation of Quantum Circuit.
ts = time.time()
qc = MonteCarloSampling(target_dist, f_to_estimate,
num_state_qubits, num_counting_qubits, epsilon, degree, method=method)
print(qc)
#creation time
creation_time = time.time() - ts
creation_times.append(creation_time)
print(f"creation time = {creation_time*1000} ms")
# Calculate gate count for the algorithmic circuit (excluding barriers and measurements)
if gate_counts_plots == True:
operations = count_operations(qc)
n1q = 0; n2q = 0
if operations != None:
for key, value in operations.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c") or key.startswith("mc"):
n2q += value
else:
n1q += value
algorithmic_1Q_gate_counts.append(n1q)
algorithmic_2Q_gate_counts.append(n2q)
# collapse the sub-circuit levels used in this benchmark (for qiskit)
qc=qc.decompose().decompose().decompose().decompose()
#print(qc)
# Calculate circuit depth
depth = calculate_circuit_depth(qc)
circuit_depths.append(depth)
# Calculate transpiled circuit depth
transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector)
transpiled_depths.append(transpiled_depth)
#print(qc)
print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}")
if gate_counts_plots == True:
# Calculate gate count for the transpiled circuit (excluding barriers and measurements)
tr_ops = qc.count_ops()
#print("tr_ops = ",tr_ops)
tr_n1q = 0; tr_n2q = 0
if tr_ops != None:
for key, value in tr_ops.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c"): tr_n2q += value
else: tr_n1q += value
transpiled_1Q_gate_counts.append(tr_n1q)
transpiled_2Q_gate_counts.append(tr_n2q)
print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}")
print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}")
#execution
if Type_of_Simulator == "built_in":
#To check if Noise is required
if Noise_Inclusion == True:
noise_model = noise_parameters
else:
noise_model = None
ts = time.time()
job = execute(qc, backend, shots=num_shots, noise_model=noise_model)
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" :
ts = time.time()
job = backend.run(qc,shots=num_shots, noise_model=noise_parameters)
#retrieving the result
result = job.result()
#print(result)
#calculating elapsed time
elapsed_time = time.time() - ts
elapsed_times.append(elapsed_time)
# Calculate quantum processing time
quantum_time = result.time_taken
quantum_times.append(quantum_time)
print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms")
#counts in result object
counts = result.get_counts()
#Correct distribution to compare with counts
correct_dist,thermal_dist = analyzer(num_counting_qubits,num_state_qubits,mu,f_of_X)
#fidelity calculation comparision of counts and correct_dist
fidelity_dict = polarization_fidelity(counts, correct_dist, thermal_dist)
###########################################################################
# NOTE: in this benchmark, we are testing how well the amplitude estimation routine
# works according to theory, and we do not measure the difference between
# the reported answer and the correct answer; the below code just helps
# demonstrate that we do approximate the expectation value accurately.
# the max in the counts is what the algorithm would report as the correct answer
a, _ = mc_utils.value_and_max_prob_from_dist(counts)
fidelity_data[num_qubits].append(fidelity_dict['fidelity'])
Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity'])
#maximum memory utilization (if required)
if Memory_utilization_plot == True:
max_mem = get_memory()
print(f"Maximum Memory Utilized: {max_mem} MB")
mem_usage.append(max_mem)
print("*********************************************")
# print a sample circuit
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
print("\nControlled Quantum Operator 'cQ' ="); print(cQ_ if cQ_ != None else " ... too large!")
print("\nQuantum Operator 'Q' ="); print(Q_ if Q_ != None else " ... too large!")
print("\nAmplitude Generator 'A' ="); print(A_ if A_ != None else " ... too large!")
print("\nDistribution Generator 'R' ="); print(R_ if R_ != None else " ... too large!")
print("\nFunction Generator 'F' ="); print(F_ if F_ != None else " ... too large!")
print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!")
return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths,
fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts,
transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage)
# Execute the benchmark program, accumulate metrics, and calculate circuit depths
(creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts,
algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run()
# Define the range of qubits for the x-axis
num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits)
print("num_qubits_range =",num_qubits_range)
# Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits
avg_creation_times = []
avg_elapsed_times = []
avg_quantum_times = []
avg_circuit_depths = []
avg_transpiled_depths = []
avg_1Q_algorithmic_gate_counts = []
avg_2Q_algorithmic_gate_counts = []
avg_1Q_Transpiled_gate_counts = []
avg_2Q_Transpiled_gate_counts = []
max_memory = []
start = 0
for num in numckts:
avg_creation_times.append(np.mean(creation_times[start:start+num]))
avg_elapsed_times.append(np.mean(elapsed_times[start:start+num]))
avg_quantum_times.append(np.mean(quantum_times[start:start+num]))
avg_circuit_depths.append(np.mean(circuit_depths[start:start+num]))
avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num]))
if gate_counts_plots == True:
avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num])))
avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num])))
avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num])))
avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num])))
if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num]))
start += num
# Calculate the fidelity data
avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison")
# Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits
# Add labels to the bars
def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"):
for rect in rects:
height = rect.get_height()
ax.annotate(str.format(height), # Formatting to two decimal places
xy=(rect.get_x() + rect.get_width() / 2, height / 2),
xytext=(0, 0),
textcoords="offset points",
ha='center', va=va,color=text_color,rotation=90)
bar_width = 0.3
# Determine the number of subplots and their arrangement
if Memory_utilization_plot and gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30))
# Plotting for both memory utilization and gate counts
# ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available
elif Memory_utilization_plot:
fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30))
# Plotting for memory utilization only
# ax1, ax2, ax3, ax6, ax7 are available
elif gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30))
# Plotting for gate counts only
# ax1, ax2, ax3, ax4, ax5, ax6 are available
else:
fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30))
# Default plotting
# ax1, ax2, ax3, ax6 are available
fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16)
for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000
avg_creation_times[i] *= 1000
ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue')
autolabel(ax1.patches, ax1)
ax1.set_xlabel('Number of Qubits')
ax1.set_ylabel('Average Creation Time (ms)')
ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14)
ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000
avg_elapsed_times[i] *= 1000
for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000
avg_quantum_times[i] *= 1000
Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time')
Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time')
autolabel(Elapsed,ax2,str='{:.1f}')
autolabel(Quantum,ax2,str='{:.1f}')
ax2.set_xlabel('Number of Qubits')
ax2.set_ylabel('Average Time (ms)')
ax2.set_title('Average Time vs Number of Qubits')
ax2.legend()
ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here
Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here
autolabel(Normalized,ax3,str='{:.2f}')
autolabel(Algorithmic,ax3,str='{:.2f}')
ax3.set_xlabel('Number of Qubits')
ax3.set_ylabel('Average Circuit Depth')
ax3.set_title('Average Circuit Depth vs Number of Qubits')
ax3.legend()
if gate_counts_plots == True:
ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_1Q_counts,ax4,str='{}')
autolabel(Algorithmic_1Q_counts,ax4,str='{}')
ax4.set_xlabel('Number of Qubits')
ax4.set_ylabel('Average 1-Qubit Gate Counts')
ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits')
ax4.legend()
ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_2Q_counts,ax5,str='{}')
autolabel(Algorithmic_2Q_counts,ax5,str='{}')
ax5.set_xlabel('Number of Qubits')
ax5.set_ylabel('Average 2-Qubit Gate Counts')
ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits')
ax5.legend()
ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here
Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here
autolabel(Hellinger,ax6,str='{:.2f}')
autolabel(Normalized,ax6,str='{:.2f}')
ax6.set_xlabel('Number of Qubits')
ax6.set_ylabel('Average Value')
ax6.set_title("Fidelity Comparison")
ax6.legend()
if Memory_utilization_plot == True:
ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations")
autolabel(ax7.patches, ax7)
ax7.set_xlabel('Number of Qubits')
ax7.set_ylabel('Maximum Memory Utilized (MB)')
ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14)
plt.tight_layout(rect=[0, 0, 1, 0.96])
if saveplots == True:
plt.savefig("ParameterPlotsSample.jpg")
plt.show()
# Quantum Volume Plot
Suptitle = f"Volumetric Positioning - {platform}"
appname=benchmark_name
if QV_ == None:
QV=2048
else:
QV=QV_
depth_base =2
ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity")
w_data = num_qubits_range
# determine width for circuit
w_max = 0
for i in range(len(w_data)):
y = float(w_data[i])
w_max = max(w_max, y)
d_tr_data = avg_transpiled_depths
f_data = avg_f
plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max)
anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# randomly create a 2-dimensional quantum state
from random import randrange
def random_quantum_state():
first_entry = randrange(101)
first_entry = first_entry/100
first_entry = first_entry**0.5
if randrange(2) == 0:
first_entry = -1 * first_entry
second_entry = 1 - (first_entry**2)
second_entry = second_entry**0.5
if randrange(2) == 0:
second_entry = -1 * second_entry
return [first_entry,second_entry]
%run qlatvia.py
draw_qubit()
from math import acos, pi
# randomly picking 6 quantum states
for i in range(6):
[x,y]=random_quantum_state() # picking a quantum state
angle_radian = acos(x) # radian of the angle with state |0>
angle_degree = 360*angle_radian/(2*pi) # degree of the angle with state |0>
state_name='|v'+str(i)+'>' # giving a name to the quantum state
draw_quantum_state(x,y,state_name) # drawing the quantum state
print(state_name,'has degree of',angle_degree,"with state |0>") # print the degree of angle with state |0>
# randomly create a 2-dimensional quantum state
from random import randrange
def random_quantum_state():
first_entry = randrange(101)
first_entry = first_entry/100
first_entry = first_entry**0.5
if randrange(2) == 0:
first_entry = -1 * first_entry
second_entry = 1 - (first_entry**2)
second_entry = second_entry**0.5
if randrange(2) == 0:
second_entry = -1 * second_entry
return [first_entry,second_entry]
# finding the angle of a 2-dimensional quantum state
from math import acos, pi
def angle_quantum_state(x,y):
angle_radian = acos(x) # radian of the angle with state |0>
angle_degree = 360*angle_radian/(2*pi) # degree of the angle with state |0>
# if the second amplitude is negative,
# then angle is (-angle_degree)
# or equivalently 360 + (-angle_degree)
if y<0: angle_degree = 360-angle_degree # degree of the angle
# else degree of the angle is the same as degree of the angle with state |0>
return angle_degree
%run qlatvia.py
draw_qubit()
from math import acos, pi
# randomly picking 6 quantum states
for i in range(4):
[x,y]=random_quantum_state() # picking a quantum state
angle_degree = angle_quantum_state(x,y)
state_name='|v'+str(i)+'>' # giving a name to the quantum state
draw_quantum_state(x,y,state_name) # drawing the quantum state
print(state_name,'has degree of',angle_degree) # print the degree of angle
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# required imports:
from qiskit.visualization import array_to_latex
from qiskit.quantum_info import Statevector, random_statevector
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit import QuantumCircuit
from qiskit.circuit.library import HGate, CXGate
import numpy as np
ket0 = [[1],[0]]
array_to_latex(ket0)
bra0 = [1,0]
array_to_latex(bra0)
ket1 = [[0], [1]]
bra1 = [0, 1]
from qc_grader.challenges.qgss_2023 import grade_lab1_ex1
grade_lab1_ex1([ket1, bra1])
sv_bra0 = Statevector(bra0)
sv_bra0
sv_bra0.draw('latex')
sv_eq = Statevector([1/2, 3/4, 4/5, 6/8])
sv_eq.draw('latex')
sv_eq.is_valid()
sv_valid = Statevector([1/2, 1/2, 1/2, 1/2])
from qc_grader.challenges.qgss_2023 import grade_lab1_ex2
grade_lab1_ex2(sv_valid)
op_bra0 = Operator(bra0)
op_bra0
op_ket0 = Operator(ket0)
op_bra0.tensor(op_ket0)
braket = np.dot(op_bra0,op_ket0)
array_to_latex(braket)
ketbra = np.outer(ket0,bra0)
array_to_latex(ketbra)
braket = np.dot(op_bra0,op_ket0)
array_to_latex(braket)
bra1ket0 = [0]
bra0ket1 = [0]
bra1ket1 = [1]
ket1bra0 = [[0, 0], [1, 0]]
ket0bra1 = [[0, 1], [0, 0]]
ket1bra1 = [[0, 0], [0, 1]]
from qc_grader.challenges.qgss_2023 import grade_lab1_ex3
grade_lab1_ex3([bra1ket0, bra0ket1, bra1ket1, ket1bra0, ket0bra1, ket1bra1])
answer = ['a']
from qc_grader.challenges.qgss_2023 import grade_lab1_ex4
grade_lab1_ex4(answer)
m1 = Operator([[1,1],[0,0]])
array_to_latex(m1)
m3 = Operator([[0,1],[1,0]])
array_to_latex(m3)
array_to_latex(m1@ket0)
m2 = Operator([[1, 0], [0, 1]])
m4 = Operator([[0, 0], [1, 1]])
from qc_grader.challenges.qgss_2023 import grade_lab1_ex5
grade_lab1_ex5([m2, m4])
cnot = CXGate()
array_to_latex(cnot)
m3.is_unitary()
random = Operator(np.array([[ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, 0.44607116+0.50778085j,
-0.14128434-0.1523741j ],
[ 0.16855994+0.12151822j, 0.55868196+0.38038841j, -0.12151822+0.16855994j,
-0.38038841+0.55868196j],
[ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, -0.44607116-0.50778085j,
0.14128434+0.1523741j ],
[ 0.16855994+0.12151822j, 0.55868196+0.38038841j, 0.12151822-0.16855994j,
0.38038841-0.55868196j]]))
random.is_unitary()
non_unitary_op = Operator(np.array([0,1,2,3]))
from qc_grader.challenges.qgss_2023 import grade_lab1_ex6
grade_lab1_ex6(non_unitary_op)
pauli_x = Pauli('X')
array_to_latex(pauli_x)
pauli_y = Pauli('Y')
array_to_latex(pauli_y)
pauli_z = Pauli('Z')
array_to_latex(pauli_z)
op_x = Operator(pauli_x)
op_x
op_new = np.dot(op_x,ket0)
array_to_latex(op_new)
result = [[0.+0.j], [-1.+0.j]]
from qc_grader.challenges.qgss_2023 import grade_lab1_ex7
grade_lab1_ex7(result)
hadamard = HGate()
array_to_latex(hadamard)
hop = Operator(hadamard)
hop.is_unitary()
bell = QuantumCircuit(2)
bell.h(0) # apply an H gate to the circuit
bell.cx(0,1) # apply a CNOT gate to the circuit
bell.draw(output="mpl")
bell_op = Operator(bell)
array_to_latex(bell_op)
ghz = QuantumCircuit(3)
##############################
# add gates to your circuit here
ghz.h(0)
ghz.cx(0, 1)
ghz.cx(1, 2)
##############################
ghz.draw(output='mpl')
from qc_grader.challenges.qgss_2023 import grade_lab1_ex8
grade_lab1_ex8(ghz)
plus_state = Statevector.from_label("+")
plus_state.draw('latex')
plus_state
plus_state.probabilities_dict()
# run this cell multiple times to show collapsing into one state or the other
res = plus_state.measure()
res
qc = QuantumCircuit(1,1)
qc.h(0)
qc.measure(0, 0)
qc.draw(output="mpl")
sv_bell = Statevector([np.sqrt(1/2), 0, 0, np.sqrt(1/2)])
sv_bell.draw('latex')
sv_bell.probabilities_dict()
sv_psi_plus = Statevector([0, np.sqrt(1/2), np.sqrt(1/2), 0])
prob_psi_plus = {'01': 0.5000000000000001, '10': 0.5000000000000001}
sv_psi_minus = Statevector([0, np.sqrt(1/2), -np.sqrt(1/2), 0])
prob_psi_minus = {'01': 0.5000000000000001, '10': 0.5000000000000001}
sv_phi_minus = Statevector([np.sqrt(1/2), 0, 0, -np.sqrt(1/2)])
prob_phi_minus = {'00': 0.5000000000000001, '11': 0.5000000000000001}
from qc_grader.challenges.qgss_2023 import grade_lab1_ex9
grade_lab1_ex9([prob_psi_plus, prob_psi_minus, prob_phi_minus])
qft = QuantumCircuit(2)
##############################
# add gates to your circuit here
qft.h(1)
qft.cp(np.pi/2, 0, 1)
qft.h(0)
qft.swap(0, 1)
##############################
qft.draw(output='mpl')
from qc_grader.challenges.qgss_2023 import grade_lab1_ex10
grade_lab1_ex10(qft)
U = Operator(qft)
array_to_latex(U)
|
https://github.com/AmirhoseynpowAsghari/Qiskit-Tutorials
|
AmirhoseynpowAsghari
|
import random
import matplotlib.pyplot as plt
def generate_n_bit_inputs(n):
"""Generate all possible n-bit inputs."""
return [bin(i)[2:].zfill(n) for i in range(2**n)]
def constant_function(value):
"""Returns a constant function that always returns the given value."""
return lambda x: value
def balanced_function(n):
"""Returns a balanced function for n-bit inputs."""
inputs = generate_n_bit_inputs(n)
half = len(inputs) // 2
random.shuffle(inputs)
lookup = {x: 0 if i < half else 1 for i, x in enumerate(inputs)}
return lambda x: lookup[x]
def determine_function_type(f, n):
"""Determine if the function f is constant or balanced."""
inputs = generate_n_bit_inputs(n)
outputs = [f(x) for x in inputs]
unique_outputs = set(outputs)
if len(unique_outputs) == 1:
return "Constant"
elif outputs.count(0) == outputs.count(1):
return "Balanced"
else:
return "Unknown"
def plot_function(f, n, title):
"""Plot the function outputs for all n-bit inputs."""
inputs = generate_n_bit_inputs(n)
outputs = [f(x) for x in inputs]
# Convert binary inputs to integers for plotting
x = [int(i, 2) for i in inputs]
y = outputs
plt.figure(figsize=(10, 5))
plt.scatter(x, y, c='blue')
plt.title(title)
plt.xlabel('Input (as integer)')
plt.ylabel('Output')
plt.xticks(range(2**n))
plt.yticks([0, 1])
plt.grid(True)
plt.show()
# Define n
n = 3
# Create a constant function that always returns 1
const_func = constant_function(1)
print("Constant Function Test:")
print(f"The function is: {determine_function_type(const_func, n)}")
plot_function(const_func, n, "Constant Function (Always 1)")
# Create a balanced function for n-bit inputs
bal_func = balanced_function(n)
print("\nBalanced Function Test:")
print(f"The function is: {determine_function_type(bal_func, n)}")
plot_function(bal_func, n, "Balanced Function")
# useful additional packages
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# importing Qiskit
from qiskit import BasicAer, IBMQ
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.monitor import job_monitor
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
n = 13 # the length of the first register for querying the oracle
# Choose a type of oracle at random. With probability half it is constant,
# and with the same probability it is balanced
oracleType, oracleValue = np.random.randint(2), np.random.randint(2)
if oracleType == 0:
print("The oracle returns a constant value ", oracleValue)
else:
print("The oracle returns a balanced function")
a = np.random.randint(1,2**n) # this is a hidden parameter for balanced oracle.
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(n+1) #all qubits are initialized to zero
# for recording the measurement on the first register
cr = ClassicalRegister(n)
circuitName = "DeutschJozsa"
djCircuit = QuantumCircuit(qr, cr)
# Create the superposition of all input queries in the first register by applying the Hadamard gate to each qubit.
for i in range(n):
djCircuit.h(qr[i])
# Flip the second register and apply the Hadamard gate.
djCircuit.x(qr[n])
djCircuit.h(qr[n])
# Apply barrier to mark the beginning of the oracle
djCircuit.barrier()
if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue for all input.
if oracleValue == 1:
djCircuit.x(qr[n])
else:
djCircuit.id(qr[n])
else: # Otherwise, it returns the inner product of the input with a (non-zero bitstring)
for i in range(n):
if (a & (1 << i)):
djCircuit.cx(qr[i], qr[n])
# Apply barrier to mark the end of the oracle
djCircuit.barrier()
# Apply Hadamard gates after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
# Measurement
djCircuit.barrier()
for i in range(n):
djCircuit.measure(qr[i], cr[i])
#draw the circuit
djCircuit.draw(output='mpl',scale=0.5)
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
job = execute(djCircuit, backend=backend, shots=shots)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog.draw()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Test cases for the pulse schedule block."""
import re
import unittest
from typing import List, Any
from qiskit import pulse, circuit
from qiskit.pulse import transforms
from qiskit.pulse.exceptions import PulseError
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeOpenPulse2Q, FakeArmonk
from qiskit.utils import has_aer
class BaseTestBlock(QiskitTestCase):
"""ScheduleBlock tests."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.test_waveform0 = pulse.Constant(100, 0.1)
self.test_waveform1 = pulse.Constant(200, 0.1)
self.d0 = pulse.DriveChannel(0)
self.d1 = pulse.DriveChannel(1)
self.left_context = transforms.AlignLeft()
self.right_context = transforms.AlignRight()
self.sequential_context = transforms.AlignSequential()
self.equispaced_context = transforms.AlignEquispaced(duration=1000)
def _align_func(j):
return {1: 0.1, 2: 0.25, 3: 0.7, 4: 0.85}.get(j)
self.func_context = transforms.AlignFunc(duration=1000, func=_align_func)
def assertScheduleEqual(self, target, reference):
"""Check if two block are equal schedule representation."""
self.assertEqual(transforms.target_qobj_transform(target), reference)
class TestTransformation(BaseTestBlock):
"""Test conversion of ScheduleBlock to Schedule."""
def test_left_alignment(self):
"""Test left alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.left_context)
block = block.append(pulse.Play(self.test_waveform0, self.d0))
block = block.append(pulse.Play(self.test_waveform1, self.d1))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
self.assertScheduleEqual(block, ref_sched)
def test_right_alignment(self):
"""Test right alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.right_context)
block = block.append(pulse.Play(self.test_waveform0, self.d0))
block = block.append(pulse.Play(self.test_waveform1, self.d1))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
self.assertScheduleEqual(block, ref_sched)
def test_sequential_alignment(self):
"""Test sequential alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block = block.append(pulse.Play(self.test_waveform0, self.d0))
block = block.append(pulse.Play(self.test_waveform1, self.d1))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d1))
self.assertScheduleEqual(block, ref_sched)
def test_equispace_alignment(self):
"""Test equispace alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
for _ in range(4):
block = block.append(pulse.Play(self.test_waveform0, self.d0))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(300, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(600, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(900, pulse.Play(self.test_waveform0, self.d0))
self.assertScheduleEqual(block, ref_sched)
def test_func_alignment(self):
"""Test func alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.func_context)
for _ in range(4):
block = block.append(pulse.Play(self.test_waveform0, self.d0))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(50, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(200, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(650, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(800, pulse.Play(self.test_waveform0, self.d0))
self.assertScheduleEqual(block, ref_sched)
def test_nested_alignment(self):
"""Test nested block scheduling."""
block_sub = pulse.ScheduleBlock(alignment_context=self.right_context)
block_sub = block_sub.append(pulse.Play(self.test_waveform0, self.d0))
block_sub = block_sub.append(pulse.Play(self.test_waveform1, self.d1))
block_main = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block_main = block_main.append(block_sub)
block_main = block_main.append(pulse.Delay(10, self.d0))
block_main = block_main.append(block_sub)
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(200, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(210, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(310, pulse.Play(self.test_waveform0, self.d0))
self.assertScheduleEqual(block_main, ref_sched)
class TestBlockOperation(BaseTestBlock):
"""Test fundamental operation on schedule block.
Because ScheduleBlock adapts to the lazy scheduling, no uniitest for
overlap constraints is necessary. Test scheme becomes simpler than the schedule.
Some tests have dependency on schedule conversion.
This operation should be tested in `test.python.pulse.test_block.TestTransformation`.
"""
def setUp(self):
super().setUp()
self.test_blocks = [
pulse.Play(self.test_waveform0, self.d0),
pulse.Play(self.test_waveform1, self.d1),
pulse.Delay(50, self.d0),
pulse.Play(self.test_waveform1, self.d0),
]
def test_append_an_instruction_to_empty_block(self):
"""Test append instructions to an empty block."""
block = pulse.ScheduleBlock()
block = block.append(pulse.Play(self.test_waveform0, self.d0))
self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0))
def test_append_an_instruction_to_empty_block_sugar(self):
"""Test append instructions to an empty block with syntax sugar."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_waveform0, self.d0)
self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0))
def test_append_an_instruction_to_empty_block_inplace(self):
"""Test append instructions to an empty block with inplace."""
block = pulse.ScheduleBlock()
block.append(pulse.Play(self.test_waveform0, self.d0), inplace=True)
self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0))
def test_append_a_block_to_empty_block(self):
"""Test append another ScheduleBlock to empty block."""
block = pulse.ScheduleBlock()
block.append(pulse.Play(self.test_waveform0, self.d0), inplace=True)
block_main = pulse.ScheduleBlock()
block_main = block_main.append(block)
self.assertEqual(block_main.blocks[0], block)
def test_append_an_instruction_to_block(self):
"""Test append instructions to a non-empty block."""
block = pulse.ScheduleBlock()
block = block.append(pulse.Delay(100, self.d0))
block = block.append(pulse.Delay(100, self.d0))
self.assertEqual(len(block.blocks), 2)
def test_append_an_instruction_to_block_inplace(self):
"""Test append instructions to a non-empty block with inplace."""
block = pulse.ScheduleBlock()
block = block.append(pulse.Delay(100, self.d0))
block.append(pulse.Delay(100, self.d0), inplace=True)
self.assertEqual(len(block.blocks), 2)
def test_duration(self):
"""Test if correct duration is returned with implicit scheduling."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(block.duration, 350)
def test_channels(self):
"""Test if all channels are returned."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(len(block.channels), 2)
def test_instructions(self):
"""Test if all instructions are returned."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(block.blocks, tuple(self.test_blocks))
def test_channel_duraction(self):
"""Test if correct durations is calculated for each channel."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(block.ch_duration(self.d0), 350)
self.assertEqual(block.ch_duration(self.d1), 200)
def test_cannot_append_schedule(self):
"""Test schedule cannot be appended. Schedule should be input as Call instruction."""
block = pulse.ScheduleBlock()
sched = pulse.Schedule()
sched += pulse.Delay(10, self.d0)
with self.assertRaises(PulseError):
block.append(sched)
def test_replace(self):
"""Test replacing specific instruction."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
replaced = pulse.Play(pulse.Constant(300, 0.1), self.d1)
target = pulse.Delay(50, self.d0)
block_replaced = block.replace(target, replaced, inplace=False)
# original schedule is not destroyed
self.assertListEqual(list(block.blocks), self.test_blocks)
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(200, replaced)
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d0))
self.assertScheduleEqual(block_replaced, ref_sched)
def test_replace_inplace(self):
"""Test replacing specific instruction with inplace."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
replaced = pulse.Play(pulse.Constant(300, 0.1), self.d1)
target = pulse.Delay(50, self.d0)
block.replace(target, replaced, inplace=True)
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(200, replaced)
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d0))
self.assertScheduleEqual(block, ref_sched)
def test_replace_block_by_instruction(self):
"""Test replacing block with instruction."""
sub_block1 = pulse.ScheduleBlock()
sub_block1 = sub_block1.append(pulse.Delay(50, self.d0))
sub_block1 = sub_block1.append(pulse.Play(self.test_waveform0, self.d0))
sub_block2 = pulse.ScheduleBlock()
sub_block2 = sub_block2.append(pulse.Delay(50, self.d0))
sub_block2 = sub_block2.append(pulse.Play(self.test_waveform1, self.d1))
main_block = pulse.ScheduleBlock()
main_block = main_block.append(pulse.Delay(50, self.d0))
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d0))
main_block = main_block.append(sub_block1)
main_block = main_block.append(sub_block2)
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d1))
replaced = main_block.replace(sub_block1, pulse.Delay(100, self.d0))
ref_blocks = [
pulse.Delay(50, self.d0),
pulse.Play(self.test_waveform0, self.d0),
pulse.Delay(100, self.d0),
sub_block2,
pulse.Play(self.test_waveform0, self.d1),
]
self.assertListEqual(list(replaced.blocks), ref_blocks)
def test_replace_instruction_by_block(self):
"""Test replacing instruction with block."""
sub_block1 = pulse.ScheduleBlock()
sub_block1 = sub_block1.append(pulse.Delay(50, self.d0))
sub_block1 = sub_block1.append(pulse.Play(self.test_waveform0, self.d0))
sub_block2 = pulse.ScheduleBlock()
sub_block2 = sub_block2.append(pulse.Delay(50, self.d0))
sub_block2 = sub_block2.append(pulse.Play(self.test_waveform1, self.d1))
main_block = pulse.ScheduleBlock()
main_block = main_block.append(pulse.Delay(50, self.d0))
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d0))
main_block = main_block.append(pulse.Delay(100, self.d0))
main_block = main_block.append(sub_block2)
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d1))
replaced = main_block.replace(pulse.Delay(100, self.d0), sub_block1)
ref_blocks = [
pulse.Delay(50, self.d0),
pulse.Play(self.test_waveform0, self.d0),
sub_block1,
sub_block2,
pulse.Play(self.test_waveform0, self.d1),
]
self.assertListEqual(list(replaced.blocks), ref_blocks)
def test_len(self):
"""Test __len__ method"""
block = pulse.ScheduleBlock()
self.assertEqual(len(block), 0)
for j in range(1, 10):
block = block.append(pulse.Delay(10, self.d0))
self.assertEqual(len(block), j)
def test_inherit_from(self):
"""Test creating schedule with another schedule."""
ref_metadata = {"test": "value"}
ref_name = "test"
base_sched = pulse.ScheduleBlock(name=ref_name, metadata=ref_metadata)
new_sched = pulse.ScheduleBlock.initialize_from(base_sched)
self.assertEqual(new_sched.name, ref_name)
self.assertDictEqual(new_sched.metadata, ref_metadata)
@unittest.skipUnless(has_aer(), "qiskit-aer doesn't appear to be installed.")
def test_execute_block(self):
"""Test executing a ScheduleBlock on a Pulse backend"""
with pulse.build(name="test_block") as sched_block:
pulse.play(pulse.Constant(160, 1.0), pulse.DriveChannel(0))
pulse.acquire(50, pulse.AcquireChannel(0), pulse.MemorySlot(0))
backend = FakeArmonk()
# TODO: Rewrite test to simulate with qiskit-dynamics
with self.assertWarns(DeprecationWarning):
test_result = backend.run(sched_block).result()
self.assertDictEqual(test_result.get_counts(), {"0": 1024})
class TestBlockEquality(BaseTestBlock):
"""Test equality of blocks.
Equality of instruction ordering is compared on DAG representation.
This should be tested for each transform.
"""
def test_different_channels(self):
"""Test equality is False if different channels."""
block1 = pulse.ScheduleBlock()
block1 += pulse.Delay(10, self.d0)
block2 = pulse.ScheduleBlock()
block2 += pulse.Delay(10, self.d1)
self.assertNotEqual(block1, block2)
def test_different_transform(self):
"""Test equality is False if different transforms."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Delay(10, self.d0)
block2 = pulse.ScheduleBlock(alignment_context=self.right_context)
block2 += pulse.Delay(10, self.d0)
self.assertNotEqual(block1, block2)
def test_different_transform_opts(self):
"""Test equality is False if different transform options."""
context1 = transforms.AlignEquispaced(duration=100)
context2 = transforms.AlignEquispaced(duration=500)
block1 = pulse.ScheduleBlock(alignment_context=context1)
block1 += pulse.Delay(10, self.d0)
block2 = pulse.ScheduleBlock(alignment_context=context2)
block2 += pulse.Delay(10, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_out_of_order_left(self):
"""Test equality is True if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertEqual(block1, block2)
def test_instruction_in_order_left(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_right(self):
"""Test equality is True if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.right_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.right_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertEqual(block1, block2)
def test_instruction_in_order_right(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.right_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.right_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_sequential(self):
"""Test equality is False if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_out_of_order_sequential_more(self):
"""Test equality is False if three blocks have instructions in different order.
This could detect a particular bug as discussed in this thread:
https://github.com/Qiskit/qiskit-terra/pull/8005#discussion_r966191018
"""
block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_in_order_sequential(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_equispaced(self):
"""Test equality is False if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_in_order_equispaced(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_func(self):
"""Test equality is False if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.func_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.func_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_in_order_func(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.func_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.func_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instrution_in_oder_but_different_node(self):
"""Test equality is False if two blocks have different instructions."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform1, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertNotEqual(block1, block2)
def test_instruction_out_of_order_complex_equal(self):
"""Test complex schedule equality can be correctly evaluated."""
block1_a = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_a += pulse.Delay(10, self.d0)
block1_a += pulse.Play(self.test_waveform1, self.d1)
block1_a += pulse.Play(self.test_waveform0, self.d0)
block1_b = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_b += pulse.Play(self.test_waveform1, self.d1)
block1_b += pulse.Delay(10, self.d0)
block1_b += pulse.Play(self.test_waveform0, self.d0)
block2_a = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_a += block1_a
block2_a += block1_b
block2_a += block1_a
block2_b = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_b += block1_a
block2_b += block1_a
block2_b += block1_b
self.assertEqual(block2_a, block2_b)
def test_instruction_out_of_order_complex_not_equal(self):
"""Test complex schedule equality can be correctly evaluated."""
block1_a = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_a += pulse.Play(self.test_waveform0, self.d0)
block1_a += pulse.Play(self.test_waveform1, self.d1)
block1_a += pulse.Delay(10, self.d0)
block1_b = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_b += pulse.Play(self.test_waveform1, self.d1)
block1_b += pulse.Delay(10, self.d0)
block1_b += pulse.Play(self.test_waveform0, self.d0)
block2_a = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_a += block1_a
block2_a += block1_b
block2_a += block1_a
block2_b = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_b += block1_a
block2_b += block1_a
block2_b += block1_b
self.assertNotEqual(block2_a, block2_b)
class TestParametrizedBlockOperation(BaseTestBlock):
"""Test fundamental operation with parametrization."""
def setUp(self):
super().setUp()
self.amp0 = circuit.Parameter("amp0")
self.amp1 = circuit.Parameter("amp1")
self.dur0 = circuit.Parameter("dur0")
self.dur1 = circuit.Parameter("dur1")
self.test_par_waveform0 = pulse.Constant(self.dur0, self.amp0)
self.test_par_waveform1 = pulse.Constant(self.dur1, self.amp1)
def test_report_parameter_assignment(self):
"""Test duration assignment check."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
# check parameter evaluation mechanism
self.assertTrue(block.is_parameterized())
self.assertFalse(block.is_schedulable())
# assign duration
block = block.assign_parameters({self.dur0: 200})
self.assertTrue(block.is_parameterized())
self.assertTrue(block.is_schedulable())
def test_cannot_get_duration_if_not_assigned(self):
"""Test raise error when duration is not assigned."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
with self.assertRaises(PulseError):
# pylint: disable=pointless-statement
block.duration
def test_get_assigend_duration(self):
"""Test duration is correctly evaluated."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
block += pulse.Play(self.test_waveform0, self.d0)
block = block.assign_parameters({self.dur0: 300})
self.assertEqual(block.duration, 400)
def test_nested_parametrized_instructions(self):
"""Test parameters of nested schedule can be assigned."""
test_waveform = pulse.Constant(100, self.amp0)
param_sched = pulse.Schedule(pulse.Play(test_waveform, self.d0))
with self.assertWarns(DeprecationWarning):
call_inst = pulse.instructions.Call(param_sched)
sub_block = pulse.ScheduleBlock()
sub_block += call_inst
block = pulse.ScheduleBlock()
block += sub_block
self.assertTrue(block.is_parameterized())
# assign durations
block = block.assign_parameters({self.amp0: 0.1})
self.assertFalse(block.is_parameterized())
def test_equality_of_parametrized_channels(self):
"""Test check equality of blocks involving parametrized channels."""
par_ch = circuit.Parameter("ch")
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, pulse.DriveChannel(par_ch))
block1 += pulse.Play(self.test_par_waveform0, self.d0)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_par_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, pulse.DriveChannel(par_ch))
self.assertEqual(block1, block2)
block1_assigned = block1.assign_parameters({par_ch: 1})
block2_assigned = block2.assign_parameters({par_ch: 1})
self.assertEqual(block1_assigned, block2_assigned)
def test_replace_parametrized_instruction(self):
"""Test parametrized instruction can updated with parameter table."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
block += pulse.Delay(100, self.d0)
block += pulse.Play(self.test_waveform0, self.d0)
replaced = block.replace(
pulse.Play(self.test_par_waveform0, self.d0),
pulse.Play(self.test_par_waveform1, self.d0),
)
self.assertTrue(replaced.is_parameterized())
# check assign parameters
replaced_assigned = replaced.assign_parameters({self.dur1: 100, self.amp1: 0.1})
self.assertFalse(replaced_assigned.is_parameterized())
def test_parametrized_context(self):
"""Test parametrize context parameter."""
duration = circuit.Parameter("dur")
param_context = transforms.AlignEquispaced(duration=duration)
block = pulse.ScheduleBlock(alignment_context=param_context)
block += pulse.Delay(10, self.d0)
block += pulse.Delay(10, self.d0)
block += pulse.Delay(10, self.d0)
block += pulse.Delay(10, self.d0)
self.assertTrue(block.is_parameterized())
self.assertFalse(block.is_schedulable())
block.assign_parameters({duration: 100}, inplace=True)
self.assertFalse(block.is_parameterized())
self.assertTrue(block.is_schedulable())
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(30, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(60, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(90, pulse.Delay(10, self.d0))
self.assertScheduleEqual(block, ref_sched)
class TestBlockFilter(BaseTestBlock):
"""Test ScheduleBlock filtering methods."""
def test_filter_channels(self):
"""Test filtering over channels."""
with pulse.build() as blk:
pulse.play(self.test_waveform0, self.d0)
pulse.delay(10, self.d0)
pulse.play(self.test_waveform1, self.d1)
filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d0])
self.assertEqual(len(filtered_blk.channels), 1)
self.assertTrue(self.d0 in filtered_blk.channels)
with pulse.build() as ref_blk:
pulse.play(self.test_waveform0, self.d0)
pulse.delay(10, self.d0)
self.assertEqual(filtered_blk, ref_blk)
filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d1])
self.assertEqual(len(filtered_blk.channels), 1)
self.assertTrue(self.d1 in filtered_blk.channels)
with pulse.build() as ref_blk:
pulse.play(self.test_waveform1, self.d1)
self.assertEqual(filtered_blk, ref_blk)
filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d0, self.d1])
self.assertEqual(len(filtered_blk.channels), 2)
for ch in [self.d0, self.d1]:
self.assertTrue(ch in filtered_blk.channels)
self.assertEqual(filtered_blk, blk)
def test_filter_channels_nested_block(self):
"""Test filtering over channels in a nested block."""
with pulse.build() as blk:
with pulse.align_sequential():
pulse.play(self.test_waveform0, self.d0)
pulse.delay(5, self.d0)
with pulse.build(self.backend) as cx_blk:
pulse.cx(0, 1)
pulse.call(cx_blk)
for ch in [self.d0, self.d1, pulse.ControlChannel(0)]:
filtered_blk = self._filter_and_test_consistency(blk, channels=[ch])
self.assertEqual(len(filtered_blk.channels), 1)
self.assertTrue(ch in filtered_blk.channels)
def test_filter_inst_types(self):
"""Test filtering on instruction types."""
with pulse.build() as blk:
pulse.acquire(5, pulse.AcquireChannel(0), pulse.MemorySlot(0))
with pulse.build() as blk_internal:
pulse.play(self.test_waveform1, self.d1)
pulse.call(blk_internal)
pulse.reference(name="dummy_reference")
pulse.delay(10, self.d0)
pulse.play(self.test_waveform0, self.d0)
pulse.barrier(self.d0, self.d1, pulse.AcquireChannel(0), pulse.MemorySlot(0))
pulse.set_frequency(10, self.d0)
pulse.shift_frequency(5, self.d1)
pulse.set_phase(3.14 / 4.0, self.d0)
pulse.shift_phase(-3.14 / 2.0, self.d1)
pulse.snapshot(label="dummy_snapshot")
# test filtering Acquire
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Acquire])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Acquire)
self.assertEqual(len(filtered_blk.channels), 2)
# test filtering Reference
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.instructions.Reference]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.instructions.Reference)
# test filtering Delay
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Delay])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Delay)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering Play
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Play])
self.assertEqual(len(filtered_blk.blocks), 2)
self.assertIsInstance(filtered_blk.blocks[0].blocks[0], pulse.Play)
self.assertIsInstance(filtered_blk.blocks[1], pulse.Play)
self.assertEqual(len(filtered_blk.channels), 2)
# test filtering RelativeBarrier
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.instructions.RelativeBarrier]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.instructions.RelativeBarrier)
self.assertEqual(len(filtered_blk.channels), 4)
# test filtering SetFrequency
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.SetFrequency]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.SetFrequency)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering ShiftFrequency
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.ShiftFrequency]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.ShiftFrequency)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering SetPhase
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.SetPhase])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.SetPhase)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering ShiftPhase
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.ShiftPhase])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.ShiftPhase)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering SnapShot
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Snapshot])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Snapshot)
self.assertEqual(len(filtered_blk.channels), 1)
def test_filter_functionals(self):
"""Test functional filtering."""
with pulse.build() as blk:
pulse.play(self.test_waveform0, self.d0, "play0")
pulse.delay(10, self.d0, "delay0")
with pulse.build() as blk_internal:
pulse.play(self.test_waveform1, self.d1, "play1")
pulse.call(blk_internal)
pulse.play(self.test_waveform1, self.d1)
def filter_with_inst_name(inst: pulse.Instruction) -> bool:
try:
if isinstance(inst.name, str):
match_obj = re.search(pattern="play", string=inst.name)
if match_obj is not None:
return True
except AttributeError:
pass
return False
filtered_blk = self._filter_and_test_consistency(blk, filter_with_inst_name)
self.assertEqual(len(filtered_blk.blocks), 2)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Play)
self.assertIsInstance(filtered_blk.blocks[1].blocks[0], pulse.Play)
self.assertEqual(len(filtered_blk.channels), 2)
def test_filter_multiple(self):
"""Test filter composition."""
with pulse.build() as blk:
pulse.play(pulse.Constant(100, 0.1, name="play0"), self.d0)
pulse.delay(10, self.d0, "delay0")
with pulse.build(name="internal_blk") as blk_internal:
pulse.play(pulse.Constant(50, 0.1, name="play1"), self.d0)
pulse.call(blk_internal)
pulse.barrier(self.d0, self.d1)
pulse.play(pulse.Constant(100, 0.1, name="play2"), self.d1)
def filter_with_pulse_name(inst: pulse.Instruction) -> bool:
try:
if isinstance(inst.pulse.name, str):
match_obj = re.search(pattern="play", string=inst.pulse.name)
if match_obj is not None:
return True
except AttributeError:
pass
return False
filtered_blk = self._filter_and_test_consistency(
blk, filter_with_pulse_name, channels=[self.d1], instruction_types=[pulse.Play]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Play)
self.assertEqual(len(filtered_blk.channels), 1)
def _filter_and_test_consistency(
self, sched_blk: pulse.ScheduleBlock, *args: Any, **kwargs: Any
) -> pulse.ScheduleBlock:
"""
Returns sched_blk.filter(*args, **kwargs),
including a test that sched_blk.filter | sched_blk.exclude == sched_blk
in terms of instructions.
"""
filtered = sched_blk.filter(*args, **kwargs)
excluded = sched_blk.exclude(*args, **kwargs)
def list_instructions(blk: pulse.ScheduleBlock) -> List[pulse.Instruction]:
insts = []
for element in blk.blocks:
if isinstance(element, pulse.ScheduleBlock):
inner_insts = list_instructions(element)
if len(inner_insts) != 0:
insts.extend(inner_insts)
elif isinstance(element, pulse.Instruction):
insts.append(element)
return insts
sum_insts = list_instructions(filtered) + list_instructions(excluded)
ref_insts = list_instructions(sched_blk)
self.assertEqual(len(sum_insts), len(ref_insts))
self.assertTrue(all(inst in ref_insts for inst in sum_insts))
return filtered
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization.problems import QuadraticProgram
# define a problem
qp = QuadraticProgram()
qp.binary_var("x")
qp.integer_var(name="y", lowerbound=-1, upperbound=4)
qp.maximize(quadratic={("x", "y"): 1})
qp.linear_constraint({"x": 1, "y": -1}, "<=", 0)
print(qp.prettyprint())
from qiskit_optimization.algorithms import CplexOptimizer, GurobiOptimizer
cplex_result = CplexOptimizer().solve(qp)
gurobi_result = GurobiOptimizer().solve(qp)
print("cplex")
print(cplex_result.prettyprint())
print()
print("gurobi")
print(gurobi_result.prettyprint())
result = CplexOptimizer(disp=True, cplex_parameters={"threads": 1, "timelimit": 0.1}).solve(qp)
print(result.prettyprint())
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_aer import Aer
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
meo = MinimumEigenOptimizer(QAOA(sampler=Sampler(), optimizer=COBYLA(maxiter=100)))
result = meo.solve(qp)
print(result.prettyprint())
print("\ndisplay the best 5 solution samples")
for sample in result.samples[:5]:
print(sample)
# docplex model
from docplex.mp.model import Model
docplex_model = Model("docplex")
x = docplex_model.binary_var("x")
y = docplex_model.integer_var(-1, 4, "y")
docplex_model.maximize(x * y)
docplex_model.add_constraint(x <= y)
docplex_model.prettyprint()
# gurobi model
import gurobipy as gp
gurobipy_model = gp.Model("gurobi")
x = gurobipy_model.addVar(vtype=gp.GRB.BINARY, name="x")
y = gurobipy_model.addVar(vtype=gp.GRB.INTEGER, lb=-1, ub=4, name="y")
gurobipy_model.setObjective(x * y, gp.GRB.MAXIMIZE)
gurobipy_model.addConstr(x - y <= 0)
gurobipy_model.update()
gurobipy_model.display()
from qiskit_optimization.translators import from_docplex_mp, from_gurobipy
qp = from_docplex_mp(docplex_model)
print("QuadraticProgram obtained from docpblex")
print(qp.prettyprint())
print("-------------")
print("QuadraticProgram obtained from gurobipy")
qp2 = from_gurobipy(gurobipy_model)
print(qp2.prettyprint())
from qiskit_optimization.translators import to_gurobipy, to_docplex_mp
gmod = to_gurobipy(from_docplex_mp(docplex_model))
print("convert docplex to gurobipy via QuadraticProgram")
gmod.display()
dmod = to_docplex_mp(from_gurobipy(gurobipy_model))
print("\nconvert gurobipy to docplex via QuadraticProgram")
print(dmod.export_as_lp_string())
ind_mod = Model("docplex")
x = ind_mod.binary_var("x")
y = ind_mod.integer_var(-1, 2, "y")
z = ind_mod.integer_var(-1, 2, "z")
ind_mod.maximize(3 * x + y - z)
ind_mod.add_indicator(x, y >= z, 1)
print(ind_mod.export_as_lp_string())
qp = from_docplex_mp(ind_mod)
result = meo.solve(qp) # apply QAOA to QuadraticProgram
print("QAOA")
print(result.prettyprint())
print("-----\nCPLEX")
print(ind_mod.solve()) # apply CPLEX directly to the Docplex model
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# load necessary Runtime libraries
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit.circuit import Parameter
from qiskit.opflow import I, X, Z
mu = Parameter('$\\mu$')
ham_pauli = mu * X
cc = Parameter('$c$')
ww = Parameter('$\\omega$')
ham_res = -(1/2)*ww*(I^Z) + cc*(X^X) + (ham_pauli^I)
tt = Parameter('$t$')
U_ham = (tt*ham_res).exp_i()
from qiskit import transpile
from qiskit.circuit import ClassicalRegister
from qiskit.opflow import PauliTrotterEvolution, Suzuki
import numpy as np
num_trot_steps = 5
total_time = 10
cr = ClassicalRegister(1, 'c')
spec_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=num_trot_steps)).convert(U_ham)
spec_circ = spec_op.to_circuit()
spec_circ_t = transpile(spec_circ, basis_gates=['sx', 'rz', 'cx'])
spec_circ_t.add_register(cr)
spec_circ_t.measure(0, cr[0])
spec_circ_t.draw('mpl')
# fixed Parameters
fixed_params = {
cc: 0.3,
mu: 0.7,
tt: total_time
}
# Parameter value for single circuit
param_keys = list(spec_circ_t.parameters)
# run through all the ww values to create a List of Lists of Parameter value
num_pts = 101
wvals = np.linspace(-2, 2, num_pts)
param_vals = []
for wval in wvals:
all_params = {**fixed_params, **{ww: wval}}
param_vals.append([all_params[key] for key in param_keys])
with Session(backend=backend):
sampler = Sampler()
job = sampler.run(
circuits=[spec_circ_t]*num_pts,
parameter_values=param_vals,
shots=1e5
)
result = job.result()
Zexps = []
for dist in result.quasi_dists:
if 1 in dist:
Zexps.append(1 - 2*dist[1])
else:
Zexps.append(1)
from qiskit.opflow import PauliExpectation, Zero
param_bind = {
cc: 0.3,
mu: 0.7,
tt: total_time
}
init_state = Zero^2
obsv = I^Z
Zexp_exact = (U_ham @ init_state).adjoint() @ obsv @ (U_ham @ init_state)
diag_meas_op = PauliExpectation().convert(Zexp_exact)
Zexact_values = []
for w_set in wvals:
param_bind[ww] = w_set
Zexact_values.append(np.real(diag_meas_op.bind_parameters(param_bind).eval()))
import matplotlib.pyplot as plt
plt.style.use('dark_background')
fig, ax = plt.subplots(dpi=100)
ax.plot([-param_bind[mu], -param_bind[mu]], [0, 1], ls='--', color='purple')
ax.plot([param_bind[mu], param_bind[mu]], [0, 1], ls='--', color='purple')
ax.plot(wvals, Zexact_values, label='Exact')
ax.plot(wvals, Zexps, label=f"{backend}")
ax.set_xlabel(r'$\omega$ (arb)')
ax.set_ylabel(r'$\langle Z \rangle$ Expectation')
ax.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
ghz.draw(output='mpl')
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
# Construct quantum circuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure([0,1], [0,1])
# Select the AerSimulator from the Aer provider
simulator = AerSimulator(method='matrix_product_state')
# Run and get counts, using the matrix_product_state method
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
counts = result.get_counts(0)
counts
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
# Define a snapshot that shows the current state vector
circ.save_statevector(label='my_sv')
circ.save_matrix_product_state(label='my_mps')
circ.measure([0,1], [0,1])
# Execute and get saved data
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
data = result.data(0)
#print the result data
data
num_qubits = 50
circ = QuantumCircuit(num_qubits, num_qubits)
# Create EPR state
circ.h(0)
for i in range (0, num_qubits-1):
circ.cx(i, i+1)
# Measure
circ.measure(range(num_qubits), range(num_qubits))
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
print("Time taken: {} sec".format(result.time_taken))
result.get_counts()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for Stinespring quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info import Stinespring
from .channel_test_case import ChannelTestCase
class TestStinespring(ChannelTestCase):
"""Tests for Stinespring channel representation."""
def test_init(self):
"""Test initialization"""
# Initialize from unitary
chan = Stinespring(self.UI)
assert_allclose(chan.data, self.UI)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Stinespring
chan = Stinespring(self.depol_stine(0.5))
assert_allclose(chan.data, self.depol_stine(0.5))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Non-CPTP
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
chan = Stinespring((stine_l, stine_r))
assert_allclose(chan.data, (stine_l, stine_r))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize with redundant second op
chan = Stinespring((stine_l, stine_l))
assert_allclose(chan.data, stine_l)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Stinespring, stine_l, input_dims=4, output_dims=4)
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Stinespring(circuit)
target = Stinespring(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Stinespring, circuit)
def test_equal(self):
"""Test __eq__ method"""
stine = tuple(self.rand_matrix(4, 2) for _ in range(2))
self.assertEqual(Stinespring(stine), Stinespring(stine))
def test_copy(self):
"""Test copy method"""
mat = np.eye(4)
with self.subTest("Deep copy"):
orig = Stinespring(mat)
cpy = orig.copy()
cpy._data[0][0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Stinespring(mat)
clone = copy.copy(orig)
clone._data[0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = Stinespring(mat)
clone = copy.copy(orig)
clone._data[0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Stinespring(self.depol_stine(0.5)).is_cptp())
self.assertTrue(Stinespring(self.UX).is_cptp())
# Non-CP
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
self.assertFalse(Stinespring((stine_l, stine_r)).is_cptp())
self.assertFalse(Stinespring(self.UI + self.UX).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
stine_l, stine_r = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Single Stinespring list
targ = Stinespring(stine_l.conj(), output_dims=4)
chan1 = Stinespring(stine_l, output_dims=4)
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
# Double Stinespring list
targ = Stinespring((stine_l.conj(), stine_r.conj()), output_dims=4)
chan1 = Stinespring((stine_l, stine_r), output_dims=4)
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
def test_transpose(self):
"""Test transpose method."""
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
# Single square Stinespring list
targ = Stinespring(stine_l.T, 4, 2)
chan1 = Stinespring(stine_l, 2, 4)
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double square Stinespring list
targ = Stinespring((stine_l.T, stine_r.T), 4, 2)
chan1 = Stinespring((stine_l, stine_r), 2, 4)
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_adjoint(self):
"""Test adjoint method."""
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
# Single square Stinespring list
targ = Stinespring(stine_l.T.conj(), 4, 2)
chan1 = Stinespring(stine_l, 2, 4)
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double square Stinespring list
targ = Stinespring((stine_l.T.conj(), stine_r.T.conj()), 4, 2)
chan1 = Stinespring((stine_l, stine_r), 2, 4)
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Stinespring(np.eye(2)).compose, Stinespring(np.eye(4)))
self.assertRaises(QiskitError, Stinespring(np.eye(2)).compose, 2)
def test_compose(self):
"""Test compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
chan = chan1.compose(chan2)
rho_targ = rho_init & Stinespring(self.UZ)
self.assertEqual(rho_init.evolve(chan), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
chan = chan1.compose(chan1)
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 & chan2
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_dot(self):
"""Test deprecated front compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
rho_targ = rho_init.evolve(Stinespring(self.UZ))
self.assertEqual(rho_init.evolve(chan1.dot(chan2)), rho_targ)
self.assertEqual(rho_init.evolve(chan1 @ chan2), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan1.dot(chan1)), rho_targ)
self.assertEqual(rho_init.evolve(chan1 @ chan1), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
self.assertEqual(rho_init.evolve(chan2.dot(chan1)), rho_targ)
self.assertEqual(rho_init.evolve(chan2 @ chan1), rho_targ)
def test_compose_front(self):
"""Test deprecated front compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
chan = chan1.compose(chan2, front=True)
rho_targ = rho_init & Stinespring(self.UZ)
self.assertEqual(rho_init.evolve(chan), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
chan = chan1.compose(chan1, front=True)
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Stinespring(self.UI)
chan2 = Stinespring(self.UX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = Stinespring(self.depol_stine(1))
chan = chan_dep.expand(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Stinespring(self.UI)
chan2 = Stinespring(self.UX)
# X \otimes I
chan = chan2.tensor(chan1)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan1.tensor(chan2)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = Stinespring(self.depol_stine(1))
chan = chan_dep.tensor(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
rho_init = DensityMatrix(np.diag([1, 0]))
p_id = 0.9
chan1 = Stinespring(self.depol_stine(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan = chan1.power(3)
rho_targ = rho_init & chan1 & chan1 & chan1
self.assertEqual(rho_init & chan, rho_targ)
rho_targ = rho_init & Stinespring(self.depol_stine(1 - p_id3))
self.assertEqual(rho_init & chan, rho_targ)
def test_add(self):
"""Test add method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Random Single-Stinespring maps
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=2, output_dims=4)
rho_targ = (rho_init & chan1) + (rho_init & chan2)
chan = chan1._add(chan2)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 + chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Random Single-Stinespring maps
chan = Stinespring((stine1, stine2))
rho_targ = 2 * (rho_init & chan)
chan = chan._add(chan)
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_subtract(self):
"""Test subtract method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Random Single-Stinespring maps
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=2, output_dims=4)
rho_targ = (rho_init & chan1) - (rho_init & chan2)
chan = chan1 - chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Random Single-Stinespring maps
chan = Stinespring((stine1, stine2))
rho_targ = 0 * (rho_init & chan)
chan = chan - chan
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_add_qargs(self):
"""Test add method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
stine = self.rand_matrix(32, 8)
stine0 = self.rand_matrix(8, 2)
op = Stinespring(stine)
op0 = Stinespring(stine0)
eye = Stinespring(self.UI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(rho & value, rho & target)
def test_sub_qargs(self):
"""Test sub method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
stine = self.rand_matrix(32, 8)
stine0 = self.rand_matrix(8, 2)
op = Stinespring(stine)
op0 = Stinespring(stine0)
eye = Stinespring(self.UI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(rho & value, rho & target)
def test_multiply(self):
"""Test multiply method."""
# Random initial state and Stinespring ops
rho_init = DensityMatrix(self.rand_rho(2))
val = 0.5
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Single Stinespring set
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
rho_targ = val * (rho_init & chan1)
chan = chan1._multiply(val)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = val * chan1
self.assertEqual(rho_init.evolve(chan), rho_targ)
rho_targ = (rho_init & chan1) * val
chan = chan1 * val
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Double Stinespring set
chan2 = Stinespring((stine1, stine2), input_dims=2, output_dims=4)
rho_targ = val * (rho_init & chan2)
chan = chan2._multiply(val)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = val * chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Stinespring(self.depol_stine(1))
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
rho_init = DensityMatrix(np.diag([1, 0]))
rho_targ = DensityMatrix(np.diag([-0.5, -0.5]))
chan = -Stinespring(self.depol_stine(1))
self.assertEqual(rho_init.evolve(chan), rho_targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure(0, 0)
circ.measure(1, 1)
circ.draw('mpl')
from qiskit import pulse
from qiskit.pulse.library import Gaussian
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration('h', [0], h_q0)
from qiskit import transpile
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
circ = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ.draw('mpl', idle_wires=False)
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
circ = QuantumCircuit(1, 1)
custom_gate = Gate('my_custom_gate', 1, [3.14, 1])
# 3.14 is an arbitrary parameter for demonstration
circ.append(custom_gate, [0])
circ.measure(0, 0)
circ.draw('mpl')
with pulse.build(backend, name='custom') as my_schedule:
pulse.play(Gaussian(duration=64, amp=0.2, sigma=8), pulse.drive_channel(0))
circ.add_calibration('my_custom_gate', [0], my_schedule, [3.14, 1])
# Alternatively: circ.add_calibration(custom_gate, [0], my_schedule)
circ = transpile(circ, backend)
circ.draw('mpl', idle_wires=False)
circ = QuantumCircuit(2, 2)
circ.append(custom_gate, [1])
from qiskit import QiskitError
try:
circ = transpile(circ, backend)
except QiskitError as e:
print(e)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/alvinli04/Quantum-Steganography
|
alvinli04
|
import qiskit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, AncillaRegister
from qiskit import execute
from qiskit import Aer
from qiskit import IBMQ
from qiskit.compiler import transpile
from time import perf_counter
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit.library import SXdgGate
import numpy as np
import neqr
import random
import math
'''
params
---------------
regY: a quantum register
regX: a quantum register
circuit: the circuit that contains all the register
result: an empty register that will hold results
return
---------------
a size 2 register, c0 c1:
If c1c0 = 00, then Y = X.
If c1c0 = 01, then Y < X.
If c1c0 = 10, then Y > X
'''
def comparator(regY, regX, circuit, result):
# regX and regY should have the same size
regLength = regX.size
ancilla = AncillaRegister(2*regLength)
circuit.add_register(ancilla)
circuit.x(ancilla)
for index in range(regLength):
circuit.x(regX[index])
circuit.mcx([regY[index], regX[index]]+[ancilla[i] for i in range(2*index)], [ancilla[index*2]])
if index < regLength-1:
circuit.mcx([regY[index], regX[index]]+[ancilla[i] for i in range(2*index)], [ancilla[2*regLength-2]])
circuit.x(regX[index])
circuit.x(regY[index])
circuit.mcx([regY[index], regX[index]]+[ancilla[i] for i in range(2*index)], [ancilla[index*2+1]])
if index < regLength-1:
circuit.mcx([regY[index], regX[index]]+[ancilla[i] for i in range(2*index)], [ancilla[2*regLength-1]])
circuit.x(regY[index])
circuit.x(ancilla)
circuit.cx(ancilla[2*regLength-2], result[0])
circuit.cx(ancilla[2*regLength-1], result[1])
'''
params
---------------
YX: a quantum register containing two coordinates, |Y>|X>
AB: a quantum register containing two coordinates, |A>|B>
return
---------------
A single qubit |r> which is |1> when YX = AB and |0> otherwise
'''
def coordinate_comparator(circuit, result, YX, AB):
assert len(YX) == len(AB)
n = YX.size
for i in range(n):
circuit.x(YX[i])
circuit.cx(YX[i], AB[i])
circuit.x(YX[i])
circuit.mcx(AB, result)
for i in range(n):
circuit.x(YX[i])
circuit.cx(YX[i], AB[i])
circuit.x(YX[i])
'''
params
---------------
Y: a quantum register
X: a quantum register
difference: an empty quantum register the same size as X and Y
return
---------------
A quantum register |D> which holds the positive difference of Y and X.
'''
def difference(circuit, Y, X, difference):
assert len(Y) == len(X)
# PART 1:
# reversible parallel subtractor
# initialize registers to store sign, difference, and junk qubits
regLength = X.size
sign = QuantumRegister(1)
ancilla = QuantumRegister(regLength - 1)
circuit.add_register(ancilla)
circuit.add_register(sign)
# perform half subtractor for last qubit
rev_half_subtractor(circuit, X[-1], Y[-1], difference[-1], ancilla[-1])
# perform full subtrator for rest of qubits
for i in range(regLength - 2, 0, -1):
rev_full_subtractor(circuit, X[i], Y[i], ancilla[i], difference[i], ancilla[i-1])
rev_full_subtractor(circuit, X[0], Y[0], ancilla[0], difference[0], sign[0])
# swap X and difference registers to fix result
# this is just sort of a thing you have to do
for i in range(regLength - 1, -1, -1):
circuit.swap(difference[i], X[i])
# PART 2:
# complementary operation
# flip the difference based on the sign (pt 1)
for i in range(regLength):
circuit.cx(sign[0], difference[i])
# flip the difference again, but based on sign and remaining bits (pt 2)
#for i in range(regLength-1, -1, -1):
for i in range(regLength):
circuit.mcx([sign[0]] + difference[i+1:], difference[i])
'''
params
---------------
regA: a quantum register, one of the numbers being subtracted
regB: a quantum register, one of the numbers being subtracted
Q: Updated depending on result
Borrow: Digit to be carried over
return
---------------
Performs A - B, and updates results into Q and Borrow
'''
def rev_half_subtractor(circuit, A, B, Q, Borrow):
csxdg_gate = SXdgGate().control()
circuit.append(csxdg_gate, [A, Borrow])
circuit.cx(A, Q)
circuit.cx(B, A)
circuit.csx(B, Borrow)
circuit.csx(A, Borrow)
circuit.barrier()
'''
params
---------------
regA: a quantum register, one of the numbers being subtracted
regB: a quantum register, one of the numbers subtracting
regC: a quantum register, one of the numbers subtracting
Q: Updated depending on result
Borrow: Digit to be carried over
return
---------------
Performs A - B - C, updates results into Q and Borrow
'''
def rev_full_subtractor(circuit, A, B, C, Q, Borrow):
csxdg_gate = SXdgGate().control()
circuit.append(csxdg_gate, [A, Borrow])
circuit.cx(A, Q)
circuit.cx(B, A)
circuit.csx(B, Borrow)
circuit.cx(C, A)
circuit.csx(C, Borrow)
circuit.csx(A, Borrow)
circuit.barrier()
def controlled_difference(controlled_qubit, circuit, Y, X, difference):
# PART 1:
# reversible parallel subtractor
# initialize registers to store sign, difference, and junk qubits
regLength = X.size
sign = QuantumRegister(1, 'sign')
ancilla = QuantumRegister(regLength - 1, 'junk')
circuit.add_register(ancilla)
circuit.add_register(sign)
# perform half subtractor for last qubit
controlled_rhs(controlled_qubit, circuit, X[-1], Y[-1], difference[-1], ancilla[-1])
# perform full subtrator for rest of qubits
for i in range(regLength - 2, 0, -1):
controlled_rfs(controlled_qubit, circuit, X[i], Y[i], ancilla[i], difference[i], ancilla[i-1])
controlled_rfs(controlled_qubit, circuit, X[0], Y[0], ancilla[0], difference[0], sign[0])
# swap X and difference registers to fix result
# this is just sort of a thing you have to do
for i in range(regLength - 1, -1, -1):
circuit.cswap(controlled_qubit, difference[i], X[i])
# PART 2:
# complementary operation
# flip the difference based on the sign (pt 1)
for i in range(regLength):
circuit.ccx(controlled_qubit, sign[0], difference[i])
# flip the difference again, but based on sign and remaining bits (pt 2)
#for i in range(regLength-1, -1, -1):
for i in range(regLength):
circuit.mcx([controlled_qubit] + [sign[0]] + difference[i+1:], difference[i])
# controlled reversible half subtractor
def controlled_rhs(controlled_qubit, circuit, A, B, Q, Borrow):
# allocate ancilla qubits
anc1 = QuantumRegister(3)
circuit.add_register(anc1)
# rewritten code to control for given qubit
csxdg_gate = SXdgGate().control()
circuit.ccx(controlled_qubit, A, anc1[0])
circuit.append(csxdg_gate, [anc1[0], Borrow])
circuit.ccx(controlled_qubit, A, Q)
circuit.ccx(controlled_qubit, B, A)
circuit.ccx(controlled_qubit, B, anc1[1])
circuit.ccx(controlled_qubit, A, anc1[2])
circuit.csx(anc1[1], Borrow)
circuit.csx(anc1[2], Borrow)
circuit.barrier()
# controlled reversible full subtractor
def controlled_rfs(controlled_qubit, circuit, A, B, C, Q, Borrow):
# allocate ancilla qubits
anc2 = QuantumRegister(4)
circuit.add_register(anc2)
# rewritten code to control for given qubit
csxdg_gate = SXdgGate().control()
circuit.ccx(controlled_qubit, A, anc2[0])
circuit.append(csxdg_gate, [anc2[0], Borrow])
circuit.cx(A, Q)
circuit.cx(B, A)
circuit.ccx(controlled_qubit, B, anc2[1])
circuit.csx(anc2[1], Borrow)
circuit.cx(C, A)
circuit.ccx(controlled_qubit, C, anc2[2])
circuit.csx(anc2[2], Borrow)
circuit.ccx(controlled_qubit, A, anc2[3])
circuit.csx(anc2[3], Borrow)
circuit.barrier()
'''
Embedding Procedure
'''
'''
params
------------------
k: the number of binary images
binary_images: a list of 2^n by 2^n binary images to construct the secret image
assume they are all the same size
return
-------------------
the secret image
'''
def get_secret_image(k, binary_images):
n = len(binary_images[0][0])
secret_image = [['' for i in range(n)] for j in range(n)]
for i in range(k):
for j in range(n):
for l in range(n):
secret_image[j][l] += str(binary_images[i][j][l])
return secret_image
'''
params
--------------------
secret_image: a quantum circuit containing the secret image
intensity: a quantum register in secret_image that contains the intensity
returns
--------------------
nothing
'''
def invert(secret_image, intensity, inverse):
secret_image.x(intensity)
for i in range(len(intensity)):
secret_image.cx(intensity[i], inverse[i])
secret_image.x(intensity)
'''
params
------------------
circuit: the quantum circuit containing all the images
key: an empty key register, to be modified
cover: the quantum cover image
secret: the quantum secret image
inv_secret: the inverse secret image
image_size: total size of the image
diff1: holds difference between cover and secret
diff2: holds difference between cover and inverse secret
image_size: number of pixels
'''
def get_key(circuit,
key_idx,
key_result,
cover_intensity,
secret_intensity,
inv_secret_intensity,
diff1,
diff2,
comp_result,
image_size):
circuit.h(key_idx)
difference(circuit, cover_intensity, secret_intensity, diff1)
difference(circuit, cover_intensity, inv_secret_intensity, diff2)
comparator(diff1, diff2, circuit, comp_result)
circuit.x(comp_result[1])
for i in range(image_size):
bin_ind = bin(i)[2:]
bin_ind = (len(key_idx) - len(bin_ind)) * '0' + bin_ind
bin_ind = bin_ind[::-1]
# X-gate (enabling zero-controlled nature)
for j in range(len(bin_ind)):
if bin_ind[j] == '0':
circuit.x(key_idx[j])
circuit.mcx(comp_result[:] + key_idx[:], key_result)
# X-gate (enabling zero-controlled nature)
for j in range(len(bin_ind)):
if bin_ind[j] == '0':
circuit.x(key_idx[j])
circuit.x(comp_result[1])
def embed(circuit, C, S, Key, cover_image_values, secret_image_values, key_i):
# removed code. can be used for unit test
'''
#preperation
array = [[random.randint(0, 255), random.randint(0, 255)], [random.randint(0, 255), random.randint(0, 255)]]
print(array)
bits_array = neqr.convert_to_bits(array)
print(bits_array)
#setting up the images, difference registers, and circuiit
_, cover_image_values = neqr.neqr(bits_array)
_, secret_image_values = neqr.neqr(bits_array)
circuit = QuantumCircuit(cover_image_values, secret_image_values, difference_1, difference_2)
'''
#part 1:
#carrying out the coordinate comparators
coord_result = QuantumRegister(2, 'coord_result')
circuit.add_register(coord_result)
coordinate_comparator(circuit, coord_result, C, S)
#getting the key through getKey (once its done)
coordinate_comparator(circuit, coord_result, C, Key)
#adding outputs to the circuit
circuit.add_register(coord_result[0])
circuit.add_register(coord_result[1])
#part 2:
#need to make a controlled difference method :(
diff1_result = QuantumRegister(C.size, 'diff1_result')
circuit.add_register(diff1_result)
controlled_difference(coord_result[0], circuit, cover_image_values, secret_image_values, diff1_result)
#after this, secret_image_values are inverted
invert(circuit, secret_image_values)
#computing difference again
diff2_result = QuantumRegister(C.size, 'diff2_result')
circuit.add_register(diff2_result)
difference(circuit,cover_image_values, secret_image_values, diff2_result)
#comparing the differences
comparator_result = QuantumRegister(2, "compare_result")
circuit.add_register(comparator_result)
comparator(circuit, diff2_result, diff1_result, comparator_result)
# flip for zero-controlled ccnots
circuit.x(comparator_result[1])
circuit.ccx(coord_result[0], comparator_result[1], cover_image_values)
circuit.ccx(coord_result[0], comparator_result[1], secret_image_values)
circuit.x(comparator_result[1]) # flip back
# do a cute little toffoli cascade for the cccswap and cccx
anc = QuantumRegister(2) # allocate ancilla qubits
circuit.add_register(anc)
circuit.ccx(coord_result[0], coord_result[1], anc[0])
circuit.ccx(anc[0], comparator_result[1], anc[1])
circuit.cswap(anc[2], cover_image_values, secret_image_values) # cccswap
circuit.cx(comparator_result[1], key_i) # cccnot
def extract(circuit, key_idx, key_val, cs_idx, cs_val, extracted, comp_result, k):
for i in range(k):
circuit.cx(cs_val[len(cs_val) - k - 1 + i], extracted[i])
coordinate_comparator(circuit, comp_result, key_idx, cs_idx)
for i in range(image_size):
bin_ind = bin(i)[2:]
bin_ind = (len(key_idx) - len(bin_ind)) * '0' + bin_ind
bin_ind = bin_ind[::-1]
# X-gate (enabling zero-controlled nature)
for j in range(len(bin_ind)):
if bin_ind[j] == '0':
circuit.x(cs_idx[j])
circuit.mcx(comp_result[:] + cs_idx[:], extracted)
# X-gate (enabling zero-controlled nature)
for j in range(len(bin_ind)):
if bin_ind[j] == '0':
circuit.x(cs_idx[j])
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import *
from qiskit.providers.ibmq import least_busy
from qiskit.tools.visualization import plot_histogram
from IPython.display import display, Math, Latex
def Increment(size):
U = QuantumCircuit(size)
control = [x for x in range(size-1)]
for k in range(size-1):
U.mcx(control, control[-1]+1)
control.pop()
U.x(0)
U = U.to_gate()
U.name = '--->'
ctl_U = U.control()
return ctl_U
def Decrement(size):
U = QuantumCircuit(size)
control = [x for x in range(size-1)]
for k in range(size-1):
U.x(control)
U.mcx(control, control[-1]+1)
U.x(control)
control.pop()
U.x(0)
U = U.to_gate()
U.name = '<---'
ctl_U = U.control()
return ctl_U
n = 2
steps = 2
graph = QuantumRegister(n+1)
mes = ClassicalRegister(n)
mcq = QuantumCircuit(graph, mes)
#define U(t)
for i in range(steps):
mcq.h(n)
mcq.append(Increment(n), [n]+list(range(0, n)))
mcq.x(n)
mcq.append(Decrement(n), [n]+list(range(0, n)))
mcq.x(n)
mcq.measure(range(n), range(n))
#mcq = transpile(mcq, basis_gates=['cx','u3'],optimization_level=3)
mcq.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
atp = 1024
res = execute(mcq, backend=backend, shots=atp).result()
ans = res.get_counts()
plot_histogram(ans)
IBMQ.load_account()
provider = IBMQ.get_provider(group='open', project='main')
backend = provider.get_backend('ibmq_16_melbourne')
job = execute(mcq, backend=backend)
ans_quantum = job.result().get_counts()
legend = ['QASM','ibmq_16_melbourne']
plot_histogram([ans,ans_quantum], legend=legend)
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
q = QuantumRegister(3, 'q')
c = ClassicalRegister(2, 'c')
qpe = QuantumCircuit(q, c)
qpe.x(q[2])
qpe.h(q[0])
qpe.h(q[1])
# controlled unitary from q[0] is the identity matrix
# controlled unitary from q[1] is a controlled-Z gate
qpe.cz(q[1], q[2]);
def qft(circ, q, n):
"""n-qubit QFT on q in circ."""
for j in range(n):
circ.h(q[j])
for k in range(j+1,n):
circ.cu1(math.pi/float(2**(k-j)), q[k], q[j])
def qft_dagger(circ, q, n):
"""n-qubit QFTdagger on q in circ."""
for j in range(n):
k = (n-1) - j
for m in range(k):
circ.cu1(-math.pi/float(2**(k-m)), q[k], q[m])
circ.h(q[k])
qft_dagger(qpe, q, 2)
qpe.measure(q[0],c[0])
qpe.measure(q[1],c[1])
qpe.draw(output="mpl")
nancilla = 4
q2 = QuantumRegister(nancilla+2, 'q')
c2 = ClassicalRegister(nancilla, 'c')
qpe2 = QuantumCircuit(q2, c2)
qpe2.x(q2[nancilla])
qpe2.x(q2[nancilla+1])
for i in range(nancilla):
qpe2.h(q2[i])
# controlled unitary from q[0] is the identity matrix
# controlled unitary from q[1] is the identity matrix
# controlled unitary from q[2] is a controlled-Z gate
qpe2.h(q2[nancilla+1])
qpe2.ccx(q2[nancilla-1], q2[nancilla], q2[nancilla+1])
qpe2.h(q2[nancilla+1])
qft_dagger(qpe2, q2, nancilla)
for i in range(nancilla):
qpe2.measure(q2[i],c2[i])
qpe2.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 2048
results = execute(qpe, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
results2 = execute(qpe2, backend=backend, shots=shots).result()
answer2 = results2.get_counts()
plot_histogram(answer2)
# Load our saved IBMQ accounts and get the least busy backend device
IBMQ.load_account()
IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = provider.get_backend('ibmq_vigo')
from qiskit.tools.monitor import job_monitor
shots = 2048
job_exp = execute(qpe, backend=backend, shots=shots)
job_monitor(job_exp, interval = 2)
# get the results from the computation
results = job_exp.result()
answer = results.get_counts(qpe)
plot_histogram(answer)
|
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/snow0369/qiskit_tutorial_2021_summerschool
|
snow0369
|
from qiskit import IBMQ, QuantumRegister, QuantumCircuit, ClassicalRegister, transpile
from qiskit.tools import backend_overview, backend_monitor
from qiskit.providers.ibmq.job import job_monitor
from qiskit.quantum_info import hellinger_fidelity
from qiskit.providers.ibmq import IBMQAccountCredentialsNotFound
from qiskit.providers.aer import AerProvider
from qiskit.tools.visualization import plot_gate_map, plot_histogram
token = 'f5876d2c6ea00ce4cefe8fcf6324956e042cd2a7cd57f6efc1e7ba38727964f10cef560830337f64c1de3743c420c1b23ded52bc01b197c6d8ce96394f13f1e0'# Input token here
try:
IBMQ.disable_account()
except IBMQAccountCredentialsNotFound:
pass
IBMQ.enable_account(token)
backend_overview()
IBMQ_provider = IBMQ.get_provider()
ibmq_manila_backend = IBMQ_provider.get_backend('ibmq_manila')
backend_monitor(ibmq_manila_backend)
plot_gate_map(ibmq_manila_backend, plot_directed=True)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
ghz3 = QuantumCircuit(qr, cr)
ghz3.h(qr[0])
ghz3.cx(qr[0], qr[1])
ghz3.cx(qr[0], qr[2])
ghz3.barrier()
ghz3.measure(qr, cr)
ghz3.draw('mpl')
job_exp = ibmq_manila_backend.run(ghz3, shots=2048)
job_monitor(job_exp) # An error must be raised here.
print(ibmq_manila_backend.configuration().basis_gates)
transpiled_circuit = transpile(ghz3, backend=ibmq_manila_backend)
transpiled_circuit.draw('mpl')
transpiled_circuit_opt = transpile(ghz3, backend=ibmq_manila_backend, optimization_level=3)
transpiled_circuit_opt.draw('mpl')
job_exp = ibmq_manila_backend.run(transpiled_circuit_opt, shots=2048)
job_monitor(job_exp)
noisy_counts = job_exp.result().get_counts()
plot_histogram(noisy_counts)
qasm_backend = AerProvider().get_backend('qasm_simulator')
job_ideal = qasm_backend.run(ghz3, shots=2048)
ideal_counts = job_ideal.result().get_counts()
print(hellinger_fidelity(noisy_counts, ideal_counts))
from qiskit.test.mock import FakeRome
fake_rome = FakeRome()
rome_transpiled = transpile(ghz3, backend=fake_rome, optimization_level=3)
job_fake_rome = fake_rome.run(rome_transpiled, shots=2048)
counts_fake_rome = job_fake_rome.result().get_counts()
plot_histogram(counts_fake_rome)
|
https://github.com/daimurat/qiskit-implementation
|
daimurat
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import Aer, QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit.opflow import StateFn, PauliSumOp, AerPauliExpectation, Gradient
from qiskit.utils import QuantumInstance
from qiskit.algorithms.optimizers import COBYLA
expval = AerPauliExpectation()
gradient = Gradient()
qi_sv = QuantumInstance(Aer.get_backend('statevector_simulator'))
qi_qasm = QuantumInstance(Aer.get_backend('qasm_simulator'), shots=1000)
from qiskit_machine_learning.neural_networks import OpflowQNN
# 演算子の定義
params1 = [Parameter('input1'), Parameter('weight1')]
qc1 = QuantumCircuit(1)
qc1.h(0)
qc1.ry(params1[0], 0)
qc1.rx(params1[1], 0)
qc_sfn1 = StateFn(qc1)
H1 = StateFn(PauliSumOp.from_list([('Z', 1.0), ('X', 1.0)]))
op1 = ~H1 @ qc_sfn1
qc1.draw('mpl')
qnn1 = OpflowQNN(op1, [params1[0]], [params1[1]], expval, gradient, qi_sv)
input1 = np.random.rand(qnn1.num_inputs)
weight1 = np.random.rand(qnn1.num_weights)
qnn1.forward(input1, weight1)
# 順伝播計算は演算子の期待値を出力していることを確認
from qiskit.opflow.converters import CircuitSampler
param_dict = dict(zip(params1, [input1[0], weight1[0]]))
op1_binded = op1.assign_parameters(param_dict)
expectation = expval.convert(op1_binded)
sampler = CircuitSampler(qi_qasm).convert(expectation)
sampler.eval().real
# output: input gradiend, weight gradient
qnn1.backward(input1, weight1)
# 逆伝播計算は演算子の期待値関数の入力と重みに対する微分計算であることを確認
state_grad = Gradient(grad_method="param_shift").convert(operator=op1, params=params1)
result = state_grad.assign_parameters(param_dict).eval()
np.array(result).real
from qiskit_machine_learning.neural_networks import TwoLayerQNN
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier
num_inputs = 2
num_samples = 20
X = 2*np.random.rand(num_samples, num_inputs) - 1 # num_sample x num_inpuutsの配列
y01 = 1*(np.sum(X, axis=1) >= 0) # in { 0, 1}
y = 2*y01-1 # in {-1, +1}
y_one_hot = np.zeros((num_samples, 2))
for i in range(num_samples):
y_one_hot[i, y01[i]] = 1
for x, y_target in zip(X, y):
if y_target == 1:
plt.plot(x[0], x[1], 'bo')
else:
plt.plot(x[0], x[1], 'go')
plt.plot([-1, 1], [1, -1], '--', color='black')
plt.show()
# default observable: Z^n
opflow_qnn = TwoLayerQNN(num_inputs, quantum_instance=qi_qasm)
opflow_classifier = NeuralNetworkClassifier(opflow_qnn, optimizer=COBYLA())
# QNNを構成している量子回路を確認する
opflow_qnn.circuit.draw('mpl')
opflow_qnn.feature_map.draw('mpl')
opflow_qnn.ansatz.draw('mpl')
opflow_classifier.fit(X, y)
opflow_classifier.score(X, y)
# 評価用のデータを生成
num_samples_test = 100
X_test = 2*np.random.rand(num_samples_test, num_inputs) - 1 # num_sample x num_inpuutsの配列
y01_test = 1*(np.sum(X_test, axis=1) >= 0) # in { 0, 1}
y_test = 2*y01_test-1 # in {-1, +1}
# plot results
def plot_predict_result(X_test, y_test, y_predict):
for x, y_target, y_p in zip(X_test, y_test, y_predict):
if y_p == 1:
plt.plot(x[0], x[1], 'bo')
else:
plt.plot(x[0], x[1], 'go')
if y_target != y_p:
plt.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2)
plt.plot([-1, 1], [1, -1], '--', color='black')
plt.show()
# evaluate data points
y_predict = opflow_classifier.predict(X_test)
plot_predict_result(X_test, y_test, y_predict)
num_samples = 200
X2 = 2*np.random.rand(num_samples, num_inputs) - 1 # num_sample x num_inpuutsの配列
y01_2 = 1*(np.sum(X2, axis=1) >= 0) # in { 0, 1}
y2 = 2*y01_2-1 # in {-1, +1}
opflow_classifier.fit(X2, y2)
opflow_classifier.score(X2, y2)
# evaluate data points
y_predict = opflow_classifier.predict(X_test)
plot_predict_result(X_test, y_test, y_predict)
params2 = [Parameter('test1'), Parameter('test2')]
simple_feature_map = QuantumCircuit(num_inputs)
for i in range(num_inputs):
simple_feature_map.ry(params2[i], [i])
opflow_qnn2= TwoLayerQNN(num_inputs, feature_map=simple_feature_map, quantum_instance=qi_qasm)
opflow_classifier2 = NeuralNetworkClassifier(opflow_qnn2, optimizer=COBYLA())
opflow_classifier2.fit(X, y)
opflow_classifier2.score(X, y)
# evaluate data points
y_predict2 = opflow_classifier2.predict(X_test)
# plot results
plot_predict_result(X_test, y_test, y_predict2)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
2*acos(sqrt(2/3)), 2*asin(sqrt(1/3)).
cos(2*pi/3), sin(2*pi/3), cos(4*pi/3), sin(4*pi/3), cos(8*pi/3), sin(8*pi/3)
cos(2*pi/3), sin(2*pi/3), cos(4*pi/3), sin(4*pi/3), cos(8*pi/3), sin(8*pi/3)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import *
from qiskit.circuit import Gate
my_gate = Gate(name='my_gate', num_qubits=2, params=[])
qr = QuantumRegister(3, 'q')
circ = QuantumCircuit(qr)
circ.append(my_gate, [qr[0], qr[1]])
circ.append(my_gate, [qr[1], qr[2]])
circ.draw()
# Build a sub-circuit
sub_q = QuantumRegister(2)
sub_circ = QuantumCircuit(sub_q, name='sub_circ')
sub_circ.h(sub_q[0])
sub_circ.crz(1, sub_q[0], sub_q[1])
sub_circ.barrier()
sub_circ.id(sub_q[1])
sub_circ.u(1, 2, -2, sub_q[0])
# Convert to a gate and stick it into an arbitrary place in the bigger circuit
sub_inst = sub_circ.to_instruction()
qr = QuantumRegister(3, 'q')
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.cx(qr[1], qr[2])
circ.append(sub_inst, [qr[1], qr[2]])
circ.draw()
decomposed_circ = circ.decompose() # Does not modify original circuit
decomposed_circ.draw()
from qiskit.circuit import Parameter
theta = Parameter('θ')
n = 5
qc = QuantumCircuit(5, 1)
qc.h(0)
for i in range(n-1):
qc.cx(i, i+1)
qc.barrier()
qc.rz(theta, range(5))
qc.barrier()
for i in reversed(range(n-1)):
qc.cx(i, i+1)
qc.h(0)
qc.measure(0, 0)
qc.draw('mpl')
print(qc.parameters)
import numpy as np
theta_range = np.linspace(0, 2 * np.pi, 128)
circuits = [qc.bind_parameters({theta: theta_val})
for theta_val in theta_range]
circuits[-1].draw()
backend = BasicAer.get_backend('qasm_simulator')
job = backend.run(transpile(circuits, backend))
counts = job.result().get_counts()
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)
ax.plot(theta_range, list(map(lambda c: c.get('0', 0), counts)), '.-', label='0')
ax.plot(theta_range, list(map(lambda c: c.get('1', 0), counts)), '.-', label='1')
ax.set_xticks([i * np.pi / 2 for i in range(5)])
ax.set_xticklabels(['0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'], fontsize=14)
ax.set_xlabel('θ', fontsize=14)
ax.set_ylabel('Counts', fontsize=14)
ax.legend(fontsize=14)
import time
from itertools import combinations
from qiskit.compiler import assemble
from qiskit.test.mock import FakeVigo
start = time.time()
qcs = []
theta_range = np.linspace(0, 2*np.pi, 32)
for n in theta_range:
qc = QuantumCircuit(5)
for k in range(8):
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qc.rz(n, range(5))
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qcs.append(qc)
compiled_circuits = transpile(qcs, backend=FakeVigo())
qobj = assemble(compiled_circuits, backend=FakeVigo())
end = time.time()
print('Time compiling over set of bound circuits: ', end-start)
start = time.time()
qc = QuantumCircuit(5)
theta = Parameter('theta')
for k in range(8):
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qc.rz(theta, range(5))
for i,j in combinations(range(5), 2):
qc.cx(i,j)
transpiled_qc = transpile(qc, backend=FakeVigo())
qobj = assemble([transpiled_qc.bind_parameters({theta: n})
for n in theta_range], backend=FakeVigo())
end = time.time()
print('Time compiling over parameterized circuit, then binding: ', end-start)
phi = Parameter('phi')
sub_circ1 = QuantumCircuit(2, name='sc_1')
sub_circ1.rz(phi, 0)
sub_circ1.rx(phi, 1)
sub_circ2 = QuantumCircuit(2, name='sc_2')
sub_circ2.rx(phi, 0)
sub_circ2.rz(phi, 1)
qc = QuantumCircuit(4)
qr = qc.qregs[0]
qc.append(sub_circ1.to_instruction(), [qr[0], qr[1]])
qc.append(sub_circ2.to_instruction(), [qr[0], qr[1]])
qc.append(sub_circ2.to_instruction(), [qr[2], qr[3]])
print(qc.draw())
# The following raises an error: "QiskitError: 'Name conflict on adding parameter: phi'"
# phi2 = Parameter('phi')
# qc.u3(0.1, phi2, 0.3, 0)
p = Parameter('p')
qc = QuantumCircuit(3, name='oracle')
qc.rz(p, 0)
qc.cx(0, 1)
qc.rz(p, 1)
qc.cx(1, 2)
qc.rz(p, 2)
theta = Parameter('theta')
phi = Parameter('phi')
gamma = Parameter('gamma')
qr = QuantumRegister(9)
larger_qc = QuantumCircuit(qr)
larger_qc.append(qc.to_instruction({p: theta}), qr[0:3])
larger_qc.append(qc.to_instruction({p: phi}), qr[3:6])
larger_qc.append(qc.to_instruction({p: gamma}), qr[6:9])
print(larger_qc.draw())
print(larger_qc.decompose().draw())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
# TODO: This example should use a real mock backend.
backend = FakeOpenPulse3Q()
d2 = pulse.DriveChannel(2)
with pulse.build(backend) as bell_prep:
pulse.u2(0, math.pi, 0)
pulse.cx(0, 1)
with pulse.build(backend) as decoupled_bell_prep_and_measure:
# We call our bell state preparation schedule constructed above.
with pulse.align_right():
pulse.call(bell_prep)
pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2)
pulse.barrier(0, 1, 2)
registers = pulse.measure_all()
decoupled_bell_prep_and_measure.draw()
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.wrapper import available_backends, get_backend
from qiskit.wrapper import execute as q_execute
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q,c)
qc.h(q[0])
qc.h(q[1])
qc.cx(q[0], q[1])
qc.measure(q, c)
z = 0.995004165 + 1j * 0.099833417
z = z / abs(z)
u_error = np.array([[1, 0], [0, z]])
noise_params = {'U':
{'gate_time': 1,
'p_depol': 0.001,
'p_pauli': [0, 0, 0.01],
'U_error': u_error
}
}
config = {"noise_params": noise_params}
ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config)
ret = ret.result()
print(ret.get_counts())
|
https://github.com/usamisaori/quantum-expressibility-entangling-capability
|
usamisaori
|
import sys
sys.path.append('../')
from circuits import sampleCircuitA, sampleCircuitB1, sampleCircuitB2,\
sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE,\
sampleCircuitF
from entanglement import Ent
import warnings
warnings.filterwarnings('ignore')
labels = [
'Circuit A', 'Circuit B1', 'Circuit B2', 'Circuit B3',
'Circuit C', 'Circuit D', 'Circuit E', 'Circuit F'
]
samplers = [
sampleCircuitA,
sampleCircuitB1,
sampleCircuitB2,
sampleCircuitB3,
sampleCircuitC,
sampleCircuitD,
sampleCircuitE,
sampleCircuitF
]
q = 4
for layer in range(1, 4):
print(f'qubtis: {q}')
print('-' * 25)
for (label, sampler) in zip(labels, samplers):
expr = Ent(sampler, layer=layer, epoch=3000)
print(f'{label}(layer={layer}): {expr}')
print()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import Statevector
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.estimation import EuropeanCallPricing
from qiskit_finance.circuit.library import NormalDistribution
# Set upper and lower data values
bounds = np.array([0.0, 7.0])
# Set number of qubits used in the uncertainty model
num_qubits = 3
# Load the trained circuit parameters
g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225]
# Set an initial state for the generator circuit
init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds)
# construct the variational form
var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1)
# keep a list of the parameters so we can associate them to the list of numerical values
# (otherwise we need a dictionary)
theta = var_form.ordered_parameters
# compose the generator circuit, this is the circuit loading the uncertainty model
g_circuit = init_dist.compose(var_form)
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 2
# set the approximation scaling for the payoff function
c_approx = 0.25
# Evaluate trained probability distribution
values = [
bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits)
]
uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params)))
amplitudes = Statevector.from_instruction(uncertainty_model).data
x = np.array(values)
y = np.abs(amplitudes) ** 2
# Sample from target probability distribution
N = 100000
log_normal = np.random.lognormal(mean=1, sigma=1, size=N)
log_normal = np.round(log_normal)
log_normal = log_normal[log_normal <= 7]
log_normal_samples = []
for i in range(8):
log_normal_samples += [np.sum(log_normal == i)]
log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples))
# Plot distributions
plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue")
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.plot(
log_normal_samples,
"-o",
color="deepskyblue",
label="target distribution",
linewidth=4,
markersize=12,
)
plt.legend(loc="best")
plt.show()
# Evaluate payoff for different distributions
payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5])
ep = np.dot(log_normal_samples, payoff)
print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep)
ep_trained = np.dot(y, payoff)
print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained)
# Plot exact payoff function (evaluated on the grid of the trained uncertainty model)
x = np.array(values)
y_strike = np.maximum(0, x - strike_price)
plt.plot(x, y_strike, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# construct circuit for payoff function
european_call_pricing = EuropeanCallPricing(
num_qubits,
strike_price=strike_price,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=uncertainty_model,
)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_pricing.to_estimation_problem()
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % ep_trained)
print("Estimated value: \t%.4f" % (result.estimation_processed))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.visualization import plot_error_map
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
plot_error_map(backend)
|
https://github.com/7enTropy7/Shor-s-Algorithm_Quantum
|
7enTropy7
|
import numpy as np
import math
import gmpy2
from gmpy2 import powmod,mpz,isqrt,invert
from qiskit.aqua.algorithms import Shor
from qiskit.aqua import QuantumInstance
from qiskit import Aer,execute,QuantumCircuit
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.ibmq import least_busy
from qiskit import IBMQ, execute
def generate_keys():
# prime number of 3 digits i.e 7 bits
random1 = np.random.randint(3,40)
random2 = np.random.randint(3,40)
p = int(gmpy2.next_prime(random1))
q = int(gmpy2.next_prime(random2))
n = p*q
while (n<100 or n>127):
random1 = np.random.randint(3,40)
random2 = np.random.randint(3,40)
p = int(gmpy2.next_prime(random1))
q = int(gmpy2.next_prime(random2))
n = p*q
phi = (p-1)*(q-1)
e = 2
while True:
if gmpy2.gcd(phi,e) != 1:
e = e + 1
else :
break
d = gmpy2.invert(e,phi)
return n,e,d
def encrypt(plain_text_blocks,public_keys):
cipher_text_blocks = []
n,e = public_keys
for plain_text in plain_text_blocks:
cipher_text = (gmpy2.powmod(plain_text,e,n))
cipher_text_blocks.append(cipher_text)
return cipher_text_blocks
def decrypt(cipher_text_blocks,secret_key,public_keys):
n,e = public_keys
d = secret_key
decypted_plain_text_blocks = []
for cipher_text in cipher_text_blocks:
plain_text = (gmpy2.powmod(cipher_text,d,n))
decypted_plain_text_blocks.append(plain_text)
return decypted_plain_text_blocks
def get_factors(public_keys):
n,e = public_keys
# backend = Aer.get_backend('qasm_simulator')
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_qasm_simulator')
quantum_instance = QuantumInstance(backend,shots=2500)
find_factors = Shor(n,a=2,quantum_instance=quantum_instance)
factors = Shor.run(find_factors)
p = ((factors['factors'])[0])[0]
q = ((factors['factors'])[0])[1]
print('Factors of',n,'are :',p,q)
return p,q
# taken in 'Hello World!!!' returns ['Hello World!','!!']
def get_blocks(PT,block_size):
blocks = []
i = 0
while i<len(PT):
temp_str=''
if i+block_size-1 < len(PT):
temp_str=temp_str+PT[i:i+block_size]
else :
temp_str=temp_str+PT[i::]
blocks.append(temp_str)
i=i+block_size
return blocks
# covert plain_text block from characters to the numbers
def format_plain_text(PT):
plain_text_blocks = []
for block in PT:
plain_text = 0
for i in range(len(block)):
# for 'd'
if ord(block[i]) == 100:
plain_text = plain_text*100 + 28
# between (101,127)
elif ord(block[i])>100:
plain_text = plain_text*100 + (ord(block[i])-100)
else :
plain_text = plain_text*100 + (ord(block[i]))
plain_text_blocks.append(plain_text)
return plain_text_blocks
# convert numeric decypted_plain_text_blocks into a single plain text of characters
def format_decrypted_plain_text(decypted_plain_text_blocks):
plain_text_blocks = []
for dc_pt in decypted_plain_text_blocks:
plain_text = ''
temp = dc_pt
# for 'd' temp = 28
while temp > 0:
if temp%100 == 28:
plain_text = plain_text + 'd'
elif (temp%100) in range(0,27):
plain_text = plain_text + chr((temp%100)+100)
else :
plain_text = plain_text + chr((temp%100))
temp = temp//100
plain_text = plain_text[::-1]
plain_text_blocks.append(plain_text)
final_plain_text = ''
for plain_text_block in plain_text_blocks:
final_plain_text = final_plain_text + plain_text_block
return final_plain_text
n,e,d = generate_keys()
public_keys = (n,e)
secret_key = d
print("\nPublic Key :")
print('n :',n)
print('e :',e)
print("Secret Key :\nd :",d)
PT = input("\nEnter Plain Text to encrypt : ")
original_plain_text = PT
block_size = 1
PT = get_blocks(PT,block_size)
print('\nPlain Text after converting to blocks',PT)
plain_text_blocks = format_plain_text(PT)
print('\nPlain text blocks after formatting to numbers:',plain_text_blocks)
cipher_text_blocks = encrypt(plain_text_blocks,public_keys)
print("\nCipher Text Blocks After RSA encryption :",cipher_text_blocks)
p,q = get_factors(public_keys)
phi = (p-1)*(q-1)
broken_d = gmpy2.invert(e,phi)
compromised_PT = decrypt(cipher_text_blocks,broken_d,public_keys)
compromised_PT = format_decrypted_plain_text(compromised_PT)
compromised_PT = '!!!Your message has been attacked!!! ' + compromised_PT
compromised_PT = get_blocks(compromised_PT,block_size)
compromised_PT = format_plain_text(compromised_PT)
compromised_CT = encrypt(compromised_PT,public_keys)
cipher_text_blocks = compromised_CT
decypted_plain_text_blocks = decrypt(cipher_text_blocks,secret_key,public_keys)
print("\nPlain Text blocks after decryption of Cipher Text blocks :",decypted_plain_text_blocks)
plain_text_after_decryption = format_decrypted_plain_text(decypted_plain_text_blocks)
print("\nAfter decryption Plain Text :",plain_text_after_decryption)
if (original_plain_text == plain_text_after_decryption):
print("\nHurrayyy!!!\n\nDecrypted plain_text is same as original plain_text! :) ")
else :
print('RSA was attacked!!! :(')
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
### removed z gate ###
pass
return qc
def decode_message(qc):
### removed cx gate ###
qc.h(1)
return qc
|
https://github.com/devilkiller-ag/UnravelQuantum
|
devilkiller-ag
|
# ########## Import Initialization ############
from qiskit import QuantumCircuit, transpile
from qiskit.providers.basic_provider import BasicProvider
from qiskit_aer import AerSimulator
from qiskit.visualization import plot_histogram, circuit_drawer
from qiskit_ibm_provider.job import job_monitor
from qiskit_ibm_provider import IBMProvider
import streamlit as st
import matplotlib.pyplot as plt
from random import choice
# #############################################
# ########## Bernstien Vazirani Algorithm ##########
def generate_secret_bitstring(n):
return "".join(choice("01") for _ in range(n))
# Oracle to implement bitstring multiplication with input state
def BVOracle(n, s=""):
oracle = QuantumCircuit(n + 1)
s = s or generate_secret_bitstring(n) # the hidden binary string
# print(s)
index = n - 1
for q in s:
if q == "1":
oracle.cx(index, n)
index -= 1
return oracle
def BernsteinVaziraniAlgo(n, bv_oracle):
# We need a circuit with n qubits, plus one ancilla qubit
# Also we need n classical bits to write the output
bv_circuit = QuantumCircuit(n + 1, n)
# Apply Hadamard gates before querying the oracle
for i in range(n):
bv_circuit.h(i)
# Put Ancilla Qubit in state |->
bv_circuit.x(n)
bv_circuit.h(n)
# Apply barrier
bv_circuit.barrier()
bv_circuit = bv_circuit.compose(bv_oracle)
# Apply barrier
bv_circuit.barrier()
# Apply Hadamard gates before querying the oracle
for i in range(n):
bv_circuit.h(i)
# Apply Measurement
for i in range(n):
bv_circuit.measure(i, i)
return bv_circuit
def RunCircuit(circuit, provider, backend_name, shots=1024):
backend = provider.get_backend(backend_name)
transpiled_circuit = transpile(circuit, backend=backend)
job = backend.run(transpiled_circuit, shots=shots)
results = job.result()
counts = results.get_counts()
job_monitor(job)
job.status()
return counts
def run_on_simulator(circuit, provider, backend):
answer = RunCircuit(circuit, provider, backend, shots=1024)
st.subheader("Result Counts:")
st.write(answer) # Display result counts as text
st.subheader("Histogram:")
fig, ax = plt.subplots() # Create a Matplotlib figure and axes
plot_histogram(answer, ax=ax) # Pass the axes to the plot_histogram function
st.pyplot(fig) # Display the Matplotlib figure using st.pyplot
def run_on_real_backend(circuit, provider_api_key, backend):
IBMProvider.save_account(provider_api_key, overwrite=True)
provider = IBMProvider()
# backend = 'ibm_perth'
answer = RunCircuit(circuit, provider, backend, shots=1024)
st.subheader("Result Counts:")
st.write(answer) # Display result counts as text
st.subheader("Histogram:")
fig, ax = plt.subplots() # Create a Matplotlib figure and axes
plot_histogram(answer, ax=ax) # Pass the axes to the plot_histogram function
st.pyplot(fig) # Display the Matplotlib figure using st.pyplot
# ########## Use the DJ Algorithm ##########
# Page Config
st.set_page_config(
page_title="Bernstein Vazirani Algorithm - Unravel Quantum",
page_icon="⚔️",
layout="wide",
)
st.title("Bernstein Vazirani Algorithm")
# n = st.slider("Select the number of qubits (n)", 1, 10, 3)
s = "" # secret binary string
header = st.columns([1])
header[0].write("**Number of qubits**")
input = st.columns([1])
n = input[0].slider(
"Select the number of qubits (n)", 1, 10, 3, label_visibility="hidden"
)
st.write(f"Selected number of qubits: {n}")
header2 = st.columns([1])
header2[0].write("**Secret Bitstring**")
input2 = st.columns([1, 1])
radio_choice = input2[0].radio(
"Secret Bitstring",
["Generate Random Secret Bitstring", "Enter Your Own Secret Bitstring Here"],
label_visibility="hidden",
)
if radio_choice == "Enter Your Own Secret Bitstring Here":
s = input2[1].text_input(
label="Create Your Own Secret Bitstring",
placeholder="Enter Your Own Secret Bitstring Here",
label_visibility="hidden",
disabled=(radio_choice == "Generate Random Secret Bitstring"),
)
s = s or generate_secret_bitstring(n)
bv_oracle = BVOracle(n, s)
bv_circuit = BernsteinVaziraniAlgo(n, bv_oracle)
st.write("**Circuit**")
fig, ax = plt.subplots()
circuit_drawer(bv_circuit, output='mpl', ax=ax) # Display the circuit using Matplotlib
st.pyplot(fig) # Show the Matplotlib figure in Streamlit
# providers = {"BasicAer": BasicProvider, "AerSimulator": AerSimulator}
providers = {"BasicAer": BasicProvider}
selected_provider = st.selectbox("Select Provider", list(providers.keys()))
backends = providers[selected_provider]().backends()
selected_backend = st.selectbox("Select Backend", list(backends))
if st.button("Run on Simulator"):
st.write("Secret Bitstring: ", s)
if selected_provider in providers:
run_on_simulator(bv_circuit, providers[selected_provider], str(selected_backend))
# provider_api_key = st.text_input("Enter your IBM Quantum Experience API Key (for real backend)")
# if st.button("Run on Real Backend") and provider_api_key:
# backends = IBMProvider.backends()
# selected_backend = st.selectbox("Select Backend", list(backends))
# run_on_real_backend(bv_circuit, provider_api_key, selected_backend)
# ################################### Show the Implementation #########################################
bv_algo_code = """
# Importing libraries
from qiskit import QuantumCircuit, transpile
from qiskit.providers.basic_provider import BasicProvider
from qiskit_aer import AerSimulator
from qiskit.visualization import plot_histogram, circuit_drawer
from qiskit_ibm_provider.job import job_monitor
from qiskit_ibm_provider import IBMProvider
from random import choice
def generate_secret_bitstring(n):
return ''.join(choice('01') for _ in range(n))
# Oracle to implement bitstring multiplication with input state
def BVOracle(n, s=''):
oracle = QuantumCircuit(n+1)
s = s if s else generate_secret_bitstring(n) # the hidden binary string
# print(s)
index = n-1
for q in s:
if q == '1':
oracle.cx(index, n)
index-=1
return oracle
def BernsteinVaziraniAlgo(n, bv_oracle):
# We need a circuit with n qubits, plus one ancilla qubit
# Also we need n classical bits to write the output
bv_circuit = QuantumCircuit(n+1, n)
# Apply Hadamard gates before querying the oracle
for i in range(n):
bv_circuit.h(i)
# Put Ancilla Qubit in state |->
bv_circuit.x(n)
bv_circuit.h(n)
# Apply barrier
bv_circuit.barrier()
bv_circuit = bv_circuit.compose(bv_oracle)
# Apply barrier
bv_circuit.barrier()
# Apply Hadamard gates before querying the oracle
for i in range(n):
bv_circuit.h(i)
# Apply Measurement
for i in range(n):
bv_circuit.measure(i, i)
return bv_circuit
def RunCircuit(circuit, provider, backend_name, shots=1024):
backend = provider.get_backend(backend_name)
transpiled_circuit = transpile(circuit, backend=backend)
job = backend.run(transpiled_circuit, shots=shots)
results = job.result()
counts = results.get_counts()
job_monitor(job)
job.status()
return counts
def run_on_simulator(circuit, provider, backend, shots=1024):
answer = RunCircuit(circuit, provider, backend, shots)
plot_histogram(answer)
return answer
def run_on_real_backend(circuit, provider_api_key, backend, shots=1024):
IBMProvider.save_account(provider_api_key, overwrite=True)
provider = IBMProvider()
answer = RunCircuit(circuit, provider, backend, shots)
plot_histogram(answer)
return answer
n = 3 # number of qubits used to represent s
bv_oracle = BVOracle(n, s='110')
bv_circuit = BernsteinVaziraniAlgo(n, bv_oracle)
bv_circuit.draw('mpl')
# Run on the simulator
provider = BasicProvider
backend = 'qasm_simulator'
run_on_simulator(bv_circuit, provider, backend, shots=1024)
# Run on the real backend
# provider_api_key = # your provider api key
backend = 'ibm_perth'
# run_on_real_backend(bv_circuit, provider_api_key, backend, shots=1024)
"""
st.subheader("Implementation of Bernstein Vazirani Algorithm")
st.write(
"""
Reference:
- [Bernstein Vazirani Algorithm - Q-munity](https://www.qmunity.tech/tutorials/bernstein-vazirani-algorithm)
"""
)
st.code(bv_algo_code, language="python")
# ################################### About the author #########################################
st.subheader("About the author: [Ashmit JaiSarita Gupta](https://jaisarita.vercel.app/)")
st.write("""
[Ashmit JaiSarita Gupta](https://jaisarita.vercel.app/) is an engineering physics undergraduate passionate about Quantum Computing, Machine Learning, UI/UX, and Web Development. I am a student driven by the community and who shares what he has learned. I love to work on real world projects about the topics I learn which can be used by others. To accomplish this I frequently attend hackathons and collaborate with companies to work on real-world projects related to my domains. Feel free to contact me if your company is interested in working on awesome projects in these fields with me. I’m currently building most frequently with: JavaScript/Typescript, C++, and Python.Some of the main frameworks and libraries I frequently use are: React.js,Express.js, Tailwind CSS, ShadCN UI, Qiskit,and Pytorch. Explore the below links to explore more about him, his previous projects, blogs, and experience at various organizations.
""")
# ############ Socials ############
c1, c2, c3 = st.columns(3)
with c1:
st.info('**Portfolio: [Ashmit JaiSarita Gupta](https://jaisarita.vercel.app/)**', icon="🔥")
with c2:
st.info('**GitHub: [@devilkiller-ag](https://github.com/devilkiller-ag)**', icon="😸")
with c3:
st.info('**GitLab: [@devilkiller-ag](https://gitlab.com/devilkiller-ag)**', icon="🚀")
c4, c5, c6 = st.columns(3)
with c4:
st.info('**LinkedIn: [jaisarita](https://www.linkedin.com/in/jaisarita/)**', icon="🌐")
with c5:
st.info('**Twitter: [@jaisarita](https://github.com/devilkiller-ag)**', icon="🐤")
with c6:
st.info('**Hashnode: [jaisarita](https://jaisarita.hashnode.dev/)**', icon="✍🏻")
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/abbarreto/qiskit3
|
abbarreto
| |
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution()
plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5))
plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5))
G
labels = nx.get_edge_attributes(G,'weight')
labels
import json
# Array of JSON Objects
products = [{"name": "HDD", "brand": "Samsung", "price": "$100"},
{"name": "Monitor", "brand": "Dell", "price": "$120"},
{"name": "Mouse", "brand": "Logitech", "price": "$10"}]
# Print the original data
print("The original JSON data:\n{0}".format(products))
# Sort the JSON data based on the value of the brand key
products.sort(key=lambda x: x["price"])
# Print the sorted JSON data
print("The sorted JSON data based on the value of the brand:\n{0}".format(products))
_LAMBDA
UNIFORM_CONVERGENCE_SAMPLE
import json
# Array of JSON Objects
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
# Print the sorted JSON data
UNIFORM_CONVERGENCE_SAMPLE
np.max(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - UNIFORM_CONVERGENCE_SAMPLE[220]["probabilities"])
# generamos las distancias entre para la convergencia uniforme
index = -1
for sample in UNIFORM_CONVERGENCE_SAMPLE:
mean = sample["mean"]
index += 1
distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"]))
UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state
UNIFORM_CONVERGENCE_SAMPLE
import csv
header = ['iteration', 'state', 'probability', 'mean']
header_q = ['iteration', 'distance']
with open('qaoa_cu.csv', 'w', encoding='UTF8') as f:
with open('qaoa_distance.csv', 'w', encoding='UTF8') as q:
writer = csv.writer(f)
writer_q = csv.writer(q)
# write the header
writer.writerow(header)
writer_q.writerow(header_q)
iteration = 0
for sample in UNIFORM_CONVERGENCE_SAMPLE:
iteration += 1
mean = sample["mean"]
distance = sample["distance_pgs"]
state = 0
for probability in sample["probabilities"]:
state += 1
# write the data
data = [iteration, state, probability, mean]
writer.writerow(data)
writer_q.writerow([iteration, distance])
#plot_histogram(job_2, color='midnightblue', title=str(mean), figsize=(30, 5)).savefig(str(contador) + "_2.png")
#print(sample["mean"])
plot_histogram(job_2, color='midnightblue', title="New Histogram", figsize=(30, 5)).savefig('out.png')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/renatawong/quantum-maxcut
|
renatawong
|
'''
(C) Renata Wong (NCTS-NTU) 2023
This is the accompanying code for the paper "Quantum speedup for the maximum cut problem"
for the example graph given in Fig. 1.
Note: It is impossible to execute it for graphs with more than 2 edges as the number of qubits exceeds the simulator limit.
'''
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import numpy as np
'''
Create the quantum circuit for the 3-vertex example
num_vertices = n = number of vertices
num_enges = m = number of edges
'''
'''
PLEASE FILL IN THE EDGE LIST FOR YOUR GRAPH IN THE LINE BELOW
'''
permanent_edge_list = [[0,1], [1,2]]
num_vertices = len({x for l in permanent_edge_list for x in l})
num_edges = len(permanent_edge_list)
range_z = (((num_edges + 1) * (num_edges + 2)) / 2) - 1
range_r = 4 * (num_edges * (num_edges + 1)) / 2
range_s = 2 * (num_edges * (num_edges + 1)) / 2
aux = QuantumRegister(1, 'aux')
z_reg = QuantumRegister(range_z, 'z_reg')
s_reg = QuantumRegister(range_s, 's_reg')
r_reg = QuantumRegister(range_r, 'r_reg')
x_reg = QuantumRegister(num_vertices, 'x_reg')
readout = ClassicalRegister(num_vertices, 'out')
qc = QuantumCircuit(aux, x_reg, r_reg, s_reg, z_reg, readout)
qc.x(aux)
qc.h(aux)
# Print this variable to see the system size
system_size = qc.num_qubits
'''
Create z_matrix to store elements of z_reg
'''
z_matrix = [ [ 0 for i in range(num_edges + 1) ] for j in range(num_edges + 1) ]
zij = 0
for i in range(1, num_edges + 1):
for j in range(i + 1):
z_matrix[i][j] = zij
zij += 1
'''
Define the CFE subcircuit
'''
sq = QuantumRegister(10,'sq')
sc = QuantumCircuit(sq, name='CFE')
# EIIAC
sc.x(sq[1])
sc.ccx(sq[0], sq[1], sq[2])
sc.x(sq[0])
sc.x(sq[1])
sc.ccx(sq[0], sq[1], sq[3])
sc.x(sq[0])
sc.x(sq[2])
sc.x(sq[3])
sc.ccx(sq[2], sq[3], sq[6])
sc.x(sq[2])
sc.x(sq[3])
# EINIAC
sc.x(sq[0])
sc.x(sq[1])
sc.ccx(sq[0], sq[1], sq[4])
sc.x(sq[0])
sc.x(sq[1])
sc.ccx(sq[0], sq[1], sq[5])
sc.x(sq[4])
sc.x(sq[5])
sc.ccx(sq[4], sq[5], sq[7])
sc.x(sq[4])
sc.x(sq[5])
# CNOTS
sc.cx(sq[6], sq[9])
sc.cx(sq[7], sq[8])
cfe = sc.to_instruction()
'''
Define the CSE subcircuit
'''
cq = QuantumRegister(11,'cq')
ce = QuantumCircuit(cq, name='CSE')
# EIIAC
ce.x(cq[1])
ce.ccx(cq[0], cq[1], cq[2])
ce.x(cq[0])
ce.x(cq[1])
ce.ccx(cq[0], cq[1], cq[3])
ce.x(cq[0])
ce.x(cq[2])
ce.x(cq[3])
ce.ccx(cq[2], cq[3], cq[6])
ce.x(cq[2])
ce.x(cq[3])
# EINIAC
ce.x(cq[0])
ce.x(cq[1])
ce.ccx(cq[0], cq[1], cq[4])
ce.x(cq[0])
ce.x(cq[1])
ce.ccx(cq[0], cq[1], cq[5])
ce.x(cq[4])
ce.x(cq[5])
ce.ccx(cq[4], cq[5], cq[7])
ce.x(cq[4])
ce.x(cq[5])
# CNOTS
ce.ccx(cq[6], cq[8], cq[9])
ce.ccx(cq[7], cq[8], cq[10])
cse = ce.to_instruction()
'''
Initialize the system and set it in a uniform superpostion -> lines 1 and 2 of Algorithm 1 in paper
'''
for qubit in s_reg:
qc.x(qubit)
for qubit in x_reg:
qc.h(qubit)
qc.barrier()
'''
NOTE: There will always be an even number of solutions, since under maximum cut 101 is the same as 010.
For Fig. 1 in the paper, we set the number of solutions to 2.
YOU MAY NEED TO ADJUST THE NUMBER OF SOLUTIONS.
'''
num_solutions = 2
num_runs = int(np.ceil(np.pi * np.sqrt((2**num_vertices) / num_solutions)) / 4)
'''
Amplitude amplification
'''
for run in range(num_runs):
# Apply CFE to |psi_1> -> line 3 in Algorithm 1
# It is assumed that the two vertices in the x_reg share an edge
r = 4
s = 2
edge_list = permanent_edge_list.copy()
if len(edge_list) > 0:
index_v1 = edge_list[0][0]
index_v2 = edge_list[0][1]
edge_list.pop(0)
cfe_qubits = []
cfe_qubits += [x_reg[index_v1]]
cfe_qubits += [x_reg[index_v2]]
cfe_qubits += [r_reg[i] for i in range(4)]
cfe_qubits += [s_reg[i] for i in range(2)]
cfe_qubits += [z_reg[i] for i in range(2)]
qc.append(cfe, cfe_qubits)
# Apply CSE to |psi_2> --> line 4 in Algorithm 1
# It is assumed that the two vertices in the x_reg share an edge
for i in range(1, num_edges):
index_v1 = edge_list[0][0]
index_v2 = edge_list[0][1]
cse_qubits = []
for j in reversed(range(i+1)):
cse_qubits += [x_reg[index_v1]]
cse_qubits += [x_reg[index_v2]]
cse_qubits += [r_reg[i] for i in range(r, r+4)]
cse_qubits += [s_reg[i] for i in range(s, s+2)]
cse_qubits += [z_reg[z_matrix[i][j]]]
cse_qubits += [z_reg[z_matrix[i+1][j+1]]]
cse_qubits += [z_reg[z_matrix[i+1][j]]]
qc.append(cse, cse_qubits)
cse_qubits.clear()
r += 4
s += 2
edge_list.pop(0)
'''
Which qubit of register z_reg is used here depends on how many edges are there in the cut.
For the example in Fig. 1 we expect 2 edges, and therefore we choose qubit 2 (counting from 0, 1, 2, etc.).
This qubit should be in the state 1.
YOU MAY NEED TO ADJUST THE CONTROL QUBIT IN THE CX GATE.
'''
qc.barrier()
qc.cx(z_reg[len(z_reg)-1], aux)
qc.barrier()
'''
Uncompute CSE and CFE operations
'''
edge_list = permanent_edge_list.copy()
for i in reversed(range(1, num_edges)):
index_v1 = edge_list[len(edge_list) - 1][0]
index_v2 = edge_list[len(edge_list) - 1][1]
cse_qubits = []
for j in range(i+1):
r -= 4
s -= 2
cse_qubits += [x_reg[index_v1]]
cse_qubits += [x_reg[index_v2]]
cse_qubits += [r_reg[i] for i in range(r, r+4)]
cse_qubits += [s_reg[i] for i in range(s, s+2)]
cse_qubits += [z_reg[z_matrix[i][j]]]
cse_qubits += [z_reg[z_matrix[i+1][j+1]]]
cse_qubits += [z_reg[z_matrix[i+1][j]]]
qc.append(cse.inverse(), cse_qubits)
cse_qubits.clear()
edge_list.pop(0)
edge_list = [permanent_edge_list[0]]
if len(edge_list) > 0:
index_v1 = edge_list[0][0]
index_v2 = edge_list[0][1]
cfe_qubits = []
cfe_qubits += [x_reg[index_v1]]
cfe_qubits += [x_reg[index_v2]]
cfe_qubits += [r_reg[i] for i in range(4)]
cfe_qubits += [s_reg[i] for i in range(2)]
cfe_qubits += [z_reg[i] for i in range(2)]
qc.append(cfe.inverse(), cfe_qubits)
edge_list.pop()
'''
Diffusion operations
'''
qc.barrier()
for qubit in x_reg:
qc.h(qubit)
qc.x(qubit)
# apply CZ to x_reg
qc.h(x_reg[len(x_reg) - 1])
multiplexer = [x_reg[i] for i in range(len(x_reg) - 1)]
qc.mcx(multiplexer, x_reg[len(x_reg) - 1])
qc.h(x_reg[len(x_reg) - 1])
for qubit in x_reg:
qc.x(qubit)
qc.h(qubit)
qc.barrier()
'''
Measurement
'''
cuts = []
for i in range(len(x_reg)):
cuts.append(x_reg[i])
# Reverse the order in which the output is shown so that it can be read from left to right.
cuts.reverse()
qc.measure(cuts, readout)
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 100).result()
counts = result.get_counts()
print(counts)
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
import cirq
import numpy as np
from qiskit import QuantumCircuit, execute, Aer
import seaborn as sns
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (15,10)
q0, q1, q2 = [cirq.LineQubit(i) for i in range(3)]
circuit = cirq.Circuit()
#entagling the 2 quibits in different laboratories
#and preparing the qubit to send
circuit.append(cirq.H(q0))
circuit.append(cirq.H(q1))
circuit.append(cirq.CNOT(q1, q2))
#entangling the qubit we want to send to the one in the first laboratory
circuit.append(cirq.CNOT(q0, q1))
circuit.append(cirq.H(q0))
#measurements
circuit.append(cirq.measure(q0, q1))
#last transformations to obtain the qubit information
circuit.append(cirq.CNOT(q1, q2))
circuit.append(cirq.CZ(q0, q2))
#measure of the qubit in the receiving laboratory along z axis
circuit.append(cirq.measure(q2, key = 'Z'))
circuit
#starting simulation
sim = cirq.Simulator()
results = sim.run(circuit, repetitions=100)
sns.histplot(results.measurements['Z'], discrete = True)
100 - np.count_nonzero(results.measurements['Z']), np.count_nonzero(results.measurements['Z'])
#in qiskit the qubits are integrated in the circuit
qc = QuantumCircuit(3, 1)
#entangling
qc.h(0)
qc.h(1)
qc.cx(1, 2)
qc.cx(0, 1)
#setting for measurment
qc.h(0)
qc.measure([0,1], [0,0])
#transformation to obtain qubit sent
qc.cx(1, 2)
qc.cz(0, 2)
qc.measure(2, 0)
print(qc)
#simulation
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, simulator, shots=100)
res = job.result().get_counts(qc)
plt.bar(res.keys(), res.values())
res
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
circ.draw('mpl')
from qiskit.quantum_info import Statevector
# Set the intial state of the simulator to the ground state using from_int
state = Statevector.from_int(0, 2**3)
# Evolve the state by the quantum circuit
state = state.evolve(circ)
#draw using latex
state.draw('latex')
from qiskit.visualization import array_to_latex
#Alternative way of representing in latex
array_to_latex(state)
state.draw('qsphere')
state.draw('hinton')
from qiskit.quantum_info import Operator
U = Operator(circ)
# Show the results
U.data
# Create a Quantum Circuit
meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
# map the quantum measurement to the classical bits
meas.measure(range(3), range(3))
# The Qiskit circuit object supports composition.
# Here the meas has to be first and front=True (putting it before)
# as compose must put a smaller circuit into a larger one.
qc = meas.compose(circ, range(3), front=True)
#drawing the circuit
qc.draw('mpl')
# Adding the transpiler to reduce the circuit to QASM instructions
# supported by the backend
from qiskit import transpile
# Use AerSimulator
from qiskit_aer import AerSimulator
backend = AerSimulator()
# First we have to transpile the quantum circuit
# to the low-level QASM instructions used by the
# backend
qc_compiled = transpile(qc, backend)
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = backend.run(qc_compiled, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc_compiled)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/dlyongemallo/qiskit-zx-transpiler
|
dlyongemallo
|
from qiskit.circuit import QuantumCircuit
from qiskit.converters import circuit_to_dag
from qiskit.visualization import dag_drawer
import numpy as np
# Taken from https://github.com/Quantomatic/pyzx/blob/master/circuits/Fast/mod5_4_before
qc = QuantumCircuit(5)
qc.x(4)
qc.h(4)
qc.ccz(0, 3, 4)
qc.ccz(2, 3, 4)
qc.h(4)
qc.cx(3, 4)
qc.h(4)
qc.ccz(1, 2, 4)
qc.h(4)
qc.cx(2, 4)
qc.h(4)
qc.ccz(0, 1, 4)
qc.h(4)
qc.cx(1, 4)
qc.cx(0, 4)
qc.draw(output='mpl', style='clifford')
dag = circuit_to_dag(qc)
dag_drawer(dag)
from qiskit.transpiler import PassManager
from zxpass import ZXPass
zxpass = ZXPass()
pass_manager = PassManager(zxpass)
zx_qc = pass_manager.run(qc)
zx_qc.draw(output='mpl', style='clifford')
from qiskit import transpile
opt_qc = transpile(qc, basis_gates=['u3', 'cx'], optimization_level=3)
opt_qc.draw(output='mpl', style='clifford')
from qiskit.quantum_info import Statevector
print("original circuit depth: ", qc.depth())
print("transpiled circuit depth: ", opt_qc.depth())
print("PyZX circuit depth: ", zx_qc.depth())
print(Statevector.from_instruction(qc).equiv(Statevector.from_instruction(zx_qc)))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import torch
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123456
_ = torch.manual_seed(123456) # suppress output
import numpy as np
num_dim = 2
num_discrete_values = 8
num_qubits = num_dim * int(np.log2(num_discrete_values))
from scipy.stats import multivariate_normal
coords = np.linspace(-2, 2, num_discrete_values)
rv = multivariate_normal(mean=[0.0, 0.0], cov=[[1, 0], [0, 1]], seed=algorithm_globals.random_seed)
grid_elements = np.transpose([np.tile(coords, len(coords)), np.repeat(coords, len(coords))])
prob_data = rv.pdf(grid_elements)
prob_data = prob_data / np.sum(prob_data)
import matplotlib.pyplot as plt
from matplotlib import cm
mesh_x, mesh_y = np.meshgrid(coords, coords)
grid_shape = (num_discrete_values, num_discrete_values)
fig, ax = plt.subplots(figsize=(9, 9), subplot_kw={"projection": "3d"})
prob_grid = np.reshape(prob_data, grid_shape)
surf = ax.plot_surface(mesh_x, mesh_y, prob_grid, cmap=cm.coolwarm, linewidth=0, antialiased=False)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
from qiskit import QuantumCircuit
from qiskit.circuit.library import EfficientSU2
qc = QuantumCircuit(num_qubits)
qc.h(qc.qubits)
ansatz = EfficientSU2(num_qubits, reps=6)
qc.compose(ansatz, inplace=True)
qc.decompose().draw("mpl")
qc.num_parameters
from qiskit.primitives import Sampler
shots = 10000
sampler = Sampler(options={"shots": shots, "seed": algorithm_globals.random_seed})
from qiskit_machine_learning.connectors import TorchConnector
from qiskit_machine_learning.neural_networks import SamplerQNN
def create_generator() -> TorchConnector:
qnn = SamplerQNN(
circuit=qc,
sampler=sampler,
input_params=[],
weight_params=qc.parameters,
sparse=False,
)
initial_weights = algorithm_globals.random.random(qc.num_parameters)
return TorchConnector(qnn, initial_weights)
from torch import nn
class Discriminator(nn.Module):
def __init__(self, input_size):
super(Discriminator, self).__init__()
self.linear_input = nn.Linear(input_size, 20)
self.leaky_relu = nn.LeakyReLU(0.2)
self.linear20 = nn.Linear(20, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, input: torch.Tensor) -> torch.Tensor:
x = self.linear_input(input)
x = self.leaky_relu(x)
x = self.linear20(x)
x = self.sigmoid(x)
return x
generator = create_generator()
discriminator = Discriminator(num_dim)
def adversarial_loss(input, target, w):
bce_loss = target * torch.log(input) + (1 - target) * torch.log(1 - input)
weighted_loss = w * bce_loss
total_loss = -torch.sum(weighted_loss)
return total_loss
from torch.optim import Adam
lr = 0.01 # learning rate
b1 = 0.7 # first momentum parameter
b2 = 0.999 # second momentum parameter
generator_optimizer = Adam(generator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005)
discriminator_optimizer = Adam(
discriminator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005
)
from IPython.display import clear_output
def plot_training_progress():
# we don't plot if we don't have enough data
if len(generator_loss_values) < 2:
return
clear_output(wait=True)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 9))
# Generator Loss
ax1.set_title("Loss")
ax1.plot(generator_loss_values, label="generator loss", color="royalblue")
ax1.plot(discriminator_loss_values, label="discriminator loss", color="magenta")
ax1.legend(loc="best")
ax1.set_xlabel("Iteration")
ax1.set_ylabel("Loss")
ax1.grid()
# Relative Entropy
ax2.set_title("Relative entropy")
ax2.plot(entropy_values)
ax2.set_xlabel("Iteration")
ax2.set_ylabel("Relative entropy")
ax2.grid()
plt.show()
import time
from scipy.stats import multivariate_normal, entropy
n_epochs = 50
num_qnn_outputs = num_discrete_values**num_dim
generator_loss_values = []
discriminator_loss_values = []
entropy_values = []
start = time.time()
for epoch in range(n_epochs):
valid = torch.ones(num_qnn_outputs, 1, dtype=torch.float)
fake = torch.zeros(num_qnn_outputs, 1, dtype=torch.float)
# Configure input
real_dist = torch.tensor(prob_data, dtype=torch.float).reshape(-1, 1)
# Configure samples
samples = torch.tensor(grid_elements, dtype=torch.float)
disc_value = discriminator(samples)
# Generate data
gen_dist = generator(torch.tensor([])).reshape(-1, 1)
# Train generator
generator_optimizer.zero_grad()
generator_loss = adversarial_loss(disc_value, valid, gen_dist)
# store for plotting
generator_loss_values.append(generator_loss.detach().item())
generator_loss.backward(retain_graph=True)
generator_optimizer.step()
# Train Discriminator
discriminator_optimizer.zero_grad()
real_loss = adversarial_loss(disc_value, valid, real_dist)
fake_loss = adversarial_loss(disc_value, fake, gen_dist.detach())
discriminator_loss = (real_loss + fake_loss) / 2
# Store for plotting
discriminator_loss_values.append(discriminator_loss.detach().item())
discriminator_loss.backward()
discriminator_optimizer.step()
entropy_value = entropy(gen_dist.detach().squeeze().numpy(), prob_data)
entropy_values.append(entropy_value)
plot_training_progress()
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} sec")
with torch.no_grad():
generated_probabilities = generator().numpy()
fig = plt.figure(figsize=(18, 9))
# Generated CDF
gen_prob_grid = np.reshape(np.cumsum(generated_probabilities), grid_shape)
ax1 = fig.add_subplot(1, 3, 1, projection="3d")
ax1.set_title("Generated CDF")
ax1.plot_surface(mesh_x, mesh_y, gen_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm)
ax1.set_zlim(-0.05, 1.05)
# Real CDF
real_prob_grid = np.reshape(np.cumsum(prob_data), grid_shape)
ax2 = fig.add_subplot(1, 3, 2, projection="3d")
ax2.set_title("True CDF")
ax2.plot_surface(mesh_x, mesh_y, real_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm)
ax2.set_zlim(-0.05, 1.05)
# Difference
ax3 = fig.add_subplot(1, 3, 3, projection="3d")
ax3.set_title("Difference between CDFs")
ax3.plot_surface(
mesh_x, mesh_y, real_prob_grid - gen_prob_grid, linewidth=2, antialiased=False, cmap=cm.coolwarm
)
ax3.set_zlim(-0.05, 0.1)
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Naphann/Solving-TSP-Grover
|
Naphann
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute
from qiskit.tools.visualization import plot_histogram
## oracle_initialize_part
def OR(qubit_1, qubit_2, k):
# enter qubit numbers here
""" function does the equivalent of a classical OR between qubit numbers a and b and stores the result in qubit number k """
# qc.barrier(q)
qc.x(q[qubit_1])
qc.x(q[qubit_2])
# qc.barrier(q)
qc.ccx(q[qubit_1], q[qubit_2], q[k])
qc.x(q[k])
# qc.barrier(q)
qc.x(q[qubit_1])
qc.x(q[qubit_2])
# qc.barrier(q)
def are_not_equal(a_0, b_0, k):
# enter node numbers here. For example, a is node 0, b is node 1 and c is node 2
""" function outputs 1 if nodes a and b are not the same. Node numbering starts from 0
as in the problem statement. k is the qubit number where the output is XOR-ed. qubit
numbering also starts from 0 """
# qc.barrier(q)
qc.cx(q[2*a_0], q[2*b_0])
qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1])
OR(2*b_0, (2*b_0)+1, k)
qc.cx(q[2*a_0], q[2*b_0])
qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1])
# qc.barrier(q)
def is_not_3(a, k):
qc.ccx(q[2*a], q[(2*a)+1], q[k])
qc.x(q[k])
def initialize_oracle_part(n):
t = 4
# qc.barrier(q)
are_not_equal(0, 1, 6) # node a and b are not equal
are_not_equal(0, 2, 7)
are_not_equal(1, 2, 8)
is_not_3(0, 11)
is_not_3(1, 12)
is_not_3(2, 13)
# qc.barrier(q)
qc.mct([q[6], q[7], q[8], q[11], q[12], q[13]], q[10],[q[9], q[14], q[15], q[16]]) # answer is stored in 10. please keep 9 a clean qubit, it's used as ancilla here
# qc.barrier(q)
is_not_3(0, 11)
is_not_3(1, 12)
is_not_3(2, 13)
are_not_equal(0, 1, 6) # node a and b are not equal
are_not_equal(0, 2, 7)
are_not_equal(1, 2, 8)
## distance_black_box
distances = {
"32": 3,
"31": 2,
"30": 4,
"21": 7,
"20": 6,
"10": 5,
}
def dist_single():
qr = QuantumRegister(2)
qr_target = QuantumRegister(5)
qc = QuantumCircuit(qr, qr_target, name='dist_single')
for edge in distances:
if edge[0] == '3':
node = format(int(edge[1]), '02b')
d_bin = format(distances[edge], '02b')
for idx in range(len(node)):
if node[idx] == '0':
qc.x(qr[idx])
for idx in range(len(d_bin)):
if d_bin[idx] == '1':
qc.ccx(qr[0], qr[1], qr_target[idx])
for idx in range(len(node)):
if node[idx] == '0':
qc.x(qr[idx])
return qc
def dist():
qr1 = QuantumRegister(2)
qr2 = QuantumRegister(2)
qr_target = QuantumRegister(5)
qr_anc = QuantumRegister(2)
qc = QuantumCircuit(qr1, qr2, qr_target, qr_anc, name='dist')
for edge in distances:
if edge[0] != '3':
# convert to binaries
node1 = format(int(edge[0]), '02b')
node2 = format(int(edge[1]), '02b')
d_bin = format(distances[edge], '02b')
for idx in range(len(node1)): # assume node1 and node2 have the same length
if node1[idx] == '0':
qc.x(qr1[idx])
for idx in range(len(node2)):
if node2[idx] == '0':
qc.x(qr2[idx])
for idx in range(len(d_bin)):
if d_bin[idx] == '1':
qc.mct(qr1[:]+qr2[:], qr_target[idx], qr_anc)
for idx in range(len(node2)): # invert back
if node2[idx] == '0':
qc.x(qr2[idx])
for idx in range(len(node1)):
if node1[idx] == '0':
qc.x(qr1[idx])
return qc
## multi_adder_1
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])
## diffusion
def diffusion():
qc.h(q[0:6])
qc.x(q[0:6])
qc.h(q[5])
qc.barrier()
qc.mct(q[0:5], q[5], q[7:10])
qc.barrier()
qc.h(q[5])
qc.x(q[0:6])
qc.h(q[0:6])
qubit_num = 25 # max is 32 if you're using the simulator
# Ancilla indices
inputs = [0, 1, 2, 3, 4, 5]
init_ancillae = [6, 7, 8, 9]
valid = [10]
temp_dist = [11, 12, 13, 14, 15]
total_dist = [16, 17, 18, 19, 20]
gate_ancillae = [21, 22, 23]
check_dist = [11, 12, 13, 14, 15] # initialize 13 here
carry_check = [24]
inputs = inputs[0]
init_ancillae = init_ancillae[0]
valid = valid[0]
temp_dist = temp_dist[0]
total_dist = total_dist[0]
gate_ancillae = gate_ancillae[0]
check_dist = check_dist[0]
carry_check = carry_check[0]
q = QuantumRegister(qubit_num)
c = ClassicalRegister(6)
qc = QuantumCircuit(q, c)
qc.h(q[0:6])
qc.x(q[carry_check])
# forward oracle
initialize_oracle_part(4)
qc.append(dist_single(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5])
multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20)
qc.append(dist_single().inverse(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5])
qc.append(dist(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20)
qc.append(dist().inverse(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
qc.append(dist(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20)
qc.append(dist().inverse(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
qc.x(q[check_dist:check_dist+3]) # init 15
multiple_adder([11, 12, 13, 14, 15], [16, 17, 18, 19, 20], init_ancillae, carry_check)
# carry_check
# qc.barrier()
qc.cz(q[valid], q[carry_check])
# qc.barrier()
# inverse oracle
multiple_adder([11, 12, 13, 14, 15], [16, 17, 18, 19, 20], init_ancillae, carry_check)
qc.x(q[check_dist:check_dist+3]) # init 15
qc.append(dist().inverse(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20)
qc.append(dist(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
qc.append(dist().inverse(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20)
qc.append(dist(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
qc.append(dist_single().inverse(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5])
multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20)
qc.append(dist_single(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5])
initialize_oracle_part(4)
diffusion()
qc.measure(q[:6], c)
# qc.draw()
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
pass_ = Unroller(['u3', 'cx'])
pm = PassManager(pass_)
new_circuit = pm.run(qc)
print(new_circuit.count_ops())
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1024)
counts = job.result().get_counts()
print(sorted(counts.items(), key=lambda x:x[1], reverse=True)[0:20])
plot_histogram(counts)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.