repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
input_3sat_instance = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
import os
import tempfile
from qiskit.exceptions import MissingOptionalLibraryError
from qiskit.circuit.library.phase_oracle import PhaseOracle
fp = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
fp.write(input_3sat_instance)
file_name = fp.name
fp.close()
oracle = None
try:
oracle = PhaseOracle.from_dimacs_file(file_name)
except MissingOptionalLibraryError as ex:
print(ex)
finally:
os.remove(file_name)
from qiskit.algorithms import AmplificationProblem
problem = None
if oracle is not None:
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
from qiskit.algorithms import Grover
from qiskit.primitives import Sampler
grover = Grover(sampler=Sampler())
result = None
if problem is not None:
result = grover.amplify(problem)
print(result.assignment)
from qiskit.tools.visualization import plot_histogram
if result is not None:
display(plot_histogram(result.circuit_results[0]))
expression = '(w ^ x) & ~(y ^ z) & (x & y & z)'
try:
oracle = PhaseOracle(expression)
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
display(plot_histogram(result.circuit_results[0]))
except MissingOptionalLibraryError as ex:
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### removed cx gate ###
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":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### removed h gate ###
return qc
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output
from qiskit.primitives import Estimator
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.observables_evaluator import estimate_observables
from qiskit.algorithms.optimizers import COBYLA, SLSQP
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit.utils import algorithm_globals
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_nature.second_q.mappers import JordanWignerMapper
def kronecker_delta_function(n: int, m: int) -> int:
"""An implementation of the Kronecker delta function.
Args:
n (int): The first integer argument.
m (int): The second integer argument.
Returns:
Returns 1 if n = m, else returns 0.
"""
return int(n == m)
def create_deuteron_hamiltonian(
N: int, hbar_omega: float = 7.0, V_0: float = -5.68658111
) -> SparsePauliOp:
"""Creates a version of the Deuteron Hamiltonian as a qubit operator.
Args:
N (int): An integer number that represents the dimension of the
basis.
hbar_omega (float, optional): The value of the product of hbar and omega. Defaults to 7.0.
V_0 (float, optional): The value of the potential energy. Defaults to -5.68658111.
Returns:
SparsePauliOp: The qubit-space Hamiltonian that represents the Deuteron.
"""
hamiltonian_terms = {}
for m in range(N):
for n in range(N):
label = "+_{} -_{}".format(str(n), str(m))
coefficient_kinect = (hbar_omega / 2) * (
(2 * n + 3 / 2) * kronecker_delta_function(n, m)
- np.sqrt(n * (n + (1 / 2))) * kronecker_delta_function(n, m + 1)
- np.sqrt((n + 1) * (n + (3 / 2)) * kronecker_delta_function(n, m - 1))
)
hamiltonian_terms[label] = coefficient_kinect
coefficient_potential = (
V_0 * kronecker_delta_function(n, 0) * kronecker_delta_function(n, m)
)
hamiltonian_terms[label] += coefficient_potential
hamiltonian = FermionicOp(hamiltonian_terms, num_spin_orbitals=N)
mapper = JordanWignerMapper()
qubit_hamiltonian = mapper.map(hamiltonian)
if not isinstance(qubit_hamiltonian, SparsePauliOp):
qubit_hamiltonian = qubit_hamiltonian.primitive
return qubit_hamiltonian
deuteron_hamiltonians = [create_deuteron_hamiltonian(i) for i in range(1, 5)]
for i, hamiltonian in enumerate(deuteron_hamiltonians):
print("Deuteron Hamiltonian: H_{}".format(i + 1))
print(hamiltonian)
print("\n")
theta = Parameter(r"$\theta$")
eta = Parameter(r"$\eta$")
wavefunction = QuantumCircuit(1)
wavefunction.ry(theta, 0)
wavefunction.draw("mpl")
wavefunction2 = QuantumCircuit(2)
wavefunction2.x(0)
wavefunction2.ry(theta, 1)
wavefunction2.cx(1, 0)
wavefunction2.draw("mpl")
wavefunction3 = QuantumCircuit(3)
wavefunction3.x(0)
wavefunction3.ry(eta, 1)
wavefunction3.ry(theta, 2)
wavefunction3.cx(2, 0)
wavefunction3.cx(0, 1)
wavefunction3.ry(-eta, 1)
wavefunction3.cx(0, 1)
wavefunction3.cx(1, 0)
wavefunction3.draw("mpl")
ansatz = [wavefunction, wavefunction2, wavefunction3]
reference_values = []
print("Exact binding energies calculated through numpy.linalg.eigh \n")
for i, hamiltonian in enumerate(deuteron_hamiltonians):
eigenvalues, eigenstates = np.linalg.eigh(hamiltonian.to_matrix())
reference_values.append(eigenvalues[0])
print("Exact binding energy for H_{}: {}".format(i + 1, eigenvalues[0]))
print(
"Results using Estimator for H_1, H_2 and H_3 with the ansatz given in the reference paper \n"
)
for i in range(3):
seed = 42
algorithm_globals.random_seed = seed
vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=SLSQP())
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
binding_energy = vqe_result.optimal_value
print("Binding energy for H_{}: {} MeV".format(i + 1, binding_energy))
def callback(eval_count, parameters, mean, std):
# Overwrites the same line when printing
display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std))
clear_output(wait=True)
counts.append(eval_count)
values.append(mean)
params.append(parameters)
deviation.append(std)
plots = []
for i in range(3):
counts = []
values = []
params = []
deviation = []
seed = 42
algorithm_globals.random_seed = seed
vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=COBYLA(), callback=callback)
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
plots.append([counts, values])
fig, ax = plt.subplots(nrows=3, ncols=1)
fig.set_size_inches((12, 12))
for i, plot in enumerate(plots):
ax[i].plot(plot[0], plot[1], "o-", label="COBYLA")
ax[i].axhline(
y=reference_values[i],
color="k",
linestyle="--",
label=f"Reference Value: {reference_values[i]}",
)
ax[i].legend()
ax[i].set_xlabel("Cost Function Evaluations", fontsize=15)
ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15)
plt.show()
twolocal_ansatzes = []
for i in range(1, 5):
ansatz = TwoLocal(
deuteron_hamiltonians[i - 1].num_qubits,
["rz", "ry"],
"cx",
entanglement="full",
reps=i,
initial_state=None,
)
twolocal_ansatzes.append(ansatz)
print("Results using Estimator for H_1, H_2, H_3 and H_4 with TwoLocal ansatz \n")
seed = 42
algorithm_globals.random_seed = seed
for i in range(4):
vqe = VQE(Estimator(), ansatz=twolocal_ansatzes[i], optimizer=SLSQP())
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
binding_energy = vqe_result.optimal_value
print("Binding energy for H_{}:".format(i + 1), binding_energy, "MeV")
seed = 42
algorithm_globals.random_seed = seed
plots_tl = []
for i in range(4):
counts = []
values = []
params = []
deviation = []
vqe = VQE(
Estimator(),
ansatz=twolocal_ansatzes[i],
optimizer=SLSQP(),
callback=callback,
)
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
plots_tl.append([counts, values])
fig, ax = plt.subplots(nrows=4, ncols=1)
fig.set_size_inches((15, 15))
for i, plot in enumerate(plots_tl):
ax[i].plot(plot[0], plot[1], "o-", label="COBYLA")
ax[i].axhline(
y=reference_values[i],
color="k",
linestyle="--",
label=f"Reference Value: {reference_values[i]}",
)
ax[i].legend()
ax[i].set_xlabel("Cost Function Evaluations", fontsize=15)
ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15)
plt.show()
def calculate_observables_exp_values(
quantum_circuit: QuantumCircuit, observables: list, angles: list
) -> list:
"""Calculate the expectation value of an observable given the quantum
circuit that represents the wavefunction and a list of parameters.
Args:
quantum_circuit (QuantumCircuit): A parameterized quantum circuit
that represents the wavefunction of the system.
observables (list): A list containing the observables that we want
to know the expectation values.
angles (list): A list with the values that will be used in the
'bind_parameters' method.
Returns:
list_exp_values (list): A list containing the expectation values
of the observables given as input.
"""
list_exp_values = []
for observable in observables:
exp_values = []
for angle in angles:
qc = quantum_circuit.bind_parameters({theta: angle})
result = estimate_observables(
Estimator(),
quantum_state=qc,
observables=[observable],
)
exp_values.append(result[0][0])
list_exp_values.append(exp_values)
return list_exp_values
angles = list(np.linspace(-np.pi, np.pi, 100))
observables = [
Pauli("IZ"),
Pauli("ZI"),
Pauli("XX"),
Pauli("YY"),
deuteron_hamiltonians[1],
]
h2_observables_exp_values = calculate_observables_exp_values(wavefunction2, observables, angles)
fig, ax = plt.subplots(nrows=2, ncols=1)
fig.set_size_inches((12, 12))
ax[0].plot(angles, h2_observables_exp_values[0], "o", label=r"$Z_0$")
ax[0].plot(angles, h2_observables_exp_values[1], "o", label=r"$Z_1$")
ax[0].plot(angles, h2_observables_exp_values[2], "o", label=r"$X_0X_1$")
ax[0].plot(angles, h2_observables_exp_values[3], "o", label=r"$Y_0Y_1$")
ax[0].axhline(
y=1,
color="k",
linestyle="--",
)
ax[0].axhline(y=-1, color="k", linestyle="--")
ax[0].legend()
ax[0].set_xlabel(r"Theta - $\theta$", fontsize=15)
ax[0].set_ylabel(r"$\langle O \rangle $ - Operator Expectation Value", fontsize=15)
ax[0].set_xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"],
)
ax[0].set_title(
r"Expectation value of the observables $Z_0$, $Z_1$, $X_0X_1$ and $Y_0Y_1$ when we vary $\theta$ in the ansatz.",
fontsize=15,
)
ax[1].plot(angles, h2_observables_exp_values[4], "o")
ax[1].axhline(
y=reference_values[1],
color="k",
linestyle="--",
label="Binding Energy: {} MeV".format(np.round(reference_values[1], 3)),
)
ax[1].legend()
ax[1].set_xlabel(r"Theta - $\theta$", fontsize=15)
ax[1].set_ylabel(r"$\langle H_2 \rangle $ - Energy (MeV)", fontsize=15)
ax[1].set_xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"],
)
ax[1].set_title(
r"Behavior of the expectation value of $H_2$ when we vary $\theta$ in the ansatz.", fontsize=15
)
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/hephaex/Quantum-Computing-Awesome-List
|
hephaex
|
import qiskit
qiskit.__qiskit_version__
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
qc_ha = QuantumCircuit(4,2)
# encode inputs in qubits 0 and 1
qc_ha.x(0) # For a=0, remove the this line. For a=1, leave it.
qc_ha.x(1) # For b=0, remove the this line. For b=1, leave it.
qc_ha.barrier()
# use cnots to write the XOR of the inputs on qubit 2
qc_ha.cx(0,2)
qc_ha.cx(1,2)
# use ccx to write the AND of the inputs on qubit 3
qc_ha.ccx(0,1,3)
qc_ha.barrier()
# extract outputs
qc_ha.measure(2,0) # extract XOR value
qc_ha.measure(3,1) # extract AND value
qc_ha.draw()
counts = execute(qc_ha, Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
# Build a quantum circuit
circuit = QuantumCircuit(3, 3)
circuit.x(1)
circuit.h(range(3))
circuit.cx(0, 1)
circuit.measure(range(3), range(3));
print(circuit)
circuit.draw()
# Matplotlib Drawing
circuit.draw(output='mpl')
# Draw a new circuit with barriers and more registers
q_a = QuantumRegister(3, name='qa')
q_b = QuantumRegister(5, name='qb')
c_a = ClassicalRegister(3)
c_b = ClassicalRegister(5)
circuit = QuantumCircuit(q_a, q_b, c_a, c_b)
circuit.x(q_a[1])
circuit.x(q_b[1])
circuit.x(q_b[2])
circuit.x(q_b[4])
circuit.barrier()
circuit.h(q_a)
circuit.barrier(q_a)
circuit.h(q_b)
circuit.cswap(q_b[0], q_b[1], q_b[2])
circuit.cswap(q_b[2], q_b[3], q_b[4])
circuit.cswap(q_b[3], q_b[4], q_b[0])
circuit.barrier(q_b)
circuit.measure(q_a, c_a)
circuit.measure(q_b, c_b);
# Draw the circuit
circuit.draw(output='mpl')
# Draw the circuit with reversed bit order
circuit.draw(output='mpl', reverse_bits=True)
# Draw the circuit without barriers
circuit.draw(output='mpl', plot_barriers=False)
# Draw the circuit without barriers and reverse bit order
circuit.draw(output='mpl', plot_barriers=False, reverse_bits=True)
# Set line length to 80 for above circuit
circuit.draw(output='text')
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circuit.draw(output='mpl', style=style)
# Scale the mpl output to 1/2 the normal size
circuit.draw(output='mpl', scale=0.5)
from qiskit.tools.visualization import circuit_drawer
circuit_drawer(circuit, output='mpl', plot_barriers=False)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Alan-Robertson/QiskitPool
|
Alan-Robertson
|
import time
import qiskitpool
from qiskit import IBMQ, QuantumCircuit
import qiskit.tools.jupyter
IBMQ.load_account()
provider = IBMQ.get_provider(group='open', project='main')
%qiskit_job_watcher
pool = qiskitpool.QPool(provider)
backend = provider.get_backend('simulator_statevector')
n_shots = 10
circ = QuantumCircuit(1, 1)
circ.x(0)
circ.measure(0, 0)
job = pool(circ, backend, shots=n_shots)
pool
while not job.poll():
time.sleep(2)
assert(job.result().get_counts()['1'] == n_shots)
pool = qiskitpool.QPool(provider)
backend = provider.get_backend('simulator_statevector')
n_shots = 10
n_rounds = 20
circ = QuantumCircuit(1, 1)
circ.x(0)
circ.measure(0, 0)
# Create jobs
jobs = [pool(circ, backend, shots=n_shots) for i in range(n_rounds)]
print(pool)
# Wait for jobs to finish
n_complete = 0
while n_complete < n_rounds - 1:
n_complete = 0
for job in jobs:
if job.poll():
n_complete += 1
for job in jobs:
assert(job.poll())
assert(job.result().get_counts()['1'] == n_shots)
pool['simulator_statevector'].finished_jobs
pool['simulator_statevector'][0]
pool.join()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.optimizers import SLSQP
from qiskit.circuit.library import TwoLocal
num_qubits = 2
ansatz = TwoLocal(num_qubits, "ry", "cz")
optimizer = SLSQP(maxiter=1000)
ansatz.decompose().draw("mpl", style="iqx")
from qiskit.primitives import Estimator
estimator = Estimator()
from qiskit.algorithms.minimum_eigensolvers import VQE
vqe = VQE(estimator, ansatz, optimizer)
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list([
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156)
])
result = vqe.compute_minimum_eigenvalue(H2_op)
print(result)
from qiskit.algorithms.optimizers import SPSA
estimator = Estimator(options={"shots": 1000})
vqe.estimator = estimator
vqe.optimizer = SPSA(maxiter=100)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
|
geduardo
|
import pew_tunnel as pew
import random
import pygame
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
import numpy as np
#########################################################################
#FUNCTIONS
#########################################################################
simulator = Aer.get_backend('statevector_simulator')
def qrand(nbits):
"""generates nbits real random numbers using quantum state measurements in qiskit."""
circ = QuantumCircuit(1, 1)
circ.h(0)
circ.measure(0, 0)
val = np.zeros(nbits)
for i in range(nbits):
job=execute(circ, simulator)
res = job.result()
vec = res.get_statevector()
val[i] = vec[0] * 1 + vec[1] * 0
#convert val array into bitstring b and then into integer
b = ''
for i in range(nbits):
b += str(int(val[i]))
integ= int(b, 2)
return integ
def Pt(U0, E, L, betac, gamma_sqc):
"""return tunneling probability for square barrier"""
return 1/ (np.cosh(betac * L)**2 + gamma_sqc * np.sinh(betac * L)**2)
def beta(U0, E):
"""supply function for Pt"""
return np.sqrt(2* (U0 - E))
def gamma_sq(U0, E):
"""supply function for Pt"""
return 0.25 * ((1 - E/U0)/(E/U0) + (E/U0)/(1-E/U0) - 2)
def theta(p_tunnel):
"""returns rotation angle corresponding to tunneling prob. p_tunnel"""
return 2 * np.arcsin(np.sqrt(p_tunnel))
def tunnelres(U0, length_snake, L, betac, gamma_sqc):
"""returns 0 if tunnel, returns 1 if no tunnel"""
P_t = Pt(U0, length_snake, L, betac, gamma_sqc) #get tunneling prob depending on current snake length
theta_rot = theta(P_t) #get rot angle
#qcirc
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circ = QuantumCircuit(qr, cr)
circ.rx(theta_rot, qr[0])
circ.measure(qr, cr)
job = execute(circ, simulator)
res = job.result()
vec = res.get_statevector()
val = vec[0] * 1 + vec[1] * 0
if val == 1:
return 0
else:
return 1
#r= random.randint(0, 1)
#return round(r)
def Qand(First_bool,Second_bool):
a = int(First_bool)
b = int(Second_bool)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
if a is 1:
qc.x(0)
if b is 1:
qc.x(1)
qc.ccx(q[0], q[1], q[2])
qc.draw()
backend = Aer.get_backend('statevector_simulator')
job = execute(qc, backend)
result = job.result()
outputstate = result.get_statevector(qc, decimals=8)
Q_and = bool(int(np.real(outputstate[7])))
return Q_and
def Qor(First_bool,Second_bool):
a = int(First_bool)
b = int(Second_bool)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
if a is 1:
qc.x(0)
if b is 1:
qc.x(1)
qc.ccx(q[0], q[1], q[2])
qc.draw()
backend = Aer.get_backend('statevector_simulator')
job = execute(qc, backend)
result = job.result()
outputstate = result.get_statevector(qc, decimals=8)
if a is 1 and b is 0:
Q_or = bool(int(np.real(outputstate[1])))
elif a is 0 and b is 1:
Q_or = bool(int(np.real(outputstate[2])))
else:
Q_or = bool(int(np.real(outputstate[7])))
return(Q_or)
##########################################################################
#MAIN
##########################################################################
#initialize pew
dis = pew.init()
screen = pew.Pix()
#set size
bits = 3
ds= 2**bits #displazsize
#set game starting parameters
game_speed = 4
snake = [(2, 4)]
dx, dy = 1, 0
apple_x, apple_y = 6, 4
screen.pixel(apple_x, apple_y, 2)
howmanyapples = 1 #marker for total number of eaten apples, used for scoring
#set graphics for probability display
pygame.font.init()
#gate backkgorund
font1 = pygame.font.Font(None, 33)
text = font1.render('Probability for tunneling is', True, (255, 0, 0))
dis.blit(text, (20, 330))
font2 = pygame.font.Font(None, 45)
text2 = font2.render('100%', True, (255, 0, 0))
dis.blit(text2, (130, 360))
ima = pygame.image.load('pewblack.jpg')
#tunneling parameters
U0=37 #max snake length = 6x6 = 36
E=1
L=0.05 #optimal barrier size for nice tunneling probabilities
#initialize tunneling tracker
tunnel=0 #don't see other side as second barrier
snakepos=1 #marker of snakepos, 1=head, increase towards tail
headtunnel=0 #let the head tunnel again through other even if tail still in process
while True: #snake runs
#create barrier
bar= []
for i in range(ds):
screen.pixel(0, i, 1)
screen.pixel(ds-1, i, 1)
screen.pixel(i, 0, 1)
screen.pixel(i, ds-1, 1)
bar.append((0, i))
bar.append((ds-1, i))
bar.append((i, 0))
bar.append((i, ds-1))
#find the head
if len(snake) > 1:
x, y = snake[-2]
screen.pixel(x, y, 1)
x, y = snake[-1]
screen.pixel(x, y, 3) #color the head yellow
pew.show(screen)
pew.tick(1 / game_speed)
#get commands
keys = pew.keys()
if headtunnel==0:
if Qand(bool(int(keys & pew.K_UP)),dy == 0) is True:
dx, dy = 0, -1
#print(bool(int(keys & pew.K_UP)))
#print(dy == 0)
#print(Qand(bool(int(keys & pew.K_UP)),dy == 0))
elif Qand(bool(int(keys & pew.K_LEFT)),dx == 0) is True:
#print(str(keys & pew.K_LEFT) + 'right')
dx, dy = -1, 0
elif Qand(bool(int(keys & pew.K_RIGHT)),dx == 0) is True:
#print(str(keys & pew.K_RIGHT) + 'right')
dx, dy = 1, 0
elif Qand(bool(int(keys & pew.K_DOWN)),dy == 0) is True:
#print(str(keys & pew.K_DOWN) + 'down')
dx, dy = 0, 1
x = (x + dx) % 8
y = (y + dy) % 8
elif headtunnel==1: #steering not allowed during tunneling of the head (during two rounds)
x = (x + dx) % 8
y = (y + dy) % 8
headtunnel=2
elif headtunnel>=2:
x = (x + dx) % 8
y = (y + dy) % 8
headtunnel=0
##TUNNELING PROCESS
#snake tail tunnels
if Qand(tunnel>0,snakepos<=len(snake)) is True:
#get segment for tunneling
sx, sy = snake[-snakepos]
E=len(snake)/2 #divide by two for lower tunnel prob for tail (lower mass->lower energy)
tunnels = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E))
if tunnels==1: #tunnels
snakepos+=1
else: #does not tunnel
del snake[-snakepos]
screen.pixel(sx, sy, 0)
#reset if last segment tunneled
if Qand(tunnel>0, snakepos==(len(snake)+1)) is True:
tunnel=0
snakepos=1
#snake head tunnels
if Qand(headtunnel==0, (x, y) in bar) is True:
E=len(snake)
tunnel = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E))
if Qand(tunnel==0, len(snake) != 1) is True: #head doesn't tunnel --> game over
break
else:
snakepos+=1
headtunnel+=1
elif Qand(headtunnel==1, (x, y) in bar) is True:
headtunnel=0
#display tunneling prob.
E = len(snake)
if E > 1:
prob = Pt(U0, E, L, beta(U0, E), gamma_sq(U0, E))
text3 = font2.render(str(int(round(prob * 100))) + '%', True, (255, 0, 0))
dis.blit(ima, (130, 360))
dis.blit(text3, (130, 360))
else: #if length of snake ==1 (only head), tunneling prob = 100%
dis.blit(ima, (130, 360)) #cover the ultimate prob. display
dis.blit(text2, (130, 360)) #text2 = '100%'
#####TUNNEL END
if (x, y) in snake: #exit, game over condition
break
snake.append((x, y))
#apple generation
if Qand(x == apple_x, y == apple_y) is True:
screen.pixel(apple_x, apple_y, 0)
apple_x, apple_y = snake[0]
while Qor((apple_x, apple_y) in snake, (apple_x, apple_y) in bar) is True:
apple_x = qrand(bits) #random.getrandbits(3) #use this for pseudo random number gen, no qiskit needed
apple_y = qrand(bits) #random.getrandbits(3)
screen.pixel(apple_x, apple_y, 2)
game_speed += 0.2 #increase game speed
howmanyapples += 1 #increase number of eaten apples, score +1
else:
x, y = snake.pop(0)
screen.pixel(x, y, 0)
text = pew.Pix.from_text("Game over!") #Game over message and closing
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
text = pew.Pix.from_text("Score:" + str(int(howmanyapples))) #Score message
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
pygame.quit()
|
https://github.com/zapata-engineering/orquestra-qiskit
|
zapata-engineering
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
import os
import unittest
import qiskit.providers.aer.noise as AerNoise
from orquestra.quantum.circuits.layouts import CircuitConnectivity
from qiskit.providers.exceptions import QiskitBackendNotFoundError
from orquestra.integrations.qiskit.noise.basic import (
create_amplitude_damping_noise,
create_phase_and_amplitude_damping_error,
create_phase_damping_noise,
create_pta_channel,
get_kraus_matrices_from_ibm_noise_model,
get_qiskit_noise_model,
)
class TestBasic(unittest.TestCase):
def setUp(self):
self.ibmq_api_token = os.getenv("ZAPATA_IBMQ_API_TOKEN")
self.all_devices = ["ibm_kyoto"]
self.T_1 = 10e-7
self.T_2 = 30e-7
self.t_step = 10e-9
self.t_1_t_2_models = [
create_phase_and_amplitude_damping_error,
create_pta_channel,
]
def test_get_qiskit_noise_model(self):
# Given
for device in self.all_devices:
# When
noise_model, coupling_map = get_qiskit_noise_model(
device, api_token=self.ibmq_api_token
)
# Then
self.assertIsInstance(noise_model, AerNoise.NoiseModel)
self.assertIsInstance(coupling_map, list)
def test_get_qiskit_noise_model_no_device(self):
# Given
not_real_devices = ["THIS IS NOT A REAL DEVICE", "qasm_simulator"]
for device in not_real_devices:
# When/then
self.assertRaises(
QiskitBackendNotFoundError,
lambda: get_qiskit_noise_model(device, api_token=self.ibmq_api_token),
)
def test_t_1_t_2_noise_models(self):
for noise in self.t_1_t_2_models:
self.assertIsInstance(
noise(self.T_1, self.T_2, self.t_step), AerNoise.NoiseModel
)
def test_amplitude_damping_model(self):
self.assertIsInstance(
create_amplitude_damping_noise(self.T_1, self.t_step), AerNoise.NoiseModel
)
def test_phase_damping_noise(self):
self.assertIsInstance(
create_phase_damping_noise(self.T_2, self.t_step), AerNoise.NoiseModel
)
def test_getting_kraus_matrices_from_noise_model(self):
noise_model = create_amplitude_damping_noise(self.T_1, self.t_step)
kraus_dict = get_kraus_matrices_from_ibm_noise_model(noise_model)
# Test to see if basis gates are in
self.assertEqual("id" in kraus_dict, True)
self.assertEqual("u3" in kraus_dict, True)
self.assertEqual("cx" in kraus_dict, True)
# Test to see if the number of kraus operators is right for a basis gate
self.assertEqual(len(kraus_dict["id"]), 2)
self.assertEqual(len(kraus_dict["u3"]), 2)
self.assertEqual(len(kraus_dict["cx"]), 4)
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
import sys
sys.path.append("..")
from qiskit import transpile
from qiskit.converters import circuit_to_dag, dag_to_circuit
from circuit_suite import circuits
circuit_label = "QFT"
qsize = 3
qc = transpile(circuits[circuit_label].circuit_lambda(qsize)).decompose()
qc.draw(output="mpl")
# from qiskit import transpile
# from qiskit.converters import circuit_to_dag, dag_to_circuit
# from circuit_suite import circuits
# circuit_label="QFT"
# c = transpile(circuits[circuit_label].circuit_lambda(qsize), basis_gates=['u', 'cx'])
# c.draw(output='mpl')
dag = circuit_to_dag(qc)
def weight_fn(source_node, target_node, weight):
if dag._multi_graph[source_node].name is None:
return 0
else:
return 1
import retworkx
longest_path = retworkx.dag_longest_path(dag._multi_graph, weight_fn=weight_fn)
dlp = [dag._multi_graph[index] for index in longest_path]
for node in dag.op_nodes():
if not node in dlp:
dag.remove_op_node(node)
qc_t = dag_to_circuit(dag)
qc_t.draw(output="mpl")
x = [qsize]
y = [
circuit_to_dag(
transpile(circuits[circuit_label].circuit_lambda(xi), basis_gates=["u", "cx"])
).count_ops_longest_path()["cx"]
for xi in x
]
z = [
circuit_to_dag(
transpile(circuits[circuit_label].circuit_lambda(xi), basis_gates=["u", "cx"])
).count_ops()["cx"]
for xi in x
]
print(y, z)
c = transpile(circuits[circuit_label].circuit_lambda(qsize), basis_gates=["u", "cx"])
d = circuit_to_dag(c)
w = d._wires
for wi in w:
print([node.name for node in d.nodes_on_wire(wi, only_ops=True)])
c.draw(output="mpl")
import numpy as np
from numpy import pi
# importing Qiskit
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit.circuit.library.basis_change import QFT
inverse_qft_lambda = lambda q: QFT(q, inverse=True)
qc = inverse_qft_lambda(qsize)
qc.decompose().draw(output="mpl")
# replace every R_z with a Riswap?
# can e made a transformation pass if wanted to
from qiskit.circuit.library.standard_gates import iSwapGate
from clonk.utils.riswap_gates.riswap import RiSwapGate
dag = circuit_to_dag(qc.decompose())
for node in dag.op_nodes():
# if we hit a Rz gate then replace it
if node.op.name in ["cp"]:
# get the rotation angle
angle = node.op.params[0]
replacement = QuantumCircuit(2)
# replacement.append(RiSwapGate(angle/np.pi), [0,1])
replacement.append(iSwapGate().power(angle / np.pi), [0, 1])
# replacement.draw(output='mpl')
dag.substitute_node_with_dag(node, circuit_to_dag(replacement))
# print(angle)
qc_modified = dag_to_circuit(dag)
qc_modified.draw(output="mpl")
nqubits = 3
number = 3
prep = QuantumCircuit(qsize)
for qubit in range(qsize):
prep.h(qubit)
prep.p(number * pi / 4, 0)
prep.p(number * pi / 2, 1)
prep.p(number * pi, 2)
prep.draw()
qc = prep + qc_modified
qc.draw(output="mpl")
# now simulate the qft to get a histogram
backend = sim = Aer.get_backend("aer_simulator")
qc.measure_all()
transpiled_qc = transpile(qc, backend, optimization_level=3, basis_gates=["u", "cx"])
job = backend.run(transpiled_qc, shots=1000)
job_monitor(job)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Randomized tests of quantum synthesis."""
import unittest
from test.python.quantum_info.test_synthesis import CheckDecompositions
from hypothesis import given, strategies, settings
import numpy as np
from qiskit import execute
from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.extensions import UnitaryGate
from qiskit.providers.basicaer import UnitarySimulatorPy
from qiskit.quantum_info.random import random_unitary
from qiskit.quantum_info.synthesis.two_qubit_decompose import (
two_qubit_cnot_decompose,
TwoQubitBasisDecomposer,
Ud,
)
class TestSynthesis(CheckDecompositions):
"""Test synthesis"""
seed = strategies.integers(min_value=0, max_value=2**32 - 1)
rotation = strategies.floats(min_value=-np.pi * 10, max_value=np.pi * 10)
@given(seed)
def test_1q_random(self, seed):
"""Checks one qubit decompositions"""
unitary = random_unitary(2, seed=seed)
self.check_one_qubit_euler_angles(unitary)
self.check_one_qubit_euler_angles(unitary, "U3")
self.check_one_qubit_euler_angles(unitary, "U1X")
self.check_one_qubit_euler_angles(unitary, "PSX")
self.check_one_qubit_euler_angles(unitary, "ZSX")
self.check_one_qubit_euler_angles(unitary, "ZYZ")
self.check_one_qubit_euler_angles(unitary, "ZXZ")
self.check_one_qubit_euler_angles(unitary, "XYX")
self.check_one_qubit_euler_angles(unitary, "RR")
@settings(deadline=None)
@given(seed)
def test_2q_random(self, seed):
"""Checks two qubit decompositions"""
unitary = random_unitary(4, seed=seed)
self.check_exact_decomposition(unitary.data, two_qubit_cnot_decompose)
@given(strategies.tuples(*[seed] * 5))
def test_exact_supercontrolled_decompose_random(self, seeds):
"""Exact decomposition for random supercontrolled basis and random target"""
k1 = np.kron(random_unitary(2, seed=seeds[0]).data, random_unitary(2, seed=seeds[1]).data)
k2 = np.kron(random_unitary(2, seed=seeds[2]).data, random_unitary(2, seed=seeds[3]).data)
basis_unitary = k1 @ Ud(np.pi / 4, 0, 0) @ k2
decomposer = TwoQubitBasisDecomposer(UnitaryGate(basis_unitary))
self.check_exact_decomposition(random_unitary(4, seed=seeds[4]).data, decomposer)
@given(strategies.tuples(*[rotation] * 6), seed)
def test_cx_equivalence_0cx_random(self, rnd, seed):
"""Check random circuits with 0 cx gates locally equivalent to identity."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 0)
@given(strategies.tuples(*[rotation] * 12), seed)
def test_cx_equivalence_1cx_random(self, rnd, seed):
"""Check random circuits with 1 cx gates locally equivalent to a cx."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 1)
@given(strategies.tuples(*[rotation] * 18), seed)
def test_cx_equivalence_2cx_random(self, rnd, seed):
"""Check random circuits with 2 cx gates locally equivalent to some circuit with 2 cx."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
qc.cx(qr[0], qr[1])
qc.u(rnd[12], rnd[13], rnd[14], qr[0])
qc.u(rnd[15], rnd[16], rnd[17], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 2)
@given(strategies.tuples(*[rotation] * 24), seed)
def test_cx_equivalence_3cx_random(self, rnd, seed):
"""Check random circuits with 3 cx gates are outside the 0, 1, and 2 qubit regions."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
qc.cx(qr[0], qr[1])
qc.u(rnd[12], rnd[13], rnd[14], qr[0])
qc.u(rnd[15], rnd[16], rnd[17], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[18], rnd[19], rnd[20], qr[0])
qc.u(rnd[21], rnd[22], rnd[23], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 3)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureDriverType,
ElectronicStructureMoleculeDriver,
PySCFDriver,
)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
from qiskit_nature.settings import settings
settings.dict_aux_operators = True
molecule = Molecule(
geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1
)
driver = ElectronicStructureMoleculeDriver(
molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF
)
# or equivalently:
driver = PySCFDriver.from_molecule(molecule, basis="sto3g")
transformer = FreezeCoreTransformer()
problem = ElectronicStructureProblem(driver, transformers=[transformer])
# Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so:
second_q_ops = problem.second_q_ops()
hamiltonian = second_q_ops["ElectronicEnergy"]
print(hamiltonian)
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1)
driver = PySCFDriver.from_molecule(molecule, basis="sto3g")
# this is now done explicitly
problem = driver.run()
transformer = FreezeCoreTransformer()
# and you also apply transformers explicitly
problem = transformer.transform(problem)
hamiltonian = problem.hamiltonian.second_q_op()
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import PySCFDriver
molecule = Molecule(
geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1
)
driver = PySCFDriver.from_molecule(molecule)
result = driver.run()
print(type(result))
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo
molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1)
driver = PySCFDriver.from_molecule(molecule, basis="sto3g")
result = driver.run()
print(type(result))
from qiskit_nature.drivers.second_quantization import FCIDumpDriver
path_to_fcidump = "aux_files/h2.fcidump"
driver = FCIDumpDriver(path_to_fcidump)
result = driver.run()
print(type(result))
from qiskit_nature.second_q.formats.fcidump import FCIDump
path_to_fcidump = "aux_files/h2.fcidump"
fcidump = FCIDump.from_file(path_to_fcidump)
print(type(fcidump))
from qiskit_nature.second_q.formats.fcidump_translator import fcidump_to_problem
problem = fcidump_to_problem(fcidump)
print(type(problem))
from qiskit_nature.drivers.second_quantization import PySCFDriver
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
transformer = FreezeCoreTransformer()
driver = PySCFDriver()
transformed_result = transformer.transform(driver.run())
print(type(transformed_result))
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
transformer = FreezeCoreTransformer()
driver = PySCFDriver()
transformed_result = transformer.transform(driver.run())
print(type(transformed_result))
from qiskit_nature.drivers.second_quantization import PySCFDriver
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
driver = PySCFDriver()
transformer = FreezeCoreTransformer()
problem = ElectronicStructureProblem(driver, transformers=[transformer])
# we trigger driver.run() implicitly like so:
second_q_ops = problem.second_q_ops()
hamiltonian_op = second_q_ops.pop("ElectronicEnergy")
aux_ops = second_q_ops
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
driver = PySCFDriver()
problem = driver.run()
transformer = FreezeCoreTransformer()
problem = transformer.transform(problem)
hamiltonian_op, aux_ops = problem.second_q_ops()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import qiskit_alt
geometry = [['H', [0., 0., 0.]], ['H', [0., 0., 0.7414]]]
#basis = 'sto3g'
basis = '631++g'
fermi_op = qiskit_alt.fermionic_hamiltonian(geometry, basis)
pauli_op = qiskit_alt.jordan_wigner(fermi_op)
#basis = '631g'
#basis = 'dzvp'
# Too big
#basis = 'dzp'
#basis = 'dzvp2'
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/Akshara-Bulkapuram/Quantum-Hadamard-Edge-detection
|
Akshara-Bulkapuram
|
# Importing standard Qiskit libraries
from qiskit import *
from qiskit import IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('dark_background')
# representing a binary image(8x8) in form of a numpy array
img = np.array([ [0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0] ])
# plot image function
def plot_image(Image, title):
plt.title(title)
plt.xticks(range(Image.shape[0]))
plt.yticks(range(Image.shape[1]))
plt.imshow(Image, extent=[ 0,Image.shape[0], Image.shape[1],0,], cmap='hot')
plt.show()
plot_image(img, 'Initial image')
#we encode the intensities of image pixels as probability amplitudes of quantum states
#we use normalization for this
#we normalize the amplitudes to lie in the range (0,1)
# Convert the raw pixel values to probability amplitudes
def amplitude_encode(img_data):
# Calculate the RMS value
rms = np.sqrt(np.sum(np.sum(img_data**2, axis=1)))
# Create normalized image
image_norm = []
for arr in img_data:
for ele in arr:
image_norm.append(ele / rms)
# Return the normalized image as a numpy array
return np.array(image_norm)
#we now normalize image and get coefficients in both horizontal and vertical directions
# Horizontal: Original image
h_norm_image = amplitude_encode(img)
print("Horizontal image normalized coefficients",h_norm_image)
print()
print()
# Vertical: Transpose of Original image
v_norm_image = amplitude_encode(img.T)
print("vertical image normalized coefficients",v_norm_image)
print()
print("size of 1d array",h_norm_image.shape)
print("size of 1d array",v_norm_image.shape)
#we require N=log(8*8) qubits
#N=6
data_q = 6
ancillary_q = 1
total_q = data_q + ancillary_q
# Initialize the amplitude permutation unitary
Amp_permutation_unitary = np.identity(2**total_q)
print(Amp_permutation_unitary)
Amp_permutation_unitary=np.roll(Amp_permutation_unitary,1,axis=1)
print()
print()
print()
print("shift Amplitude permutation matrix by 1 unit to the right column wise")
print()
print(Amp_permutation_unitary)
print()
print("we will later use this for while applying hadamard operation to image coefficient vectors")
print()
print(Amp_permutation_unitary.shape)
# Creating the circuit for horizontal scan
qc_h = QuantumCircuit(total_q)
qc_h.initialize(h_norm_image, range(1, total_q))
qc_h.h(0)
qc_h.unitary(Amp_permutation_unitary, range(total_q))
qc_h.h(0)
display(qc_h.draw('mpl', fold=-1))
# Create the circuit for vertical scan
qc_v = QuantumCircuit(total_q)
qc_v.initialize(v_norm_image, range(1, total_q))
qc_v.h(0)
qc_v.unitary(Amp_permutation_unitary, range(total_q))
qc_v.h(0)
display(qc_v.draw('mpl', fold=-1))
# Combine both circuits into a single list
circ_list = [qc_h, qc_v]
# Simulating cirucits
back = Aer.get_backend('statevector_simulator')
results = execute(circ_list, backend=back).result()
state_vector_h = results.get_statevector(qc_h)
state_vector_v = results.get_statevector(qc_v)
print("print size is ",state_vector_h.size)
from qiskit.visualization import array_to_latex
print('Horizontal scan statevector:')
display(array_to_latex(state_vector_h, max_size=128))
print()
print('Vertical scan statevector:')
display(array_to_latex(state_vector_v, max_size=128))
# postprocessing for plotting the output (Classical)
# Defining a lambda function for thresholding to binary values
# returns true for specified Amplitude values else false
threshold = lambda amp: (amp > 1e-15 or amp < -1e-15)
# Selecting odd states from the raw statevector and
# reshaping column vector of size 64 to an 8x8 matrix
h_edge_scan_img = np.abs(np.array([1 if threshold(state_vector_h[(2*i)+1].real) else 0 for i in range(2**data_q)])).reshape(8, 8)
v_edge_scan_img= np.abs(np.array([1 if threshold(state_vector_v[(2*i)+1].real) else 0 for i in range(2**data_q)])).reshape(8, 8).T
# Plotting the Horizontal and vertical scans
plot_image(h_edge_scan_img, 'Horizontal scan output')
plot_image(v_edge_scan_img, 'Vertical scan output')
# Combining the horizontal and vertical component of the result by or operator
edge_scan_image = h_edge_scan_img | v_edge_scan_img
# Plotting the original and edge-detected images
plot_image(img, 'Original image')
plot_image(edge_scan_image, 'Edge-Detected image')
from PIL import Image
from numpy import asarray
image = Image.open('cat.png')
image.show()
new_image = image.resize((32, 32)).convert('1')
new_image.save('IMAGE_32.png')
new_image.show()
imgg=asarray(new_image)
print(imgg.shape)
def plot_image(Image, title):
plt.title(title)
plt.xticks(range(Image.shape[0]))
plt.yticks(range(Image.shape[1]))
plt.imshow(Image, extent=[ 0,Image.shape[0], Image.shape[1],0,], cmap='hot')
plt.show()
plot_image(imgg, 'Initial image')
print("size=",imgg.shape)
#we encode the intensities of image pixels as probability amplitudes of quantum states
#we use normalization for this
#we normalize the amplitudes to lie in the range (0,1)
# Convert the raw pixel values to probability amplitudes
def amplitude_encode(img_data):
# Calculate the RMS value
rms_32 = np.sqrt(np.sum(np.sum(img_data**2, axis=1)))
# Create normalized image
image_norm = []
for arr in img_data:
for ele in arr:
image_norm.append(ele / rms_32)
# Return the normalized image as a numpy array
return np.array(image_norm)
#we now normalize image and get coefficients in both horizontal and vertical directions
# Horizontal: Original image
h_norm_image_32 = amplitude_encode(imgg)
print("Horizontal image normalized coefficients",h_norm_image_32)
print()
print()
# Vertical: Transpose of Original image
v_norm_image_32 = amplitude_encode(imgg.T)
print("vertical image normalized coefficients",v_norm_image_32)
print()
print("size of 1d array",h_norm_image_32.shape)
print("size of 1d array",v_norm_image_32.shape)
#we require N=log(32*32) qubits
#N=10
data_q_32 = 10
ancillary_q_32 = 1
total_q_32 = data_q_32 + ancillary_q_32
# Initialize the amplitude permutation unitary
Amp_permutation_unitary_32 = np.identity(2**total_q_32)
print(Amp_permutation_unitary_32)
Amp_permutation_unitary_32=np.roll(Amp_permutation_unitary_32,1,axis=1)
print()
print()
print()
print("shift Amplitude permutation matrix by 1 unit to the right column wise")
print()
print(Amp_permutation_unitary_32)
print()
print("we will later use this for while applying hadamard operation to image coefficient vectors")
print()
print(Amp_permutation_unitary_32.shape)
# Creating the circuit for horizontal scan
qc_h_32 = QuantumCircuit(total_q_32)
qc_h_32.initialize(h_norm_image_32, range(1, total_q_32))
qc_h_32.h(0)
qc_h_32.unitary(Amp_permutation_unitary_32, range(total_q_32))
qc_h_32.h(0)
display(qc_h_32.draw('mpl', fold=-1))
# Create the circuit for vertical scan
qc_v_32 = QuantumCircuit(total_q_32)
qc_v_32.initialize(v_norm_image_32, range(1, total_q_32))
qc_v_32.h(0)
qc_v_32.unitary(Amp_permutation_unitary_32, range(total_q_32))
qc_v_32.h(0)
display(qc_v_32.draw('mpl', fold=-1))
# Combine both circuits into a single list
circ_list_32 = [qc_h_32, qc_v_32]
# Simulating cirucits
back = Aer.get_backend('statevector_simulator')
results = execute(circ_list_32, backend=back).result()
state_vector_h_32 = results.get_statevector(qc_h_32)
state_vector_v_32 = results.get_statevector(qc_v_32)
print("size is ",state_vector_h_32.size)
from qiskit.visualization import array_to_latex
print('Horizontal scan statevector:')
display(array_to_latex(state_vector_h_32, max_size=128))
print()
print('Vertical scan statevector:')
display(array_to_latex(state_vector_v_32, max_size=128))
# postprocessing for plotting the output (Classical)
# Defining a lambda function for thresholding to binary values
# returns true for specified Amplitude values else false
threshold = lambda amp: (amp > 1e-15 or amp < -1e-15)
# Selecting odd states from the raw statevector and
# reshaping column vector of size 64 to an 8x8 matrix
h_edge_scan_img_32 = np.abs(np.array([1 if threshold(state_vector_h_32[2*(i)+1].real) else 0 for i in range(2**data_q_32)])).reshape(32, 32)
v_edge_scan_img_32= np.abs(np.array([1 if threshold(state_vector_v_32[2*(i)+1].real) else 0 for i in range(2**data_q_32)])).reshape(32, 32).T
# Plotting the Horizontal and vertical scans
plot_image(h_edge_scan_img_32, 'Horizontal scan output')
plot_image(v_edge_scan_img_32, 'Vertical scan output')
# Combining the horizontal and vertical component of the result by or operator
edge_scan_image_32 = h_edge_scan_img_32 | v_edge_scan_img_32
# Plotting the original and edge-detected images
plot_image(imgg, 'Original image')
plot_image(edge_scan_image_32, 'Edge-Detected image')
from qiskit import *
from qiskit import IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import skimage.color
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import math
from PIL import Image
from numpy import asarray
image_o = Image.open('Apple1.jpg').convert('1')
image_o.show()
new_image_o = Image.open('Apple1.jpg')
imggg=asarray(image_o)
imggg_=asarray(new_image_o)
#print(imggg.shape)
#for item in imggg:
# print(item)
plot_image(imggg_, 'Initial image')
print("size=",imggg_.shape)
#we encode the intensities of image pixels as probability amplitudes of quantum states
#we use normalization for this
#we normalize the amplitudes to lie in the range (0,1)
# Convert the raw pixel values to probability amplitudes
def amplitude_encode(img_data):
# Calculate the RMS value
rms_32_rgb = np.sqrt(np.sum(np.sum(img_data**2, axis=1)))
# Create normalized image
image_norm = []
for arr in img_data:
for ele in arr:
image_norm.append(ele / rms_32_rgb)
# Return the normalized image as a numpy array
return np.array(image_norm)
#we now normalize image and get coefficients in both horizontal and vertical directions
# Horizontal: Original image
h_norm_image_32_rgb = amplitude_encode(imggg)
print("Horizontal image normalized coefficients",h_norm_image_32_rgb)
print()
print()
# Vertical: Transpose of Original image
v_norm_image_32_rgb = amplitude_encode(imggg.T)
print("vertical image normalized coefficients",v_norm_image_32_rgb)
print()
print("size of 1d array",h_norm_image_32_rgb.shape)
print("size of 1d array",v_norm_image_32_rgb.shape)
#we require N=log(32*32) qubits
#N=10
data_q_32_rgb = 10
ancillary_q_32_rgb = 1
total_q_32_rgb = data_q_32_rgb + ancillary_q_32_rgb
# Initialize the amplitude permutation unitary
Amp_permutation_unitary_32_rgb = np.identity(2**total_q_32_rgb)
print(Amp_permutation_unitary_32_rgb)
Amp_permutation_unitary_32_rgb=np.roll(Amp_permutation_unitary_32_rgb,1,axis=1)
print()
print()
print()
print("shift Amplitude permutation matrix by 1 unit to the right column wise")
print()
print(Amp_permutation_unitary_32_rgb)
print()
print("we will later use this for while applying hadamard operation to image coefficient vectors")
print()
print(Amp_permutation_unitary_32_rgb.shape)
# Creating the circuit for horizontal scan
qc_h_32_rgb = QuantumCircuit(total_q_32_rgb)
qc_h_32_rgb.initialize(h_norm_image_32_rgb, range(1, total_q_32_rgb))
qc_h_32_rgb.h(0)
qc_h_32_rgb.unitary(Amp_permutation_unitary_32_rgb, range(total_q_32_rgb))
qc_h_32_rgb.h(0)
display(qc_h_32_rgb.draw('mpl', fold=-1))
# Create the circuit for vertical scan
qc_v_32_rgb = QuantumCircuit(total_q_32_rgb)
qc_v_32_rgb.initialize(v_norm_image_32_rgb, range(1, total_q_32_rgb))
qc_v_32_rgb.h(0)
qc_v_32_rgb.unitary(Amp_permutation_unitary_32_rgb, range(total_q_32_rgb))
qc_v_32_rgb.h(0)
display(qc_v_32_rgb.draw('mpl', fold=-1))
# Combine both circuits into a single list
circ_list_32_rgb = [qc_h_32_rgb, qc_v_32_rgb]
# Simulating cirucits
back = Aer.get_backend('statevector_simulator')
results = execute(circ_list_32_rgb, backend=back).result()
state_vector_h_32_rgb = results.get_statevector(qc_h_32_rgb)
state_vector_v_32_rgb = results.get_statevector(qc_v_32_rgb)
print("size is ",state_vector_h_32_rgb.size)
from qiskit.visualization import array_to_latex
print('Horizontal scan statevector:')
display(array_to_latex(state_vector_h_32_rgb, max_size=128))
print()
print('Vertical scan statevector:')
display(array_to_latex(state_vector_v_32_rgb, max_size=128))
# postprocessing for plotting the output (Classical)
# Defining a lambda function for thresholding to binary values
# returns true for specified Amplitude values else false
threshold = lambda amp: (amp > 1e-15 or amp < -1e-15)
# Selecting odd states from the raw statevector and
# reshaping column vector of size 64 to an 8x8 matrix
h_edge_scan_img_32_rgb = np.abs(np.array([1 if threshold(state_vector_h_32_rgb[2*(i)+1].real) else 0 for i in range(2**data_q_32_rgb)])).reshape(32, 32)
v_edge_scan_img_32_rgb= np.abs(np.array([1 if threshold(state_vector_v_32_rgb[2*(i)+1].real) else 0 for i in range(2**data_q_32_rgb)])).reshape(32, 32).T
# Plotting the Horizontal and vertical scans
plot_image(h_edge_scan_img_32_rgb, 'Horizontal scan output')
plot_image(v_edge_scan_img_32_rgb, 'Vertical scan output')
# Combining the horizontal and vertical component of the result by or operator
edge_scan_image_32_rgb = h_edge_scan_img_32_rgb | v_edge_scan_img_32_rgb
# Plotting the original and edge-detected images
plot_image(imggg_, 'Original image')
plot_image(edge_scan_image_32_rgb, 'Edge-Detected image')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
https://github.com/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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
# Virtual -> physical
# 0 -> 3
# 1 -> 4
# 2 -> 2
my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2])
plot_circuit_layout(my_ghz, backend)
|
https://github.com/Heisenbug-s-Dog/qnn_visualization
|
Heisenbug-s-Dog
|
# OpenMP: number of parallel threads.
%env OMP_NUM_THREADS=1
# Plotting
%matplotlib inline
import matplotlib.pyplot as plt
# PyTorch
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import datasets, models, transforms
# Pennylane
import pennylane as qml
from pennylane import numpy as np
# Other tools
import time
import copy
filtered_classes = ['cat', 'dog'] # Subset of CIFAR ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck')
n_qubits = 4 # Number of qubits
quantum = True # If set to "False", the dressed quantum circuit is replaced by
# An enterily classical net (defined by the next parameter).
classical_model = '512_n' # Possible choices: '512_n','512_nq_n','551_512_n'. [nq=n_qubits, n=num_filtered_classes]
step = 0.001 # Learning rate
batch_size = 8 # Number of samples for each training step
num_epochs = 3 # Number of training epochs
q_depth = 5 # Depth of the quantum circuit (number of variational layers)
gamma_lr_scheduler = 1 # Learning rate reduction applied every 10 epochs.
max_layers = 15 # Keep 15 even if not all are used.
q_delta = 0.01 # Initial spread of random quantum weights
rng_seed = 0 # Seed for random number generator
start_time = time.time() # start of the computation timer
torch.manual_seed(rng_seed)
dev = qml.device('default.qubit', wires=n_qubits)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def H_layer(nqubits):
"""Layer of single-qubit Hadamard gates.
"""
for idx in range(nqubits):
qml.Hadamard(wires=idx)
def RY_layer(w):
"""Layer of parametrized qubit rotations around the y axis.
"""
for idx, element in enumerate(w):
qml.RY(element, wires=idx)
def entangling_layer(nqubits):
"""Layer of CNOTs followed by another shifted layer of CNOT.
"""
# In other words it should apply something like :
# CNOT CNOT CNOT CNOT... CNOT
# CNOT CNOT CNOT... CNOT
for i in range(0, nqubits - 1, 2): # Loop over even indices: i=0,2,...N-2
qml.CNOT(wires=[i, i + 1])
for i in range(1, nqubits - 1,2): # Loop over odd indices: i=1,3,...N-3
qml.CNOT(wires=[i, i + 1])
@qml.qnode(dev, interface='torch')
def q_net(q_in, q_weights_flat):
# Reshape weights
q_weights = q_weights_flat.reshape(max_layers, n_qubits)
# Start from state |+> , unbiased w.r.t. |0> and |1>
H_layer(n_qubits)
# Embed features in the quantum node
RY_layer(q_in)
# Sequence of trainable variational layers
for k in range(q_depth):
entangling_layer(n_qubits)
RY_layer(q_weights[k+1])
# Expectation values in the Z basis
return [qml.expval(qml.PauliZ(j)) for j in range(n_qubits)]
class Quantumnet(nn.Module):
def __init__(self):
super().__init__()
self.pre_net = nn.Linear(512, n_qubits)
self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits))
self.post_net = nn.Linear(n_qubits, len(filtered_classes))
def forward(self, input_features):
pre_out = self.pre_net(input_features)
q_in = torch.tanh(pre_out) * np.pi / 2.0
# Apply the quantum circuit to each element of the batch, and append to q_out
q_out = torch.Tensor(0, n_qubits)
q_out = q_out.to(device)
for elem in q_in:
q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0)
q_out = torch.cat((q_out, q_out_elem))
return self.post_net(q_out)
class Quantumnet_Cut(nn.Module):
def __init__(self):
super().__init__()
self.pre_net = nn.Linear(512, n_qubits)
self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits))
def forward(self, input_features):
pre_out = self.pre_net(input_features)
q_in = torch.tanh(pre_out) * np.pi / 2.0
# Apply the quantum circuit to each element of the batch, and append to q_out
q_out = torch.Tensor(0, n_qubits)
q_out = q_out.to(device)
for elem in q_in:
q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0)
q_out = torch.cat((q_out, q_out_elem))
return q_out
class Quantumnet_Classical_Cut(nn.Module):
def __init__(self):
super().__init__()
self.pre_net = nn.Linear(512, n_qubits)
self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits))
def forward(self, input_features):
pre_out = self.pre_net(input_features)
q_in = torch.tanh(pre_out) * np.pi / 2.0
return q_in
model = torchvision.models.resnet18(pretrained=True)
model.fc = Quantumnet()
for param in model.parameters():
param.requires_grad = False
# Use CUDA or CPU according to the "device" object.
model = model.to(device)
model_cut = torchvision.models.resnet18(pretrained=True)
model_cut.fc = Quantumnet_Cut()
for param in model_cut.parameters():
param.requires_grad = False
# Use CUDA or CPU according to the "device" object.
model_cut = model_cut.to(device)
model_classical_cut = torchvision.models.resnet18(pretrained=True)
model_classical_cut.fc = Quantumnet_Classical_Cut()
for param in model_cut.parameters():
param.requires_grad = False
# Use CUDA or CPU according to the "device" object.
model_classical_cut = model_classical_cut.to(device)
# Load model from file
path = 'drive/MyDrive/'
if quantum:
model.load_state_dict(torch.load(
path+'quantum_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt'
)
)
else:
model.load_state_dict(torch.load(
path+'classical_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt'
)
)
model_dict = model.state_dict()
model_cut_dict = model_cut.state_dict()
model_cut_dict = {k: v for k, v in model_dict.items() if k in model_cut_dict}
model_cut.load_state_dict(model_cut_dict)
model_classical_cut_dict = model_classical_cut.state_dict()
model_classical_cut_dict = {k: v for k, v in model_dict.items() if k in model_classical_cut_dict}
model_classical_cut.load_state_dict(model_classical_cut_dict)
import sys
sys.path.append('drive/My Drive/')
from torchvis import util
vis_param_dict, reset_state, remove_handles = util.augment_module(model)
from PIL import Image # so, this woorks better than skimage, as torchvision transforms work best with PIL and Tensor.
from torchvision import transforms
img_to_use = Image.open(path + 'dog.jpg')
print(img_to_use.size)
transform_1 = transforms.Compose([
transforms.Scale(256),
transforms.CenterCrop(224),
])
# since it's 0-255 range.
transform_2 = transforms.Compose([
transforms.ToTensor(),
# convert RGB to BGR
# from <https://github.com/mrzhu-cool/pix2pix-pytorch/blob/master/util.py>
transforms.Lambda(lambda x: torch.index_select(x, 0, torch.LongTensor([2, 1, 0]))),
transforms.Lambda(lambda x: x*255),
transforms.Normalize(mean = [103.939, 116.779, 123.68],
std = [ 1, 1, 1 ]),
])
img_to_use_cropped = transform_1(img_to_use)
# so, forward one time, and backward multiple times.
vis_param_dict['layer'] = 'classifier.6'
vis_param_dict['method'] = util.GradType.NAIVE
# which one coresponds
# this is the max one. I assume it's the correct one.
# indeed, it's correct.
# 55 is n01729977, corresponding to "green snake, grass snake".
vis_param_dict['index'] = 55
# alexnet gives 64, which is n01749939, or green mamba. not sure which one is correct.
loss.backward(retain_graph=True)
# adapted from <https://github.com/Lasagne/Recipes/blob/master/examples/Saliency%20Maps%20and%20Guided%20Backpropagation.ipynb>
def show_images(img_original, saliency, title):
# convert from c01 to 01c
print(saliency.min(), saliency.max(), saliency.mean(), saliency.std())
saliency = saliency[::-1] # to BGR
saliency = saliency.transpose(1, 2, 0)
# # put back std fixing.
# saliency = saliency * np.array([ 0.229, 0.224, 0.225 ])
# plot the original image and the three saliency map variants
plt.figure(figsize=(10, 10), facecolor='w')
plt.subplot(2, 2, 1)
plt.title('input')
plt.imshow(np.asarray(img_original))
plt.subplot(2, 2, 2)
plt.title('abs. saliency')
plt.imshow(np.abs(saliency).max(axis=-1), cmap='gray')
plt.subplot(2, 2, 3)
plt.title('pos. saliency')
plt.imshow((np.maximum(0, saliency) / saliency.max()))
plt.subplot(2, 2, 4)
plt.title('neg. saliency')
plt.imshow((np.maximum(0, -saliency) / -saliency.min()))
plt.suptitle(title)
plt.show()
show_images(img_to_use_cropped, input_img.grad.data.cpu().numpy()[0], '')
# so, forward one time, and backward multiple times.
vis_param_dict['method'] = util.GradType.GUIDED
# alexnet gives 64, which is n01749939, or green mamba. not sure which one is correct.
if input_img.grad is not None:
input_img.grad.data.zero_()
model.zero_grad()
loss.backward(retain_graph=True)
show_images(img_to_use_cropped, input_img.grad.data.cpu().numpy()[0], 'guided')
# so, forward one time, and backward multiple times.
vis_param_dict['method'] = util.GradType.DECONV
# alexnet gives 64, which is n01749939, or green mamba. not sure which one is correct.
if input_img.grad is not None:
input_img.grad.data.zero_()
model.zero_grad()
loss.backward(retain_graph=True)
show_images(img_to_use_cropped, input_img.grad.data.cpu().numpy()[0], 'deconv')
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import IBMQ
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle
from qiskit.visualization import plot_histogram
IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
expression = '(a & b)& ~(c)'
oracle = LogicalExpressionOracle(expression)
grover = Grover(oracle)
result = grover.run(backend, shots=1024)
counts = result['measurement']
print(counts)
print('Press any key to close')
input()
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
"""
Constant: Output equal 1.
"""
""" Create the quantum Circuit. """
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
qrx = QuantumRegister(1, 'q0')
qry = QuantumRegister(1, 'q1')
cr = ClassicalRegister(1, 'c')
qc = QuantumCircuit(qrx, qry, cr)
qc.h(qrx)
qc.x(qry)
qc.h(qry)
qc.barrier()
qc.x(qry)
qc.barrier()
qc.h(qrx)
qc.h(qry)
qc.measure(qrx, cr)
qc.draw("mpl")
""" Proof through histogram. """
from qiskit import execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
sim = AerSimulator()
job = execute(qc, backend = sim, shots = 1000)
result = job.result()
counts = result.get_counts(qc)
print("Counts: ", counts)
plot_histogram(counts)
""" Also in Quantum Computer. """
from qiskit import QuantumCircuit, IBMQ, execute
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram
IBMQ.save_account('your_token')
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
qcomp = provider.get_backend('ibmq_manila')
job = execute(qc, backend = qcomp, shots = 1000)
job_monitor(job)
result = job.result()
counts = result.get_counts(qc)
print("Total counts for qubit states are:", counts)
plot_histogram(counts)
|
https://github.com/OJB-Quantum/Qiskit-Metal-to-Litho
|
OJB-Quantum
|
%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!
design = designs.DesignPlanar()
gui = MetalGUI(design)
# Select a QComponent to create (The QComponent is a python class named `TransmonPocket`)
from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket
# Create a new qcomponent object
q1 = TransmonPocket(design)
gui.rebuild() # rebuild the design and plot
# Delete all QComponents in our design, which in this case is just the transmon pocket "Pocket_1"
design.delete_all_components()
gui.rebuild() # rebuild the design and plot
# Create a new qcomponent object with name 'Q1'
q1 = TransmonPocket(design, 'Q1')
gui.rebuild() # rebuild the design and plot
q1
TransmonPocket.get_template_options(design)
# Change options
q1.options.pos_x = '2.0 mm'
q1.options.pos_y = '2.0 mm'
q1.options.pad_height = '250 um'
q1.options.pad_width = '300 um'
# Update the geoemtry and render to the gui, since we changed the options
gui.rebuild()
# Copy q1 and place the new Qcomponent ("q1_copy") at (-2,2):
q1_copy = design.copy_qcomponent(q1, 'Q1_copy')
q1_copy.options['pos_x']='-2.0mm'
gui.rebuild()
gui.autoscale()
# Let's copy the two QComponents and change the y-coordinates of the copies to both be -2:
newcopies = design.copy_multiple_qcomponents([q1, q1_copy], ['Q3', 'Q4'], [dict(pos_y='-2.0mm'), dict(pos_y='-2.0mm')])
gui.rebuild()
gui.autoscale()
design.delete_component('Q1')
gui.rebuild()
gui.autoscale()
design._delete_component(3)
gui.rebuild()
gui.autoscale()
design.rename_component(4,'Q_three') # rename "Q3" to "Q_three"
design.rename_component(5,'Q_four') # rename "Q4" to "Q_four"
design.overwrite_enabled = True
gui.main_window.close()
|
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/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
|
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/matheusmtta/Quantum-Computing
|
matheusmtta
|
open Microsoft.Quantum.Intrinsic;
open Microsoft.Quantum.Canon;
open Microsoft.Quantum.Math;
open Microsoft.Quantum.Diagnostics;
open Microsoft.Quantum.Measurement;
open Microsoft.Quantum.Convert;
open Microsoft.Quantum.Preparation;
open Microsoft.Quantum.Arithmetic;
//If all entries of x are One, the Oracle returns |y> = |1>
operation andOracle (x : Qubit[], y : Qubit) : Unit {
body {
(Controlled X)(x, y);
}
adjoint auto;
}
//If all entries of x are Zero, the Oracle returns |y> = |0>
operation orOracle (x : Qubit[], y : Qubit) : Unit {
body {
ApplyToEachA(X, x);
Controlled X (x, y);
X(y);
ApplyToEachA(X, x);
}
adjoint auto;
}
//Given two qubits, XOR gate if 01 or 10 |y> = |1>
operation xorOracle2 (x : Qubit[], y : Qubit) : Unit {
X(y);
Controlled X(x, y);
X(x[0]);
X(x[1]);
Controlled X(x, y);
X(x[0]);
X(x[1]);
}
//Puts a state |000...0> into the GHZ state |000..0> + |111..1>/sqrt2
operation buildGHZ (qs : Qubit[]) : Unit{
body {
H(qs[0]);
for (i in 1..Length(qs)-1){
CNOT(qs[0], qs[i]);
}
}
adjoint auto;
}
//Puts a state |000...0> into the GHZ state |100..0> + |010..0> + ... |000..1>/sqrtN
operation buildW (qs : Qubit[]) : Unit is Adj + Ctl {
body {
let N = Length(qs);
Ry(2.0*ArcSin(Sqrt(1.0/(IntAsDouble(N)))), qs[0]);
if (N > 1){
((ControlledOnInt)(0, buildW))([qs[0]], qs[1...]);
}
}
adjoint auto;
}
operation isAllZeros (qs : Qubit[]) : Int {
return MeasureInteger(LittleEndian(qs)) == 0 ? 0 | 1;
}
//Generate Bell State 0 : |00>, 1 : |01>, 2 : |10>, 3 |11>
operation buildBell (qs : Qubit[], index : Int) : Unit {
H(qs[0]);
CNOT(qs[0], qs[1]);
if (index%2 == 1){
Z(qs[1]);
}
if (index/2 == 1){
X(qs[0]);
}
}
//Distinguish Bell State 0 : |00>, 1 : |01>, 2 : |10>, 3 : |11>
operation distinguishBell (qs : Qubit[]) : Int {
CNOT(qs[0], qs[1]);
H(qs[0]);
let m1 = M(qs[0]) == One ? 1 | 0;
let m2 = M(qs[1]) == One ? 1 | 0;
return 2*m2 + m1;
}
//Create a copy of a the given state
operation stateCopy (qs : Qubit[], copy : Qubit[]) : Unit {
for (i in 0..Length(qs)-1){
CNOT(qs[i], copy[i]);
}
}
//takes a integer array of 0/1s and creates an equivalent qubit string
operation arrToQbit (bits : Int[], qs : Qubit[]) : Unit {
for (i in 0..Length(qs)-1){
if (bits[i] == 1){
X(qs[i]);
}
}
}
//Teleport 2 qubits + message
operation Teleport (qAlice : Qubit, qBob : Qubit, qMessage : Qubit) : Unit {
H(qAlice);
CNOT(qAlice, qBob);
CNOT(qMessage, qAlice);
H(qMessage);
(Controlled Z)([qMessage], qBob);
(Controlled X)([qAlice], qBob);
}
//Superdensecoding protocol
operation SuperdenseCodingProtocol (b1 : Bool, b2 : Bool) : (Bool, Bool) {
using ((qAlice, qBob) = (Qubit(), Qubit())){
H(qAlice);
CNOT(qAlice, qBob);
//MCMAHON BOOK P236
if (b1){
Z(qAlice);
}
if (b2){
X(qAlice);
}
CNOT(qAlice, qBob);
H(qAlice);
//Measure the qubit at Z basis, and reset it
return ((MResetZ(qAlice) == One, MResetZ(qBob) == One));
}
}
//Destruct state
//Given a superposition state and a integer representing
//the state to be destroied we build a uniform superposition
//with the remaining ones.
operation Destruct(qs : Qubit[], state : Int) : Unit {
using (a = Qubit()) {
repeat {
(ControlledOnInt(state, X)) (qs, a);
let r = MResetZ(a);
}
until (r == Zero)
fixup {
ResetAll(qs);
}
}
}
//Increment, sum two qubits
operation Increment(register : LittleEndian) : Unit is Adj + Ctl {
using (q = Qubit[Length(register!)]){
X(q[0]);
RippleCarryAdderNoCarryTTK(LittleEndian(q), register);
X(q[0]);
}
}
//Decrement,
operation Decrement(register : LittleEndian) : Unit is Adj + Ctl {
using (q = Qubit[Length(register!)]){
ApplyToEachCA(X, q);
RippleCarryAdderNoCarryTTK(LittleEndian(q), register);
ApplyToEachCA(X, q);
}
}
//QUANTUM FOURIER TRANSFORM
operation Reverse(x : Qubit[]) : Unit is Adj+Ctl {
let N = Length(x);
for (i in 0 .. N/2-1) {
SWAP(x[i], x[N-1-i]);
}
}
operation myQFT(x : Qubit[]) : Unit is Adj+Ctl {
let n = Length(x);
for (i in n-1..-1..0) {
H(x[i]);
for (j in i-1..-1..0) {
let theta = (2.0*PI())/(IntAsDouble(1 <<< i-j+1));
Controlled R1([x[j]], (theta, x[i]));
}
}
Reverse (x);
}
|
https://github.com/DEBARGHYA4469/quantum-compiler
|
DEBARGHYA4469
|
# Main routine for synthesis of n-qubit unitary
# Written by Debarghya Kundu
# Email : debarghya4469@iitg.ernet.in
from two_level_decompose import *
from two_dimensionalise import *
from block import *
import numpy as np
import math
from random import randint
from graycode import *
from nontrivial import *
from qiskit import ClassicalRegister,QuantumRegister
from qiskit import available_backends,execute,register
from qiskit import get_backend,QuantumJob
from zy_decomposition import *
from control_U2 import *
def dagger(U):
return U.conjugate().transpose()
def get_Vk(U,dim,l):# call only once .........
VSET = dcmp(U,dim) # set of all two-level-matrices
Vk = []
for V in VSET:
V = dagger(V)
Vk.append(V)
V_tilde = []
ntv_cols = []
for V in Vk :
V_tilde.append(twoD(V,dim)[0]) # only matrix...
ntv_cols.append([twoD(V,dim)[1],twoD(V,dim)[2]])
return Vk,V_tilde,ntv_cols
#------------------------------------------------------TRAVERSAL ---------------------------------------------------------
#
# U = V1 x V2 x V3 x V4 x .....................x Vk
#
# <--------- V1 ------------------------------> <--------------------V2--------------------------> .......Vk........>
# g11 g21 g31 g41 ............gm-1,1 C~U gm-1,1 ........g12 g22............gm...........................................
# [ Call this part a BLOCK 1 ]
#
# g(i,j)'s are represented by n qubit tofolli gate. Stimulate this by 3-Q Tofollis
# Controlled-U by SWAP and Tofolli operations ............
#
# 1. Get the set of matrices Vi's
# 2. Get the two-dimensional form of it
# 3. get the set of non-trivial qubits g1 and gm from Vk
# 4. Get the Grey code sequence
# 5. Traverse g1 to gm-1
# 6. Apply controlled-U
# 7. Traverse gm-1 to gm
# 8. Go to step 1 unless set replenishes
#----------------------------------------------------TRAVERSAL------------------------------------------------------------
def bitflip(gi,gj,n): # checked..................................
for i in range(n):
if(gi[i] != gj[i]):
return i
def cUop2(ckt,V_tilde,q,n):
alpha,beta,gama,delta = zy_decompose(V_tilde)
ckt = Rz(ckt,(delta-beta)/2.0,q,n) # Apply :: C
ckt.cx(q[0],q[1]) # ancilla as ctr,tgt
ckt = Rz(ckt,-1.0*(beta+delta)/2.0,q,n) # Apply :: B
ckt = Ry(ckt,-1.0*gama/2.0,q,n) # Apply :: B
ckt.cx(q[0],q[1]) # ancilla as ctr,tgt
ckt = Ry(ckt,gama/2.0,q,n) # Apply :: A
ckt = Rz(ckt,beta,q,n) # Apply :: A
ckt.u1(alpha,q[0]) # phase to ancilla -> ref: N&C
return ckt
def synth(U,dim,nqubit):
q = QuantumRegister(2*nqubit-1)
c = ClassicalRegister(2*nqubit-1)
ckt = QuantumCircuit(q,c)
Vk,V_tilde,ntv_cols = get_Vk(U,dim,dim) # all the two-level matrices
for block in range(len(Vk)):
#print("\n--------------------------NEW BLOCK----------------------------------\n")
#print(np.round(Vk[block],decimals=2))
#print(np.round(V_tilde[block],decimals=2))
g1,gm = ntvl(ntv_cols[block][0],ntv_cols[block][1],nqubit) # correct
Gcode_sq = []
g1_list = []
gm_list = []
for k in range(nqubit):
g1_list.append(g1[k])
gm_list.append(gm[k])
Gcode_sq = graycodes(g1_list,gm_list) # all the gray codes for Vk
m = len(Gcode_sq) # g1----->gm
#print(g1,gm,Gcode_sq,m) # correct
j = 1
#....................................................DEBUGGED........................................................................
while(j<=m-2): # all the first m-2 tofollis
#print("\n.........Each tofollis...................\n")
bflip=bitflip(Gcode_sq[j-1],Gcode_sq[j],nqubit)
#print("bitflip:-->",bflip)
for bi in range(nqubit):
if(bflip==bi):continue
if(Gcode_sq[j][bi]=='0'):
ckt.x(q[bi]) # X
# print("x is done on:",bi)
if(bflip != nqubit-1):#not last bit flip
ckt = swaper(ckt,bflip,nqubit-1,q)
# print("swap",bflip,nqubit-1)
if(nqubit ==2): ckt.cx(q[0],q[1])
if(nqubit > 2): ckt = nQ_tofolli(ckt,nqubit,q)
#print("Toffoli")
if(bflip != nqubit-1):#not last bit flip
ckt = swaper(ckt,bflip,nqubit-1,q)
# print("swap",bflip,nqubit-1)
for bi in range(nqubit):
if(bflip==bi):continue
if(Gcode_sq[j][bi]=='0'):
ckt.x(q[bi]) # X
# print("x is done on:",bi)
j = j + 1
# Apply controlled-U for change from gm-1 to gm
#---------------------------------------------------------------------------------------------------------------------
bflip = bitflip(Gcode_sq[m-2],Gcode_sq[m-1],nqubit)
for bi in range(nqubit):
if(bflip==bi):continue
if(Gcode_sq[j][bi]=='0'):
ckt.x(q[bi]) # X
if(bflip != nqubit-1):#not last bit flip
ckt = swaper(ckt,bflip,nqubit-1,q)
if(nqubit == 2): ckt = cUop2(ckt,V_tilde,q,nqubit)
if(nqubit > 2): ckt = Control_U(ckt,V_tilde[block],q,nqubit)
if(bflip != nqubit-1):#not last bit flip
ckt = swaper(ckt,bflip,nqubit-1,q)
for bi in range(nqubit):
if(bflip==bi):continue
if(Gcode_sq[j][bi]=='0'):
ckt.x(q[bi]) # X
#----------------------------------------------------------------------------------------------------------------------
# Reverse the states ......................................
j = m-2
while(j >= 1): # all the first m-2 tofollis
bflip=bitflip(Gcode_sq[j-1],Gcode_sq[j],nqubit)
#print("bitflip:",j,"-->",bflip)
for bi in range(nqubit):
if(bflip==bi):continue
if(Gcode_sq[j][bi]=='0'):
ckt.x(q[bi]) # X
if(bflip != nqubit-1):#not last bit flip
ckt = swaper(ckt,bflip,nqubit-1,q)
if(nqubit ==2): ckt.cx(q[0],q[1])
if(nqubit > 2): ckt = nQ_tofolli(ckt,nqubit,q)
#print("Toffoli")
if(bflip != nqubit-1):#not last bit flip
ckt = swaper(ckt,bflip,nqubit-1,q)
for bi in range(nqubit):
if(bflip==bi):continue
if(Gcode_sq[j][bi]=='0'):
ckt.x(q[bi]) # X
j = j - 1
for i in range(2*nqubit-1):
ckt.measure(q[i],c[i])
get_result(ckt)
def kronecker(str): # find the kroncker product
z=0
if(str[0]=='0'):
z=np.array([[1],[0]])
if(str[0]=='1'):
z=np.array([[0],[1]])
for i in range(len(str)-1):
if(str[i+1]=='0'): z = np.kron(z,np.array([[1],[0]]))
if(str[i+1]=='1'): z = np.kron(z,np.array([[0],[1]]))
print(z)
def handle_1Qgates(U,dim,n):
q = QuantumRegister(n)
c = ClassicalRegister(n)
ckt = QuantumCircuit(q,c)
alpha,beta,gama,delta = zy_decompose(U) # decompose
ckt = Rz(ckt,(delta-beta)/2.0,q,n) # Apply :: C
ckt.x(q[0]) # ancilla as ctr,tgt
ckt = Rz(ckt,-1.0*(beta+delta)/2.0,q,n) # Apply :: B
ckt = Ry(ckt,-1.0*gama/2.0,q,n) # Apply :: B
ckt.x(q[0]) # ancilla as ctr,tgt
ckt = Ry(ckt,gama/2.0,q,n) # Apply :: A
ckt = Rz(ckt,beta,q,n) # Apply :: A
ckt.u1(alpha,q[0]) # phase to ancilla -> ref: N&C
for i in range(n):
ckt.measure(q[i],c[i])
get_result(ckt)
#u1 = np.array([[0,1],[1,0]]) # Pauli-X
#u2 = np.array([[1,1],[1,-1]])/math.sqrt(2.0) # Hadamard
#u2 = np.array([[1,1],[1,-1]])/math.sqrt(2.0)
#u= np.kron(u1,u1)
#u= np.kron(u,u1)
#u = unitary()
#u= np.kron(u,u2)
#u= np.kron(u,u2)
#u = np.array([[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],[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,0,0,0,0]])
#u = np.identity(16)
#for i in range(16):
# u[i][i]=0
# u[i][15-i]=1
#print(u)
#kk = np.array([[1],[0],[0],[0],[0],[0],[0],[0]])
#print(np.matmul(u,kk))
#synth(u,8,3)
# test .....................2018
#Vk,V_tilde,ntv_cols = get_Vk(u,8,8) # all the two-level matrices
#for V in range(len(Vk)):
# print(np.round(Vk[V],decimals=2),"\n")
# print(np.round(V_tilde[V],decimals=2),"\n")
# print("gcodes-->",ntv_cols[V][0],ntv_cols[V][1])
#print(np.allclose(np.identity(8),Vk[len(Vk)-1]))
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
""" This file allows to test the Multiplication blocks Ua. This blocks, when put together as explain in
the report, do the exponentiation.
The user can change N, n, a and the input state, to create the circuit:
up_reg |+> ---------------------|----------------------- |+>
|
|
|
-------|---------
------------ | | ------------
down_reg |x> ------------ | Mult | ------------ |(x*a) mod N>
------------ | | ------------
-----------------
Where |x> has n qubits and is the input state, the user can change it to whatever he wants
This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves
the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient
qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits
"""
""" Imports from qiskit"""
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, IBMQ, BasicAer
""" Imports to Python functions """
import math
import time
""" Local Imports """
from qfunctions import create_QFT, create_inverse_QFT
from qfunctions import cMULTmodN
""" Function to properly get the final state, it prints it to user """
""" This is only possible in this way because the program uses the statevector_simulator """
def get_final(results, number_aux, number_up, number_down):
i=0
""" Get total number of qubits to go through all possibilities """
total_number = number_aux + number_up + number_down
max = pow(2,total_number)
print('|aux>|top_register>|bottom_register>\n')
while i<max:
binary = bin(i)[2:].zfill(total_number)
number = results.item(i)
number = round(number.real, 3) + round(number.imag, 3) * 1j
""" If the respective state is not zero, then print it and store the state of the register where the result we are looking for is.
This works because that state is the same for every case where number !=0 """
if number!=0:
print('|{0}>|{1}>|{2}>'.format(binary[0:number_aux],binary[number_aux:(number_aux+number_up)],binary[(number_aux+number_up):(total_number)]),number)
if binary[number_aux:(number_aux+number_up)]=='1':
store = binary[(number_aux+number_up):(total_number)]
i=i+1
print(' ')
return int(store, 2)
""" Main program """
if __name__ == '__main__':
""" Select number N to do modN"""
N = int(input('Please insert integer number N: '))
print(' ')
""" Get n value used in QFT, to know how many qubits are used """
n = math.ceil(math.log(N,2))
""" Select the value for 'a' """
a = int(input('Please insert integer number a: '))
print(' ')
""" Please make sure the a and N are coprime"""
if math.gcd(a,N)!=1:
print('Please make sure the a and N are coprime. Exiting program.')
exit()
print('Total number of qubits used: {0}\n'.format(2*n+3))
print('Please check source file to change input quantum state. By default is |2>.\n')
ts = time.time()
""" Create quantum and classical registers """
aux = QuantumRegister(n+2)
up_reg = QuantumRegister(1)
down_reg = QuantumRegister(n)
aux_classic = ClassicalRegister(n+2)
up_classic = ClassicalRegister(1)
down_classic = ClassicalRegister(n)
""" Create Quantum Circuit """
circuit = QuantumCircuit(down_reg , up_reg , aux, down_classic, up_classic, aux_classic)
""" Initialize with |+> to also check if the control is working"""
circuit.h(up_reg[0])
""" Put the desired input state in the down quantum register. By default we put |2> """
circuit.x(down_reg[1])
""" Apply multiplication"""
cMULTmodN(circuit, up_reg[0], down_reg, aux, int(a), N, n)
""" show results of circuit creation """
create_time = round(time.time()-ts, 3)
if n < 8: print(circuit)
print(f"... circuit creation time = {create_time}")
ts = time.time()
""" Simulate the created Quantum Circuit """
simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1)
""" Get the results of the simulation in proper structure """
sim_result=simulation.result()
""" Get the statevector of the final quantum state """
outputstate = sim_result.get_statevector(circuit, decimals=3)
""" Show the final state after the multiplication """
after_exp = get_final(outputstate, n+2, 1, n)
""" show execution time """
exec_time = round(time.time()-ts, 3)
print(f"... circuit execute time = {exec_time}")
""" Print final quantum state to user """
print('When control=1, value after exponentiation is in bottom quantum register: |{0}>'.format(after_exp))
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
"""
Hydogen Lattice Benchmark Program - Qiskit
"""
import datetime
import json
import logging
import os
import re
import sys
import time
from collections import namedtuple
from typing import Optional
import numpy as np
from scipy.optimize import minimize
from qiskit import Aer, QuantumCircuit, execute
from qiskit.circuit import ParameterVector
from qiskit.exceptions import QiskitError
from qiskit.quantum_info import SparsePauliOp
from qiskit.result import sampled_expectation_value
sys.path[1:1] = ["_common", "_common/qiskit", "hydrogen-lattice/_common"]
sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../hydrogen-lattice/_common/"]
# benchmark-specific imports
import common
import execute as ex
import metrics as metrics
# import h-lattice_metrics from _common folder
import h_lattice_metrics as h_metrics
# DEVNOTE: this logging feature should be moved to common level
logger = logging.getLogger(__name__)
fname, _, ext = os.path.basename(__file__).partition(".")
log_to_file = False
try:
if log_to_file:
logging.basicConfig(
# filename=f"{fname}_{datetime.datetime.now().strftime('%Y_%m_%d_%S')}.log",
filename=f"{fname}.log",
filemode="w",
encoding="utf-8",
level=logging.INFO,
format="%(asctime)s %(name)s - %(levelname)s:%(message)s",
)
else:
logging.basicConfig(
level=logging.WARNING,
format='%(asctime)s %(name)s - %(levelname)s:%(message)s')
except Exception as e:
print(f"Exception {e} occured while configuring logger: bypassing logger config to prevent data loss")
pass
# Benchmark Name
benchmark_name = "Hydrogen Lattice"
np.random.seed(0)
# Hydrogen Lattice inputs ( Here input is Hamiltonian matrix --- Need to change)
hl_inputs = dict() # inputs to the run method
verbose = False
print_sample_circuit = True
# Indicates whether to perform the (expensive) pre compute of expectations
do_compute_expectation = True
# Array of energy values collected during iterations of VQE
lowest_energy_values = []
# Key metrics collected on last iteration of VQE
key_metrics = {}
# saved circuits for display
QC_ = None
Uf_ = None
# #theta parameters
vqe_parameter = namedtuple("vqe_parameter", "theta")
# DEBUG prints
# give argument to the python script as "debug" or "true" or "1" to enable debug prints
if len(sys.argv) > 1:
DEBUG = sys.argv[1].lower() in ["debug", "true", "1"]
else:
DEBUG = False
# Add custom metric names to metrics module
def add_custom_metric_names():
metrics.known_x_labels.update(
{
"iteration_count": "Iterations"
}
)
metrics.known_score_labels.update(
{
"solution_quality": "Solution Quality",
"accuracy_volume": "Accuracy Volume",
"accuracy_ratio": "Accuracy Ratio",
"energy": "Energy (Hartree)",
"standard_error": "Std Error",
}
)
metrics.score_label_save_str.update(
{
"solution_quality": "solution_quality",
"accuracy_volume": "accuracy_volume",
"accuracy_ratio": "accuracy_ratio",
"energy": "energy",
}
)
###################################
# HYDROGEN LATTICE CIRCUIT
# parameter mode to control length of initial thetas_array (global during dev phase)
# 1 - length 1
# 2 - length N, where N is number of excitation pairs
saved_parameter_mode = 1
def get_initial_parameters(num_qubits: int, thetas_array):
"""
Generate an initial set of parameters given the number of qubits and user-provided thetas_array.
If thetas_array is None, generate random array of parameters based on the parameter_mode
If thetas_array is of length 1, repeat to the required length based on parameter_mode
Otherwise, use the provided thetas_array.
Parameters
----------
num_qubits : int
number of qubits in circuit
thetas_array : array of floats
user-supplied array of initial values
Returns
-------
initial_parameters : array
array of parameter values required
"""
# compute required size of array based on number of occupation pairs
size = 1
if saved_parameter_mode > 1:
num_occ_pairs = (num_qubits // 2)
size = num_occ_pairs**2
# if None passed in, create array of random values
if thetas_array is None:
initial_parameters = np.random.random(size=size)
# if single value passed in, extend to required size
elif size > 1 and len(thetas_array) == 1:
initial_parameters = np.repeat(thetas_array, size)
# otherwise, use what user provided
else:
if len(thetas_array) != size:
print(f"WARNING: length of thetas_array {len(thetas_array)} does not equal required length {size}")
print(" Generating random values instead.")
initial_parameters = get_initial_parameters(num_qubits, None)
else:
initial_parameters = np.array(thetas_array)
if verbose:
print(f"... get_initial_parameters(num_qubits={num_qubits}, mode={saved_parameter_mode})")
print(f" --> initial_parameter[{size}]={initial_parameters}")
return initial_parameters
# Create the ansatz quantum circuit for the VQE algorithm.
def VQE_ansatz(num_qubits: int,
thetas_array,
parameterized,
num_occ_pairs: Optional[int] = None,
*args, **kwargs) -> QuantumCircuit:
if verbose:
print(f" ... VQE_ansatz(num_qubits={num_qubits}, thetas_array={thetas_array}")
# Generate the ansatz circuit for the VQE algorithm.
if num_occ_pairs is None:
num_occ_pairs = (num_qubits // 2) # e.g., half-filling, which is a reasonable chemical case
# do all possible excitations if not passed a list of excitations directly
excitation_pairs = []
for i in range(num_occ_pairs):
for a in range(num_occ_pairs, num_qubits):
excitation_pairs.append([i, a])
# create circuit of num_qubits
circuit = QuantumCircuit(num_qubits)
# Hartree Fock initial state
for occ in range(num_occ_pairs):
circuit.x(occ)
# if parameterized flag set, create a ParameterVector
parameter_vector = None
if parameterized:
parameter_vector = ParameterVector("t", length=len(excitation_pairs))
# for parameter mode 1, make all thetas the same as the first
if saved_parameter_mode == 1:
thetas_array = np.repeat(thetas_array, len(excitation_pairs))
# create a Hartree Fock initial state
for idx, pair in enumerate(excitation_pairs):
# if parameterized, use ParamterVector, otherwise raw theta value
theta = parameter_vector[idx] if parameterized else thetas_array[idx]
# apply excitation
i, a = pair[0], pair[1]
# implement the magic gate
circuit.s(i)
circuit.s(a)
circuit.h(a)
circuit.cx(a, i)
# Ry rotation
circuit.ry(theta, i)
circuit.ry(theta, a)
# implement M^-1
circuit.cx(a, i)
circuit.h(a)
circuit.sdg(a)
circuit.sdg(i)
""" TMI ...
if verbose:
print(f" --> thetas_array={thetas_array}")
print(f" --> parameter_vector={str(parameter_vector)}")
"""
return circuit, parameter_vector, thetas_array
# Create the benchmark program circuit array, for the given operator
def HydrogenLattice (num_qubits, operator, secret_int = 000000,
thetas_array = None, parameterized = None, use_estimator=False):
if verbose:
print(f"... HydrogenLattice(num_qubits={num_qubits}, thetas_array={thetas_array}")
# if no thetas_array passed in, create defaults
if thetas_array is None:
thetas_array = [1.0]
# create parameters in the form expected by the ansatz generator
# this is an array of betas followed by array of gammas, each of length = rounds
global _qc
global theta
# create the circuit the first time, add measurements
if ex.do_transpile_for_execute:
logger.info(f"*** Constructing parameterized circuit for {num_qubits = } {secret_int}")
_qc, parameter_vector, thetas_array = VQE_ansatz(
num_qubits=num_qubits,
thetas_array=thetas_array, parameterized=parameterized,
num_occ_pairs=None
)
# create a binding of Parameter values
params = {parameter_vector: thetas_array} if parameterized else None
if verbose:
print(f" --> params={params}")
logger.info(f"Create binding parameters for {thetas_array} {params}")
# for estimator, save the ansatz circuit to be used an example for display purposes
if use_estimator:
qc = _qc
# Prepare an array of circuits from the ansatz, with measurements in different bases
# save the first circuit in the array returned from prepare_circuits (with appendage)
# to be used an example for display purposes
else:
_qc_array, _formatted_observables = prepare_circuits(_qc, operator)
qc = _qc_array[0]
# print(qc)
# save small circuit example for display
global QC_
if QC_ is None or num_qubits <= 4:
if num_qubits <= 7:
QC_ = qc
# for estimator, return the ansatz circuit, operator, and parameters
if use_estimator:
return _qc, operator, params
# for single circuit execution, return a handle on the circuit array, the observables, and parameters
else:
return _qc_array, _formatted_observables, params
############### Prepare Circuits from Observables
# ---- classical Pauli sum operator from list of Pauli operators and coefficients ----
# Below function is to reduce some dependency on qiskit ( String data type issue) ----
# def pauli_sum_op(ops, coefs):
# if len(ops) != len(coefs):
# raise ValueError("The number of Pauli operators and coefficients must be equal.")
# pauli_sum_op_list = [(op, coef) for op, coef in zip(ops, coefs)]
# return pauli_sum_op_list
# ---- classical Pauli sum operator from list of Pauli operators and coefficients ----
def prepare_circuits(base_circuit, operator):
"""
Prepare the qubit-wise commuting circuits for a given operator.
Parameters
----------
base_circuit : QuantumCircuit
Initial quantum circuit without basis rotations.
operator : SparsePauliOp
Sparse Pauli operator / Hamiltonian.
Returns
-------
list
Array of QuantumCircuits with applied basis change.
list
Array of observables formatted as SparsePauliOps.
"""
# Mapping from Pauli operators to basis change gates
basis_change_map = {"X": ["h"], "Y": ["sdg", "h"], "Z": [], "I": []}
# Group commuting Pauli operators
commuting_ops = operator.group_commuting(qubit_wise=True)
# Initialize empty lists for storing output quantum circuits and formatted observables
qc_list = []
formatted_obs = []
# Loop over each group of commuting operators
for comm_op in commuting_ops:
basis = ""
pauli_labels = np.array([list(pauli_label) for pauli_label in comm_op.paulis.to_labels()])
for qubit in range(pauli_labels.shape[1]):
# return the pauli operations on qubits that aren't identity so we can rotate them
qubit_ops = "".join(filter(lambda x: x != "I", pauli_labels[:, qubit]))
basis += qubit_ops[0] if qubit_ops else "Z"
# Separate terms and coefficients
term_coeff_list = comm_op.to_list()
terms, coeffs = zip(*term_coeff_list)
# Initialize list for storing new terms
new_terms = []
# Loop to transform terms from 'X' and 'Y' to 'Z'
for term in terms:
new_term = ""
for c in term:
new_term += "Z" if c in "XY" else c
new_terms.append(new_term)
# Create and store new SparsePauliOp
new_op = SparsePauliOp.from_list(list(zip(new_terms, coeffs)))
formatted_obs.append(new_op)
# Create single quantum circuit for each group of commuting operators
basis_circuit = QuantumCircuit(len(basis))
basis_circuit.barrier()
for idx, pauli in enumerate(reversed(basis)):
for gate in basis_change_map[pauli]:
getattr(basis_circuit, gate)(idx)
composed_qc = base_circuit.compose(basis_circuit)
composed_qc.measure_all()
qc_list.append(composed_qc)
return qc_list, formatted_obs
def compute_energy(result_array, formatted_observables, num_qubits):
"""
Compute the expectation value of the circuit with respect to the Hamiltonian for optimization
"""
_probabilities = list()
for _res in result_array:
_counts = _res.get_counts()
_probs = normalize_counts(_counts, num_qubits=num_qubits)
_probabilities.append(_probs)
_expectation_values = calculate_expectation_values(_probabilities, formatted_observables)
energy = sum(_expectation_values)
# now get <H^2>, assuming Cov[si,si'] = 0
formatted_observables_sq = [(obs @ obs).simplify(atol=0) for obs in formatted_observables]
_expectation_values_sq = calculate_expectation_values(_probabilities, formatted_observables_sq)
# now since Cov is assumed to be zero, we compute each term's variance and sum the result.
# see Eq 5, e.g. in https://arxiv.org/abs/2004.06252
variance = sum([exp_sq - exp**2 for exp_sq, exp in zip(_expectation_values_sq, _expectation_values)])
return energy, variance
def calculate_expectation_values(probabilities, observables):
"""
Return the expectation values for an operator given the probabilities.
"""
expectation_values = list()
for idx, op in enumerate(observables):
expectation_value = sampled_expectation_value(probabilities[idx], op)
expectation_values.append(expectation_value)
return expectation_values
def normalize_counts(counts, num_qubits=None):
"""
Normalize the counts to get probabilities and convert to bitstrings.
"""
normalizer = sum(counts.values())
try:
dict({str(int(key, 2)): value for key, value in counts.items()})
if num_qubits is None:
num_qubits = max(len(key) for key in counts)
bitstrings = {key.zfill(num_qubits): value for key, value in counts.items()}
except ValueError:
bitstrings = counts
probabilities = dict({key: value / normalizer for key, value in bitstrings.items()})
assert abs(sum(probabilities.values()) - 1) < 1e-9
return probabilities
############### Prepare Circuits for Execution
def get_operator_for_problem(instance_filepath):
"""
Return an operator object for the problem.
Argument:
instance_filepath : problem defined by instance_filepath (but should be num_qubits + radius)
Returns:
operator : an object encapsulating the Hamiltoian for the problem
"""
# operator is paired hamiltonian for each instance in the loop
ops, coefs = common.read_paired_instance(instance_filepath)
operator = SparsePauliOp.from_list(list(zip(ops, coefs)))
return operator
# A dictionary of random energy filename, obtained once
random_energies_dict = None
def get_random_energy(instance_filepath):
"""
Get the 'random_energy' associated with the problem
"""
# read precomputed energies file from the random energies path
global random_energies_dict
# get the list of random energy filenames once
# (DEVNOTE: probably don't want an exception here, should just return 0)
if not random_energies_dict:
try:
random_energies_dict = common.get_random_energies_dict()
except ValueError as err:
logger.error(err)
print("Error reading precomputed random energies json file. Please create the file by running the script 'compute_random_energies.py' in the _common/random_sampler directory")
raise
# get the filename from the instance_filepath and get the random energy from the dictionary
filename = os.path.basename(instance_filepath)
filename = filename.split(".")[0]
random_energy = random_energies_dict[filename]
return random_energy
def get_classical_solutions(instance_filepath):
"""
Get a list of the classical solutions for this problem
"""
# solution has list of classical solutions for each instance in the loop
sol_file_name = instance_filepath[:-5] + ".sol"
method_names, values = common.read_puccd_solution(sol_file_name)
solution = list(zip(method_names, values))
return solution
# Return the file identifier (path) for the problem at this width, radius, and instance
def get_problem_identifier(num_qubits, radius, instance_num):
# if radius is given we should do same radius for max_circuits times
if radius is not None:
try:
instance_filepath = common.get_instance_filepaths(num_qubits, radius)
except ValueError as err:
logger.error(err)
instance_filepath = None
# if radius is not given we should do all the radius for max_circuits times
else:
instance_filepath_list = common.get_instance_filepaths(num_qubits)
try:
if len(instance_filepath_list) >= instance_num:
instance_filepath = instance_filepath_list[instance_num - 1]
else:
instance_filepath = None
except ValueError as err:
logger.error(err)
instance_filepath = None
return instance_filepath
#################################################
# EXPECTED RESULT TABLES (METHOD 1)
############### Expectation Tables Created using State Vector Simulator
# DEVNOTE: We are building these tables on-demand for now, but for larger circuits
# this will need to be pre-computed ahead of time and stored in a data file to avoid run-time delays.
# dictionary used to store pre-computed expectations, keyed by num_qubits and secret_string
# these are created at the time the circuit is created, then deleted when results are processed
expectations = {}
# Compute array of expectation values in range 0.0 to 1.0
# Use statevector_simulator to obtain exact expectation
def compute_expectation(qc, num_qubits, secret_int, backend_id="statevector_simulator", params=None):
# ts = time.time()
# to execute on Aer state vector simulator, need to remove measurements
qc = qc.remove_final_measurements(inplace=False)
if params is not None:
qc = qc.bind_parameters(params)
# execute statevector simulation
sv_backend = Aer.get_backend(backend_id)
sv_result = execute(qc, sv_backend, params=params).result()
# get the probability distribution
counts = sv_result.get_counts()
# print(f"... statevector expectation = {counts}")
# store in table until circuit execution is complete
id = f"_{num_qubits}_{secret_int}"
expectations[id] = counts
#print(f" ... time to execute statevector simulator: {time.time() - ts}")
# Return expected measurement array scaled to number of shots executed
def get_expectation(num_qubits, secret_int, num_shots):
# find expectation counts for the given circuit
id = f"_{num_qubits}_{secret_int}"
if id in expectations:
counts = expectations[id]
# scale probabilities to number of shots to obtain counts
for k, v in counts.items():
counts[k] = round(v * num_shots)
# delete from the dictionary
del expectations[id]
return counts
else:
return None
#################################################
# RESULT DATA ANALYSIS (METHOD 1)
expected_dist = {}
# Compare the measurement results obtained with the expected measurements to determine fidelity
def analyze_and_print_result(qc, result, num_qubits, secret_int, num_shots):
global expected_dist
# obtain counts from the result object
counts = result.get_counts(qc)
# retrieve pre-computed expectation values for the circuit that just completed
expected_dist = get_expectation(num_qubits, secret_int, num_shots)
# if the expectation is not being calculated (only need if we want to compute fidelity)
# assume that the expectation is the same as measured counts, yielding fidelity = 1
if expected_dist is None:
expected_dist = counts
if verbose:
print(f"For width {num_qubits} measured: {counts}\n expected: {expected_dist}")
# if verbose: print(f"For width {num_qubits} problem {secret_int}\n measured: {counts}\n expected: {expected_dist}")
# use our polarization fidelity rescaling
fidelity = metrics.polarization_fidelity(counts, expected_dist)
# if verbose: print(f"For secret int {secret_int} fidelity: {fidelity}")
return counts, fidelity
##### METHOD 2 function to compute application-specific figures of merit
def calculate_quality_metric(energy=None,
fci_energy=0,
random_energy=0,
precision = 4,
num_electrons = 2):
"""
Returns the quality metrics, namely solution quality, accuracy volume, and accuracy ratio.
Solution quality is a value between zero and one. The other two metrics can take any value.
Parameters
----------
energy : list
list of energies calculated for each iteration.
fci_energy : float
FCI energy for the problem.
random_energy : float
Random energy for the problem, precomputed and stored and read from json file
precision : float
precision factor used in solution quality calculation
changes the behavior of the monotonic arctan function
num_electrons : int
number of electrons in the problem
"""
_delta_energy_fci = np.absolute(np.subtract( np.array(energy), fci_energy))
_delta_random_fci = np.absolute(np.subtract( np.array(random_energy), fci_energy))
_relative_energy = np.absolute(
np.divide(
np.subtract( np.array(energy), fci_energy),
fci_energy)
)
#scale the solution quality to 0 to 1 using arctan
_solution_quality = np.subtract(
1,
np.divide(
np.arctan(
np.multiply(precision,_relative_energy)
),
np.pi/2)
)
# define accuracy volume as the absolute energy difference between the FCI energy and the energy of the solution normalized per electron
_accuracy_volume = np.divide(
np.absolute(
np.subtract( np.array(energy), fci_energy)
),
num_electrons
)
# define accuracy ratio as 1.0 minus the error in energy over the error in random energy:
# accuracy_ratio = 1.0 - abs(energy - FCI) ) / abs(random - FCI)
_accuracy_ratio = np.subtract(1.0, np.divide(_delta_energy_fci,_delta_random_fci))
return _solution_quality, _accuracy_volume, _accuracy_ratio
#################################################
# DATA SAVE FUNCTIONS
# Create a folder where the results will be saved.
# For every circuit width, metrics will be stored the moment the results are obtained
# In addition to the metrics, the parameter values obtained by the optimizer, as well as the counts
# measured for the final circuit will be stored.
def create_data_folder(save_res_to_file, detailed_save_names, backend_id):
global parent_folder_save
# if detailed filenames requested, use directory name with timestamp
if detailed_save_names:
start_time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
parent_folder_save = os.path.join("__data", f"{backend_id}{metrics.data_suffix}", f"run_start_{start_time_str}")
# otherwise, just put all json files under __data/backend_id
else:
parent_folder_save = os.path.join("__data", f"{backend_id}{metrics.data_suffix}")
# create the folder if it doesn't exist already
if save_res_to_file and not os.path.exists(parent_folder_save):
os.makedirs(os.path.join(parent_folder_save))
# Function to save final iteration data to file
def store_final_iter_to_metrics_json(
backend_id,
num_qubits,
radius,
instance_num,
num_shots,
converged_thetas_list,
energy,
detailed_save_names,
dict_of_inputs,
save_final_counts,
save_res_to_file,
_instances=None,
):
"""
For a given problem (specified by num_qubits and instance),
1. For a given restart, store properties of the final minimizer iteration to metrics.circuit_metrics_final_iter, and
2. Store various properties for all minimizer iterations for each restart to a json file.
"""
# In order to compare with uniform random sampling, get some samples
# Store properties of the final iteration, the converged theta values,
# as well as the known optimal value for the current problem,
# in metrics.circuit_metrics_final_iter.
metrics.store_props_final_iter(num_qubits, instance_num, "energy", energy)
metrics.store_props_final_iter(num_qubits, instance_num, "converged_thetas_list", converged_thetas_list)
# Save final iteration data to metrics.circuit_metrics_final_iter
# This data includes final counts, cuts, etc.
if save_res_to_file:
# Save data to a json file
dump_to_json(
parent_folder_save,
num_qubits,
radius,
instance_num,
dict_of_inputs,
converged_thetas_list,
energy,
save_final_counts=save_final_counts,
)
def dump_to_json(
parent_folder_save,
num_qubits,
radius,
instance_num,
dict_of_inputs,
converged_thetas_list,
energy,
save_final_counts=False,
):
"""
For a given problem (specified by number of qubits and instance_number),
save the evolution of various properties in a json file.
Items stored in the json file: Data from all iterations (iterations), inputs to run program ('general properties'), converged theta values ('converged_thetas_list'), computes results.
if save_final_counts is True, then also store the distribution counts
"""
# print(f"... saving data for width={num_qubits} radius={radius} instance={instance_num}")
if not os.path.exists(parent_folder_save):
os.makedirs(parent_folder_save)
store_loc = os.path.join(parent_folder_save, "width_{}_instance_{}.json".format(num_qubits, instance_num))
# Obtain dictionary with iterations data corresponding to given instance_num
all_restart_ids = list(metrics.circuit_metrics[str(num_qubits)].keys())
ids_this_restart = [r_id for r_id in all_restart_ids if int(r_id) // 1000 == instance_num]
iterations_dict_this_restart = {r_id: metrics.circuit_metrics[str(num_qubits)][r_id] for r_id in ids_this_restart}
# Values to be stored in json file
dict_to_store = {"iterations": iterations_dict_this_restart}
dict_to_store["general_properties"] = dict_of_inputs
dict_to_store["converged_thetas_list"] = converged_thetas_list
dict_to_store["energy"] = energy
# dict_to_store['unif_dict'] = unif_dict
# Also store the value of counts obtained for the final counts
"""
if save_final_counts:
dict_to_store['final_counts'] = iter_dist
#iter_dist.get_counts()
"""
# Now write the data fo;e
with open(store_loc, "w") as outfile:
json.dump(dict_to_store, outfile)
#################################################
# DATA LOAD FUNCTIONS
# %% Loading saved data (from json files)
def load_data_and_plot(folder=None, backend_id=None, **kwargs):
"""
The highest level function for loading stored data from a previous run
and plotting optgaps and area metrics
Parameters
----------
folder : string
Directory where json files are saved.
"""
_gen_prop = load_all_metrics(folder, backend_id=backend_id)
if _gen_prop is not None:
gen_prop = {**_gen_prop, **kwargs}
plot_results_from_data(**gen_prop)
def load_all_metrics(folder=None, backend_id=None):
"""
Load all data that was saved in a folder.
The saved data will be in json files in this folder
Parameters
----------
folder : string
Directory where json files are saved.
Returns
-------
gen_prop : dict
of inputs that were used in maxcut_benchmark.run method
"""
# if folder not passed in, create its name using standard format
if folder is None:
folder = f"__data/{metrics.get_backend_label(backend_id=backend_id)}"
# Note: folder here should be the folder where only the width=... files are stored, and not a folder higher up in the directory
assert os.path.isdir(folder), f"Specified folder ({folder}) does not exist."
metrics.init_metrics()
list_of_files = os.listdir(folder)
# print(list_of_files)
# list with elements that are tuples->(width,restartInd,filename)
width_restart_file_tuples = [
(*get_width_restart_tuple_from_filename(fileName), fileName)
for (ind, fileName) in enumerate(list_of_files)
if fileName.startswith("width")
]
# sort first by width, and then by restartInd
width_restart_file_tuples = sorted(width_restart_file_tuples, key=lambda x: (x[0], x[1]))
distinct_widths = list(set(it[0] for it in width_restart_file_tuples))
list_of_files = [[tup[2] for tup in width_restart_file_tuples if tup[0] == width] for width in distinct_widths]
# connot continue without at least one dataset
if len(list_of_files) < 1:
print("ERROR: No result files found")
return None
for width_files in list_of_files:
# For each width, first load all the restart files
for fileName in width_files:
gen_prop = load_from_width_restart_file(folder, fileName)
# next, do processing for the width
method = gen_prop["method"]
if method == 2:
num_qubits, _ = get_width_restart_tuple_from_filename(width_files[0])
metrics.process_circuit_metrics_2_level(num_qubits)
metrics.finalize_group(num_qubits)
# override device name with the backend_id if supplied by caller
if backend_id is not None:
metrics.set_plot_subtitle(f"Device = {backend_id}")
return gen_prop
# # load data from a specific file
def load_from_width_restart_file(folder, fileName):
"""
Given a folder name and a file in it, load all the stored data and store the values in metrics.circuit_metrics.
Also return the converged values of thetas, the final counts and general properties.
Parameters
----------
folder : string
folder where the json file is located
fileName : string
name of the json file
Returns
-------
gen_prop : dict
of inputs that were used in maxcut_benchmark.run method
"""
# Extract num_qubits and s from file name
num_qubits, restart_ind = get_width_restart_tuple_from_filename(fileName)
print(f"Loading from {fileName}, corresponding to {num_qubits} qubits and restart index {restart_ind}")
with open(os.path.join(folder, fileName), "r") as json_file:
data = json.load(json_file)
gen_prop = data["general_properties"]
converged_thetas_list = data["converged_thetas_list"]
energy = data["energy"]
if gen_prop["save_final_counts"]:
# Distribution of measured cuts
final_counts = data["final_counts"]
backend_id = gen_prop.get("backend_id")
metrics.set_plot_subtitle(f"Device = {backend_id}")
# Update circuit metrics
for circuit_id in data["iterations"]:
# circuit_id = restart_ind * 1000 + minimizer_loop_ind
for metric, value in data["iterations"][circuit_id].items():
metrics.store_metric(num_qubits, circuit_id, metric, value)
method = gen_prop["method"]
if method == 2:
metrics.store_props_final_iter(num_qubits, restart_ind, "energy", energy)
metrics.store_props_final_iter(num_qubits, restart_ind, "converged_thetas_list", converged_thetas_list)
if gen_prop["save_final_counts"]:
metrics.store_props_final_iter(num_qubits, restart_ind, None, final_counts)
return gen_prop
def get_width_restart_tuple_from_filename(fileName):
"""
Given a filename, extract the corresponding width and degree it corresponds to
For example the file "width=4_degree=3.json" corresponds to 4 qubits and degree 3
Parameters
----------
fileName : TYPE
DESCRIPTION.
Returns
-------
num_qubits : int
circuit width
degree : int
graph degree.
"""
pattern = "width_([0-9]+)_instance_([0-9]+).json"
match = re.search(pattern, fileName)
# print(match)
# assert match is not None, f"File {fileName} found inside folder. All files inside specified folder must be named in the format 'width_int_restartInd_int.json"
num_qubits = int(match.groups()[0])
degree = int(match.groups()[1])
return (num_qubits, degree)
################################################
# PLOT METHODS
def plot_results_from_data(
num_shots=100,
radius=0.75,
max_iter=30,
max_circuits=1,
method=2,
line_x_metrics=["iteration_count", "cumulative_exec_time"],
line_y_metrics=["energy", "accuracy_ratio_error"],
plot_layout_style="grid",
bar_y_metrics=["average_exec_times", "accuracy_ratio_error"],
bar_x_metrics=["num_qubits"],
show_elapsed_times=True,
use_logscale_for_times=False,
score_metric=["accuracy_ratio"],
y_metric=["num_qubits"],
x_metric=["cumulative_exec_time", "cumulative_elapsed_time"],
fixed_metrics={},
num_x_bins=15,
y_size=None,
x_size=None,
x_min=None,
x_max=None,
detailed_save_names=False,
**kwargs,
):
"""
Plot results from the data contained in metrics tables.
"""
# Add custom metric names to metrics module (in case this is run outside of run())
add_custom_metric_names()
# handle single string form of score metrics
if type(score_metric) == str:
score_metric = [score_metric]
# for hydrogen lattice, objective function is always 'Energy'
obj_str = "Energy"
suffix = ""
# If detailed names are desired for saving plots, put date of creation, etc.
if detailed_save_names:
cur_time = datetime.datetime.now()
dt = cur_time.strftime("%Y-%m-%d_%H-%M-%S")
suffix = f"s{num_shots}_r{radius}_mi{max_iter}_{dt}"
suptitle = f"Benchmark Results - {benchmark_name} ({method}) - Qiskit"
backend_id = metrics.get_backend_id()
options = {"shots": num_shots, "radius": radius, "restarts": max_circuits}
# plot all line metrics, including solution quality and accuracy ratio
# vs iteration count and cumulative execution time
h_metrics.plot_all_line_metrics(
suptitle,
line_x_metrics=line_x_metrics,
line_y_metrics=line_y_metrics,
plot_layout_style=plot_layout_style,
backend_id=backend_id,
options=options,
)
# plot all cumulative metrics, including average_execution_time and accuracy ratio
# over number of qubits
h_metrics.plot_all_cumulative_metrics(
suptitle,
bar_y_metrics=bar_y_metrics,
bar_x_metrics=bar_x_metrics,
show_elapsed_times=show_elapsed_times,
use_logscale_for_times=use_logscale_for_times,
plot_layout_style=plot_layout_style,
backend_id=backend_id,
options=options,
)
# plot all area metrics
metrics.plot_all_area_metrics(
suptitle,
score_metric=score_metric,
x_metric=x_metric,
y_metric=y_metric,
fixed_metrics=fixed_metrics,
num_x_bins=num_x_bins,
x_size=x_size,
y_size=y_size,
x_min=x_min,
x_max=x_max,
options=options,
suffix=suffix,
which_metric="solution_quality",
)
################################################
################################################
# RUN METHOD
MAX_QUBITS = 16
def run(
min_qubits=2, max_qubits=4, skip_qubits=2, max_circuits=3, num_shots=100,
method=2,
radius=None,
thetas_array=None,
parameterized=False, parameter_mode=1,
use_estimator=False,
do_fidelities=True,
minimizer_function=None,
minimizer_tolerance=1e-3, max_iter=30, comfort=False,
line_x_metrics=["iteration_count", "cumulative_exec_time"],
line_y_metrics=["energy", "accuracy_ratio_error"],
bar_y_metrics=["average_exec_times", "accuracy_ratio_error"],
bar_x_metrics=["num_qubits"],
score_metric=["accuracy_ratio"],
x_metric=["cumulative_exec_time", "cumulative_elapsed_time"],
y_metric="num_qubits",
fixed_metrics={},
num_x_bins=15,
y_size=None,
x_size=None,
show_results_summary=True,
plot_results=True,
plot_layout_style="grid",
show_elapsed_times=True,
use_logscale_for_times=False,
save_res_to_file=True, save_final_counts=False, detailed_save_names=False,
backend_id="qasm_simulator",
provider_backend=None, hub="ibm-q", group="open", project="main",
exec_options=None,
context=None,
_instances=None,
):
"""
Parameters
----------
min_qubits : int, optional
The smallest circuit width for which benchmarking will be done The default is 3.
max_qubits : int, optional
The largest circuit width for which benchmarking will be done. The default is 6.
max_circuits : int, optional
Number of restarts. The default is None.
num_shots : int, optional
Number of times the circut will be measured, for each iteration. The default is 100.
method : int, optional
If 1, then do standard metrics, if 2, implement iterative algo metrics. The default is 1.
thetas_array : list, optional
list or ndarray of theta values. The default is None.
N : int, optional
For the max % counts metric, choose the highest N% counts. The default is 10.
alpha : float, optional
Value between 0 and 1. The default is 0.1.
parameterized : bool, optional
Whether to use parameter objects in circuits or not. The default is False.
parameter_mode : bool, optional
If True, use thetas_array of length 1, otherwise (num_qubits//2)**2, to match excitation pairs
use_estimator : bool, optional
If True, use the estimator within the objective function, instead of multiple circuits
do_fidelities : bool, optional
Compute circuit fidelity. The default is True.
minimizer_function : function
custom function used for minimizer
minimizer_tolerance : float
tolerance for minimizer, default is 1e-3,
max_iter : int, optional
Number of iterations for the minimizer routine. The default is 30.
plot_layout_style : str, optional
Style of plot layout, 'grid', 'stacked', or 'individual', default = 'grid'
line_x_metrics : list or string, optional
Which metrics are to be plotted on x-axis in line metrics plots.
line_y_metrics : list or string, optional
Which metrics are to be plotted on y-axis in line metrics plots.
show_elapsed_times : bool, optional
In execution times bar chart, include elapsed times if True
use_logscale_for_times : bool, optional
In execution times bar plot, use a log scale to show data
score_metric : list or string, optional
Which metrics are to be plotted in area metrics plots. The default is 'fidelity'.
x_metric : list or string, optional
Horizontal axis for area plots. The default is 'cumulative_exec_time'.
y_metric : list or string, optional
Vertical axis for area plots. The default is 'num_qubits'.
fixed_metrics : TYPE, optional
DESCRIPTION. The default is {}.
num_x_bins : int, optional
DESCRIPTION. The default is 15.
y_size : TYPint, optional
DESCRIPTION. The default is None.
x_size : string, optional
DESCRIPTION. The default is None.
backend_id : string, optional
DESCRIPTION. The default is 'qasm_simulator'.
provider_backend : string, optional
DESCRIPTION. The default is None.
hub : string, optional
DESCRIPTION. The default is "ibm-q".
group : string, optional
DESCRIPTION. The default is "open".
project : string, optional
DESCRIPTION. The default is "main".
exec_options : string, optional
DESCRIPTION. The default is None.
plot_results : bool, optional
Plot results only if True. The default is True.
save_res_to_file : bool, optional
Save results to json files. The default is True.
save_final_counts : bool, optional
If True, also save the counts from the final iteration for each problem in the json files. The default is True.
detailed_save_names : bool, optional
If true, the data and plots will be saved with more detailed names. Default is False
confort : bool, optional
If true, print comfort dots during execution
"""
# Store all the input parameters into a dictionary.
# This dictionary will later be stored in a json file
# It will also be used for sending parameters to the plotting function
dict_of_inputs = locals()
thetas = [] # a default empty list of thetas
# Update the dictionary of inputs
dict_of_inputs = {**dict_of_inputs, **{"thetas_array": thetas, "max_circuits": max_circuits}}
# Delete some entries from the dictionary; they may contain secrets or function pointers
for key in ["hub", "group", "project", "provider_backend", "exec_options", "minimizer_function"]:
dict_of_inputs.pop(key)
global hydrogen_lattice_inputs
hydrogen_lattice_inputs = dict_of_inputs
###########################
# Benchmark Initializeation
global QC_
global circuits_done
global minimizer_loop_index
global opt_ts
print(f"{benchmark_name} ({method}) Benchmark Program - Qiskit")
QC_ = None
# validate parameters
max_qubits = max(2, max_qubits)
max_qubits = min(MAX_QUBITS, max_qubits)
min_qubits = min(max(2, min_qubits), max_qubits)
skip_qubits = max(2, skip_qubits)
# create context identifier
if context is None: context = f"{benchmark_name} ({method}) Benchmark"
try:
print("Validating user inputs...")
# raise an exception if either min_qubits or max_qubits is not even
if min_qubits % 2 != 0 or max_qubits % 2 != 0:
raise ValueError(
"min_qubits and max_qubits must be even. min_qubits = {}, max_qubits = {}".format(
min_qubits, max_qubits
)
)
except ValueError as err:
# display error message and stop execution if min_qubits or max_qubits is not even
logger.error(err)
if min_qubits % 2 != 0:
min_qubits += 1
if max_qubits % 2 != 0:
max_qubits -= 1
max_qubits = min(max_qubits, MAX_QUBITS)
print(err.args[0] + "\n Running for for values min_qubits = {}, max_qubits = {}".format(min_qubits, max_qubits))
# don't compute exectation unless fidelity is is needed
global do_compute_expectation
do_compute_expectation = do_fidelities
# save the desired parameter mode globally (for now, during dev)
global saved_parameter_mode
saved_parameter_mode = parameter_mode
# given that this benchmark does every other width, set y_size default to 1.5
if y_size is None:
y_size = 1.5
##########
# Initialize metrics module with empty metrics arrays
metrics.init_metrics()
# Add custom metric names to metrics module
add_custom_metric_names()
# Define custom result handler
def execution_handler(qc, result, num_qubits, s_int, num_shots):
# determine fidelity of result set
num_qubits = int(num_qubits)
counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots)
metrics.store_metric(num_qubits, s_int, "solution_quality", fidelity)
def execution_handler2(qc, result, num_qubits, s_int, num_shots):
# Stores the results to the global saved_result variable
global saved_result
saved_result = result
# Initialize execution module using the execution result handler above and specified backend_id
# for method=2 we need to set max_jobs_active to 1, so each circuit completes before continuing
if method == 2:
ex.max_jobs_active = 1
ex.init_execution(execution_handler2)
else:
ex.init_execution(execution_handler)
# initialize the execution module with target information
ex.set_execution_target(backend_id, provider_backend=provider_backend,
hub=hub, group=group, project=project,
exec_options=exec_options,
context=context
)
# create a data folder for the results
create_data_folder(save_res_to_file, detailed_save_names, backend_id)
###########################
# Benchmark Execution Loop
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
# DEVNOTE: increment by 2 for paired electron circuits
for num_qubits in range(min_qubits, max_qubits + 1, 2):
if method == 1:
print(f"************\nExecuting [{max_circuits}] circuits for num_qubits = {num_qubits}")
else:
print(f"************\nExecuting [{max_circuits}] restarts for num_qubits = {num_qubits}")
# # If radius is negative,
# if radius < 0 :
# radius = max(3, (num_qubits + radius))
# loop over all instance files according to max_circuits given
# instance_num index starts from 1
for instance_num in range(1, max_circuits + 1):
# get the file identifier (path) for the problem at this width, radius, and instance
# DEVNOTE: this identifier should NOT be the filepath, use another method
instance_filepath = get_problem_identifier(num_qubits, radius, instance_num)
if instance_filepath is None:
print(
f"WARNING: cannot find problem file for num_qubits={num_qubits}, radius={radius}, instance={instance_num}\n"
)
break
# if radius given, each instance will use this same radius
if radius is not None:
current_radius = radius
# else find current radius from the filename found for this num_qubits and instance_num
# DEVNOTE: klunky, improve later
else:
current_radius = float(os.path.basename(instance_filepath).split("_")[2])
current_radius += float(os.path.basename(instance_filepath).split("_")[3][:2]) * 0.01
if verbose:
print(f"... executing problem num_qubits={num_qubits}, radius={radius}, instance={instance_num}")
# obtain the Hamiltonian operator object for the current problem
# if the problem is not pre-defined, we are done with this number of qubits
operator = get_operator_for_problem(instance_filepath)
if operator is None:
print(f" ... problem not found.")
break
# get a list of the classical solutions for this problem
solution = get_classical_solutions(instance_filepath)
# get the 'random_energy' associated with the problem
random_energy = get_random_energy(instance_filepath)
# create an intial thetas_array, given the circuit width and user input
thetas_array_0 = get_initial_parameters(num_qubits, thetas_array)
###############
if method == 1:
# create the circuit(s) for given qubit size and secret string, store time metric
ts = time.time()
# create the circuits to be tested
# for Estimator, we only need circuit and params, we have operator
if use_estimator:
qc, _, params = HydrogenLattice(
num_qubits=num_qubits,
secret_int=instance_num,
thetas_array=thetas_array,
parameterized=parameterized,
operator=operator,
use_estimator=use_estimator
)
# for single circuit execution, we need an array of ciruiits and observables
else:
qc_array, frmt_obs, params = HydrogenLattice(
num_qubits=num_qubits,
secret_int=instance_num,
thetas_array=thetas_array,
parameterized=parameterized,
operator=operator,
use_estimator=use_estimator
)
# We only execute one of the circuits created, the last one. which is in the
# z-basis. This is the one that is most illustrative of a device's fidelity.
# DEVNOTE: maybe we should do all three, and aggregate, just as in method 2?
qc = qc_array[-1]
""" TMI ...
# for testing and debugging ...
#if using parameter objects, bind before printing
if verbose:
print(qc.bind_parameters(params) if parameterized else qc)
"""
# store the creation time for these circuits
metrics.store_metric(num_qubits, instance_num, "create_time", time.time() - ts)
# classically pre-compute and cache an array of expected measurement counts
# for comparison against actual measured counts for fidelity calc (in analysis)
if do_compute_expectation:
logger.info("Computing expectation")
# pass parameters as they are used during execution
compute_expectation(qc, num_qubits, instance_num, params=params)
# submit circuit for execution on target, with parameters
ex.submit_circuit(qc, num_qubits, instance_num, shots=num_shots, params=params)
###############
if method == 2:
logger.info(f"=============== Begin method 2 loop, enabling transpile")
# a unique circuit index used inside the inner minimizer loop as identifier
# Value of 0 corresponds to the 0th iteration of the minimizer
minimizer_loop_index = 0
# Always start by enabling transpile ...
ex.set_tranpilation_flags(do_transpile_metrics=True, do_transpile_for_execute=True)
# get the classically computed expected energy variables from solution object
doci_energy = float(next(value for key, value in solution if key == "doci_energy"))
fci_energy = float(next(value for key, value in solution if key == "fci_energy"))
hf_energy = float(next(value for key, value in solution if key == "hf_energy"))
# begin timer accumulation
cumlative_iter_time = [0]
start_iters_t = time.time()
#########################################
#### Objective function to compute energy
def objective_function(thetas_array):
"""
Objective function that calculates the expected energy for the given parameterized circuit
Parameters
----------
thetas_array : list
list of theta values.
"""
# Every circuit needs a unique id; add unique_circuit_index instead of s_int
global minimizer_loop_index
unique_id = instance_num * 1000 + minimizer_loop_index
# variables used to aggregate metrics for all terms
result_array = []
quantum_execution_time = 0.0
quantum_elapsed_time = 0.0
# create ansatz from the operator, in multiple circuits, one for each measured basis
# call the HydrogenLattice ansatz to generate a parameterized hamiltonian
ts = time.time()
# for Estimator, we only need circuit and params, we have operator
if use_estimator:
qc, _, params = HydrogenLattice(
num_qubits=num_qubits,
secret_int=unique_id,
thetas_array=thetas_array,
parameterized=parameterized,
operator=operator,
use_estimator=use_estimator
)
# for single circuit execution, we need an array of ciruiits and observables
else:
qc_array, frmt_obs, params = HydrogenLattice(
num_qubits=num_qubits,
secret_int=unique_id,
thetas_array=thetas_array,
parameterized=parameterized,
operator=operator,
use_estimator=use_estimator
)
# store the time it took to create the circuit
metrics.store_metric(num_qubits, unique_id, "create_time", time.time() - ts)
#####################
# loop over each of the circuits that are generated with basis measurements and execute
if verbose:
print(f"... ** compute energy for num_qubits={num_qubits}, circuit={unique_id}, parameters={params}, thetas_array={thetas_array}")
# If using Estimator, pass the ansatz to Estimator with operator and get result energy
if use_estimator:
# submit the ansatz circuit to the Estimator for execution
result = submit_to_estimator(qc, num_qubits, unique_id, parameterized, params, operator, num_shots, backend_id, provider_backend)
# after first execution and thereafter, no need for transpilation if parameterized
if parameterized:
# DEVNOTE: since Hydro uses 3 circuits inside this loop, and execute.py can only
# cache 1 at a time, we cannot yet implement caching. Transpile every time for now.
cached_circuits = False
if cached_circuits:
ex.set_tranpilation_flags(do_transpile_metrics=False, do_transpile_for_execute=False)
logger.info(f"**** First execution complete, disabling transpile")
# result array stores the multiple results we measure along different Pauli basis.
#global saved_result
# Aggregate execution and elapsed time for running all three circuits
# corresponding to different measurements along the different Pauli bases
quantum_execution_time = (
quantum_execution_time
+ metrics.get_metric(num_qubits, unique_id, "exec_time")
)
quantum_elapsed_time = (
quantum_elapsed_time
+ metrics.get_metric(num_qubits, unique_id, "elapsed_time")
)
# with single circuit mode, execute array of circuits and computer energy from observables
else:
# loop over each circuit and execute
for qc in qc_array:
# bind parameters to circuit before execution
if parameterized:
qc.bind_parameters(params)
# submit circuit for execution on target with the current parameters
ex.submit_circuit(qc, num_qubits, unique_id, shots=num_shots, params=params)
# wait for circuit to complete by calling finalize ...
# finalize execution of group (each circuit in loop accumulates metrics)
ex.finalize_execution(None, report_end=False)
# after first execution and thereafter, no need for transpilation if parameterized
if parameterized:
# DEVNOTE: since Hydro uses 3 circuits inside this loop, and execute.py can only
# cache 1 at a time, we cannot yet implement caching. Transpile every time for now.
cached_circuits = False
if cached_circuits:
ex.set_tranpilation_flags(do_transpile_metrics=False, do_transpile_for_execute=False)
logger.info(f"**** First execution complete, disabling transpile")
# result array stores the multiple results we measure along different Pauli basis.
global saved_result
result_array.append(saved_result)
# Aggregate execution and elapsed time for running all three circuits
# corresponding to different measurements along the different Pauli bases
quantum_execution_time = (
quantum_execution_time
+ metrics.get_metric(num_qubits, unique_id, "exec_time")
)
quantum_elapsed_time = (
quantum_elapsed_time
+ metrics.get_metric(num_qubits, unique_id, "elapsed_time")
)
#####################
# classical processing of results
global opt_ts
global cumulative_iter_time
cumlative_iter_time.append(cumlative_iter_time[-1] + quantum_execution_time)
# store the new exec time and elapsed time back to metrics
metrics.store_metric(num_qubits, unique_id, "exec_time", quantum_execution_time)
metrics.store_metric(num_qubits, unique_id, "elapsed_time", quantum_elapsed_time)
# increment the minimizer loop index, the index is increased by one
# for the group of three circuits created ( three measurement basis circuits)
minimizer_loop_index += 1
# print "comfort dots" (newline before the first iteration)
if comfort:
if minimizer_loop_index == 1:
print("")
print(".", end="")
if verbose:
print("")
# Start counting classical optimizer time here again
tc1 = time.time()
# compute energy for this combination of observables and measurements
global energy
global variance
global standard_error
# for Estimator, energy and variance are returned directly
if use_estimator:
energy = result.values[0]
variance = result.metadata[0]['variance']
# for single circuit execution, need to compute energy from results and observables
else:
energy, variance = compute_energy(
result_array=result_array, formatted_observables=frmt_obs, num_qubits=num_qubits
)
# calculate std error from the variance -- identically zero if using statevector simulator
if backend_id.lower() != "statevector_simulator":
standard_error = np.sqrt(variance/num_shots)
else:
standard_error = 0.0
if verbose:
print(f" ... energy={energy:.5f} +/- stderr={standard_error:.5f}")
# append the most recent energy value to the list
lowest_energy_values.append(energy)
# calculate the solution quality, accuracy volume and accuracy ratio
global solution_quality, accuracy_volume, accuracy_ratio
solution_quality, accuracy_volume, accuracy_ratio = calculate_quality_metric(
energy=energy,
fci_energy=fci_energy,
random_energy=random_energy,
precision=0.5,
num_electrons=num_qubits,
)
# store the metrics for the current iteration
metrics.store_metric(num_qubits, unique_id, "energy", energy)
metrics.store_metric(num_qubits, unique_id, "variance", variance)
metrics.store_metric(num_qubits, unique_id, "standard_error", standard_error)
metrics.store_metric(num_qubits, unique_id, "random_energy", random_energy)
metrics.store_metric(num_qubits, unique_id, "solution_quality", solution_quality)
metrics.store_metric(num_qubits, unique_id, "accuracy_volume", accuracy_volume)
metrics.store_metric(num_qubits, unique_id, "accuracy_ratio", accuracy_ratio)
metrics.store_metric(num_qubits, unique_id, "fci_energy", fci_energy)
metrics.store_metric(num_qubits, unique_id, "doci_energy", doci_energy)
metrics.store_metric(num_qubits, unique_id, "hf_energy", hf_energy)
metrics.store_metric(num_qubits, unique_id, "radius", current_radius)
metrics.store_metric(num_qubits, unique_id, "iteration_count", minimizer_loop_index)
# store most recent metrics for export
key_metrics["radius"] = current_radius
key_metrics["fci_energy"] = fci_energy
key_metrics["doci_energy"] = doci_energy
key_metrics["hf_energy"] = hf_energy
key_metrics["random_energy"] = random_energy
key_metrics["iteration_count"] = minimizer_loop_index
key_metrics["energy"] = energy
key_metrics["variance"] = variance
key_metrics["standard_error"] = standard_error
key_metrics["accuracy_ratio"] = accuracy_ratio
key_metrics["solution_quality"] = solution_quality
key_metrics["accuracy_volume"] = accuracy_volume
return energy
# callback for each iteration (currently unused)
def callback_thetas_array(thetas_array):
pass
###########################
# End of Objective Function
# if in verbose mode, comfort dots need a newline before optimizer gets going
# if comfort and verbose:
# print("")
# Initialize an empty list to store the energy values from each iteration
lowest_energy_values.clear()
# execute COPYLA classical optimizer to minimize the objective function
# objective function is called repeatedly with varying parameters
# until the lowest energy found
if minimizer_function is None:
ret = minimize(
objective_function,
x0=thetas_array_0.ravel(), # note: revel not really needed for this ansatz
method="COBYLA",
tol=minimizer_tolerance,
options={"maxiter": max_iter, "disp": False},
callback=callback_thetas_array,
)
# or, execute a custom minimizer
else:
ret = minimizer_function(
objective_function=objective_function,
initial_parameters=thetas_array_0.ravel(), # note: revel not really needed for this ansatz
callback=callback_thetas_array,
)
# if verbose:
# print(f"\nEnergies for problem of {num_qubits} qubits and radius {current_radius} of paired hamiltionians")
# print(f" PUCCD calculated energy : {ideal_energy}")
if comfort:
print("")
# show results to console
if show_results_summary:
print(
f"Classically Computed Energies from solution file for {num_qubits} qubits and radius {current_radius}"
)
print(f" DOCI calculated energy : {doci_energy}")
print(f" FCI calculated energy : {fci_energy}")
print(f" Hartree-Fock calculated energy : {hf_energy}")
print(f" Random Solution calculated energy : {random_energy}")
print(f"Computed Energies for {num_qubits} qubits and radius {current_radius}")
print(f" Solution Energy : {lowest_energy_values[-1]}")
print(f" Accuracy Ratio : {accuracy_ratio}, Solution Quality : {solution_quality}")
# pLotting each instance of qubit count given
cumlative_iter_time = cumlative_iter_time[1:]
# save the data for this qubit width, and instance number
store_final_iter_to_metrics_json(
backend_id=backend_id,
num_qubits=num_qubits,
radius=radius,
instance_num=instance_num,
num_shots=num_shots,
converged_thetas_list=ret.x.tolist(),
energy=lowest_energy_values[-1],
# iter_size_dist=iter_size_dist, iter_dist=iter_dist,
detailed_save_names=detailed_save_names,
dict_of_inputs=dict_of_inputs,
save_final_counts=save_final_counts,
save_res_to_file=save_res_to_file,
_instances=_instances,
)
###### End of instance processing
# for method 2, need to aggregate the detail metrics appropriately for each group
# Note that this assumes that all iterations of the circuit have completed by this point
if method == 2:
metrics.process_circuit_metrics_2_level(num_qubits)
metrics.finalize_group(num_qubits)
# 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 a sample circuit
if print_sample_circuit:
if method == 1:
print("Sample Circuit:")
print(QC_ if QC_ is not None else " ... too large!")
# Plot metrics for all circuit sizes
if method == 1:
metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - Qiskit",
options=dict(shots=num_shots))
elif method == 2:
if plot_results:
plot_results_from_data(**dict_of_inputs)
def get_final_results():
"""
Return the energy and dict of key metrics of the last run().
"""
# find the final energy value and return it
energy=lowest_energy_values[-1] if len(lowest_energy_values) > 0 else None
return energy, key_metrics
###################################
# DEVNOTE: This function should be re-implemented as just the objective function
# as it is defined in the run loop above with the necessary parameters
def run_objective_function(**kwargs):
"""
Define a function to perform one iteration of the objective function.
These argruments are preset to single execution: method=2, max_circuits=1, max+iter=1
"""
# Fix arguments required to execute of single instance
hl_single_args = dict(
method=2, # method 2 defines the objective function
max_circuits=1, # only one repetition
max_iter=1, # maximum minimizer iterations to perform, set to 1
# disable display options for line plots
line_y_metrics=None,
line_x_metrics=None,
# disable display options for bar plots
bar_y_metrics=None,
bar_x_metrics=None,
# disable display options for area plots
score_metric=None,
x_metric=None,
)
# get the num_qubits are so we can force min and max to it.
num_qubits = kwargs.pop("num_qubits")
# Run the benchmark in method 2 at just one qubit size
run(min_qubits=num_qubits, max_qubits=num_qubits,
**kwargs, **hl_single_args)
# find the final energy value and return it
energy=lowest_energy_values[-1] if len(lowest_energy_values) > 0 else None
return energy, key_metrics
#################################
# QISKit ESTIMATOR EXECUTION
# DEVNOTE: This code will be moved to common/qiskit/execute.py so it can be used elsewhere
def submit_to_estimator(qc=None, num_qubits=1, unique_id=-1, parameterized=False, params=None, operator=None, num_shots=100, backend_id=None, provider_backend=None):
#print(f"... *** using Estimator")
from qiskit.primitives import BackendEstimator, Estimator
# start timing of estimator here
ts_launch = time.time()
# bind parameters to circuit before execution
if parameterized:
qc_bound = qc.assign_parameters(params, inplace=False)
else:
qc_bound = qc
if backend_id.lower() == "statevector_simulator":
estimator = Estimator() # statevector doesn't work w/ vanilla BackendEstimator
else:
estimator = BackendEstimator(backend=Aer.get_backend(backend_id)) # FIXME: won't work for vendor QPUs
#estimator = BackendEstimator(backend=provider_backend)
ts_start = time.time()
#print(operator)
job = estimator.run(qc_bound, operator, shots=num_shots)
#print(job)
#print(job.metrics())
result = job.result()
ts_done = time.time()
exec_time = ts_done - ts_start
elapsed_time = ts_done - ts_launch
#print(f"... elapsed, exec = {elapsed_time}, {exec_time}")
metrics.store_metric(num_qubits, unique_id, "exec_time", exec_time)
metrics.store_metric(num_qubits, unique_id, "elapsed_time", elapsed_time)
return result
#################################
# MAIN
# # if main, execute method
if __name__ == "__main__":
run()
# # %%
# run()
|
https://github.com/qismib/TraNQI
|
qismib
|
#------------------------------------------------------------------------------
# Qaoa.py
#
# Implementation of the Quantum Approximate Optimization Algorithm (QAOA) [1],[2]
# specifically tailored for solving the MaxCut problem on graphs [3].
# This class facilitates the creation of QAOA circuits with
# various types of mixer operators and allows execution on a quantum simulator
# backend provided by Qiskit.
#
# The `Qaoa` class provides methods to:
# - Initialize with QAOA parameters, graph instance, mixer type, and backend settings
# - Create cost operator and various mixer operators (x, xx, y, yy, xy)
# - Generate the complete QAOA circuit
#
# Initialization parameters include the number of QAOA layers, angles for the
# mixer and cost operators, and options for setting verbosity, measurement, and
# random seed. The class checks for consistency in the provided parameters and
# supports visualizing the graph and QAOA circuit.
#
# Refs.
# [1] https://arxiv.org/abs/1411.4028
# [2] https://learning.quantum.ibm.com/tutorial/quantum-approximate-optimization-algorithm
# [3] https://en.wikipedia.org/wiki/Maximum_cut
#
# © Leonardo Lavagna 2024
# @ NESYA https://github.com/NesyaLab
#------------------------------------------------------------------------------
import numpy as np
from matplotlib import pyplot as plt
from classes import Problems as P
from functions import qaoa_utilities as utils
from qiskit import QuantumCircuit
from qiskit_aer import Aer
from typing import List, Tuple
from networkx import Graph
from qiskit.circuit import ParameterVector
class Qaoa:
def __init__(self, p: int = 0, G: Graph = None, betas: List[float] = None, gammas: List[float] = None,
mixer: str = "x", backend = Aer.get_backend('qasm_simulator'), measure: bool = True,
seed: int = None, verbose: bool = True):
"""Initialize class QAOA.
Args:
p (int): Positive number of QAOA layers. The default is 0.
G (Graph): A graph created with the Problem class used as MaxCut problem instance. The default is None.
betas (float): Angles for the mixer operator.
gammas (float): Angles for the cost operator.
mixer (str): Type of mixer operator to be used. The default is "x".
backend (Qiskit backend): Qiskit backend to execute the code on a quantum simulator.
The default is Aer.get_backend('qasm_simulator').
measure (bool): If True measure the qaoa circuit. The default is True.
seed (int): Seed for a pseudo-random number generator. The default is None.
verbose (bool): If True enters in debugging mode. The default is True.
"""
# Setup
self.p = p
self.G = G
self.mixer = mixer
self.backend = backend
self.measure = measure
self.verbose = verbose
self.seed = seed
self.problems_class = P.Problems(p_type="custom", G=self.G)
if self.seed is not None:
np.random.seed(self.seed)
if self.G is None:
self.N = 0
self.w = [[]]
self.betas = []
self.gammas = []
if self.G is not None:
self.N = G.get_number_of_nodes()
self.w = G.get_adjacency_matrix()
if betas is None or gammas is None:
self.betas = utils.generate_parameters(n=self.p, k=1)
self.gammas = utils.generate_parameters(n=self.p, k=2)
if betas is not None and gammas is not None:
self.betas = betas
self.gammas = gammas
# Checking...
if self.problems_class.__class__.__name__ != self.G.__class__.__name__ and G is not None:
raise Exception("Invalid parameters. The graph G should be created with the Problems class.")
if (self.p == 0 and self.G is not None) or (self.p > 0 and G is None):
raise ValueError("If G is not the empty graph p should be a strictly positive integer, and viceversa.")
if len(self.betas) != p or len(self.gammas) != p or len(self.betas) != len(self.gammas):
raise ValueError("Invalid angles list. The length of betas and gammas should be equal to p.")
# Initializing...
if self.verbose is True:
print(" --------------------------- ")
print("| Intializing Qaoa class... |".upper())
print(" --------------------------- ")
print("-> Getting problem instance...".upper())
if self.G is not None:
self.G.get_draw()
plt.show()
if self.G is None:
print("\t * G = ø")
if self.betas is None and self.G is not None:
print("-> Beta angles not provided. Generating angles...".upper())
print(f"\t * betas = {self.betas}")
if self.gammas is None and self.G is not None:
print("-> Gamma angles not provided. Generating angles...".upper())
print(f"\t * gammas = {self.gammas}")
print("-> Getting the ansatz...".upper())
if self.G is not None:
print(self.get_circuit())
if self.G is None:
print("\t * Qaoa circuit = ø")
print("-> The Qaoa class was initialized with the following parameters.".upper())
print(f"\t * Number of layers: p = {self.p};")
if self.G is None:
print(f"\t * Graph: G = ø;")
if self.G is not None:
print(f"\t * Graph: G = {self.G.p_type};")
print("\t * Angles:")
print(f"\t\t - betas = {self.betas};")
print(f"\t\t - gammas = {self.gammas};")
print(f"\t * Mixer Hamiltonian type: '{self.mixer}';")
print(f"\t * Random seed: seed = {self.seed};")
print(f"\t * Measurement setting: measure = {self.measure}.")
def cost_operator(self, gamma: float) -> QuantumCircuit:
"""Create an instance of the cost operator with angle 'gamma'.
Args:
gamma (float): Angle for the cost operator.
Returns:
QuantumCircuit: Circuit representing the cost operator.
"""
qc = QuantumCircuit(self.N, self.N)
for i,j in self.G.get_edges():
qc.cx(i, j)
qc.rz(gamma, j)
qc.cx(i, j)
return qc
def x_mixer_operator(self, beta: float) -> QuantumCircuit:
"""Create an instance of the x-mixer operator with angle 'beta'.
Args:
beta (float): Angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
for v in self.G.get_nodes():
qc.rx(beta, v)
return qc
def xx_mixer_operator(self, beta: float) -> QuantumCircuit:
"""Create an instance of the xx-mixer operator with angle 'beta'.
Args:
beta (float): Angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
for i, j in self.G.get_edges():
if self.w[i, j] > 0:
qc.rxx(beta, i, j)
return qc
def y_mixer_operator(self, beta: float) -> QuantumCircuit:
"""Create an instance of the y-mixer operator with angle 'beta'.
Args:
beta (float): Angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
for v in self.G.get_nodes():
qc.ry(2 * beta, v)
return qc
def yy_mixer_operator(self, beta: float) -> QuantumCircuit:
"""Create an instance of the yy-mixer operator with angle 'beta'.
Args:
beta (float): Time-slice angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
for i, j in self.G.get_edges():
if self.w[i, j] > 0:
qc.ryy(beta / 2, i, j)
return qc
def xy_mixer_operator(self, phi: float, psi: float) -> QuantumCircuit:
"""Create an instance of the xy-mixer operator with angle 'beta'.
Args:
beta (float): Angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
# X_iX_j
for i, j in self.G.get_edges():
if self.w[i, j] > 0:
qc.rxx(phi / 2, i, j)
# Y_iY_j
for i, j in self.G.get_edges():
if self.w[i, j] > 0:
qc.ryy(psi / 2, i, j)
return qc
def get_circuit(self) -> QuantumCircuit:
"""Create an instance of the Qaoa circuit with given parameters.
Returns:
QuantumCircuit: Circuit representing the Qaoa.
"""
qc = QuantumCircuit(self.N, self.N)
params = ParameterVector("params", 2 * self.p)
betas = params[0 : self.p]
gammas = params[self.p : 2 * self.p]
qc.h(range(self.N))
qc.barrier(range(self.N))
for i in range(self.p):
qc = qc.compose(self.cost_operator(gammas[i]))
qc.barrier(range(self.N))
if self.mixer == "x":
qc = qc.compose(self.x_mixer_operator(betas[i]))
qc.barrier(range(self.N))
elif self.mixer == "xx":
qc = qc.compose(self.xx_mixer_operator(betas[i]))
qc.barrier(range(self.N))
elif self.mixer == "y":
qc = qc.compose(self.y_mixer_operator(betas[i]))
qc.barrier(range(self.N))
elif self.mixer == "yy":
qc = qc.compose(self.yy_mixer_operator(betas[i]))
qc.barrier(range(self.N))
elif self.mixer == "xy":
qc = qc.compose(self.xy_mixer_operator(betas[i],betas[i]))
qc.barrier(range(self.N))
qc.barrier(range(self.N))
if self.measure:
qc.measure(range(self.N), range(self.N))
return qc
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""The Maximum Likelihood Amplitude Estimation algorithm."""
from __future__ import annotations
import warnings
from collections.abc import Sequence
from typing import Callable, List, Tuple
import numpy as np
from scipy.optimize import brute
from scipy.stats import norm, chi2
from qiskit.providers import Backend
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.utils import QuantumInstance
from qiskit.primitives import BaseSampler
from qiskit.utils.deprecation import deprecate_arg, deprecate_func
from .amplitude_estimator import AmplitudeEstimator, AmplitudeEstimatorResult
from .estimation_problem import EstimationProblem
from ..exceptions import AlgorithmError
MINIMIZER = Callable[[Callable[[float], float], List[Tuple[float, float]]], float]
class MaximumLikelihoodAmplitudeEstimation(AmplitudeEstimator):
"""The Maximum Likelihood Amplitude Estimation algorithm.
This class implements the quantum amplitude estimation (QAE) algorithm without phase
estimation, as introduced in [1]. In comparison to the original QAE algorithm [2],
this implementation relies solely on different powers of the Grover operator and does not
require additional evaluation qubits.
Finally, the estimate is determined via a maximum likelihood estimation, which is why this
class in named ``MaximumLikelihoodAmplitudeEstimation``.
References:
[1]: Suzuki, Y., Uno, S., Raymond, R., Tanaka, T., Onodera, T., & Yamamoto, N. (2019).
Amplitude Estimation without Phase Estimation.
`arXiv:1904.10246 <https://arxiv.org/abs/1904.10246>`_.
[2]: Brassard, G., Hoyer, P., Mosca, M., & Tapp, A. (2000).
Quantum Amplitude Amplification and Estimation.
`arXiv:quant-ph/0005055 <http://arxiv.org/abs/quant-ph/0005055>`_.
"""
@deprecate_arg(
"quantum_instance",
additional_msg=(
"Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a "
"migration guide."
),
since="0.24.0",
)
def __init__(
self,
evaluation_schedule: list[int] | int,
minimizer: MINIMIZER | None = None,
quantum_instance: QuantumInstance | Backend | None = None,
sampler: BaseSampler | None = None,
) -> None:
r"""
Args:
evaluation_schedule: If a list, the powers applied to the Grover operator. The list
element must be non-negative. If a non-negative integer, an exponential schedule is
used where the highest power is 2 to the integer minus 1:
`[id, Q^2^0, ..., Q^2^(evaluation_schedule-1)]`.
minimizer: A minimizer used to find the minimum of the likelihood function.
Defaults to a brute search where the number of evaluation points is determined
according to ``evaluation_schedule``. The minimizer takes a function as first
argument and a list of (float, float) tuples (as bounds) as second argument and
returns a single float which is the found minimum.
quantum_instance: Deprecated: Quantum Instance or Backend
sampler: A sampler primitive to evaluate the circuits.
Raises:
ValueError: If the number of oracle circuits is smaller than 1.
"""
super().__init__()
# set quantum instance
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self.quantum_instance = quantum_instance
# get parameters
if isinstance(evaluation_schedule, int):
if evaluation_schedule < 0:
raise ValueError("The evaluation schedule cannot be < 0.")
self._evaluation_schedule = [0] + [2**j for j in range(evaluation_schedule)]
else:
if any(value < 0 for value in evaluation_schedule):
raise ValueError("The elements of the evaluation schedule cannot be < 0.")
self._evaluation_schedule = evaluation_schedule
if minimizer is None:
# default number of evaluations is max(10^4, pi/2 * 10^3 * 2^(m))
nevals = max(10000, int(np.pi / 2 * 1000 * 2 * self._evaluation_schedule[-1]))
def default_minimizer(objective_fn, bounds):
return brute(objective_fn, bounds, Ns=nevals)[0]
self._minimizer = default_minimizer
else:
self._minimizer = minimizer
self._sampler = sampler
@property
def sampler(self) -> BaseSampler | None:
"""Get the sampler primitive.
Returns:
The sampler primitive to evaluate the circuits.
"""
return self._sampler
@sampler.setter
def sampler(self, sampler: BaseSampler) -> None:
"""Set sampler primitive.
Args:
sampler: A sampler primitive to evaluate the circuits.
"""
self._sampler = sampler
@property
@deprecate_func(
since="0.24.0",
is_property=True,
additional_msg="See https://qisk.it/algo_migration for a migration guide.",
)
def quantum_instance(self) -> QuantumInstance | None:
"""Deprecated. Get the quantum instance.
Returns:
The quantum instance used to run this algorithm.
"""
return self._quantum_instance
@quantum_instance.setter
@deprecate_func(
since="0.24.0",
is_property=True,
additional_msg="See https://qisk.it/algo_migration for a migration guide.",
)
def quantum_instance(self, quantum_instance: QuantumInstance | Backend) -> None:
"""Deprecated. Set quantum instance.
Args:
quantum_instance: The quantum instance used to run this algorithm.
"""
if isinstance(quantum_instance, Backend):
quantum_instance = QuantumInstance(quantum_instance)
self._quantum_instance = quantum_instance
def construct_circuits(
self, estimation_problem: EstimationProblem, measurement: bool = False
) -> list[QuantumCircuit]:
"""Construct the Amplitude Estimation w/o QPE quantum circuits.
Args:
estimation_problem: The estimation problem for which to construct the QAE circuit.
measurement: Boolean flag to indicate if measurement should be included in the circuits.
Returns:
A list with the QuantumCircuit objects for the algorithm.
"""
# keep track of the Q-oracle queries
circuits = []
num_qubits = max(
estimation_problem.state_preparation.num_qubits,
estimation_problem.grover_operator.num_qubits,
)
q = QuantumRegister(num_qubits, "q")
qc_0 = QuantumCircuit(q, name="qc_a") # 0 applications of Q, only a single A operator
# add classical register if needed
if measurement:
c = ClassicalRegister(len(estimation_problem.objective_qubits))
qc_0.add_register(c)
qc_0.compose(estimation_problem.state_preparation, inplace=True)
for k in self._evaluation_schedule:
qc_k = qc_0.copy(name=f"qc_a_q_{k}")
if k != 0:
qc_k.compose(estimation_problem.grover_operator.power(k), inplace=True)
if measurement:
# real hardware can currently not handle operations after measurements,
# which might happen if the circuit gets transpiled, hence we're adding
# a safeguard-barrier
qc_k.barrier()
qc_k.measure(estimation_problem.objective_qubits, c[:])
circuits += [qc_k]
return circuits
@staticmethod
def compute_confidence_interval(
result: "MaximumLikelihoodAmplitudeEstimationResult",
alpha: float,
kind: str = "fisher",
apply_post_processing: bool = False,
) -> tuple[float, float]:
"""Compute the `alpha` confidence interval using the method `kind`.
The confidence level is (1 - `alpha`) and supported kinds are 'fisher',
'likelihood_ratio' and 'observed_fisher' with shorthand
notations 'fi', 'lr' and 'oi', respectively.
Args:
result: A maximum likelihood amplitude estimation result.
alpha: The confidence level.
kind: The method to compute the confidence interval. Defaults to 'fisher', which
computes the theoretical Fisher information.
apply_post_processing: If True, apply post-processing to the confidence interval.
Returns:
The specified confidence interval.
Raises:
AlgorithmError: If `run()` hasn't been called yet.
NotImplementedError: If the method `kind` is not supported.
"""
interval: tuple[float, float] | None = None
# if statevector simulator the estimate is exact
if all(isinstance(data, (list, np.ndarray)) for data in result.circuit_results):
interval = (result.estimation, result.estimation)
elif kind in ["likelihood_ratio", "lr"]:
interval = _likelihood_ratio_confint(result, alpha)
elif kind in ["fisher", "fi"]:
interval = _fisher_confint(result, alpha, observed=False)
elif kind in ["observed_fisher", "observed_information", "oi"]:
interval = _fisher_confint(result, alpha, observed=True)
if interval is None:
raise NotImplementedError(f"CI `{kind}` is not implemented.")
if apply_post_processing:
return result.post_processing(interval[0]), result.post_processing(interval[1])
return interval
def compute_mle(
self,
circuit_results: list[dict[str, int] | np.ndarray],
estimation_problem: EstimationProblem,
num_state_qubits: int | None = None,
return_counts: bool = False,
) -> float | tuple[float, list[float]]:
"""Compute the MLE via a grid-search.
This is a stable approach if sufficient gridpoints are used.
Args:
circuit_results: A list of circuit outcomes. Can be counts or statevectors.
estimation_problem: The estimation problem containing the evaluation schedule and the
number of likelihood function evaluations used to find the minimum.
num_state_qubits: The number of state qubits, required for statevector simulations.
return_counts: If True, returns the good counts.
Returns:
The MLE for the provided result object.
"""
good_counts, all_counts = _get_counts(circuit_results, estimation_problem, num_state_qubits)
# search range
eps = 1e-15 # to avoid invalid value in log
search_range = [0 + eps, np.pi / 2 - eps]
def loglikelihood(theta):
# loglik contains the first `it` terms of the full loglikelihood
loglik = 0
for i, k in enumerate(self._evaluation_schedule):
angle = (2 * k + 1) * theta
loglik += np.log(np.sin(angle) ** 2) * good_counts[i]
loglik += np.log(np.cos(angle) ** 2) * (all_counts[i] - good_counts[i])
return -loglik
est_theta = self._minimizer(loglikelihood, [search_range])
if return_counts:
return est_theta, good_counts
return est_theta
def estimate(
self, estimation_problem: EstimationProblem
) -> "MaximumLikelihoodAmplitudeEstimationResult":
"""Run the amplitude estimation algorithm on provided estimation problem.
Args:
estimation_problem: The estimation problem.
Returns:
An amplitude estimation results object.
Raises:
ValueError: A quantum instance or Sampler must be provided.
AlgorithmError: If `state_preparation` is not set in
`estimation_problem`.
AlgorithmError: Sampler job run error
"""
if self._quantum_instance is None and self._sampler is None:
raise ValueError("A quantum instance or sampler must be provided.")
if estimation_problem.state_preparation is None:
raise AlgorithmError(
"The state_preparation property of the estimation problem must be set."
)
result = MaximumLikelihoodAmplitudeEstimationResult()
result.evaluation_schedule = self._evaluation_schedule
result.minimizer = self._minimizer
result.post_processing = estimation_problem.post_processing
shots = 0
if self._quantum_instance is not None and self._quantum_instance.is_statevector:
# run circuit on statevector simulator
circuits = self.construct_circuits(estimation_problem, measurement=False)
ret = self._quantum_instance.execute(circuits)
# get statevectors and construct MLE input
statevectors = [np.asarray(ret.get_statevector(circuit)) for circuit in circuits]
result.circuit_results = statevectors
# to count the number of Q-oracle calls (don't count shots)
result.shots = 1
else:
circuits = self.construct_circuits(estimation_problem, measurement=True)
if self._quantum_instance is not None:
# run circuit on QASM simulator
ret = self._quantum_instance.execute(circuits)
# get counts and construct MLE input
result.circuit_results = [ret.get_counts(circuit) for circuit in circuits]
shots = self._quantum_instance._run_config.shots
else:
try:
job = self._sampler.run(circuits)
ret = job.result()
except Exception as exc:
raise AlgorithmError("The job was not completed successfully. ") from exc
result.circuit_results = []
shots = ret.metadata[0].get("shots")
if shots is None:
for quasi_dist in ret.quasi_dists:
circuit_result = quasi_dist.binary_probabilities()
result.circuit_results.append(circuit_result)
shots = 1
else:
# get counts and construct MLE input
for quasi_dist in ret.quasi_dists:
counts = {
k: round(v * shots)
for k, v in quasi_dist.binary_probabilities().items()
}
result.circuit_results.append(counts)
result.shots = shots
# run maximum likelihood estimation
num_state_qubits = circuits[0].num_qubits - circuits[0].num_ancillas
theta, good_counts = self.compute_mle(
result.circuit_results, estimation_problem, num_state_qubits, True
)
# store results
result.theta = theta
result.good_counts = good_counts
result.estimation = np.sin(result.theta) ** 2
# not sure why pylint complains, this is a callable and the tests pass
# pylint: disable=not-callable
result.estimation_processed = result.post_processing(result.estimation)
result.fisher_information = _compute_fisher_information(result)
result.num_oracle_queries = result.shots * sum(k for k in result.evaluation_schedule)
# compute and store confidence interval
confidence_interval = self.compute_confidence_interval(result, alpha=0.05, kind="fisher")
result.confidence_interval = confidence_interval
result.confidence_interval_processed = tuple(
estimation_problem.post_processing(value) for value in confidence_interval
)
return result
class MaximumLikelihoodAmplitudeEstimationResult(AmplitudeEstimatorResult):
"""The ``MaximumLikelihoodAmplitudeEstimation`` result object."""
def __init__(self) -> None:
super().__init__()
self._theta: float | None = None
self._minimizer: Callable | None = None
self._good_counts: list[float] | None = None
self._evaluation_schedule: list[int] | None = None
self._fisher_information: float | None = None
@property
def theta(self) -> float:
r"""Return the estimate for the angle :math:`\theta`."""
return self._theta
@theta.setter
def theta(self, value: float) -> None:
r"""Set the estimate for the angle :math:`\theta`."""
self._theta = value
@property
def minimizer(self) -> Callable:
"""Return the minimizer used for the search of the likelihood function."""
return self._minimizer
@minimizer.setter
def minimizer(self, value: Callable) -> None:
"""Set the number minimizer used for the search of the likelihood function."""
self._minimizer = value
@property
def good_counts(self) -> list[float]:
"""Return the percentage of good counts per circuit power."""
return self._good_counts
@good_counts.setter
def good_counts(self, counts: list[float]) -> None:
"""Set the percentage of good counts per circuit power."""
self._good_counts = counts
@property
def evaluation_schedule(self) -> list[int]:
"""Return the evaluation schedule for the powers of the Grover operator."""
return self._evaluation_schedule
@evaluation_schedule.setter
def evaluation_schedule(self, evaluation_schedule: list[int]) -> None:
"""Set the evaluation schedule for the powers of the Grover operator."""
self._evaluation_schedule = evaluation_schedule
@property
def fisher_information(self) -> float:
"""Return the Fisher information for the estimated amplitude."""
return self._fisher_information
@fisher_information.setter
def fisher_information(self, value: float) -> None:
"""Set the Fisher information for the estimated amplitude."""
self._fisher_information = value
def _safe_min(array, default=0):
if len(array) == 0:
return default
return np.min(array)
def _safe_max(array, default=(np.pi / 2)):
if len(array) == 0:
return default
return np.max(array)
def _compute_fisher_information(
result: "MaximumLikelihoodAmplitudeEstimationResult",
num_sum_terms: int | None = None,
observed: bool = False,
) -> float:
"""Compute the Fisher information.
Args:
result: A maximum likelihood amplitude estimation result.
num_sum_terms: The number of sum terms to be included in the calculation of the
Fisher information. By default all values are included.
observed: If True, compute the observed Fisher information, otherwise the theoretical
one.
Returns:
The computed Fisher information, or np.inf if statevector simulation was used.
Raises:
KeyError: Call run() first!
"""
a = result.estimation
# Corresponding angle to the value a (only use real part of 'a')
theta_a = np.arcsin(np.sqrt(np.real(a)))
# Get the number of hits (shots_k) and one-hits (h_k)
one_hits = result.good_counts
all_hits = [result.shots] * len(one_hits)
# Include all sum terms or just up to a certain term?
evaluation_schedule = result.evaluation_schedule
if num_sum_terms is not None:
evaluation_schedule = evaluation_schedule[:num_sum_terms]
# not necessary since zip goes as far as shortest list:
# all_hits = all_hits[:num_sum_terms]
# one_hits = one_hits[:num_sum_terms]
# Compute the Fisher information
fisher_information = None
if observed:
# Note, that the observed Fisher information is very unreliable in this algorithm!
d_loglik = 0
for shots_k, h_k, m_k in zip(all_hits, one_hits, evaluation_schedule):
tan = np.tan((2 * m_k + 1) * theta_a)
d_loglik += (2 * m_k + 1) * (h_k / tan + (shots_k - h_k) * tan)
d_loglik /= np.sqrt(a * (1 - a))
fisher_information = d_loglik**2 / len(all_hits)
else:
fisher_information = sum(
shots_k * (2 * m_k + 1) ** 2 for shots_k, m_k in zip(all_hits, evaluation_schedule)
)
fisher_information /= a * (1 - a)
return fisher_information
def _fisher_confint(
result: MaximumLikelihoodAmplitudeEstimationResult, alpha: float = 0.05, observed: bool = False
) -> tuple[float, float]:
"""Compute the `alpha` confidence interval based on the Fisher information.
Args:
result: A maximum likelihood amplitude estimation results object.
alpha: The level of the confidence interval (must be <= 0.5), default to 0.05.
observed: If True, use observed Fisher information.
Returns:
float: The alpha confidence interval based on the Fisher information
Raises:
AssertionError: Call run() first!
"""
# Get the (observed) Fisher information
fisher_information = None
try:
fisher_information = result.fisher_information
except KeyError as ex:
raise AssertionError("Call run() first!") from ex
if observed:
fisher_information = _compute_fisher_information(result, observed=True)
normal_quantile = norm.ppf(1 - alpha / 2)
confint = np.real(result.estimation) + normal_quantile / np.sqrt(fisher_information) * np.array(
[-1, 1]
)
return result.post_processing(confint[0]), result.post_processing(confint[1])
def _likelihood_ratio_confint(
result: MaximumLikelihoodAmplitudeEstimationResult,
alpha: float = 0.05,
nevals: int | None = None,
) -> tuple[float, float]:
"""Compute the likelihood-ratio confidence interval.
Args:
result: A maximum likelihood amplitude estimation results object.
alpha: The level of the confidence interval (< 0.5), defaults to 0.05.
nevals: The number of evaluations to find the intersection with the loglikelihood
function. Defaults to an adaptive value based on the maximal power of Q.
Returns:
The alpha-likelihood-ratio confidence interval.
"""
if nevals is None:
nevals = max(10000, int(np.pi / 2 * 1000 * 2 * result.evaluation_schedule[-1]))
def loglikelihood(theta, one_counts, all_counts):
loglik = 0
for i, k in enumerate(result.evaluation_schedule):
loglik += np.log(np.sin((2 * k + 1) * theta) ** 2) * one_counts[i]
loglik += np.log(np.cos((2 * k + 1) * theta) ** 2) * (all_counts[i] - one_counts[i])
return loglik
one_counts = result.good_counts
all_counts = [result.shots] * len(one_counts)
eps = 1e-15 # to avoid invalid value in log
thetas = np.linspace(0 + eps, np.pi / 2 - eps, nevals)
values = np.zeros(len(thetas))
for i, theta in enumerate(thetas):
values[i] = loglikelihood(theta, one_counts, all_counts)
loglik_mle = loglikelihood(result.theta, one_counts, all_counts)
chi2_quantile = chi2.ppf(1 - alpha, df=1)
thres = loglik_mle - chi2_quantile / 2
# the (outer) LR confidence interval
above_thres = thetas[values >= thres]
# it might happen that the `above_thres` array is empty,
# to still provide a valid result use safe_min/max which
# then yield [0, pi/2]
confint = [_safe_min(above_thres, default=0), _safe_max(above_thres, default=np.pi / 2)]
mapped_confint = tuple(result.post_processing(np.sin(bound) ** 2) for bound in confint)
return mapped_confint
def _get_counts(
circuit_results: Sequence[np.ndarray | list[float] | dict[str, int]],
estimation_problem: EstimationProblem,
num_state_qubits: int,
) -> tuple[list[float], list[int]]:
"""Get the good and total counts.
Returns:
A pair of two lists, ([1-counts per experiment], [shots per experiment]).
Raises:
AlgorithmError: If self.run() has not been called yet.
"""
one_hits = [] # h_k: how often 1 has been measured, for a power Q^(m_k)
# shots_k: how often has been measured at a power Q^(m_k)
all_hits: np.ndarray | list[float] = []
if all(isinstance(data, (list, np.ndarray)) for data in circuit_results):
probabilities = []
num_qubits = int(np.log2(len(circuit_results[0]))) # the total number of qubits
for statevector in circuit_results:
p_k = 0.0
for i, amplitude in enumerate(statevector):
probability = np.abs(amplitude) ** 2
# consider only state qubits and revert bit order
bitstr = bin(i)[2:].zfill(num_qubits)[-num_state_qubits:][::-1]
objectives = [bitstr[index] for index in estimation_problem.objective_qubits]
if estimation_problem.is_good_state(objectives):
p_k += probability
probabilities += [p_k]
one_hits = probabilities
all_hits = np.ones_like(one_hits)
else:
for counts in circuit_results:
all_hits.append(sum(counts.values()))
one_hits.append(
sum(
count
for bitstr, count in counts.items()
if estimation_problem.is_good_state(bitstr)
)
)
return one_hits, all_hits
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
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()
# Qiskit module
from qiskit import QuantumCircuit
import qiskit.circuit.library as circuit_library
import qiskit.quantum_info as qi
import qiskit.ignis.mitigation as mit
# Qiskit tools for noisy simulation
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.utils import insert_noise
# Qiskit tools for running and monitoring jobs
from qiskit import execute
from qiskit.tools.monitor import job_monitor
# Other imports
import numpy as np
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
num_qubits = 7
# adjacency matrix for `ibmq_casablanca`
adjmat = [
[0, 1, 0, 0, 0, 0, 0],
[1, 0, 1, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 1, 0, 1],
[0, 0, 0, 0, 0, 1, 0]]
def create_graph_state():
graph_state_circuit = circuit_library.GraphState(adjmat)
return graph_state_circuit
# the graph state can be created using Qiskit's circuit library
state_circuit = create_graph_state()
state_circuit.draw()
def compute_stabilizer_group(circuit):
"""Compute the stabilizer group for stabilizer circuit."""
state = qi.Statevector.from_instruction(circuit)
labels = []
for i in qi.pauli_basis(state.num_qubits):
val = round(qi.state_fidelity(i.to_matrix()[0], state, validate=False))
if val != 0:
label = i.to_labels()[0]
if val == 1:
label = '+' + label
else:
label = '-' + label
labels.append(label)
return labels
def stabilizer_coeff_pauli(stabilizer):
"""Return the 1 or -1 coeff and Pauli label."""
coeff = 1
pauli = coeff
if stabilizer[0] == '-':
coeff = -1
if stabilizer[0] in ['+', '-']:
pauli = stabilizer[1:]
else:
pauli = stabilizer
return coeff, pauli
def stabilizer_measure_circuit(stabilizer, initial_circuit=None):
"""Return a stabilizer measurement circuits.
Args:
stabilizer (str): a stabilizer string
initial_circuit (QuantumCircuit): Optional, the initial circuit.
Returns:
QuantumCircuit: the circuit with stabilizer measurements.
"""
_, pauli = stabilizer_coeff_pauli(stabilizer)
if initial_circuit is None:
circ = QuantumCircuit(len(pauli))
else:
circ = initial_circuit.copy()
for i, s in enumerate(reversed(pauli)):
if s == 'X':
circ.h(i)
if s == 'Y':
circ.sdg(i)
circ.h(i)
circ.measure_all()
return circ
## Compute the stabilizers for this graph state
generators = qi.Clifford(state_circuit).stabilizer.pauli.to_labels()
stabilizers = compute_stabilizer_group(state_circuit)
print('Stabilizers:', stabilizers)
print('Generators:', generators)
## Append the stabilizer measurements to the graph state circuit
stabilizer_circuits = [stabilizer_measure_circuit(stab, state_circuit)
for stab in stabilizers]
stabilizer_circuits[0].draw()
labels = ['0000000', '0000011', '0000101',
'0001001', '0001010', '0001100',
'0010001', '0010010', '0010100', '0011000',
'0100001', '0100010', '0100100', '0101000', '0110000',
'1000001', '1000010', '1000100', '1001000', '1010000', '1100000',
'1111111']
meas_cal_circuits, metadata = mit.expval_meas_mitigator_circuits(num_qubits, labels=labels)
[meas_cal_circuits_full, state_labels] = mit.complete_meas_cal(range(num_qubits))
#backend = QasmSimulator.from_backend(provider.get_backend('ibmq_casablanca'))
IBMQ.load_account() # Load account from disk
IBMQ.providers()
from qiskit import IBMQ, assemble, transpile
from qiskit.circuit.random import random_circuit
backend = provider.backend.ibmq_qasm_simulator
reps = 10
all_jobs = []
all_jobs_mit = []
for ii in range(reps):
# Run QPT on backend
shots = 8192
il = [0,1,2,3,4,5,6]
job_backend = execute(stabilizer_circuits, backend, shots=shots, initial_layout=il)
job_mit_backend = execute(meas_cal_circuits, backend, shots=shots, initial_layout=il)
print('Job IDs ({}/{}): \n measurement calibration: {}\n stabilizer measurements: {}'.format(
ii+1, reps, job_mit_backend.job_id(), job_backend.job_id()))
all_jobs.append(job_backend)
all_jobs_mit.append(job_mit_backend)
for job in all_jobs:
job_monitor(job)
try:
if job.error_message() is not None:
print(job.error_message())
except:
pass
result_backend = []
result_mit_backend = []
for job in all_jobs:
# Retrieve results (this may take a while depending on the queue)
result_backend.append(job.result())
for job in all_jobs_mit:
result_mit_backend.append(job.result())
def stabilizer_measure_diagonal(stabilizer):
"""Return the diagonal vector for a stabilizer measurement.
Args:
stabilizer (str): a stabilizer string
Returns:
np.ndarray: the diagonal for measurement in the stabilizer basis.
"""
coeff, pauli = stabilizer_coeff_pauli(stabilizer)
diag = np.array([1])
for s in reversed(pauli):
if s == 'I':
tmp = np.array([1, 1])
else:
tmp = np.array([1, -1])
diag = np.kron(tmp, diag)
return coeff * diag
def stabilizer_fidelity(expvals, stddevs=None):
"""Compute stabilizer state fidelity from stabilizer expvals."""
mean = np.mean(expvals)
if stddevs is None:
return mean
stddev = np.sqrt(np.sum(stddevs ** 2))
return mean, stddev
def stabilizer_expvals(result, stabilizers, meas_mitigator=None):
"""Compute expectation values from stabilizer measurement results."""
### YOUR CODE GOES HERE -- START
expvals = []
stddevs = []
for i, stab in enumerate(stabilizers):
expval, stddev = mit.expectation_value(
result.get_counts(i),
diagonal=stabilizer_measure_diagonal(stab),
meas_mitigator=meas_mitigator)
expvals.append(expval)
stddevs.append(stddev)
return np.array(expvals), np.array(stddevs)
## Mitigate the stabilizer expectation values
F_nomit_backend = []
F_mit_backend = []
for ii in range(reps):
# Unmitigated Expectation Values
expvals_nomit_b, stddevs_nomit_b = stabilizer_expvals(
result_backend[ii], stabilizers)
# Fit measurement error mitigators
mitigator_backend = mit.ExpvalMeasMitigatorFitter(result_mit_backend[ii], metadata).fit()
# Measurement error mitigated expectation values
expvals_mit_b, stddevs_mit_b = stabilizer_expvals(
result_backend[ii], stabilizers, meas_mitigator=mitigator_backend)
# save the fidelities for this iteration
F_nomit_backend.append(stabilizer_fidelity(expvals_nomit_b, stddevs_nomit_b)[0])
F_mit_backend.append(stabilizer_fidelity(expvals_mit_b, stddevs_mit_b)[0])
## The final results
print('Graph-state fidelity estimates')
print('\nNo mitigation')
print('F({}) = {:.3f} \u00B1 {:.3f}'.format(properties.backend_name, np.mean(F_nomit_backend), np.std(F_nomit_backend)))
print('\nCTMP error mitigation')
print('F({}) = {:.3f} \u00B1 {:.3f}'.format(properties.backend_name, np.mean(F_mit_backend), np.std(F_mit_backend)))
|
https://github.com/kaelynj/Qiskit-HubbardModel
|
kaelynj
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister
from qiskit.compiler import transpile, assemble
from qiskit.quantum_info import Operator
from qiskit.tools.monitor import job_monitor
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from matplotlib import rcParams
rcParams['text.usetex'] = True
#Useful tool for converting an integer to a binary bit string
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters: x (int), n (int, number of digits)"""
return format(x, 'b').zfill(n)
|
https://github.com/bibscore/qiskit_kindergarten
|
bibscore
|
import os
from qiskit import *
import qiskit.tools.visualization as qt
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
from numpy import pi
import matplotlib.pyplot as plt
%matplotlib inline
qreg_q = QuantumRegister(2, 'q')
creg_c = ClassicalRegister(2, 'c')
circuits = []
for i in range(0, 4):
circuits.append(QuantumCircuit(qreg_q, creg_c))
def entlanging(circuit, qreg_q):
circuit.barrier()
circuit.h(qreg_q[0])
circuit.cnot(qreg_q[0], qreg_q[1])
circuit.barrier()
# 00 state
circuits[0].reset(qreg_q[0])
circuits[0].reset(qreg_q[1])
entlanging(circuits[0], qreg_q)
# 01 state
circuits[1].reset(qreg_q[0])
circuits[1].x(qreg_q[1])
entlanging(circuits[1], qreg_q)
# 10 state
circuits[2].x(qreg_q[0])
circuits[2].reset(qreg_q[1])
entlanging(circuits[2], qreg_q)
# 11 state
circuits[3].x(qreg_q[0])
circuits[3].x(qreg_q[1])
entlanging(circuits[3], qreg_q)
simulator = Aer.get_backend('qasm_simulator')
circuits[0].measure(qreg_q[0], creg_c[0])
circuits[0].measure(qreg_q[1], creg_c[1])
result0 = execute(circuits[0], backend=simulator, shots=1024).result()
counts0 = result0.get_counts()
qt.plot_histogram(counts0, color="#5C9DFF", title="Entangled qubits values for input |00>")
circuits[0].draw(output='mpl')
circuits[1].measure(qreg_q[0], creg_c[0])
circuits[1].measure(qreg_q[1], creg_c[1])
result1 = execute(circuits[1], backend=simulator, shots=1024).result()
counts1 = result1.get_counts()
qt.plot_histogram(counts1, color="#5C9DFF", title="Entangled qubits values for input |01>")
circuits[1].draw(output='mpl')
circuits[2].measure(qreg_q[0], creg_c[0])
circuits[2].measure(qreg_q[1], creg_c[1])
result2 = execute(circuits[2], backend=simulator, shots=1024).result()
counts2 = result2.get_counts()
qt.plot_histogram(counts2, color="#5C9DFF", title="Entangled qubits values for input |10>")
circuits[2].draw(output='mpl')
circuits[3].measure(qreg_q[0], creg_c[0])
circuits[3].measure(qreg_q[1], creg_c[1])
result3 = execute(circuits[3], backend=simulator, shots=1024).result()
counts3 = result3.get_counts()
qt.plot_histogram(counts3, color="#5C9DFF", title="Entangled qubits values for input |11>")
circuits[3].draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.visualization import dag_drawer
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
dag_drawer(dag)
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumCircuit, Aer
from qiskit.visualization import array_to_latex
sim = Aer.get_backend("aer_simulator")
qc = QuantumCircuit(2)
qc.cx(0, 1)
display(qc.draw("mpl"))
qc.save_unitary()
unitary = sim.run(qc).result().get_unitary()
display(array_to_latex(unitary, prefix="\\text{CNOT (LSB as Target) = }"))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
pw_approximation._build()
qc = QuantumCircuit(pw_approximation.num_qubits)
qc.h(list(range(num_state_qubits)))
qc.append(pw_approximation.to_instruction(), qc.qubits)
qc.draw(output='mpl')
|
https://github.com/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/AsishMandoi/VRP-explorations
|
AsishMandoi
|
import time
from dwave_qbsolv.dimod_wrapper import QBSolv
import hybrid
import dwave.inspector
from greedy import SteepestDescentSolver
from dwave.system import LeapHybridSampler, DWaveSampler, EmbeddingComposite
from neal import SimulatedAnnealingSampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit.algorithms import QAOA, NumPyMinimumEigensolver
from qiskit import Aer
class SolverBackend:
"""Class containing all backend solvers that may be used to solve the Vehicle Routing Problem."""
def __init__(self, vrp):
"""Initializes required variables and stores the supplied instance of the VehicleRouter object."""
# Store relevant data
self.vrp = vrp
# Solver dictionary
self.solvers = {'dwave': self.solve_dwave,
'leap': self.solve_leap,
'hybrid': self.solve_hybrid,
'neal': self.solve_neal,
'qbsolv': self.solve_qbsolv,
'qaoa': self.solve_qaoa,
'npme': self.solve_npme}
# Initialize necessary variables
self.dwave_result = None
self.result_dict = None
self.solver_limit = 4
def solve(self, solver, **params):
"""Takes the solver as input and redirects control to the corresponding solver.
Args:
solver: The selected solver.
params: Parameters to send to the selected backend solver..
"""
# Select solver and solve
solver = self.solvers[solver]
solver(**params)
def solve_dwave(self, **params):
"""Solve using DWaveSampler and EmbeddingComposite.
Args:
params: inspect: Defaults to False. Set to True to run D-Wave inspector for the sampled solution.
params: post_process: Defaults to False. Set to True to run classical post processing for improving the
D-Wave solution.
"""
# Resolve parameters
params['solver'] = 'dwave'
inspect = params.setdefault('inspect', False)
post_process = params.setdefault('post_process', False)
# Solve
sampler = EmbeddingComposite(DWaveSampler())
result = sampler.sample(self.vrp.bqm, num_reads=self.vrp.num_reads, chain_strength=self.vrp.chain_strength)
# Post process
if not post_process:
self.vrp.result = result
else:
post_processor = SteepestDescentSolver()
self.vrp.result = post_processor.sample(self.vrp.bqm, num_reads=self.vrp.num_reads, initial_states=result)
# Extract solution
self.vrp.timing.update(result.info["timing"])
self.result_dict = self.vrp.result.first.sample
self.vrp.extract_solution(self.result_dict)
# Inspection
self.dwave_result = result
if inspect:
dwave.inspector.show(result)
def solve_hybrid(self, **params):
"""Solve using dwave-hybrid.
Args:
params: Additional parameters that may be required by a solver. Not required here.
"""
# Resolve parameters
params['solver'] = 'hybrid'
# Build sampler workflow
workflow = hybrid.Loop(
hybrid.RacingBranches(
hybrid.InterruptableTabuSampler(),
hybrid.EnergyImpactDecomposer(size=30, rolling=True, rolling_history=0.75)
| hybrid.QPUSubproblemAutoEmbeddingSampler()
| hybrid.SplatComposer()) | hybrid.ArgMin(), convergence=3)
# Solve
sampler = hybrid.HybridSampler(workflow)
self.vrp.result = sampler.sample(self.vrp.bqm, num_reads=self.vrp.num_reads,
chain_strength=self.vrp.chain_strength)
# Extract solution
self.result_dict = self.vrp.result.first.sample
self.vrp.extract_solution(self.result_dict)
def solve_leap(self, **params):
"""Solve using Leap Hybrid Sampler.
Args:
params: Additional parameters that may be required by a solver. Not required here.
"""
# Resolve parameters
params['solver'] = 'leap'
# Solve
sampler = LeapHybridSampler()
self.vrp.result = sampler.sample(self.vrp.bqm)
# Extract solution
self.vrp.timing.update(self.vrp.result.info)
self.result_dict = self.vrp.result.first.sample
self.vrp.extract_solution(self.result_dict)
def solve_neal(self, **params):
"""Solve using Simulated Annealing Sampler.
Args:
params: Additional parameters that may be required by a solver. Not required here.
"""
# Resolve parameters
params['solver'] = 'neal'
# Solve
sampler = SimulatedAnnealingSampler()
self.vrp.result = sampler.sample(self.vrp.bqm)
# Extract solution
self.vrp.timing.update(self.vrp.result.info)
self.result_dict = self.vrp.result.first.sample
self.vrp.extract_solution(self.result_dict)
def solve_qbsolv(self, **params):
"""Solve using Simulated Annealing Sampler.
Args:
params: Additional parameters that may be required by a solver. Not required here.
"""
# Resolve parameters
params['solver'] = 'qbsolv'
# Solve
self.vrp.result = QBSolv().sample(self.vrp.bqm, solver_limit=self.solver_limit)
# Extract solution
self.vrp.timing.update(self.vrp.result.info)
self.result_dict = self.vrp.result.first.sample
self.vrp.extract_solution(self.result_dict)
def solve_qaoa(self, **params):
"""Solve using qiskit Minimum Eigen Optimizer based on a QAOA backend.
Args:
params: Additional parameters that may be required by a solver. Not required here.
"""
# Resolve parameters
params['solver'] = 'qaoa'
self.vrp.clock = time.time()
# Build optimizer and solve
solver = QAOA(quantum_instance=Aer.get_backend('qasm_simulator'))
optimizer = MinimumEigenOptimizer(min_eigen_solver=solver)
self.vrp.result = optimizer.solve(self.vrp.qp)
self.vrp.timing['qaoa_solution_time'] = (time.time() - self.vrp.clock) * 1e6
# Build result dictionary
self.result_dict = {self.vrp.result.variable_names[i]: self.vrp.result.x[i]
for i in range(len(self.vrp.result.variable_names))}
# Extract solution
self.vrp.extract_solution(self.result_dict)
def solve_npme(self, **params):
"""Solve using qiskit Minimum Eigen Optimizer based on NumPyMinimumEigensolver().
Args:
params: Additional parameters that may be required by a solver. Not required here.
"""
# Resolve parameters
params['solver'] = 'npme'
self.vrp.clock = time.time()
# Build optimizer and solve
solver = NumPyMinimumEigensolver()
optimizer = MinimumEigenOptimizer(min_eigen_solver=solver)
self.vrp.result = optimizer.solve(self.vrp.qp)
self.vrp.timing['npme_solution_time'] = (time.time() - self.vrp.clock) * 1e6
# Build result dictionary
self.result_dict = {self.vrp.result.variable_names[i]: self.vrp.result.x[i]
for i in range(len(self.vrp.result.variable_names))}
# Extract solution
self.vrp.extract_solution(self.result_dict)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can show the phase of each state and use
# degrees instead of radians
from qiskit.quantum_info import DensityMatrix
import numpy as np
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
qc.z(1)
matrix = DensityMatrix(qc)
plot_state_qsphere(matrix,
show_state_phases = True, use_degrees = True)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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.
"""Helper function for converting a circuit to a dag"""
import copy
from qiskit.dagcircuit.dagcircuit import DAGCircuit
def circuit_to_dag(circuit, copy_operations=True, *, qubit_order=None, clbit_order=None):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
copy_operations (bool): Deep copy the operation objects
in the :class:`~.QuantumCircuit` for the output :class:`~.DAGCircuit`.
This should only be set to ``False`` if the input :class:`~.QuantumCircuit`
will not be used anymore as the operations in the output
:class:`~.DAGCircuit` will be shared instances and modifications to
operations in the :class:`~.DAGCircuit` will be reflected in the
:class:`~.QuantumCircuit` (and vice versa).
qubit_order (Iterable[Qubit] or None): the order that the qubits should be indexed in the
output DAG. Defaults to the same order as in the circuit.
clbit_order (Iterable[Clbit] or None): the order that the clbits should be indexed in the
output DAG. Defaults to the same order as in the circuit.
Return:
DAGCircuit: the DAG representing the input circuit.
Raises:
ValueError: if the ``qubit_order`` or ``clbit_order`` parameters do not match the bits in
the circuit.
Example:
.. code-block::
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
dagcircuit.global_phase = circuit.global_phase
dagcircuit.calibrations = circuit.calibrations
dagcircuit.metadata = circuit.metadata
if qubit_order is None:
qubits = circuit.qubits
elif len(qubit_order) != circuit.num_qubits or set(qubit_order) != set(circuit.qubits):
raise ValueError("'qubit_order' does not contain exactly the same qubits as the circuit")
else:
qubits = qubit_order
if clbit_order is None:
clbits = circuit.clbits
elif len(clbit_order) != circuit.num_clbits or set(clbit_order) != set(circuit.clbits):
raise ValueError("'clbit_order' does not contain exactly the same clbits as the circuit")
else:
clbits = clbit_order
dagcircuit.add_qubits(qubits)
dagcircuit.add_clbits(clbits)
for register in circuit.qregs:
dagcircuit.add_qreg(register)
for register in circuit.cregs:
dagcircuit.add_creg(register)
for instruction in circuit.data:
op = instruction.operation
if copy_operations:
op = copy.deepcopy(op)
dagcircuit.apply_operation_back(op, instruction.qubits, instruction.clbits)
dagcircuit.duration = circuit.duration
dagcircuit.unit = circuit.unit
return dagcircuit
|
https://github.com/jenglick/scipy22-qiskit-runtime-tutorial
|
jenglick
|
import numpy as np
w = np.array([[0., 1., 1., 1.],
[1., 0., 1., 0.],
[1., 1., 0., 1.],
[1., 0., 1., 0.]])
from qiskit_optimization.applications import Maxcut
max_cut = Maxcut(w)
qp = max_cut.to_quadratic_program()
print(qp.export_as_lp_string())
qubitOp, offset = qp.to_ising()
num_qubits = qubitOp.num_qubits
print("Offset:", offset)
print("Ising Hamiltonian:")
print(str(qubitOp))
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit.algorithms import NumPyMinimumEigensolver
exact = MinimumEigenOptimizer(NumPyMinimumEigensolver())
result = exact.solve(qp)
print(result)
from qiskit.opflow import PauliSumOp
import numpy as np
ops = []
h = qubitOp.primitive
h.coeffs = np.real(qubitOp.coeffs)
ops.append(PauliSumOp(h))
print(ops)
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
options = {"backend" : "ibmq_qasm_simulator"}
from qiskit.circuit.library import TwoLocal
circuit = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear")
circuit.decompose().draw(fold=300)
from qiskit_ibm_runtime import Estimator
from qiskit.algorithms.optimizers import SPSA
history = {"nfevs": [], "points": [], "fvals": [], "updates": [], "accepted": []}
with Estimator(
circuits=circuit,
observables=ops,
options=options,
service=service
) as estimator:
def evaluate_expectation(x):
x = list(x)
results = estimator(circuits=[0], observables=[0], parameter_values=[x]).values[0]
return np.real(results)
def callback(nfev, point, fval, update, accepted):
print('expectation value: {}'.format(fval))
history["nfevs"].append(nfev)
history["points"].append(point)
history["fvals"].append(fval)
history["updates"].append(update)
history["accepted"].append(accepted)
np.random.seed(1)
initial_point = np.random.uniform(-np.pi, np.pi, len(circuit.parameters))
optimizer = SPSA(50, callback=callback)
result = optimizer.minimize(fun=evaluate_expectation, x0=initial_point)
print('optimized circuit parameters:\n{}'.format(result.x))
from qiskit_ibm_runtime import Sampler
circut = circuit.measure_all()
with Sampler(
circuits=circuit,
options=options,
service=service
) as sampler:
sampler_result = sampler(circuits=[0], parameter_values=[result.x], shots=8000)
print(result)
bitstrings = sampler_result.quasi_dists[0] # get the dictionary of bitstring counts
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1, 2, figsize=(14, 5))
axs[0].plot(history['fvals'])
axs[1].bar(list(bitstrings.keys()), list(bitstrings.values()))
axs[0].set_xlabel("Energy Evaluation Number")
axs[0].set_ylabel("Energy")
axs[1].set_xlabel("Objective Function Value")
axs[1].set_ylabel("Probability")
samples = []
for x, probability in bitstrings.items():
x = list(map(int, x)) # convert bitstring to list
status = qp.is_feasible(x)
fval = qp.objective.evaluate(x)
samples.append((x, fval, probability, status))
sorted_samples = sorted(
samples,
key=lambda v: (1-v[3], qp.objective.sense.value * v[1]) # feasible: 0; infeasible: 1
)
print('\nsorted')
for sample in sorted_samples:
print(sample)
best = sorted_samples[0]
print('optimal value: {}'.format(best[0]))
print('optimal function value: {}'.format(best[1]))
print('probability of optimal value: {}'.format(best[2]))
from qiskit_optimization import QuadraticProgram
qp = QuadraticProgram()
qp.binary_var("x")
qp.binary_var("y")
qp.binary_var("z")
qp.minimize(linear=[1, -2, 3], quadratic={("x", "y"): 1, ("x", "z"): -1, ("y", "z"): 2})
print(qp.export_as_lp_string())
qubitOp, offset = qp.to_ising()
num_qubits = qubitOp.num_qubits
print("offset: {}".format(offset))
print("operator:\n{}".format(qubitOp))
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit.algorithms import NumPyMinimumEigensolver
exact = MinimumEigenOptimizer(NumPyMinimumEigensolver())
result = exact.solve(qp)
print(result)
from qiskit.opflow import PauliSumOp
import numpy as np
ops = []
h = qubitOp.primitive
h.coeffs = np.real(qubitOp.coeffs)
ops.append(PauliSumOp(h))
print(ops)
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
options = {"backend" : "ibmq_qasm_simulator"}
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=num_qubits, reps=2)
circuit.decompose().draw(fold=100)
from qiskit_ibm_runtime import Estimator
from qiskit.algorithms.optimizers import SPSA
history = {"nfevs": [], "points": [], "fvals": [], "updates": [], "accepted": []}
with Estimator(
circuits=circuit,
observables=ops,
options=options,
service=service
) as estimator:
def evaluate_expectation(x):
x = list(x)
results = estimator(circuits=[0], observables=[0], parameter_values=[x]).values[0]
return np.real(results)
def callback(nfev, point, fval, update, accepted):
print('expectation value: {}'.format(fval))
history["nfevs"].append(nfev)
history["points"].append(point)
history["fvals"].append(fval)
history["updates"].append(update)
history["accepted"].append(accepted)
np.random.seed(1)
initial_point = np.random.uniform(-np.pi, np.pi, len(circuit.parameters))
optimizer = SPSA(30, callback=callback)
result = optimizer.minimize(fun=evaluate_expectation, x0=initial_point)
print('optimized circuit parameters:\n{}'.format(result.x))
from qiskit_ibm_runtime import Sampler
circut = circuit.measure_all()
with Sampler(
circuits=circuit,
options=options,
service=service
) as sampler:
sampler_result = sampler(circuits=[0], parameter_values=[result.x], shots=8000)
print(sampler_result)
bitstrings = sampler_result.quasi_dists[0] # get the dictionary of bitstring counts
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1, 2, figsize=(14, 5))
axs[0].plot(history['fvals'])
axs[1].bar(list(bitstrings.keys()), list(bitstrings.values()))
axs[0].set_xlabel("Energy Evaluation Number")
axs[0].set_ylabel("Energy")
axs[1].set_xlabel("Objective Function Value")
axs[1].set_ylabel("Probability")
samples = []
for x, probability in bitstrings.items():
x = list(map(int, x)) # convert bitstring to list
status = qp.is_feasible(x)
fval = qp.objective.evaluate(x)
samples.append((x, fval, probability, status))
sorted_samples = sorted(
samples,
key=lambda v: (1-v[3], qp.objective.sense.value * v[1]) # feasible: 0; infeasible: 1
)
print('\nsorted')
for sample in sorted_samples:
print(sample)
best = sorted_samples[0]
print('optimal value: {}'.format(best[0]))
print('optimal function value: {}'.format(best[1]))
print('probability of optimal value: {}'.format(best[2]))
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0)
plot_circuit_layout(new_circ_lv0, backend)
|
https://github.com/AmirhoseynpowAsghari/Qiskit-Tutorials
|
AmirhoseynpowAsghari
|
from qiskit import QuantumCircuit, execute, Aer
from qiskit.quantum_info import DensityMatrix, entropy
from qiskit.visualization import plot_histogram
import numpy as np
# Helper function to compute von Neumann entropy
def von_neumann_entropy(rho):
return entropy(DensityMatrix(rho))
# Step 1: Create the entangled state (Bell state)
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
# Simulate to get the density matrix of the initial entangled state
backend = Aer.get_backend('statevector_simulator')
result = execute(qc, backend).result()
statevector = result.get_statevector(qc)
rho_AB = DensityMatrix(statevector).data
# Calculate the initial entropy
S_rho_AB = von_neumann_entropy(rho_AB)
print(f"Initial entropy S(ρ_AB): {S_rho_AB}")
# Step 2: Apply local operations and calculate the averaged density matrix
pauli_operators = [np.array([[1, 0], [0, 1]]), # I
np.array([[0, 1], [1, 0]]), # X
np.array([[0, -1j], [1j, 0]]), # Y
np.array([[1, 0], [0, -1]])] # Z
rho_bar_AB = np.zeros((4, 4), dtype=complex)
for sigma in pauli_operators:
U = np.kron(sigma, np.eye(2))
rho_bar_AB += U @ rho_AB @ U.conj().T
rho_bar_AB /= 4
# Calculate the entropy of the averaged state
S_rho_bar_AB = von_neumann_entropy(rho_bar_AB)
print(f"Entropy of averaged state S(ρ̄_AB): {S_rho_bar_AB}")
# Step 3: Compute the Holevo quantity
holevo_quantity = S_rho_bar_AB - S_rho_AB
print(f"Holevo quantity χ(ρ_AB): {holevo_quantity}")
# Optionally visualize the density matrices
import matplotlib.pyplot as plt
from qiskit.visualization import plot_state_city
# Plot the density matrix of the original state
plot_state_city(DensityMatrix(rho_AB), title="Original State ρ_AB")
plt.show()
# Plot the density matrix of the averaged state
plot_state_city(DensityMatrix(rho_bar_AB), title="Averaged State ρ̄_AB")
plt.show()
|
https://github.com/Interlin-q/diskit
|
Interlin-q
|
from qiskit import BasicAer
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import Shor
N = 15
shor = Shor(N)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
ret = shor.run(quantum_instance)
print("The list of factors of {} as computed by the Shor's algorithm is {}.".format(N, ret['factors'][0]))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
# Virtual -> physical
# 0 -> 3
# 1 -> 4
# 2 -> 2
my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2])
plot_circuit_layout(my_ghz, backend)
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
# Bundle ckts into single job
qc_list = [qc1, qc2]
job = execute(qc_list, backend)
job.result().get_counts()
# Counts come here, as list of counts objects
job.result().get_counts(qc1) # gives only one ckt results
# to transpile, assemble and run qckts seperatl
tqc_list = transpile(qc_list, vigo) # returns a list of transpiled quantm ckts
qobj = assemble(tqc_list, vigo)
vigo.run(qobj)
job.result().get_counts()
# Visualise qckts using latex
qc.draw('latex') #needs pylatexenc, pillow
print(qc.draw('latex_source')) # for latex code
# Convert Quantum ckt to and from QASM
print(qc.qasm()) # returns the qasm string
# or
qc.qasm(formatted = True)
# or
qc.qasm(formatted = True, filename='')
# to create from qasm
new_qc = QuantumCircuit.from_qasm_file('my_circuit.qasm')
# Monitoring a job
job = execute(qc,backend)
# to see the status
job.status() #avoid this, can be rejected by server
# or
job.wait_for_final_state()
# using qiskit job monitor
from qiskit.tools import job_monitor
job_monitor(job)
# or use qiskit job watcher magic
import qiskit.tools.jupyter
%qiskit_job_watcher
# implement a multi-control toffoli gate
qc.ccx(0,1,2)
#or
qc.mct([0,1,2,3],4) # MCT- multicontrol toffoli, ([Control], target)
# use a specific version of qiskit
qiskit.__qiskit_version__
# Difference bt gate and instruction
# qiskit's gate object represents a unitary qGate, whereas instruction objs have non unitary parts
gate = qc.to_gate() # convert ckt to gate
new_qc.append(gate.power(5),[0,1])
#or
instructoin = qc.to_intruction()
instructoin.reverse_ops()
new_qc.append
# adding non unitary parts to qckt
qc = QuantumCircuit(2)
qc.initialize([0,1],0) # it is an initialize gate
qc.h(0)
qc.cx(0,1)
qc.measure_all()
qc.h(0).c_if(qc.clbits[0].register,1) # put h, conditioned on a classical register
qc.draw()
instructoin = qc.to_instruction()
# can't do gate = qc.to_gate(), because it is non-unitary
# but we can still append it to another ckt
new_qc.append(instructoin,[0,1],[0,1])
new_qx.decompose().draw() # to see original instruction
# control unitary part of ckt
# measuring or ressetting a ckt is non-unitary
controlled_qc = qc.control() # create control ckt, thus adding more qubits automatically to access it
# or, to add more control qubits
controlled_qc = qc.control(2)
new_qc = new_qc.compose(controlled_qc, range(4))
new_qc.decompose().draw()
# Combine 2 qckts
new_qc = qc1 + qc2
new_qc.draw()
# but to add ckts with different no. of qubits, we need to have qc1 and qc2 with same register name, or else we can do below
# use compose method
new_qc = qc1.compose(qc2, [1,2])
# Parametrised ckts in qiskit
a = Parameter("a")
qc.cul(a,0,1)
b = Parameter("b")
qc.assign_parameters({a:b}, inplace=True) # to replace a with b in the ckt
transpiled_qc = transpile(qc, basis_gates-['cx','u3'], optimization_level=3)
specific_transpiled_qc = transpiled_qc.assign_parameters({b:2})
# convert a unitary matrix to a set of one & two qubit gates, so that we can run code on older qcomputers
U = [[...],
[...],
[...],
[...]]
qc.unitary(U,[0,1])
trans_qc = transpile(qc, basis_gates=['cx','u3']) # cx and u3 are universal gates, so we can convert any ckt to these gates
# What is the unitary simulator
# What is a qsphere
plot_state_qsphere(sv.data)
#use mock backends in qiskit
from qiskit.test.mock import FakeVigo
fake_vigo = FakeVigo()
# this backend can be used without an account or que
results = execute(qc, fake_vigo).result()
counts = results.get_counts()
plot.........
# view device properties and config in qiskit
from qiskit.tools.jupyter import *
vigo = provider.get_backend('ibmq_vigo')
vigo # displays widget
vigo.configuration()
# or
vigo.configuration().coupling_map
# etc
vigo.properties() # or ().t1(3)
vigo.defaults()
# simulate sv in qiskit
# sv describes the state of the computer by a vector with 2^n elements, n=no. of qubits
from qiskit.quantum_info import Statevector
sv = Statevector.from_label('000') #all 3 qubits initialized to 0
sv # gives output, statevector objects
sv = sv.evolve(qc) # Evolve the object through the circuits, returns the simulated state of the qubits, after we run the ckt
sv.data # to get the state vector array
# Retrieve old job from IBM quantum
backend.jobs() # returns 10 most recent jobs
# or we can do
backend.jobs(limit=2) # for 2 jobs
job = backend.jobs(limit=2)[0] # to store the results of the first job
counts = job.result().get_counts()
# another way to retrieve the job, using the job id
job = backend.retrieve_job('JOB_ID_HERE')
job.properties().qubits(0)
# invert unitary part of ckt
my_gate = qc.to_gate()
my_inverse_gate = my_gate.inverse()
my_inverse_gate.name = 'inverted gate'
qc2 = QuantumCircuit(3)
qc2.append(my_inverse_gate, [0,1,2])
inverse_qc = qc.inverse() # doesnt work when we have non-unitary part
# Not in the Series, Use dark mode for matplotlib plots
import matplotlib.pyplot as plt
plt.style.use('dark_background')
plot_histogram(job.result().get_counts())
# Save Circuit Drawings to Different File Types
qc.draw().savefig('fileName.png', dpi=700) # for saving matplotlib image as a png file, dpi is optional
qc.draw().savefig('fileName.svg') # for saving as svg
qc.draw('latex').save('fileName.png', dpi=700) # to save latex as image
# to save as text
with open('fileName.txt','w') as f:
f.write(str(qc.draw('text')))
# Construct a Quantum Volume Circuit
# import the quantum volume constructor from the qiskit library
from qiskit.circuit.library import QuantumVolume
qv = QuantumVolume(4).decompose()
# learn more about the Quantum Volume here
# https://learn.qiskit.org/course/quantum-hardware/measuring-quantum-volume
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""
Test of measurement calibration:
1) Preparation of the basis states, generating the calibration circuits
(without noise), computing the calibration matrices,
and validating that they equal
to the identity matrices
2) Generating ideal (equally distributed) results, computing
the calibration output (without noise),
and validating that it is equally distributed
3) Testing the the measurement calibration on a circuit
(without noise), verifying that it is close to the
expected (equally distributed) result
4) Testing the fitters on pre-generated data with noise
"""
import unittest
import numpy as np
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.result.result import Result
from qiskit.utils.mitigation import (
CompleteMeasFitter,
TensoredMeasFitter,
complete_meas_cal,
tensored_meas_cal,
)
from qiskit.utils.mitigation._filters import MeasurementFilter
from qiskit.utils.mitigation.circuits import count_keys
from qiskit.utils import optionals
if optionals.HAS_AER:
# pylint: disable=no-name-in-module
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel
from qiskit_aer.noise.errors.standard_errors import pauli_error
# fixed seed for tests - for both simulator and transpiler
SEED = 42
def convert_ndarray_to_list_in_data(data: np.ndarray):
"""
converts ndarray format into list format (keeps all the dicts in the array)
also convert inner ndarrays into lists (recursively)
Args:
data: ndarray containing dicts or ndarrays in it
Returns:
list: same array, converted to list format (in order to save it as json)
"""
new_data = []
for item in data:
if isinstance(item, np.ndarray):
new_item = convert_ndarray_to_list_in_data(item)
elif isinstance(item, dict):
new_item = {}
for key, value in item.items():
new_item[key] = value.tolist()
else:
new_item = item
new_data.append(new_item)
return new_data
def meas_calib_circ_creation():
"""
create measurement calibration circuits and a GHZ state circuit for the tests
Returns:
QuantumCircuit: the measurement calibrations circuits
list[str]: the mitigation pattern
QuantumCircuit: ghz circuit with 5 qubits (3 are used)
"""
qubit_list = [1, 2, 3]
total_number_of_qubit = 5
meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=total_number_of_qubit)
# Choose 3 qubits
qubit_1 = qubit_list[0]
qubit_2 = qubit_list[1]
qubit_3 = qubit_list[2]
ghz = qiskit.QuantumCircuit(total_number_of_qubit, len(qubit_list))
ghz.h(qubit_1)
ghz.cx(qubit_1, qubit_2)
ghz.cx(qubit_1, qubit_3)
for i in qubit_list:
ghz.measure(i, i - 1)
return meas_calibs, state_labels, ghz
def tensored_calib_circ_creation():
"""
create tensored measurement calibration circuits and a GHZ state circuit for the tests
Returns:
QuantumCircuit: the tensored measurement calibration circuit
list[list[int]]: the mitigation pattern
QuantumCircuit: ghz circuit with 5 qubits (3 are used)
"""
mit_pattern = [[2], [4, 1]]
meas_layout = [2, 4, 1]
qr = qiskit.QuantumRegister(5)
# Generate the calibration circuits
meas_calibs, mit_pattern = tensored_meas_cal(mit_pattern, qr=qr)
cr = qiskit.ClassicalRegister(3)
ghz_circ = qiskit.QuantumCircuit(qr, cr)
ghz_circ.h(mit_pattern[0][0])
ghz_circ.cx(mit_pattern[0][0], mit_pattern[1][0])
ghz_circ.cx(mit_pattern[0][0], mit_pattern[1][1])
ghz_circ.measure(mit_pattern[0][0], cr[0])
ghz_circ.measure(mit_pattern[1][0], cr[1])
ghz_circ.measure(mit_pattern[1][1], cr[2])
return meas_calibs, mit_pattern, ghz_circ, meas_layout
def meas_calibration_circ_execution(shots: int, seed: int):
"""
create measurement calibration circuits and simulate them with noise
Args:
shots (int): number of shots per simulation
seed (int): the seed to use in the simulations
Returns:
list: list of Results of the measurement calibration simulations
list: list of all the possible states with this amount of qubits
dict: dictionary of results counts of GHZ circuit simulation with measurement errors
"""
# define the circuits
meas_calibs, state_labels, ghz = meas_calib_circ_creation()
# define noise
prob = 0.2
error_meas = pauli_error([("X", prob), ("I", 1 - prob)])
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error_meas, "measure")
# run the circuits multiple times
backend = AerSimulator()
cal_results = qiskit.execute(
meas_calibs, backend=backend, shots=shots, noise_model=noise_model, seed_simulator=seed
).result()
ghz_results = (
qiskit.execute(
ghz, backend=backend, shots=shots, noise_model=noise_model, seed_simulator=seed
)
.result()
.get_counts()
)
return cal_results, state_labels, ghz_results
def tensored_calib_circ_execution(shots: int, seed: int):
"""
create tensored measurement calibration circuits and simulate them with noise
Args:
shots (int): number of shots per simulation
seed (int): the seed to use in the simulations
Returns:
list: list of Results of the measurement calibration simulations
list: the mitigation pattern
dict: dictionary of results counts of GHZ circuit simulation with measurement errors
"""
# define the circuits
meas_calibs, mit_pattern, ghz_circ, meas_layout = tensored_calib_circ_creation()
# define noise
prob = 0.2
error_meas = pauli_error([("X", prob), ("I", 1 - prob)])
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error_meas, "measure")
# run the circuits multiple times
backend = AerSimulator()
cal_results = qiskit.execute(
meas_calibs, backend=backend, shots=shots, noise_model=noise_model, seed_simulator=seed
).result()
ghz_results = qiskit.execute(
ghz_circ, backend=backend, shots=shots, noise_model=noise_model, seed_simulator=seed
).result()
return cal_results, mit_pattern, ghz_results, meas_layout
@unittest.skipUnless(optionals.HAS_AER, "Qiskit aer is required to run these tests")
class TestMeasCal(QiskitTestCase):
"""The test class."""
def setUp(self):
super().setUp()
self.nq_list = [1, 2, 3, 4, 5] # Test up to 5 qubits
self.shots = 1024 # Number of shots (should be a power of 2)
@staticmethod
def choose_calibration(nq, pattern_type):
"""
Generate a calibration circuit
Args:
nq (int): number of qubits
pattern_type (int): a pattern in range(1, 2**nq)
Returns:
qubits: a list of qubits according to the given pattern
weight: the weight of the pattern_type,
equals to the number of qubits
Additional Information:
qr[i] exists if and only if the i-th bit in the binary
expression of
pattern_type equals 1
"""
qubits = []
weight = 0
for i in range(nq):
pattern_bit = pattern_type & 1
pattern_type = pattern_type >> 1
if pattern_bit == 1:
qubits.append(i)
weight += 1
return qubits, weight
def generate_ideal_results(self, state_labels, weight):
"""
Generate ideal equally distributed results
Args:
state_labels (list): a list of calibration state labels
weight (int): the number of qubits
Returns:
results_dict: a dictionary of equally distributed results
results_list: a list of equally distributed results
Additional Information:
for each state in state_labels:
result_dict[state] = #shots/len(state_labels)
"""
results_dict = {}
results_list = [0] * (2**weight)
state_num = len(state_labels)
for state in state_labels:
shots_per_state = self.shots / state_num
results_dict[state] = shots_per_state
# converting state (binary) to an integer
place = int(state, 2)
results_list[place] = shots_per_state
return results_dict, results_list
def test_ideal_meas_cal(self):
"""Test ideal execution, without noise."""
for nq in self.nq_list:
for pattern_type in range(1, 2**nq):
# Generate the quantum register according to the pattern
qubits, weight = self.choose_calibration(nq, pattern_type)
with self.assertWarns(DeprecationWarning):
# Generate the calibration circuits
meas_calibs, state_labels = complete_meas_cal(
qubit_list=qubits, circlabel="test"
)
# Perform an ideal execution on the generated circuits
backend = AerSimulator()
job = qiskit.execute(meas_calibs, backend=backend, shots=self.shots)
cal_results = job.result()
with self.assertWarns(DeprecationWarning):
# Make a calibration matrix
meas_cal = CompleteMeasFitter(cal_results, state_labels, circlabel="test")
# Assert that the calibration matrix is equal to identity
IdentityMatrix = np.identity(2**weight)
self.assertListEqual(
meas_cal.cal_matrix.tolist(),
IdentityMatrix.tolist(),
"Error: the calibration matrix is not equal to identity",
)
# Assert that the readout fidelity is equal to 1
self.assertEqual(
meas_cal.readout_fidelity(),
1.0,
"Error: the average fidelity is not equal to 1",
)
# Generate ideal (equally distributed) results
results_dict, results_list = self.generate_ideal_results(state_labels, weight)
with self.assertWarns(DeprecationWarning):
# Output the filter
meas_filter = meas_cal.filter
# Apply the calibration matrix to results
# in list and dict forms using different methods
results_dict_1 = meas_filter.apply(results_dict, method="least_squares")
results_dict_0 = meas_filter.apply(results_dict, method="pseudo_inverse")
results_list_1 = meas_filter.apply(results_list, method="least_squares")
results_list_0 = meas_filter.apply(results_list, method="pseudo_inverse")
# Assert that the results are equally distributed
self.assertListEqual(results_list, results_list_0.tolist())
self.assertListEqual(results_list, np.round(results_list_1).tolist())
self.assertDictEqual(results_dict, results_dict_0)
round_results = {}
for key, val in results_dict_1.items():
round_results[key] = np.round(val)
self.assertDictEqual(results_dict, round_results)
def test_meas_cal_on_circuit(self):
"""Test an execution on a circuit."""
# Generate the calibration circuits
with self.assertWarns(DeprecationWarning):
meas_calibs, state_labels, ghz = meas_calib_circ_creation()
# Run the calibration circuits
backend = AerSimulator()
job = qiskit.execute(
meas_calibs,
backend=backend,
shots=self.shots,
seed_simulator=SEED,
seed_transpiler=SEED,
)
cal_results = job.result()
with self.assertWarns(DeprecationWarning):
# Make a calibration matrix
meas_cal = CompleteMeasFitter(cal_results, state_labels)
# Calculate the fidelity
fidelity = meas_cal.readout_fidelity()
job = qiskit.execute(
[ghz], backend=backend, shots=self.shots, seed_simulator=SEED, seed_transpiler=SEED
)
results = job.result()
# Predicted equally distributed results
predicted_results = {"000": 0.5, "111": 0.5}
with self.assertWarns(DeprecationWarning):
meas_filter = meas_cal.filter
# Calculate the results after mitigation
output_results_pseudo_inverse = meas_filter.apply(
results, method="pseudo_inverse"
).get_counts(0)
output_results_least_square = meas_filter.apply(results, method="least_squares").get_counts(
0
)
# Compare with expected fidelity and expected results
self.assertAlmostEqual(fidelity, 1.0)
self.assertAlmostEqual(
output_results_pseudo_inverse["000"] / self.shots, predicted_results["000"], places=1
)
self.assertAlmostEqual(
output_results_least_square["000"] / self.shots, predicted_results["000"], places=1
)
self.assertAlmostEqual(
output_results_pseudo_inverse["111"] / self.shots, predicted_results["111"], places=1
)
self.assertAlmostEqual(
output_results_least_square["111"] / self.shots, predicted_results["111"], places=1
)
def test_ideal_tensored_meas_cal(self):
"""Test ideal execution, without noise."""
mit_pattern = [[1, 2], [3, 4, 5], [6]]
meas_layout = [1, 2, 3, 4, 5, 6]
# Generate the calibration circuits
with self.assertWarns(DeprecationWarning):
meas_calibs, _ = tensored_meas_cal(mit_pattern=mit_pattern)
# Perform an ideal execution on the generated circuits
backend = AerSimulator()
cal_results = qiskit.execute(meas_calibs, backend=backend, shots=self.shots).result()
with self.assertWarns(DeprecationWarning):
# Make calibration matrices
meas_cal = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern)
# Assert that the calibration matrices are equal to identity
cal_matrices = meas_cal.cal_matrices
self.assertEqual(
len(mit_pattern), len(cal_matrices), "Wrong number of calibration matrices"
)
for qubit_list, cal_mat in zip(mit_pattern, cal_matrices):
IdentityMatrix = np.identity(2 ** len(qubit_list))
self.assertListEqual(
cal_mat.tolist(),
IdentityMatrix.tolist(),
"Error: the calibration matrix is not equal to identity",
)
# Assert that the readout fidelity is equal to 1
self.assertEqual(
meas_cal.readout_fidelity(),
1.0,
"Error: the average fidelity is not equal to 1",
)
with self.assertWarns(DeprecationWarning):
# Generate ideal (equally distributed) results
results_dict, _ = self.generate_ideal_results(count_keys(6), 6)
# Output the filter
meas_filter = meas_cal.filter
# Apply the calibration matrix to results
# in list and dict forms using different methods
results_dict_1 = meas_filter.apply(
results_dict, method="least_squares", meas_layout=meas_layout
)
results_dict_0 = meas_filter.apply(
results_dict, method="pseudo_inverse", meas_layout=meas_layout
)
# Assert that the results are equally distributed
self.assertDictEqual(results_dict, results_dict_0)
round_results = {}
for key, val in results_dict_1.items():
round_results[key] = np.round(val)
self.assertDictEqual(results_dict, round_results)
def test_tensored_meas_cal_on_circuit(self):
"""Test an execution on a circuit."""
with self.assertWarns(DeprecationWarning):
# Generate the calibration circuits
meas_calibs, mit_pattern, ghz, meas_layout = tensored_calib_circ_creation()
# Run the calibration circuits
backend = AerSimulator()
cal_results = qiskit.execute(
meas_calibs,
backend=backend,
shots=self.shots,
seed_simulator=SEED,
seed_transpiler=SEED,
).result()
with self.assertWarns(DeprecationWarning):
# Make a calibration matrix
meas_cal = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern)
# Calculate the fidelity
fidelity = meas_cal.readout_fidelity(0) * meas_cal.readout_fidelity(1)
results = qiskit.execute(
[ghz], backend=backend, shots=self.shots, seed_simulator=SEED, seed_transpiler=SEED
).result()
# Predicted equally distributed results
predicted_results = {"000": 0.5, "111": 0.5}
with self.assertWarns(DeprecationWarning):
meas_filter = meas_cal.filter
# Calculate the results after mitigation
output_results_pseudo_inverse = meas_filter.apply(
results, method="pseudo_inverse", meas_layout=meas_layout
).get_counts(0)
output_results_least_square = meas_filter.apply(
results, method="least_squares", meas_layout=meas_layout
).get_counts(0)
# Compare with expected fidelity and expected results
self.assertAlmostEqual(fidelity, 1.0)
self.assertAlmostEqual(
output_results_pseudo_inverse["000"] / self.shots, predicted_results["000"], places=1
)
self.assertAlmostEqual(
output_results_least_square["000"] / self.shots, predicted_results["000"], places=1
)
self.assertAlmostEqual(
output_results_pseudo_inverse["111"] / self.shots, predicted_results["111"], places=1
)
self.assertAlmostEqual(
output_results_least_square["111"] / self.shots, predicted_results["111"], places=1
)
def test_meas_fitter_with_noise(self):
"""Test the MeasurementFitter with noise."""
tests = []
runs = 3
with self.assertWarns(DeprecationWarning):
for run in range(runs):
cal_results, state_labels, circuit_results = meas_calibration_circ_execution(
1000, SEED + run
)
meas_cal = CompleteMeasFitter(cal_results, state_labels)
meas_filter = MeasurementFilter(meas_cal.cal_matrix, state_labels)
# Calculate the results after mitigation
results_pseudo_inverse = meas_filter.apply(circuit_results, method="pseudo_inverse")
results_least_square = meas_filter.apply(circuit_results, method="least_squares")
tests.append(
{
"cal_matrix": convert_ndarray_to_list_in_data(meas_cal.cal_matrix),
"fidelity": meas_cal.readout_fidelity(),
"results": circuit_results,
"results_pseudo_inverse": results_pseudo_inverse,
"results_least_square": results_least_square,
}
)
# Set the state labels
state_labels = ["000", "001", "010", "011", "100", "101", "110", "111"]
meas_cal = CompleteMeasFitter(None, state_labels, circlabel="test")
for tst_index, _ in enumerate(tests):
# Set the calibration matrix
meas_cal.cal_matrix = tests[tst_index]["cal_matrix"]
# Calculate the fidelity
fidelity = meas_cal.readout_fidelity()
meas_filter = MeasurementFilter(tests[tst_index]["cal_matrix"], state_labels)
# Calculate the results after mitigation
output_results_pseudo_inverse = meas_filter.apply(
tests[tst_index]["results"], method="pseudo_inverse"
)
output_results_least_square = meas_filter.apply(
tests[tst_index]["results"], method="least_squares"
)
# Compare with expected fidelity and expected results
self.assertAlmostEqual(fidelity, tests[tst_index]["fidelity"], places=0)
self.assertAlmostEqual(
output_results_pseudo_inverse["000"],
tests[tst_index]["results_pseudo_inverse"]["000"],
places=0,
)
self.assertAlmostEqual(
output_results_least_square["000"],
tests[tst_index]["results_least_square"]["000"],
places=0,
)
self.assertAlmostEqual(
output_results_pseudo_inverse["111"],
tests[tst_index]["results_pseudo_inverse"]["111"],
places=0,
)
self.assertAlmostEqual(
output_results_least_square["111"],
tests[tst_index]["results_least_square"]["111"],
places=0,
)
def test_tensored_meas_fitter_with_noise(self):
"""Test the TensoredFitter with noise."""
with self.assertWarns(DeprecationWarning):
cal_results, mit_pattern, circuit_results, meas_layout = tensored_calib_circ_execution(
1000, SEED
)
meas_cal = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern)
meas_filter = meas_cal.filter
# Calculate the results after mitigation
results_pseudo_inverse = meas_filter.apply(
circuit_results.get_counts(), method="pseudo_inverse", meas_layout=meas_layout
)
results_least_square = meas_filter.apply(
circuit_results.get_counts(), method="least_squares", meas_layout=meas_layout
)
saved_info = {
"cal_results": cal_results.to_dict(),
"results": circuit_results.to_dict(),
"mit_pattern": mit_pattern,
"meas_layout": meas_layout,
"fidelity": meas_cal.readout_fidelity(),
"results_pseudo_inverse": results_pseudo_inverse,
"results_least_square": results_least_square,
}
saved_info["cal_results"] = Result.from_dict(saved_info["cal_results"])
saved_info["results"] = Result.from_dict(saved_info["results"])
with self.assertWarns(DeprecationWarning):
meas_cal = TensoredMeasFitter(
saved_info["cal_results"], mit_pattern=saved_info["mit_pattern"]
)
# Calculate the fidelity
fidelity = meas_cal.readout_fidelity(0) * meas_cal.readout_fidelity(1)
# Compare with expected fidelity and expected results
self.assertAlmostEqual(fidelity, saved_info["fidelity"], places=0)
with self.assertWarns(DeprecationWarning):
meas_filter = meas_cal.filter
# Calculate the results after mitigation
output_results_pseudo_inverse = meas_filter.apply(
saved_info["results"].get_counts(0),
method="pseudo_inverse",
meas_layout=saved_info["meas_layout"],
)
output_results_least_square = meas_filter.apply(
saved_info["results"], method="least_squares", meas_layout=saved_info["meas_layout"]
)
self.assertAlmostEqual(
output_results_pseudo_inverse["000"],
saved_info["results_pseudo_inverse"]["000"],
places=0,
)
self.assertAlmostEqual(
output_results_least_square.get_counts(0)["000"],
saved_info["results_least_square"]["000"],
places=0,
)
self.assertAlmostEqual(
output_results_pseudo_inverse["111"],
saved_info["results_pseudo_inverse"]["111"],
places=0,
)
self.assertAlmostEqual(
output_results_least_square.get_counts(0)["111"],
saved_info["results_least_square"]["111"],
places=0,
)
substates_list = []
with self.assertWarns(DeprecationWarning):
for qubit_list in saved_info["mit_pattern"]:
substates_list.append(count_keys(len(qubit_list))[::-1])
fitter_other_order = TensoredMeasFitter(
saved_info["cal_results"],
substate_labels_list=substates_list,
mit_pattern=saved_info["mit_pattern"],
)
fidelity = fitter_other_order.readout_fidelity(0) * meas_cal.readout_fidelity(1)
self.assertAlmostEqual(fidelity, saved_info["fidelity"], places=0)
with self.assertWarns(DeprecationWarning):
meas_filter = fitter_other_order.filter
# Calculate the results after mitigation
output_results_pseudo_inverse = meas_filter.apply(
saved_info["results"].get_counts(0),
method="pseudo_inverse",
meas_layout=saved_info["meas_layout"],
)
output_results_least_square = meas_filter.apply(
saved_info["results"], method="least_squares", meas_layout=saved_info["meas_layout"]
)
self.assertAlmostEqual(
output_results_pseudo_inverse["000"],
saved_info["results_pseudo_inverse"]["000"],
places=0,
)
self.assertAlmostEqual(
output_results_least_square.get_counts(0)["000"],
saved_info["results_least_square"]["000"],
places=0,
)
self.assertAlmostEqual(
output_results_pseudo_inverse["111"],
saved_info["results_pseudo_inverse"]["111"],
places=0,
)
self.assertAlmostEqual(
output_results_least_square.get_counts(0)["111"],
saved_info["results_least_square"]["111"],
places=0,
)
if __name__ == "__main__":
unittest.main()
|
https://github.com/hephaex/Quantum-Computing-Awesome-List
|
hephaex
|
from qiskit import *
from math import pi
from qiskit.visualization import plot_bloch_multivector
%config InlineBackend.figure_format = 'svg' # For Jupyter Notebooks
qc = QuantumCircuit(1)
qc.x(0)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
plot_bloch_multivector(out)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import 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("./")
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)
# 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
t1 = time.perf_counter()
qc = qc.bind_parameters({dt: target_time / num_steps})
t2 = time.perf_counter()
print("created qc,", t2 - t1, "s")
# Generate state tomography circuits to evaluate fidelity of simulation
t1 = time.perf_counter()
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
t2 = time.perf_counter()
print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s")
# remove barriers
t1 = time.perf_counter()
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
t2 = time.perf_counter()
print("removed barriers from st_qcs,", t2 - t1, "s")
# optimize circuit
t1 = time.perf_counter()
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s")
t3_st_qcs[0].draw("mpl")
# zne wrapping
t1 = time.perf_counter()
zne_qcs = zne_wrapper(t3_st_qcs)
t2 = time.perf_counter()
print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
t2 = time.perf_counter()
print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
# QREM
shots = 1 << 13
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level = 0) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
jobs.append(job)
dt_now = datetime.datetime.now()
print(dt_now)
import pickle
with open("jobs_jakarta_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("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "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_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results)
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fidelity = state_fidelity(rho, target_state)
print(fidelity)
|
https://github.com/Ilan-Bondarevsky/qiskit_algorithm
|
Ilan-Bondarevsky
|
from qiskit import *
from qiskit.visualization import plot_histogram
def simon_oracle(b):
n = len(b)
circ = QuantumCircuit(2*n, n)
for i in range(n):
circ.cx(i, i+n)
# for i in range(n):
# if b[n-1-i] == '1':
# for j in range(n):
# if b[j] == '1':
# circ.cx(i, j + n)
# break
for i in range(n):
if b[n-1-i] == '1':
circ.cx(i, i+n)
return circ
b = '1001'
n = len(b)
circ = QuantumCircuit(2*n, n)
circ.h(range(n))
circ.barrier()
circ = circ.compose(simon_oracle(b))
circ.barrier()
circ.h(range(n))
circ.measure(range(n), range(n))
print("the coresponding function should saticfy")
b_dex = int(b, base=2)
for num in range(2**(n-1)):
print(f"f({num}) = f({num ^ b_dex})")
circ.draw('mpl')
sim = Aer.get_backend("qasm_simulator")
result = execute(circ, backend=sim).result()
plot_histogram(result.get_counts())
#find b
def bdotz(b, z):
accum = 0
for i in range(len(b)):
accum += int(b[i]) * int(z[i])
return (accum % 2)
shots = 1024
for z in result.get_counts().keys():
print( '{} . {} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), result.get_counts()[z]*100/shots))
import random
import timeit
import matplotlib.colors as mcolors
from backend_operation import run_simulator, get_transpiled_circuits_of_circuit, get_fake_backend_list,get_unitary, get_fake_backend, get_fake_backend_list
from itertools import combinations, permutations
fake_backed_name = 'FakeAuckland'
transpiled_circuit = get_transpiled_circuits_of_circuit(circ, ['Aer', fake_backed_name],
[None, "Full_Range"],
optimization_level_list=[0,3])
result_for_circuiut = [
run_simulator(qc,shots = 1024 * 4)
for qc in transpiled_circuit
]
output = []
for index, run_circuit in enumerate(result_for_circuiut):
result_dict= run_circuit.to_dict()
cirq_result = result_dict['results'][0]
cirq_counts = cirq_result['data']['counts']
cirq_time = cirq_result['time_taken']
cirq_name = cirq_result['header']['name']
cirq_depth = transpiled_circuit[index].depth()
output.append({'name' : cirq_name, 'time_taken' :cirq_time, 'depth':cirq_depth, 'count':cirq_counts})
print(output)
import pandas as pd
df = pd.DataFrame(output)
df
plot_histogram([run_simulator(qc,shots = 1024).get_counts() for qc in transpiled_circuit],
legend=[qc.name for qc in transpiled_circuit], color=list(random.choices(list(mcolors.get_named_colors_mapping().values()), k = len(transpiled_circuit))),
title="Result transpilers")
plot_histogram({
qc.name : qc.depth()
for qc in transpiled_circuit
})
|
https://github.com/usamisaori/qLipschitz
|
usamisaori
|
import numpy as np
from qiskit.quantum_info import DensityMatrix, Statevector
def getDensityMatrix(circuit):
return DensityMatrix(circuit).data
def getStatevector(circuit):
return Statevector(circuit).data
from functools import reduce
Dag = lambda matrix: matrix.conj().T
Kron = lambda *matrices: reduce(np.kron, matrices)
def powerSets(items):
N = len(items)
combs = []
for i in range(2 ** N):
comb = []
for j in range(N):
if (i >> j) % 2:
comb.append(items[j])
combs.append(comb)
return combs
# Measurements
psi_0 = np.array([1.0, 0.0])
psi_1 = np.array([0.0, 1.0])
I = np.eye(2)
M_0 = psi_0.reshape([2, 1]) @ psi_0.reshape([1, 2]).conj()
M_1 = psi_1.reshape([2, 1]) @ psi_1.reshape([1, 2]).conj()
def getMeasurements(qubits_num):
measurement_0 = [M_0]
measurement_1 = [M_1]
for i in range(qubits_num - 1):
measurement_0.append(I)
measurement_1.append(I)
return [
Kron(*measurement_0),
Kron(*measurement_1)
]
class Algorithm:
def __init__(self, model_circuit, measurements, outputs):
# DensityMatrix of model
self.E = getDensityMatrix(model_circuit)
# Measurements
self.M = dict()
for index, output in enumerate(outputs):
self.M[output] = measurements[index]
# Outputs
self.O = outputs
self.O_ = powerSets(outputs)
def qLipschitz(A):
E, M, O, O_ = A.E, A.M, A.O, A.O_
# Step 1: Calculate W_i
W = dict()
for i in O:
W[i] = Dag(E) @ Dag(M[i]) @ M[i] @ E
# Step 2: Calculate K_star
K_star = 0; vectors = [None, None]
M_star = np.zeros(E.shape)
for S in O_:
if len(S) == 0:
continue
# calculate M_S = Σ Wi
M_S = np.zeros(E.shape).astype('complex64')
for i in S:
M_S += W[i]
# calculate eigenvalues and eigenvectors of M_S
eigenvalues, eigenvectors = np.linalg.eigh(M_S)
min_index = np.where(eigenvalues == eigenvalues.min())
max_index = np.where(eigenvalues == eigenvalues.max())
# calculate K_S
K_S = np.linalg.norm(eigenvalues[max_index][0] - eigenvalues[min_index][0])
if K_S > K_star:
K_star = K_S
vectors[0] = eigenvectors.T[max_index][0]
vectors[1] = eigenvectors.T[min_index][0]
return K_star, np.array(vectors)
def FairVeriQ(A, epsilon, delta):
# epsilon <= 1 and delta > 0
K_star, kernel = qLipschitz(A)
if delta >= K_star * epsilon:
return True, None
else:
return False, kernel
def generateBiasPair(sigma, kernel, epsilon):
psi, phi = kernel
size = len(psi)
psi = psi.reshape(size, 1) @ Dag(psi.reshape(size, 1))
phi = phi.reshape(size, 1) @ Dag(phi.reshape(size, 1))
rou_psi = epsilon * psi + (1 - epsilon) * sigma
rou_phi = epsilon * phi + (1 - epsilon) * sigma
return np.array([
rou_psi, rou_phi
])
class QLipschitz:
def __init__(self, model_circuit, outputs):
measurements = getMeasurements(model_circuit.num_qubits)
self.A = Algorithm(model_circuit, measurements, outputs)
@property
def constant(self):
return qLipschitz(self.A)
def fairVeriQ(self, epsilon, delta):
return FairVeriQ(self.A, epsilon, delta)
def generateBiasPair(self, sigma, kernel, epsilon):
return generateBiasPair(sigma, kernel, epsilon)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
#
# your solution is here
#
#
# your solution
#
#
# your code is here
#
|
https://github.com/mousepad01/qiskit_POCs
|
mousepad01
|
import numpy as np
import random
from copy import deepcopy
import matplotlib.pyplot as plt
from qiskit import *
from qiskit.visualization import plot_state_city, plot_histogram
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import random_statevector
from qiskit.quantum_info.operators import Operator
from qiskit.circuit.library import XGate
backend_statevector = Aer.get_backend('statevector_simulator')
backend_sim = Aer.get_backend('qasm_simulator')
with open('t.txt', "r") as token_f:
TOKEN = token_f.read()
# ===========================
# convert "endianess" of qubit order
def qiskit_tensor_conversion(t: np.array, n: int):
def _conv(x: int):
x_ = 0
for i in range(n):
x_ |= ((x >> i) & 0x01) << (n - i - 1)
return x_
if type(t) == list:
t = np.array(t)
t_ = deepcopy(t)
for i in range(t.shape[0]):
for j in range(t.shape[1]):
t_[i][j] = t[_conv(i)][_conv(j)]
return t_
# simulation for state vector
def get_statevector(circuit: QuantumCircuit):
return backend_statevector.run(circuit).result().get_statevector(circuit, decimals=2)
def plot_statevector(circuit: QuantumCircuit):
plot_state_city(get_statevector(circuit))
# simulation for measurement outputs
def simulate_runs(circuit: QuantumCircuit, runs: int = 1024):
return backend_sim.run(transpile(circuit, backend_sim), shots=runs).result().get_counts()
def plot_simulated_runs(circuit: QuantumCircuit, runs: int = 1024):
plot_histogram(simulate_runs(circuit, runs))
# real run on IBM 5 qubit quantum computers (measurement outputs)
def real_runs(circuit: QuantumCircuit, runs: int = 1024):
IBMQ.enable_account(TOKEN)
provider = IBMQ.get_provider(hub='ibm-q')
backend_q = least_busy(provider.backends(filters = lambda x: x.configuration().n_qubits == 5
and not x.configuration().simulator
and x.status().operational == True))
return backend_q.run(transpile(circuit, backend_q, optimization_level=3), shots=runs).result().get_counts()
def plot_runs(circuit: QuantumCircuit, runs: int = 1024):
plot_histogram(real_runs(circuit, runs))
# ===========================
def example():
c = QuantumCircuit(3, 3)
c.h(0)
c.cx(0, 1)
c.cx(1, 2)
mes = QuantumCircuit(3, 3)
mes.measure(range(3), range(3))
cmes = c.compose(mes)
plot_statevector(c)
plot_simulated_runs(cmes)
plt.show()
def superdense_coding_v0(a, b):
a = [0, 1] if a == 1 else [1, 0]
b = [0, 1] if b == 1 else [1, 0]
qc_init = QuantumCircuit(4, 2)
qc_alicebob = QuantumCircuit(4, 2)
qc_init.h(2)
qc_init.cx(2, 3)
qc_init.initialize(a, 0)
qc_init.initialize(b, 1)
qc_alicebob.cx(1, 2)
qc_alicebob.cz(0, 2)
qc_alicebob.cx(2, 3)
qc_alicebob.h(2)
qc_alicebob.measure(2, 0)
qc_alicebob.measure(3, 1)
superdense_coding_qc = qc_init.compose(qc_alicebob)
#superdense_coding_qc.draw('mpl')
plot_simulated_runs(superdense_coding_qc)
plt.show()
def superdense_coding(a, b):
def _init_bell_pair():
bell_state = QuantumCircuit(2)
bell_state.h(0)
bell_state.cx(0, 1)
return bell_state
def _encode(qc, qubit, b0, b1):
if b0 not in [0, 1] or b1 not in [0, 1]:
raise RuntimeError(f'invalid bytes {b0} {b1}')
if b0 == 1:
qc.x(qubit)
if b1 == 1:
qc.z(qubit)
return qc
def _decode(qc):
qc.cx(0, 1)
qc.h(0)
qc.measure_all()
return qc
bell_pair = _init_bell_pair()
bell_pair = _encode(bell_pair, 0, a, b)
bell_pair = _decode(bell_pair)
plot_simulated_runs(bell_pair)
bell_pair.draw('mpl')
plt.show()
def superdense_coding_real(a, b):
def _init_bell_pair():
bell_state = QuantumCircuit(2)
bell_state.h(0)
bell_state.cx(0, 1)
return bell_state
def _encode(qc, qubit, b0, b1):
if b0 not in [0, 1] or b1 not in [0, 1]:
raise RuntimeError(f'invalid bytes {b0} {b1}')
if b0 == 1:
qc.x(qubit)
if b1 == 1:
qc.z(qubit)
return qc
def _decode(qc):
qc.cx(0, 1)
qc.h(0)
qc.measure_all()
return qc
bell_pair = _init_bell_pair()
bell_pair = _encode(bell_pair, 0, a, b)
bell_pair = _decode(bell_pair)
plot_runs(bell_pair)
bell_pair.draw('mpl')
plt.show()
def quantum_teleportation(p0, p1):
qc = QuantumRegister(3)
a, b, psi_measured = ClassicalRegister(1), ClassicalRegister(1), ClassicalRegister(1)
qc_teleportation = QuantumCircuit(qc, a, b, psi_measured)
def _init_psi():
qc_teleportation.initialize([p0, p1], 0)
def _init_bell_state():
qc_teleportation.h(1)
qc_teleportation.cx(1, 2)
qc_teleportation.barrier()
def _entangle_psi():
qc_teleportation.cx(0, 1)
qc_teleportation.h(0)
qc_teleportation.barrier()
def _measure():
qc_teleportation.measure(0, a)
qc_teleportation.measure(1, b)
qc_teleportation.barrier()
def _apply_xz():
qc_teleportation.x(2).c_if(b, 1)
qc_teleportation.z(2).c_if(a, 1)
qc_teleportation.barrier()
def _measure_psi():
qc_teleportation.measure(2, psi_measured)
_init_psi()
_init_bell_state()
_entangle_psi()
_measure()
_apply_xz()
_measure_psi()
qc_teleportation.draw('mpl')
psi_cnts = {'0': 0, '1': 0}
cnts = simulate_runs(qc_teleportation)
for state, fr in cnts.items():
psi_cnts[state[0]] += fr
plot_histogram(psi_cnts)
plt.show()
def equiv_test():
def _test(a, b, c, d):
q0_init_state = random_statevector(2)
q1_init_state = random_statevector(2)
qc_fst = QuantumCircuit(2)
qc_fst.initialize(q0_init_state, 0)
qc_fst.initialize(q1_init_state, 0)
qc_fst.cx(0, 1)
if a == 1:
qc_fst.x(0)
if b == 1:
qc_fst.z(0)
if c == 1:
qc_fst.x(1)
if d == 1:
qc_fst.z(1)
qc_fst.cx(0, 1)
qc_fst.barrier()
qc_fst.measure_all()
qc_snd = QuantumCircuit(2)
qc_snd.initialize(q0_init_state, 0)
qc_snd.initialize(q1_init_state, 0)
a_ = a
d_ = d
c_ = (1 - a) * c + a * (1 - c)
b_ = (1 - d) * b + d * (1 - b)
if a_ == 1:
qc_snd.x(0)
if b_ == 1:
qc_snd.z(0)
if c_ == 1:
qc_snd.x(1)
if d_ == 1:
qc_snd.z(1)
qc_snd.barrier()
qc_snd.measure_all()
plot_simulated_runs(qc_fst)
plot_simulated_runs(qc_snd)
plt.show()
for a in [0, 1]:
for b in [0, 1]:
for c in [0, 1]:
for d in [0, 1]:
_test(a, b, c, d)
def deutsch_josza():
'''
n = 4
uses random generated functions that are either constant or balanced
'''
# build the Uf operator
n = 4
ct = random.randint(0, 1)
Uf = [[0 for _ in range(1 << (n + 1))] for _ in range(1 << (n + 1))]
if random.randint(0, 1) == 1:
constant = True
for x in range(1 << (n + 1)):
Uf[x][x] = 1
else:
constant = False
f = {x: (ct if x < (1 << (n - 1)) else 1 - ct) for x in range(1 << n)}
for x in range((1 << n) - 1):
x_ = random.randint(x + 1, (1 << n) - 1)
aux = f[x]
f[x] = f[x_]
f[x_] = aux
#print(f)
cnt_ = 0
for x in range(1 << n):
if f[x] == 1:
cnt_ += 1
assert(cnt_ == (1 << (n - 1)))
for x in range(1 << (n + 1)):
Uf[x ^ f[x >> 1]][x] = 1
print(f'function is constant? {constant}')
#print(Uf)
#q_uf = Operator(Uf)
#print(q_uf)
Uf = qiskit_tensor_conversion(Uf, n + 1)
#print(Uf)
q_uf = Operator(Uf)
#print(q_uf)
qc = QuantumCircuit(n + 1, n)
for x in range(n):
qc.initialize([1, 0], x)
qc.h(x)
qc.initialize([0, 1], n)
qc.h(n)
qc.append(q_uf, [x for x in range(n + 1)])
for x in range(n):
qc.h(x)
qc.measure(x, x)
qc.draw('mpl')
plot_simulated_runs(qc, runs=128)
#print(get_statevector(qc))
plt.show()
def simon_alg():
'''
n = 4
probabilistic version (ends after n + 3 runs)
it only checks for orthogonality of the returned values wrt s
'''
# build the Uf operator
n = 4
s = random.randint(1, (1 << n) - 1)
f_values = [x for x in range(1 << n)]
f = {x: None for x in range(1 << n)}
for x in range(1 << n):
if f[x] is None:
f[x] = random.choice(f_values)
f[x ^ s] = f[x]
f_values.remove(f[x])
print(f"secret {s}, f {f}")
Uf = [[0 for _ in range(1 << (n * 2))] for _ in range(1 << (n * 2))]
for k in range(1 << (n * 2)):
Uf[k ^ f[k >> n]][k] = 1
Uf = qiskit_tensor_conversion(Uf, n * 2)
q_uf = Operator(Uf)
qc = QuantumCircuit(n * 2, n * 2)
for x in range(n * 2):
qc.initialize([1, 0], x)
for x in range(n):
qc.h(x)
qc.append(q_uf, [x for x in range(n * 2)])
# sanity check
v = get_statevector(qc).to_dict()
for k, _ in v.items():
x, fx = k[n: 2 * n], k[:n]
x, fx = int(x[::-1], 2), int(fx[::-1], 2)
assert(fx == f[x])
# --------
for x in range(n, n * 2):
qc.measure(x, x)
#v = get_statevector(qc).to_dict()
#print(v)
for x in range(n):
qc.h(x)
qc.measure(x, x)
qc.draw('mpl')
for _ in range(n + 3):
for res in simulate_runs(qc, runs = 1).keys():
w = res[n: 2 * n]
w = int(w[::-1], 2)
break
# solving the system manually
# here just checking for s * w = 0
dot_prod = s & w
s_ = 0
while dot_prod > 0:
s_ ^= dot_prod & 0x01
dot_prod >>= 1
assert(s_ == 0)
plot_simulated_runs(qc, runs=128)
#print(get_statevector(qc))
plt.show()
def grover_alg():
'''
n = 4\n
generates random f: {0, 1}^n -> {0, 1} with exactly one x s.t. f(x) = 1
'''
n = 4
def _init_uniform_superposition():
# also adds ancilla qubit initialized to |->
unif = QuantumCircuit(n + 1)
unif.initialize([0, 1], n)
unif.h([qb for qb in range(n + 1)])
return unif
def _get_random_Uf():
x_1 = random.randint(0, (1 << n) - 1)
f = {x: 0 for x in range(1 << n)}
f[x_1] = 1
print(f"f({x_1}) = 1")
Uf = [[0 for _ in range(1 << (n + 1))] for _ in range(1 << (n + 1))]
for k in range(1 << (n + 1)):
Uf[k ^ f[k >> 1]][k] = 1
Uf = qiskit_tensor_conversion(Uf, n + 1)
q_uf = Operator(Uf)
return q_uf
def _get_U0():
U0 = [[0 for _ in range(1 << n)] for _ in range(1 << n)]
for k in range(1 << n):
U0[k][k] = -1
U0[0][0] = 1
U0 = qiskit_tensor_conversion(U0, n)
q_u0 = Operator(U0)
return q_u0
def _get_grover_iterate(q_uf, q_u0):
g = QuantumCircuit(n + 1)
g.append(q_uf, [qb for qb in range(n + 1)])
g.h([qb for qb in range(n)])
g.append(q_u0, [qb for qb in range(n)])
g.h([qb for qb in range(n)])
return g
def _measure_output(qc: QuantumCircuit):
qc.add_register(ClassicalRegister(n))
for qb in range(n):
qc.measure(qb, qb)
plot_simulated_runs(qc)
qc = _init_uniform_superposition()
q_uf = _get_random_Uf()
q_u0 = _get_U0()
for _ in range(int(np.floor(np.sqrt(n)))):
qc.append(_get_grover_iterate(q_uf, q_u0), [qb for qb in range(n + 1)])
#qc.draw('mpl')
_measure_output(qc)
plt.show()
def start():
#example()
#superdense_coding_real(1, 1)
#quantum_teleportation(np.sqrt(3) / 2, 0.5)
#equiv_test()
#deutsch_josza()
#simon_alg()
grover_alg()
return
if __name__ == "__main__":
start()
|
https://github.com/Tojarieh97/VQE
|
Tojarieh97
|
import numpy as np
def get_first_k_eigenvectors_from_n_computational_basis(k, n):
n_computational_basis = np.identity(n)
return n_computational_basis[:k]
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub="ibm-q", group="open", project="main")
program_id = "qaoa"
qaoa_program = provider.runtime.program(program_id)
print(f"Program name: {qaoa_program.name}, Program id: {qaoa_program.program_id}")
print(qaoa_program.parameters())
import numpy as np
from qiskit.tools import job_monitor
from qiskit.opflow import PauliSumOp, Z, I
from qiskit.algorithms.optimizers import SPSA
# Define the cost operator to run.
op = (
(Z ^ Z ^ I ^ I ^ I)
- (I ^ I ^ Z ^ Z ^ I)
+ (I ^ I ^ Z ^ I ^ Z)
- (Z ^ I ^ Z ^ I ^ I)
- (I ^ Z ^ Z ^ I ^ I)
+ (I ^ Z ^ I ^ Z ^ I)
+ (I ^ I ^ I ^ Z ^ Z)
)
# SPSA helps deal with noisy environments.
optimizer = SPSA(maxiter=100)
# We will run a depth two QAOA.
reps = 2
# The initial point for the optimization, chosen at random.
initial_point = np.random.random(2 * reps)
# The backend that will run the programm.
options = {"backend_name": "ibmq_qasm_simulator"}
# The inputs of the program as described above.
runtime_inputs = {
"operator": op,
"reps": reps,
"optimizer": optimizer,
"initial_point": initial_point,
"shots": 2**13,
# Set to True when running on real backends to reduce circuit
# depth by leveraging swap strategies. If False the
# given optimization_level (default is 1) will be used.
"use_swap_strategies": False,
# Set to True when optimizing sparse problems.
"use_initial_mapping": False,
# Set to true when using echoed-cross-resonance hardware.
"use_pulse_efficient": False,
}
job = provider.runtime.run(
program_id=program_id,
options=options,
inputs=runtime_inputs,
)
job_monitor(job)
print(f"Job id: {job.job_id()}")
print(f"Job status: {job.status()}")
result = job.result()
from collections import defaultdict
def op_adj_mat(op: PauliSumOp) -> np.array:
"""Extract the adjacency matrix from the op."""
adj_mat = np.zeros((op.num_qubits, op.num_qubits))
for pauli, coeff in op.primitive.to_list():
idx = tuple([i for i, c in enumerate(pauli[::-1]) if c == "Z"]) # index of Z
adj_mat[idx[0], idx[1]], adj_mat[idx[1], idx[0]] = np.real(coeff), np.real(coeff)
return adj_mat
def get_cost(bit_str: str, adj_mat: np.array) -> float:
"""Return the cut value of the bit string."""
n, x = len(bit_str), [int(bit) for bit in bit_str[::-1]]
cost = 0
for i in range(n):
for j in range(n):
cost += adj_mat[i, j] * x[i] * (1 - x[j])
return cost
def get_cut_distribution(result) -> dict:
"""Extract the cut distribution from the result.
Returns:
A dict of cut value: probability.
"""
adj_mat = op_adj_mat(PauliSumOp.from_list(result["inputs"]["operator"]))
state_results = []
for bit_str, amp in result["eigenstate"].items():
state_results.append((bit_str, get_cost(bit_str, adj_mat), amp**2 * 100))
vals = defaultdict(int)
for res in state_results:
vals[res[1]] += res[2]
return dict(vals)
import matplotlib.pyplot as plt
cut_vals = get_cut_distribution(result)
fig, axs = plt.subplots(1, 2, figsize=(14, 5))
axs[0].plot(result["optimizer_history"]["energy"])
axs[1].bar(list(cut_vals.keys()), list(cut_vals.values()))
axs[0].set_xlabel("Energy evaluation number")
axs[0].set_ylabel("Energy")
axs[1].set_xlabel("Cut value")
axs[1].set_ylabel("Probability")
from qiskit_optimization.runtime import QAOAClient
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization import QuadraticProgram
qubo = QuadraticProgram()
qubo.binary_var("x")
qubo.binary_var("y")
qubo.binary_var("z")
qubo.minimize(linear=[1, -2, 3], quadratic={("x", "y"): 1, ("x", "z"): -1, ("y", "z"): 2})
print(qubo.prettyprint())
qaoa_mes = QAOAClient(
provider=provider, backend=provider.get_backend("ibmq_qasm_simulator"), reps=2, alpha=0.75
)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qubo)
print(result.prettyprint())
from qiskit.transpiler import PassManager
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary as std_eqlib,
)
from qiskit.transpiler.passes import (
Collect2qBlocks,
ConsolidateBlocks,
UnrollCustomDefinitions,
BasisTranslator,
Optimize1qGatesDecomposition,
)
from qiskit.transpiler.passes.calibration.builders import RZXCalibrationBuilderNoEcho
from qiskit.transpiler.passes.optimization.echo_rzx_weyl_decomposition import (
EchoRZXWeylDecomposition,
)
from qiskit.test.mock import FakeBelem
backend = FakeBelem()
inst_map = backend.defaults().instruction_schedule_map
channel_map = backend.configuration().qubit_channel_mapping
rzx_basis = ["rzx", "rz", "x", "sx"]
pulse_efficient = PassManager(
[
# Consolidate consecutive two-qubit operations.
Collect2qBlocks(),
ConsolidateBlocks(basis_gates=["rz", "sx", "x", "rxx"]),
# Rewrite circuit in terms of Weyl-decomposed echoed RZX gates.
EchoRZXWeylDecomposition(backend.defaults().instruction_schedule_map),
# Attach scaled CR pulse schedules to the RZX gates.
RZXCalibrationBuilderNoEcho(
instruction_schedule_map=inst_map, qubit_channel_mapping=channel_map
),
# Simplify single-qubit gates.
UnrollCustomDefinitions(std_eqlib, rzx_basis),
BasisTranslator(std_eqlib, rzx_basis),
Optimize1qGatesDecomposition(rzx_basis),
]
)
from qiskit import QuantumCircuit
circ = QuantumCircuit(3)
circ.h([0, 1, 2])
circ.rzx(0.5, 0, 1)
circ.swap(0, 1)
circ.cx(2, 1)
circ.rz(0.4, 1)
circ.cx(2, 1)
circ.rx(1.23, 2)
circ.cx(2, 1)
circ.draw("mpl")
pulse_efficient.run(circ).draw("mpl", fold=False)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Phase estimation for the spectrum of a Hamiltonian"""
from __future__ import annotations
import warnings
from qiskit import QuantumCircuit
from qiskit.utils import QuantumInstance
from qiskit.utils.deprecation import deprecate_arg
from qiskit.opflow import (
SummedOp,
PauliOp,
MatrixOp,
PauliSumOp,
StateFn,
EvolutionBase,
PauliTrotterEvolution,
I,
)
from qiskit.providers import Backend
from .phase_estimation import PhaseEstimation
from .hamiltonian_phase_estimation_result import HamiltonianPhaseEstimationResult
from .phase_estimation_scale import PhaseEstimationScale
from ...circuit.library import PauliEvolutionGate
from ...primitives import BaseSampler
from ...quantum_info import SparsePauliOp, Statevector, Pauli
from ...synthesis import EvolutionSynthesis
class HamiltonianPhaseEstimation:
r"""Run the Quantum Phase Estimation algorithm to find the eigenvalues of a Hermitian operator.
This class is nearly the same as :class:`~qiskit_algorithms.PhaseEstimation`, differing only
in that the input in that class is a unitary operator, whereas here the input is a Hermitian
operator from which a unitary will be obtained by scaling and exponentiating. The scaling is
performed in order to prevent the phases from wrapping around :math:`2\pi`.
The problem of estimating eigenvalues :math:`\lambda_j` of the Hermitian operator
:math:`H` is solved by running a circuit representing
.. math::
\exp(i b H) |\psi\rangle = \sum_j \exp(i b \lambda_j) c_j |\lambda_j\rangle,
where the input state is
.. math::
|\psi\rangle = \sum_j c_j |\lambda_j\rangle,
and :math:`\lambda_j` are the eigenvalues of :math:`H`.
Here, :math:`b` is a scaling factor sufficiently large to map positive :math:`\lambda` to
:math:`[0,\pi)` and negative :math:`\lambda` to :math:`[\pi,2\pi)`. Each time the circuit is
run, one measures a phase corresponding to :math:`lambda_j` with probability :math:`|c_j|^2`.
If :math:`H` is a Pauli sum, the bound :math:`b` is computed from the sum of the absolute
values of the coefficients of the terms. There is no way to reliably recover eigenvalues
from phases very near the endpoints of these intervals. Because of this you should be aware
that for degenerate cases, such as :math:`H=Z`, the eigenvalues :math:`\pm 1` will be
mapped to the same phase, :math:`\pi`, and so cannot be distinguished. In this case, you need
to specify a larger bound as an argument to the method ``estimate``.
This class uses and works together with :class:`~qiskit_algorithms.PhaseEstimationScale` to
manage scaling the Hamiltonian and the phases that are obtained by the QPE algorithm. This
includes setting, or computing, a bound on the eigenvalues of the operator, using this
bound to obtain a scale factor, scaling the operator, and shifting and scaling the measured
phases to recover the eigenvalues.
Note that, although we speak of "evolving" the state according the Hamiltonian, in the
present algorithm, we are not actually considering time evolution. Rather, the role of time is
played by the scaling factor, which is chosen to best extract the eigenvalues of the
Hamiltonian.
A few of the ideas in the algorithm may be found in Ref. [1].
**Reference:**
[1]: Quantum phase estimation of multiple eigenvalues for small-scale (noisy) experiments
T.E. O'Brien, B. Tarasinski, B.M. Terhal
`arXiv:1809.09697 <https://arxiv.org/abs/1809.09697>`_
"""
@deprecate_arg(
"quantum_instance",
additional_msg=(
"Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a "
"migration guide."
),
since="0.24.0",
)
def __init__(
self,
num_evaluation_qubits: int,
quantum_instance: QuantumInstance | Backend | None = None,
sampler: BaseSampler | None = None,
) -> None:
r"""
Args:
num_evaluation_qubits: The number of qubits used in estimating the phase. The phase will
be estimated as a binary string with this many bits.
quantum_instance: Deprecated: The quantum instance on which
the circuit will be run.
sampler: The sampler primitive on which the circuit will be sampled.
"""
# Avoid double warning on deprecated used of `quantum_instance`.
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
self._phase_estimation = PhaseEstimation(
num_evaluation_qubits=num_evaluation_qubits,
quantum_instance=quantum_instance,
sampler=sampler,
)
def _get_scale(self, hamiltonian, bound=None) -> PhaseEstimationScale:
if bound is None:
return PhaseEstimationScale.from_pauli_sum(hamiltonian)
return PhaseEstimationScale(bound)
def _get_unitary(
self, hamiltonian, pe_scale, evolution: EvolutionSynthesis | EvolutionBase
) -> QuantumCircuit:
"""Evolve the Hamiltonian to obtain a unitary.
Apply the scaling to the Hamiltonian that has been computed from an eigenvalue bound
and compute the unitary by applying the evolution object.
"""
if self._phase_estimation._sampler is not None:
evo = PauliEvolutionGate(hamiltonian, -pe_scale.scale, synthesis=evolution)
unitary = QuantumCircuit(evo.num_qubits)
unitary.append(evo, unitary.qubits)
return unitary.decompose().decompose()
else:
# scale so that phase does not wrap.
scaled_hamiltonian = -pe_scale.scale * hamiltonian
unitary = evolution.convert(scaled_hamiltonian.exp_i())
if not isinstance(unitary, QuantumCircuit):
unitary = unitary.to_circuit()
return unitary.decompose().decompose()
# Decomposing twice allows some 1Q Hamiltonians to give correct results
# when using MatrixEvolution(), that otherwise would give incorrect results.
# It does not break any others that we tested.
def estimate(
self,
hamiltonian: PauliOp | MatrixOp | SummedOp | Pauli | SparsePauliOp | PauliSumOp,
state_preparation: StateFn | QuantumCircuit | Statevector | None = None,
evolution: EvolutionSynthesis | EvolutionBase | None = None,
bound: float | None = None,
) -> HamiltonianPhaseEstimationResult:
"""Run the Hamiltonian phase estimation algorithm.
Args:
hamiltonian: A Hermitian operator. If the algorithm is used with a ``Sampler``
primitive, the allowed types are ``Pauli``, ``SparsePauliOp``, and ``PauliSumOp``.
If the algorithm is used with a ``QuantumInstance``, ``PauliOp, ``MatrixOp``,
``PauliSumOp``, and ``SummedOp`` types are allowed.
state_preparation: The ``StateFn`` to be prepared, whose eigenphase will be
measured. If this parameter is omitted, no preparation circuit will be run and
input state will be the all-zero state in the computational basis.
evolution: An evolution converter that generates a unitary from ``hamiltonian``. If
``None``, then the default ``PauliTrotterEvolution`` is used.
bound: An upper bound on the absolute value of the eigenvalues of
``hamiltonian``. If omitted, then ``hamiltonian`` must be a Pauli sum, or a
``PauliOp``, in which case a bound will be computed. If ``hamiltonian``
is a ``MatrixOp``, then ``bound`` may not be ``None``. The tighter the bound,
the higher the resolution of computed phases.
Returns:
``HamiltonianPhaseEstimationResult`` instance containing the result of the estimation
and diagnostic information.
Raises:
TypeError: If ``evolution`` is not of type ``EvolutionSynthesis`` when a ``Sampler`` is
provided.
TypeError: If ``hamiltonian`` type is not ``Pauli`` or ``SparsePauliOp`` or
``PauliSumOp`` when a ``Sampler`` is provided.
ValueError: If ``bound`` is ``None`` and ``hamiltonian`` is not a Pauli sum, i.e. a
``PauliSumOp`` or a ``SummedOp`` whose terms are of type ``PauliOp``.
TypeError: If ``evolution`` is not of type ``EvolutionBase`` when no ``Sampler`` is
provided.
"""
if self._phase_estimation._sampler is not None:
if evolution is not None and not isinstance(evolution, EvolutionSynthesis):
raise TypeError(f"Expecting type EvolutionSynthesis, got {type(evolution)}")
if not isinstance(hamiltonian, (Pauli, SparsePauliOp, PauliSumOp)):
raise TypeError(
f"Expecting Hamiltonian type Pauli, SparsePauliOp or PauliSumOp, "
f"got {type(hamiltonian)}."
)
if isinstance(state_preparation, Statevector):
circuit = QuantumCircuit(state_preparation.num_qubits)
circuit.prepare_state(state_preparation.data)
state_preparation = circuit
if isinstance(hamiltonian, PauliSumOp):
id_coefficient, hamiltonian_no_id = _remove_identity_pauli_sum_op(hamiltonian)
else:
id_coefficient = 0.0
hamiltonian_no_id = hamiltonian
pe_scale = self._get_scale(hamiltonian_no_id, bound)
unitary = self._get_unitary(hamiltonian_no_id, pe_scale, evolution)
else:
if evolution is None:
evolution = PauliTrotterEvolution()
elif not isinstance(evolution, EvolutionBase):
raise TypeError(f"Expecting type EvolutionBase, got {type(evolution)}")
if isinstance(hamiltonian, PauliSumOp):
hamiltonian = hamiltonian.to_pauli_op()
elif isinstance(hamiltonian, PauliOp):
hamiltonian = SummedOp([hamiltonian])
if isinstance(hamiltonian, SummedOp):
# remove identitiy terms
# The term prop to the identity is removed from hamiltonian.
# This is done for three reasons:
# 1. Work around an unknown bug that otherwise causes the energies to be wrong in some
# cases.
# 2. Allow working with a simpler Hamiltonian, one with fewer terms.
# 3. Tighten the bound on the eigenvalues so that the spectrum is better resolved, i.e.
# occupies more of the range of values representable by the qubit register.
# The coefficient of this term will be added to the eigenvalues.
id_coefficient, hamiltonian_no_id = _remove_identity(hamiltonian)
# get the rescaling object
pe_scale = self._get_scale(hamiltonian_no_id, bound)
# get the unitary
unitary = self._get_unitary(hamiltonian_no_id, pe_scale, evolution)
elif isinstance(hamiltonian, MatrixOp):
if bound is None:
raise ValueError("bound must be specified if Hermitian operator is MatrixOp")
# Do not subtract an identity term from the matrix, so do not compensate.
id_coefficient = 0.0
pe_scale = self._get_scale(hamiltonian, bound)
unitary = self._get_unitary(hamiltonian, pe_scale, evolution)
else:
raise TypeError(f"Hermitian operator of type {type(hamiltonian)} not supported.")
if state_preparation is not None and isinstance(state_preparation, StateFn):
state_preparation = state_preparation.to_circuit_op().to_circuit()
# run phase estimation
phase_estimation_result = self._phase_estimation.estimate(
unitary=unitary, state_preparation=state_preparation
)
return HamiltonianPhaseEstimationResult(
phase_estimation_result=phase_estimation_result,
id_coefficient=id_coefficient,
phase_estimation_scale=pe_scale,
)
def _remove_identity(pauli_sum: SummedOp):
"""Remove any identity operators from `pauli_sum`. Return
the sum of the coefficients of the identities and the new operator.
"""
idcoeff = 0.0
ops = []
for op in pauli_sum:
p = op.primitive
if p.x.any() or p.z.any():
ops.append(op)
else:
idcoeff += op.coeff
return idcoeff, SummedOp(ops)
def _remove_identity_pauli_sum_op(pauli_sum: PauliSumOp | SparsePauliOp):
"""Remove any identity operators from ``pauli_sum``. Return
the sum of the coefficients of the identities and the new operator.
"""
def _get_identity(size):
identity = I
for _ in range(size - 1):
identity = identity ^ I
return identity
idcoeff = 0.0
if isinstance(pauli_sum, PauliSumOp):
for operator in pauli_sum:
if operator.primitive.paulis == ["I" * pauli_sum.num_qubits]:
idcoeff += operator.primitive.coeffs[0]
pauli_sum = pauli_sum - operator.primitive.coeffs[0] * _get_identity(
pauli_sum.num_qubits
)
return idcoeff, pauli_sum.reduce()
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit.opflow import I, X, Y, Z
h2_op = (
-1.052373245772859 * (I ^ I)
+ 0.39793742484318045 * (I ^ Z)
- 0.39793742484318045 * (Z ^ I)
- 0.01128010425623538 * (Z ^ Z)
+ 0.18093119978423156 * (X ^ X)
)
list_aux_ops = [
2.0 * (I ^ I),
0.5 * (
(I ^ I) + (Z ^ Z) + (Y ^ Y) - (X ^ X)
),
]
dict_aux_ops = {
"AuxOp1": 2.0 * (I ^ I),
"AuxOp2": 0.5 * (
(I ^ I) + (Z ^ Z) + (Y ^ Y) - (X ^ X)
),
}
from qiskit.algorithms import NumPyMinimumEigensolver
solver = NumPyMinimumEigensolver()
list_result = solver.compute_minimum_eigenvalue(h2_op, aux_operators=list_aux_ops)
print(list_result)
dict_result = solver.compute_minimum_eigenvalue(h2_op, aux_operators=dict_aux_ops)
print(dict_result)
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureMoleculeDriver,
ElectronicStructureDriverType,
)
molecule = Molecule(geometry=[("H", (0.0, 0.0, 0.0)), ("H", (0.0, 0.0, 0.735))])
driver = ElectronicStructureMoleculeDriver(molecule, "sto3g", driver_type=ElectronicStructureDriverType.PYSCF)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
problem = ElectronicStructureProblem(driver)
problem.second_q_ops()
from qiskit_nature import settings
settings.dict_aux_operators = True
problem.second_q_ops()
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
converter = QubitConverter(JordanWignerMapper())
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver
from qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import NumPyMinimumEigensolverFactory
solver = GroundStateEigensolver(converter, NumPyMinimumEigensolverFactory(use_default_filter_criterion=True))
result = solver.solve(problem)
print(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
for idx in range(5):
qc.h(idx)
qc.cx(idx, idx+5)
qc.cx(1, 7)
qc.x(8)
qc.cx(1, 9)
qc.x(7)
qc.cx(1, 11)
qc.swap(6, 11)
qc.swap(6, 9)
qc.swap(6, 10)
qc.x(6)
qc.draw('mpl')
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
%matplotlib inline
from qiskit import *
from qiskit.visualization import *
from qiskit.tools.monitor import *
n = 4 # Number of qubits that we are going to use in the oracle
q = QuantumRegister(n, 'q') # The oracle qubits
out = QuantumRegister(1, 'out') # Qubit for the oracle output
c = ClassicalRegister(n, 'c') # Classical bits needed for the result of the measurement
circ_init = QuantumCircuit(q,out,c) # Initial part of the circuit
for i in range(n):
circ_init.h(q[i]) # We apply H to all the oracle qubits
circ_init.x(out) # We apply X and H to the output qubit
circ_init.h(out)
circ_init.barrier() # Visual barrier to separate the parts of the circuit
circ_init.draw(output='mpl')
circ_end = QuantumCircuit(q,out,c)
circ_end.barrier() # Visual barrier to separate the parts of the circuit
for i in range(n):
circ_end.h(q[i]) # We apply H to all the oracle qubits
circ_end.measure(q,c)
circ_end.draw(output='mpl')
# Oracle for a boolean function that always returns 1
const = QuantumCircuit(q,out,c)
const.cx(q[0],out)
const.x(q[0])
const.cx(q[0],out)
const.x(q[0])
const.draw(output='mpl')
# Oracle for a boolean function that returns 1 for half of the inputs
bal = QuantumCircuit(q,out,c)
bal.cx(q[0],out)
bal.draw(output='mpl')
circ_const = circ_init + const + circ_end
circ_const.draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(circ_const, backend, shots=10)
counts = job.result().get_counts()
print(counts)
circ_bal = circ_init + bal + circ_end
circ_bal.draw(output='mpl')
job = execute(circ_bal, backend, shots=10)
counts = job.result().get_counts()
print(counts)
from qiskit.providers.ibmq import least_busy
provider = IBMQ.load_account()
# We choose the least busy device
backend = least_busy(provider.backends(operational = True, simulator=False, status_msg='active',
filters=lambda x: x.configuration().n_qubits >= n+1))
print("We are using...",backend)
print("It has",backend.status().pending_jobs,"pending jobs")
# We send both circuits at a time
circuits = [circ_const,circ_bal]
job_exp = execute(circuits, backend=backend)
job_monitor(job_exp)
result_exp = job_exp.result()
counts_const = result_exp.get_counts(circ_const)
print("Results for the circuit with the constant function")
print(counts_const)
print()
counts_equi = result_exp.get_counts(circ_bal)
print("Results for the circuit with the balanced function")
print(counts_equi)
|
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":
qc.z(qubit)
### added x gate ###
qc.x(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### added z gate ###
qc.z(1)
qc.h(1)
return qc
|
https://github.com/abhishekchak52/quantum-computing-course
|
abhishekchak52
|
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
import numpy as np
#prepares the initial quantum states for the BB84 protocol by generating a list of quantum states and their associated bases.
def prepare_bb84_states(num_qubits):
states = []
bases = []
for _ in range(num_qubits):
state, basis = generate_bb84_state()
states.append(state)
bases.append(basis)
return states, bases
#generates a single BB84 quantum state and its associated measurement basis.
def generate_bb84_state():
basis = np.random.randint(2) # 0 for rectilinear basis, 1 for diagonal basis
if np.random.rand() < 0.5:
state = QuantumCircuit(1, 1)
if basis == 0:
state.h(0)
else:
state.s(0)
state.h(0)
else:
state = QuantumCircuit(1, 1)
if basis == 0:
state.x(0)
state.h(0)
else:
state.x(0)
state.s(0)
state.h(0)
return state, basis
#measures the quantum states with the appropriate basis and returns the measurement results
def measure_bb84_states(states, bases):
measurements = []
for state, basis in zip(states, bases):
if basis == 0:
state.measure(0, 0)
else:
state.h(0)
state.measure(0, 0)
measurements.append(state)
return measurements
#sifts the keys by comparing Alice and Bob's measurement bases and bits. It checks if the measurement bases match (the same basis) and appends the corresponding bits to the sifted keys
def sift_keys(alice_bases, bob_bases, alice_bits, bob_bits):
sifted_alice_bits = []
sifted_bob_bits = []
for a_basis, b_basis, a_bit, b_bit in zip(alice_bases, bob_bases, alice_bits, bob_bits):
if a_basis == b_basis:
sifted_alice_bits.append(a_bit)
sifted_bob_bits.append(b_bit)
return sifted_alice_bits, sifted_bob_bits
#calculates the error rate between Alice's and Bob's sifted bits
def error_rate(alice_bits, bob_bits):
errors = sum([1 for a, b in zip(alice_bits, bob_bits) if a != b])
return errors / len(alice_bits)
# simulates the BB84 protocol
num_qubits = 100
num_qubits = 100
alice_states, alice_bases = prepare_bb84_states(num_qubits)
bob_bases = np.random.randint(2, size=num_qubits)
bob_measurements = measure_bb84_states(alice_states, bob_bases)
alice_bits = []
for state in alice_states:
result = execute(state, Aer.get_backend('qasm_simulator')).result()
counts = result.get_counts(state)
max_count = max(counts, key=counts.get)
alice_bits.append(int(max_count))
bob_bits = []
for state in bob_measurements:
result = execute(state, Aer.get_backend('qasm_simulator')).result()
counts = result.get_counts(state)
max_count = max(counts, key=counts.get)
bob_bits.append(int(max_count))
sifted_alice_bits, sifted_bob_bits = sift_keys(alice_bases, bob_bases, alice_bits, bob_bits)
error = error_rate(sifted_alice_bits, sifted_bob_bits)
final_key = privacy_amplification(sifted_alice_bits)
print("Sifted key length:", len(sifted_alice_bits))
print("Error rate:", error)
print("Final secret key:", final_key)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
""" This file allows to test the various QFT implemented. The user must specify:
1) The number of qubits it wants the QFT to be implemented on
2) The kind of QFT want to implement, among the options:
-> Normal QFT with SWAP gates at the end
-> Normal QFT without SWAP gates at the end
-> Inverse QFT with SWAP gates at the end
-> Inverse QFT without SWAP gates at the end
The user must can also specify, in the main function, the input quantum state. By default is a maximal superposition state
This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves
the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient
qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits
"""
""" Imports from qiskit"""
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, IBMQ, BasicAer
""" Imports to Python functions """
import time
""" Local Imports """
from qfunctions import create_QFT, create_inverse_QFT
""" Function to properly print the final state of the simulation """
""" This is only possible in this way because the program uses the statevector_simulator """
def show_good_coef(results, n):
i=0
max = pow(2,n)
if max > 100: max = 100
""" Iterate to all possible states """
while i<max:
binary = bin(i)[2:].zfill(n)
number = results.item(i)
number = round(number.real, 3) + round(number.imag, 3) * 1j
""" Print the respective component of the state if it has a non-zero coefficient """
if number!=0:
print('|{}>'.format(binary),number)
i=i+1
""" Main program """
if __name__ == '__main__':
""" Select how many qubits want to apply the QFT on """
n = int(input('\nPlease select how many qubits want to apply the QFT on: '))
""" Select the kind of QFT to apply using the variable what_to_test:
what_to_test = 0: Apply normal QFT with the SWAP gates at the end
what_to_test = 1: Apply normal QFT without the SWAP gates at the end
what_to_test = 2: Apply inverse QFT with the SWAP gates at the end
what_to_test = 3: Apply inverse QFT without the SWAP gates at the end
"""
print('\nSelect the kind of QFT to apply:')
print('Select 0 to apply normal QFT with the SWAP gates at the end')
print('Select 1 to apply normal QFT without the SWAP gates at the end')
print('Select 2 to apply inverse QFT with the SWAP gates at the end')
print('Select 3 to apply inverse QFT without the SWAP gates at the end\n')
what_to_test = int(input('Select your option: '))
if what_to_test<0 or what_to_test>3:
print('Please select one of the options')
exit()
print('\nTotal number of qubits used: {0}\n'.format(n))
print('Please check source file to change input quantum state. By default is a maximal superposition state with |+> in every qubit.\n')
ts = time.time()
""" Create quantum and classical registers """
quantum_reg = QuantumRegister(n)
classic_reg = ClassicalRegister(n)
""" Create Quantum Circuit """
circuit = QuantumCircuit(quantum_reg, classic_reg)
""" Create the input state desired
Please change this as you like, by default we put H gates in every qubit,
initializing with a maximimal superposition state
"""
#circuit.h(quantum_reg)
""" Test the right QFT according to the variable specified before"""
if what_to_test == 0:
create_QFT(circuit,quantum_reg,n,1)
elif what_to_test == 1:
create_QFT(circuit,quantum_reg,n,0)
elif what_to_test == 2:
create_inverse_QFT(circuit,quantum_reg,n,1)
elif what_to_test == 3:
create_inverse_QFT(circuit,quantum_reg,n,0)
else:
print('Noting to implement, exiting program')
exit()
""" show results of circuit creation """
create_time = round(time.time()-ts, 3)
if n < 8: print(circuit)
print(f"... circuit creation time = {create_time}")
ts = time.time()
""" Simulate the created Quantum Circuit """
simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1)
""" Get the results of the simulation in proper structure """
sim_result=simulation.result()
""" Get the statevector of the final quantum state """
outputstate = sim_result.get_statevector(circuit, decimals=3)
""" show execution time """
exec_time = round(time.time()-ts, 3)
print(f"... circuit execute time = {exec_time}")
""" Print final quantum state to user """
print('The final state after applying the QFT is:\n')
show_good_coef(outputstate,n)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
|
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/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""The two-local gate circuit."""
from __future__ import annotations
import typing
from collections.abc import Callable, Sequence
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.circuit import Gate, Instruction, Parameter
from .n_local import NLocal
from ..standard_gates import (
IGate,
XGate,
YGate,
ZGate,
RXGate,
RYGate,
RZGate,
HGate,
SGate,
SdgGate,
TGate,
TdgGate,
RXXGate,
RYYGate,
RZXGate,
RZZGate,
SwapGate,
CXGate,
CYGate,
CZGate,
CRXGate,
CRYGate,
CRZGate,
CHGate,
)
if typing.TYPE_CHECKING:
import qiskit # pylint: disable=cyclic-import
class TwoLocal(NLocal):
r"""The two-local circuit.
The two-local circuit is a parameterized circuit consisting of alternating rotation layers and
entanglement layers. The rotation layers are single qubit gates applied on all qubits.
The entanglement layer uses two-qubit gates to entangle the qubits according to a strategy set
using ``entanglement``. Both the rotation and entanglement gates can be specified as
string (e.g. ``'ry'`` or ``'cx'``), as gate-type (e.g. ``RYGate`` or ``CXGate``) or
as QuantumCircuit (e.g. a 1-qubit circuit or 2-qubit circuit).
A set of default entanglement strategies is provided:
* ``'full'`` entanglement is each qubit is entangled with all the others.
* ``'linear'`` entanglement is qubit :math:`i` entangled with qubit :math:`i + 1`,
for all :math:`i \in \{0, 1, ... , n - 2\}`, where :math:`n` is the total number of qubits.
* ``'reverse_linear'`` entanglement is qubit :math:`i` entangled with qubit :math:`i + 1`,
for all :math:`i \in \{n-2, n-3, ... , 1, 0\}`, where :math:`n` is the total number of qubits.
Note that if ``entanglement_blocks = 'cx'`` then this option provides the same unitary as
``'full'`` with fewer entangling gates.
* ``'pairwise'`` entanglement is one layer where qubit :math:`i` is entangled with qubit
:math:`i + 1`, for all even values of :math:`i`, and then a second layer where qubit :math:`i`
is entangled with qubit :math:`i + 1`, for all odd values of :math:`i`.
* ``'circular'`` entanglement is linear entanglement but with an additional entanglement of the
first and last qubit before the linear part.
* ``'sca'`` (shifted-circular-alternating) entanglement is a generalized and modified version
of the proposed circuit 14 in `Sim et al. <https://arxiv.org/abs/1905.10876>`__.
It consists of circular entanglement where the 'long' entanglement connecting the first with
the last qubit is shifted by one each block. Furthermore the role of control and target
qubits are swapped every block (therefore alternating).
The entanglement can further be specified using an entangler map, which is a list of index
pairs, such as
>>> entangler_map = [(0, 1), (1, 2), (2, 0)]
If different entanglements per block should be used, provide a list of entangler maps.
See the examples below on how this can be used.
>>> entanglement = [entangler_map_layer_1, entangler_map_layer_2, ... ]
Barriers can be inserted in between the different layers for better visualization using the
``insert_barriers`` attribute.
For each parameterized gate a new parameter is generated using a
:class:`~qiskit.circuit.library.ParameterVector`. The name of these parameters can be chosen
using the ``parameter_prefix``.
Examples:
>>> two = TwoLocal(3, 'ry', 'cx', 'linear', reps=2, insert_barriers=True)
>>> print(two) # decompose the layers into standard gates
┌──────────┐ ░ ░ ┌──────────┐ ░ ░ ┌──────────┐
q_0: ┤ Ry(θ[0]) ├─░───■────────░─┤ Ry(θ[3]) ├─░───■────────░─┤ Ry(θ[6]) ├
├──────────┤ ░ ┌─┴─┐ ░ ├──────────┤ ░ ┌─┴─┐ ░ ├──────────┤
q_1: ┤ Ry(θ[1]) ├─░─┤ X ├──■───░─┤ Ry(θ[4]) ├─░─┤ X ├──■───░─┤ Ry(θ[7]) ├
├──────────┤ ░ └───┘┌─┴─┐ ░ ├──────────┤ ░ └───┘┌─┴─┐ ░ ├──────────┤
q_2: ┤ Ry(θ[2]) ├─░──────┤ X ├─░─┤ Ry(θ[5]) ├─░──────┤ X ├─░─┤ Ry(θ[8]) ├
└──────────┘ ░ └───┘ ░ └──────────┘ ░ └───┘ ░ └──────────┘
>>> two = TwoLocal(3, ['ry','rz'], 'cz', 'full', reps=1, insert_barriers=True)
>>> qc = QuantumCircuit(3)
>>> qc += two
>>> print(qc.decompose().draw())
┌──────────┐┌──────────┐ ░ ░ ┌──────────┐ ┌──────────┐
q_0: ┤ Ry(θ[0]) ├┤ Rz(θ[3]) ├─░──■──■─────░─┤ Ry(θ[6]) ├─┤ Rz(θ[9]) ├
├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤┌┴──────────┤
q_1: ┤ Ry(θ[1]) ├┤ Rz(θ[4]) ├─░──■──┼──■──░─┤ Ry(θ[7]) ├┤ Rz(θ[10]) ├
├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤├───────────┤
q_2: ┤ Ry(θ[2]) ├┤ Rz(θ[5]) ├─░─────■──■──░─┤ Ry(θ[8]) ├┤ Rz(θ[11]) ├
└──────────┘└──────────┘ ░ ░ └──────────┘└───────────┘
>>> entangler_map = [[0, 1], [1, 2], [2, 0]] # circular entanglement for 3 qubits
>>> two = TwoLocal(3, 'x', 'crx', entangler_map, reps=1)
>>> print(two) # note: no barriers inserted this time!
┌───┐ ┌──────────┐┌───┐
q_0: |0>┤ X ├─────■───────────────────────┤ Rx(θ[2]) ├┤ X ├
├───┤┌────┴─────┐ ┌───┐└─────┬────┘└───┘
q_1: |0>┤ X ├┤ Rx(θ[0]) ├─────■──────┤ X ├──────┼──────────
├───┤└──────────┘┌────┴─────┐└───┘ │ ┌───┐
q_2: |0>┤ X ├────────────┤ Rx(θ[1]) ├───────────■─────┤ X ├
└───┘ └──────────┘ └───┘
>>> entangler_map = [[0, 3], [0, 2]] # entangle the first and last two-way
>>> two = TwoLocal(4, [], 'cry', entangler_map, reps=1)
>>> circuit = two + two
>>> print(circuit.decompose().draw()) # note, that the parameters are the same!
q_0: ─────■───────────■───────────■───────────■──────
│ │ │ │
q_1: ─────┼───────────┼───────────┼───────────┼──────
│ ┌────┴─────┐ │ ┌────┴─────┐
q_2: ─────┼──────┤ Ry(θ[1]) ├─────┼──────┤ Ry(θ[1]) ├
┌────┴─────┐└──────────┘┌────┴─────┐└──────────┘
q_3: ┤ Ry(θ[0]) ├────────────┤ Ry(θ[0]) ├────────────
└──────────┘ └──────────┘
>>> layer_1 = [(0, 1), (0, 2)]
>>> layer_2 = [(1, 2)]
>>> two = TwoLocal(3, 'x', 'cx', [layer_1, layer_2], reps=2, insert_barriers=True)
>>> print(two)
┌───┐ ░ ░ ┌───┐ ░ ░ ┌───┐
q_0: ┤ X ├─░───■────■───░─┤ X ├─░───────░─┤ X ├
├───┤ ░ ┌─┴─┐ │ ░ ├───┤ ░ ░ ├───┤
q_1: ┤ X ├─░─┤ X ├──┼───░─┤ X ├─░───■───░─┤ X ├
├───┤ ░ └───┘┌─┴─┐ ░ ├───┤ ░ ┌─┴─┐ ░ ├───┤
q_2: ┤ X ├─░──────┤ X ├─░─┤ X ├─░─┤ X ├─░─┤ X ├
└───┘ ░ └───┘ ░ └───┘ ░ └───┘ ░ └───┘
"""
def __init__(
self,
num_qubits: int | None = None,
rotation_blocks: str
| type
| qiskit.circuit.Instruction
| QuantumCircuit
| list[str | type | qiskit.circuit.Instruction | QuantumCircuit]
| None = None,
entanglement_blocks: str
| type
| qiskit.circuit.Instruction
| QuantumCircuit
| list[str | type | qiskit.circuit.Instruction | QuantumCircuit]
| None = None,
entanglement: str | list[list[int]] | Callable[[int], list[int]] = "full",
reps: int = 3,
skip_unentangled_qubits: bool = False,
skip_final_rotation_layer: bool = False,
parameter_prefix: str = "θ",
insert_barriers: bool = False,
initial_state: QuantumCircuit | None = None,
name: str = "TwoLocal",
flatten: bool | None = None,
) -> None:
"""
Args:
num_qubits: The number of qubits of the two-local circuit.
rotation_blocks: The gates used in the rotation layer. Can be specified via the name of
a gate (e.g. ``'ry'``) or the gate type itself (e.g. :class:`.RYGate`).
If only one gate is provided, the gate same gate is applied to each qubit.
If a list of gates is provided, all gates are applied to each qubit in the provided
order.
See the Examples section for more detail.
entanglement_blocks: The gates used in the entanglement layer. Can be specified in
the same format as ``rotation_blocks``.
entanglement: Specifies the entanglement structure. Can be a string (``'full'``,
``'linear'``, ``'reverse_linear'``, ``'circular'`` or ``'sca'``),
a list of integer-pairs specifying the indices
of qubits entangled with one another, or a callable returning such a list provided with
the index of the entanglement layer.
Default to ``'full'`` entanglement.
Note that if ``entanglement_blocks = 'cx'``, then ``'full'`` entanglement provides the
same unitary as ``'reverse_linear'`` but the latter option has fewer entangling gates.
See the Examples section for more detail.
reps: Specifies how often a block consisting of a rotation layer and entanglement
layer is repeated.
skip_unentangled_qubits: If ``True``, the single qubit gates are only applied to qubits
that are entangled with another qubit. If ``False``, the single qubit gates are applied
to each qubit in the ansatz. Defaults to ``False``.
skip_final_rotation_layer: If ``False``, a rotation layer is added at the end of the
ansatz. If ``True``, no rotation layer is added.
parameter_prefix: The parameterized gates require a parameter to be defined, for which
we use instances of :class:`~qiskit.circuit.Parameter`. The name of each parameter will
be this specified prefix plus its index.
insert_barriers: If ``True``, barriers are inserted in between each layer. If ``False``,
no barriers are inserted. Defaults to ``False``.
initial_state: A :class:`.QuantumCircuit` object to prepend to the circuit.
flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple
layers of gate objects. By default currently the contents of
the output circuit will be wrapped in nested objects for
cleaner visualization. However, if you're using this circuit
for anything besides visualization its **strongly** recommended
to set this flag to ``True`` to avoid a large performance
overhead for parameter binding.
"""
super().__init__(
num_qubits=num_qubits,
rotation_blocks=rotation_blocks,
entanglement_blocks=entanglement_blocks,
entanglement=entanglement,
reps=reps,
skip_final_rotation_layer=skip_final_rotation_layer,
skip_unentangled_qubits=skip_unentangled_qubits,
insert_barriers=insert_barriers,
initial_state=initial_state,
parameter_prefix=parameter_prefix,
name=name,
flatten=flatten,
)
def _convert_to_block(self, layer: str | type | Gate | QuantumCircuit) -> QuantumCircuit:
"""For a layer provided as str (e.g. ``'ry'``) or type (e.g. :class:`.RYGate`) this function
returns the
according layer type along with the number of parameters (e.g. ``(RYGate, 1)``).
Args:
layer: The qubit layer.
Returns:
The specified layer with the required number of parameters.
Raises:
TypeError: The type of ``layer`` is invalid.
ValueError: The type of ``layer`` is str but the name is unknown.
ValueError: The type of ``layer`` is type but the layer type is unknown.
Note:
Outlook: If layers knew their number of parameters as static property, we could also
allow custom layer types.
"""
if isinstance(layer, QuantumCircuit):
return layer
# check the list of valid layers
# this could be a lot easier if the standard layers would have ``name`` and ``num_params``
# as static types, which might be something they should have anyway
theta = Parameter("θ")
valid_layers = {
"ch": CHGate(),
"cx": CXGate(),
"cy": CYGate(),
"cz": CZGate(),
"crx": CRXGate(theta),
"cry": CRYGate(theta),
"crz": CRZGate(theta),
"h": HGate(),
"i": IGate(),
"id": IGate(),
"iden": IGate(),
"rx": RXGate(theta),
"rxx": RXXGate(theta),
"ry": RYGate(theta),
"ryy": RYYGate(theta),
"rz": RZGate(theta),
"rzx": RZXGate(theta),
"rzz": RZZGate(theta),
"s": SGate(),
"sdg": SdgGate(),
"swap": SwapGate(),
"x": XGate(),
"y": YGate(),
"z": ZGate(),
"t": TGate(),
"tdg": TdgGate(),
}
# try to exchange `layer` from a string to a gate instance
if isinstance(layer, str):
try:
layer = valid_layers[layer]
except KeyError as ex:
raise ValueError(f"Unknown layer name `{layer}`.") from ex
# try to exchange `layer` from a type to a gate instance
if isinstance(layer, type):
# iterate over the layer types and look for the specified layer
instance = None
for gate in valid_layers.values():
if isinstance(gate, layer):
instance = gate
if instance is None:
raise ValueError(f"Unknown layer type`{layer}`.")
layer = instance
if isinstance(layer, Instruction):
circuit = QuantumCircuit(layer.num_qubits)
circuit.append(layer, list(range(layer.num_qubits)))
return circuit
raise TypeError(
f"Invalid input type {type(layer)}. " + "`layer` must be a type, str or QuantumCircuit."
)
def get_entangler_map(
self, rep_num: int, block_num: int, num_block_qubits: int
) -> Sequence[Sequence[int]]:
"""Overloading to handle the special case of 1 qubit where the entanglement are ignored."""
if self.num_qubits <= 1:
return []
return super().get_entangler_map(rep_num, block_num, num_block_qubits)
|
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.
"""Disassemble function for a qobj into a list of circuits and its config"""
from typing import Any, Dict, List, NewType, Tuple, Union
import collections
import math
from qiskit import pulse
from qiskit.circuit.classicalregister import ClassicalRegister
from qiskit.circuit.instruction import Instruction
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.circuit.quantumregister import QuantumRegister
from qiskit.qobj import PulseQobjInstruction
from qiskit.qobj.converters import QobjToInstructionConverter
# A ``CircuitModule`` is a representation of a circuit execution on the backend.
# It is currently a list of quantum circuits to execute, a run Qobj dictionary
# and a header dictionary.
CircuitModule = NewType(
"CircuitModule", Tuple[List[QuantumCircuit], Dict[str, Any], Dict[str, Any]]
)
# A ``PulseModule`` is a representation of a pulse execution on the backend.
# It is currently a list of pulse schedules to execute, a run Qobj dictionary
# and a header dictionary.
PulseModule = NewType("PulseModule", Tuple[List[pulse.Schedule], Dict[str, Any], Dict[str, Any]])
def disassemble(qobj) -> Union[CircuitModule, PulseModule]:
"""Disassemble a qobj and return the circuits or pulse schedules, run_config, and user header.
.. note::
``disassemble(assemble(qc))`` is not guaranteed to produce an exactly equal circuit to the
input, due to limitations in the :obj:`.QasmQobj` format that need to be maintained for
backend system compatibility. This is most likely to be the case when using newer features
of :obj:`.QuantumCircuit`. In most cases, the output should be equivalent, if not quite
equal.
Args:
qobj (Qobj): The input qobj object to disassemble
Returns:
Union[CircuitModule, PulseModule]: The disassembled program which consists of:
* programs: A list of quantum circuits or pulse schedules
* run_config: The dict of the run config
* user_qobj_header: The dict of any user headers in the qobj
Examples:
.. code-block:: python
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler.assembler import assemble
from qiskit.assembler.disassemble import disassemble
# Create a circuit to assemble into a qobj
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c)
# Assemble the circuit into a Qobj
qobj = assemble(qc, shots=2000, memory=True)
# Disassemble the qobj back into a circuit
circuits, run_config_out, headers = disassemble(qobj)
"""
if qobj.type == "PULSE":
return _disassemble_pulse_schedule(qobj)
else:
return _disassemble_circuit(qobj)
def _disassemble_circuit(qobj) -> CircuitModule:
run_config = qobj.config.to_dict()
# convert lo freq back to Hz
qubit_lo_freq = run_config.get("qubit_lo_freq", [])
if qubit_lo_freq:
run_config["qubit_lo_freq"] = [freq * 1e9 for freq in qubit_lo_freq]
meas_lo_freq = run_config.get("meas_lo_freq", [])
if meas_lo_freq:
run_config["meas_lo_freq"] = [freq * 1e9 for freq in meas_lo_freq]
user_qobj_header = qobj.header.to_dict()
return CircuitModule((_experiments_to_circuits(qobj), run_config, user_qobj_header))
def _qobj_to_circuit_cals(qobj, pulse_lib):
"""Return circuit calibrations dictionary from qobj/exp config calibrations."""
qobj_cals = qobj.config.calibrations.to_dict()["gates"]
converter = QobjToInstructionConverter(pulse_lib)
qc_cals = {}
for gate in qobj_cals:
config = (tuple(gate["qubits"]), tuple(gate["params"]))
cal = {
config: pulse.Schedule(
name="{} {} {}".format(gate["name"], str(gate["params"]), str(gate["qubits"]))
)
}
for instruction in gate["instructions"]:
qobj_instruction = PulseQobjInstruction.from_dict(instruction)
schedule = converter(qobj_instruction)
cal[config] = cal[config].insert(schedule.ch_start_time(), schedule)
if gate["name"] in qc_cals:
qc_cals[gate["name"]].update(cal)
else:
qc_cals[gate["name"]] = cal
return qc_cals
def _experiments_to_circuits(qobj):
"""Return a list of QuantumCircuit object(s) from a qobj.
Args:
qobj (Qobj): The Qobj object to convert to QuantumCircuits
Returns:
list: A list of QuantumCircuit objects from the qobj
"""
if not qobj.experiments:
return None
circuits = []
for exp in qobj.experiments:
quantum_registers = [QuantumRegister(i[1], name=i[0]) for i in exp.header.qreg_sizes]
classical_registers = [ClassicalRegister(i[1], name=i[0]) for i in exp.header.creg_sizes]
circuit = QuantumCircuit(*quantum_registers, *classical_registers, name=exp.header.name)
qreg_dict = collections.OrderedDict()
creg_dict = collections.OrderedDict()
for reg in quantum_registers:
qreg_dict[reg.name] = reg
for reg in classical_registers:
creg_dict[reg.name] = reg
conditional = {}
for i in exp.instructions:
name = i.name
qubits = []
params = getattr(i, "params", [])
try:
for qubit in i.qubits:
qubit_label = exp.header.qubit_labels[qubit]
qubits.append(qreg_dict[qubit_label[0]][qubit_label[1]])
except Exception: # pylint: disable=broad-except
pass
clbits = []
try:
for clbit in i.memory:
clbit_label = exp.header.clbit_labels[clbit]
clbits.append(creg_dict[clbit_label[0]][clbit_label[1]])
except Exception: # pylint: disable=broad-except
pass
if hasattr(circuit, name):
instr_method = getattr(circuit, name)
if i.name in ["snapshot"]:
_inst = instr_method(
i.label, snapshot_type=i.snapshot_type, qubits=qubits, params=params
)
elif i.name == "initialize":
_inst = instr_method(params, qubits)
elif i.name == "isometry":
_inst = instr_method(*params, qubits, clbits)
elif i.name in ["mcx", "mcu1", "mcp"]:
_inst = instr_method(*params, qubits[:-1], qubits[-1], *clbits)
else:
_inst = instr_method(*params, *qubits, *clbits)
elif name == "bfunc":
conditional["value"] = int(i.val, 16)
full_bit_size = sum(creg_dict[x].size for x in creg_dict)
mask_map = {}
raw_map = {}
raw = []
for creg in creg_dict:
size = creg_dict[creg].size
reg_raw = [1] * size
if not raw:
raw = reg_raw
else:
for pos, val in enumerate(raw):
if val == 1:
raw[pos] = 0
raw = reg_raw + raw
mask = [0] * (full_bit_size - len(raw)) + raw
raw_map[creg] = mask
mask_map[int("".join(str(x) for x in mask), 2)] = creg
if bin(int(i.mask, 16)).count("1") == 1:
# The condition is on a single bit. This might be a single-bit condition, or it
# might be a register of length one. The case that it's a single-bit condition
# in a register of length one is ambiguous, and we choose to return a condition
# on the register. This may not match the input circuit exactly, but is at
# least equivalent.
cbit = int(math.log2(int(i.mask, 16)))
for reg in creg_dict.values():
size = reg.size
if cbit >= size:
cbit -= size
else:
conditional["register"] = reg if reg.size == 1 else reg[cbit]
break
mask_str = bin(int(i.mask, 16))[2:].zfill(full_bit_size)
mask = [int(item) for item in list(mask_str)]
else:
creg = mask_map[int(i.mask, 16)]
conditional["register"] = creg_dict[creg]
mask = raw_map[creg]
val = int(i.val, 16)
for j in reversed(mask):
if j == 0:
val = val >> 1
else:
conditional["value"] = val
break
else:
_inst = temp_opaque_instruction = Instruction(
name=name, num_qubits=len(qubits), num_clbits=len(clbits), params=params
)
circuit.append(temp_opaque_instruction, qubits, clbits)
if conditional and name != "bfunc":
_inst.c_if(conditional["register"], conditional["value"])
conditional = {}
pulse_lib = qobj.config.pulse_library if hasattr(qobj.config, "pulse_library") else []
# The dict update method did not work here; could investigate in the future
if hasattr(qobj.config, "calibrations"):
circuit.calibrations = dict(
**circuit.calibrations, **_qobj_to_circuit_cals(qobj, pulse_lib)
)
if hasattr(exp.config, "calibrations"):
circuit.calibrations = dict(
**circuit.calibrations, **_qobj_to_circuit_cals(exp, pulse_lib)
)
circuits.append(circuit)
return circuits
def _disassemble_pulse_schedule(qobj) -> PulseModule:
run_config = qobj.config.to_dict()
run_config.pop("pulse_library")
qubit_lo_freq = run_config.get("qubit_lo_freq")
if qubit_lo_freq:
run_config["qubit_lo_freq"] = [freq * 1e9 for freq in qubit_lo_freq]
meas_lo_freq = run_config.get("meas_lo_freq")
if meas_lo_freq:
run_config["meas_lo_freq"] = [freq * 1e9 for freq in meas_lo_freq]
user_qobj_header = qobj.header.to_dict()
# extract schedule lo settings
schedule_los = []
for program in qobj.experiments:
program_los = {}
if hasattr(program, "config"):
if hasattr(program.config, "qubit_lo_freq"):
for i, lo in enumerate(program.config.qubit_lo_freq):
program_los[pulse.DriveChannel(i)] = lo * 1e9
if hasattr(program.config, "meas_lo_freq"):
for i, lo in enumerate(program.config.meas_lo_freq):
program_los[pulse.MeasureChannel(i)] = lo * 1e9
schedule_los.append(program_los)
if any(schedule_los):
run_config["schedule_los"] = schedule_los
return PulseModule((_experiments_to_schedules(qobj), run_config, user_qobj_header))
def _experiments_to_schedules(qobj) -> List[pulse.Schedule]:
"""Return a list of :class:`qiskit.pulse.Schedule` object(s) from a qobj.
Args:
qobj (Qobj): The Qobj object to convert to pulse schedules.
Returns:
A list of :class:`qiskit.pulse.Schedule` objects from the qobj
Raises:
pulse.PulseError: If a parameterized instruction is supplied.
"""
converter = QobjToInstructionConverter(qobj.config.pulse_library)
schedules = []
for program in qobj.experiments:
insts = []
for inst in program.instructions:
insts.append(converter(inst))
schedule = pulse.Schedule(*insts)
schedules.append(schedule)
return schedules
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Classical Real Evolver."""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from ddt import data, ddt, unpack
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit_algorithms import SciPyRealEvolver, TimeEvolutionProblem
from qiskit.quantum_info import Statevector, SparsePauliOp
def zero(n):
"""Auxiliary function to create an initial state on n qubits."""
qr = QuantumRegister(n)
qc = QuantumCircuit(qr)
return Statevector(qc)
def one(n):
"""Auxiliary function to create an initial state on n qubits."""
qr = QuantumRegister(n)
qc = QuantumCircuit(qr)
qc.x(qr)
return Statevector(qc)
@ddt
class TestClassicalRealEvolver(QiskitAlgorithmsTestCase):
"""Test Classical Real Evolver."""
@data(
(one(1), np.pi / 2, SparsePauliOp("X"), -1.0j * zero(1)),
(
one(1).expand(zero(1)),
np.pi / 2,
SparsePauliOp(["XX", "YY"], [0.5, 0.5]),
-1.0j * zero(1).expand(one(1)),
),
(
one(1).expand(zero(1)),
np.pi / 4,
SparsePauliOp(["XX", "YY"], [0.5, 0.5]),
((one(1).expand(zero(1)) - 1.0j * zero(1).expand(one(1)))) / np.sqrt(2),
),
(zero(12), np.pi / 2, SparsePauliOp("X" * 12), -1.0j * (one(12))),
)
@unpack
def test_evolve(
self,
initial_state: Statevector,
time_ev: float,
hamiltonian: SparsePauliOp,
expected_state: Statevector,
):
"""Initializes a classical real evolver and evolves a state."""
evolution_problem = TimeEvolutionProblem(hamiltonian, time_ev, initial_state)
classic_evolver = SciPyRealEvolver(num_timesteps=1)
result = classic_evolver.evolve(evolution_problem)
np.testing.assert_allclose(
result.evolved_state.data,
expected_state.data,
atol=1e-10,
rtol=0,
)
def test_observables(self):
"""Tests if the observables are properly evaluated at each timestep."""
initial_state = zero(1)
time_ev = 10.0
hamiltonian = SparsePauliOp("X")
observables = {"Energy": SparsePauliOp("X"), "Z": SparsePauliOp("Z")}
evolution_problem = TimeEvolutionProblem(
hamiltonian, time_ev, initial_state, aux_operators=observables
)
classic_evolver = SciPyRealEvolver(num_timesteps=10)
result = classic_evolver.evolve(evolution_problem)
z_mean, z_std = result.observables["Z"]
timesteps = z_mean.shape[0]
time_vector = np.linspace(0, time_ev, timesteps)
expected_z = 1 - 2 * (np.sin(time_vector)) ** 2
expected_z_std = np.zeros_like(expected_z)
np.testing.assert_allclose(z_mean, expected_z, atol=1e-10, rtol=0)
np.testing.assert_allclose(z_std, expected_z_std, atol=1e-10, rtol=0)
np.testing.assert_equal(time_vector, result.times)
def test_quantum_circuit_initial_state(self):
"""Tests if the system can be evolved with a quantum circuit as an initial state."""
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, range(1, 3))
evolution_problem = TimeEvolutionProblem(
hamiltonian=SparsePauliOp("X" * 3), time=2 * np.pi, initial_state=qc
)
classic_evolver = SciPyRealEvolver(num_timesteps=500)
result = classic_evolver.evolve(evolution_problem)
np.testing.assert_almost_equal(
result.evolved_state.data,
np.array([1, 0, 0, 0, 0, 0, 0, 1]) / np.sqrt(2),
decimal=10,
)
def test_error_time_dependency(self):
"""Tests if an error is raised for time dependent hamiltonian."""
evolution_problem = TimeEvolutionProblem(
hamiltonian=SparsePauliOp("X" * 3), time=1.0, initial_state=zero(3), t_param=0
)
classic_evolver = SciPyRealEvolver(num_timesteps=5)
with self.assertRaises(ValueError):
classic_evolver.evolve(evolution_problem)
def test_no_time_steps(self):
"""Tests if the evolver handles some edge cases related to the number of timesteps."""
evolution_problem = TimeEvolutionProblem(
hamiltonian=SparsePauliOp("X"),
time=1.0,
initial_state=zero(1),
aux_operators={"Energy": SparsePauliOp("X")},
)
with self.subTest("0 timesteps"):
with self.assertRaises(ValueError):
classic_evolver = SciPyRealEvolver(num_timesteps=0)
classic_evolver.evolve(evolution_problem)
with self.subTest("1 timestep"):
classic_evolver = SciPyRealEvolver(num_timesteps=1)
result = classic_evolver.evolve(evolution_problem)
np.testing.assert_equal(result.times, np.array([0.0, 1.0]))
with self.subTest("Negative timesteps"):
with self.assertRaises(ValueError):
classic_evolver = SciPyRealEvolver(num_timesteps=-5)
classic_evolver.evolve(evolution_problem)
if __name__ == "__main__":
unittest.main()
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
def trotter_gate(dt, to_instruction = True):
qc = QuantumCircuit(2)
qc.rx(2*dt,0)
qc.rz(2*dt,1)
qc.h(1)
qc.cx(1,0)
qc.rz(-2*dt, 0)
qc.rx(-2*dt, 1)
qc.rz(2*dt, 1)
qc.cx(1,0)
qc.h(1)
qc.rz(2*dt, 0)
return qc.to_instruction() if to_instruction else qc
trotter_gate(np.pi / 6, to_instruction=False).draw("mpl")
# 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)
# Number of trotter steps
trotter_steps = 15 ### CAN BE >= 4
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(7)
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>)
qc.x([2]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, [qr[1], qr[2]])
qc.cx(qr[1], qr[0])
qc.cx(qr[2], qr[1])
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time/trotter_steps})
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(t3_qc, [qr[0], qr[1], qr[2]])
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw("mpl") # only view trotter gates
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibm_lagos")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3)
print('Job ID', cal_job.job_id())
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = []
for job in jobs:
mit_results.append( meas_fitter.filter.apply(job.result()) )
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Compute tomography fidelities for each repetition
fids = []
for result in mit_results:
fid = state_tomo(result, st_qcs)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/EavCmr/QKD-E91
|
EavCmr
|
#!pip install qiskit
from qiskit import QuantumCircuit, Aer, transpile, assemble, execute, IBMQ
from qiskit.visualization import plot_histogram
import numpy as np
import random
import math
import warnings
warnings.filterwarnings('ignore')
# Determine the amount of entanglement between these bits using the CHSH value
def entanglement_amount(alice_choices, alice_bits, bob_choices, bob_bits):
# count the different measurement results
# rows correspond to Alice and Bob's circuit choices: 00, 02, 20, 22
# NOTE: We do not consider circuits 1 or 3 for this test
# columns correspond to Alice and Bob's qubit measurements: 00, 01, 10, and 11
circuits = {'00': 0, '02': 1, '20': 2, '22': 3}
counts = [[0]*4 for i in range(4)]
for i in range(len(alice_choices)):
circuit = str(alice_choices[i]) + str(bob_choices[i])
state = int(alice_bits[i]) + 2*int(bob_bits[i])
if circuit in circuits: counts[circuits[circuit]][state] += 1
# expectation values calculated by
# adding times Alice and Bob's bits agreed and
# subtracting times Alice and Bob's bits disagreed
expectations = []
for circuit in range(4):
expectations += [counts[circuit][0] + counts[circuit][3] - counts[circuit][1] - counts[circuit][2]]
total = sum(counts[circuit])
if total != 0: expectations[circuit] /= total
# returning CHSH correlation
return expectations[0] - expectations[1] + expectations[2] + expectations[3]
print("Libraries Imported Successfully!")
alice_bob_qubits = QuantumCircuit(2, 2)
alice_bob_qubits.# COMPLETE THIS CODE
alice_bob_qubits.# COMPLETE THIS CODE
alice_bob_qubits.# COMPLETE THIS CODE
alice_bob_qubits.# COMPLETE THIS CODE
alice_bob_qubits.draw()
alice_option_1 = QuantumCircuit(1, 1)
alice_option_1.h(0)
alice_option_1.measure(0, 0)
alice_option_2 = QuantumCircuit(1, 1)
alice_option_2.rz(math.pi# COMPLETE THIS LINE
alice_option_2.h(0)
alice_option_2.measure(0, 0)
alice_option_3 = QuantumCircuit(1, 1)
alice_option_3.# COMPLETE THIS LINE
alice_alice_option_3.h(0)
alice_option_3.measure(0, 0)
alice_options = [alice_option_1, # COMPLETE THIS LINE WITH THE OTHER OPTIONS
alice_choice = random.randint(0, 2)
alice_circuit = options[alice_choice]
alice_circuit.draw()
alice_bob_qubits = alice_bob_qubits.compose(alice_circuit, qubits = 0, clbits = 0)
alice_bob_qubits.draw()
bob_option_1 = QuantumCircuit(1, 1)
bob_option_1.# COMPLETE THIS LINE
bob_option_1.# COMPLETE THIS LINE
bob_option_1.measure(0, 0)
bob_option_2 # COMPLETE THIS CODE
bob_option_3 # COMPLETE THIS CODE
bob_options = # COMPLETE THIS LINE
bob_choice = random.randint(0, 2)
bob_circuit = options[bob_choice]
bob_circuit.draw()
alice_bob_qubits = alice_bob_qubits.compose(bob_circuit, qubits = 1, clbits = 1)
alice_bob_qubits.draw()
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1024)
result = job.result()
counts = result.get_counts()
bits = random.choices(list(counts.keys()), weights = counts.values(), k = 1)[0]
alice_bits = bits[0]
bob_bits = bits[1]
plot_histogram(counts)
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
# MATCHING CHOICE
if alice_options[alice_choice] == bob_options[bob_choice]:
alice_key += [int(alice_bits[0])]
bob_key += [1 - int(bob_bits[0])]
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [alice_choice]
bob_mismatched_choices += [bob_choice]
alice_mismatched_choice_bits += [alice_bits[0]]
bob_mismatched_choice_bits += [bob_bits[0]]
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
#========
# STEP 1
#========
alice_bob_qubits = QuantumCircuit(2, 2)
# COMPLETE THIS CODE
#========
# STEP 2
#========
alice_choice = random.randint(0, 2)
alice_circuit = # COMPLETE THIS LINE
#========
# STEP 3
#========
alice_bob_qubits = alice_bob_qubits.compose(# COMPLETE THIS LINE
#========
# STEP 4
#========
bob_choice = random.randint(0, 2)
bob_circuit = # COMPLETE THIS LINE
#========
# STEP 5
#========
alice_bob_qubits = alice_bob_qubits.compose(# COMPLETE THIS LINE
#======================
# SIMULATE THE CIRCUIT
#======================
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1024)
result = job.result()
counts = result.get_counts()
bits = random.choices(list(counts.keys()), weights = counts.values(), k = 1)[0]
alice_bits = bits[0]
bob_bits = bits[1]
plot_histogram(counts)
#========
# STEP 6
#========
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
# MATCHING CHOICE
if alice_options[alice_choice] == bob_options[bob_choice]:
alice_key += [int(# COMPLETE THIS LINE
bob_key += [1 - int(# COMPLETE THIS LINE
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [# COMPLETE THIS LINE
bob_mismatched_choices += [# COMPLETE THIS LINE
alice_mismatched_choice_bits += [# COMPLETE THIS LINE
bob_mismatched_choice_bits += [# COMPLETE THIS LINE
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
n = 100
alice_bob_qubits = []
for i in range(# COMPLETE THIS LINE
alice_bob_qubits += [QuantumCircuit(# COMPLETE THIS LINE
alice_bob_qubits[i].# COMPLETE THIS LINE
alice_bob_qubits[i].# COMPLETE THIS LINE
alice_bob_qubits[i].# COMPLETE THIS LINE
alice_bob_qubits[i].# COMPLETE THIS LINE
alice_choices = []
alice_circuits = []
for # COMPLETE THIS LINE
alice_choices += [random.randint(0, 2)]
alice_circuits += [# COMPLETE THIS LINE
# COMPLETE THIS LINE
alice_bob_qubits[i] = alice_bob_qubits[i].compose(# COMPLETE THIS LINE
# COMPLETE THIS CODE
# COMPLETE THIS CODE
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
alice_bits = []
bob_bits = []
for i in range(n):
bits = list(counts[i].keys())[0]
alice_bits += [bits[0]]
bob_bits += [bits[1]]
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
for # COMPLETE THIS LINE
# MATCHING CHOICE
if alice_options[alice_choices[i]] == # COMPLETE THIS LINE
alice_key += [int(alice_bits[i])]
bob_key += [1 - int(# COMPLETE THIS LINE
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [alice_choices[i]]
bob_mismatched_choices += [ # COMPLETE THIS LINE
alice_mismatched_choice_bits += [ # COMPLETE THIS LINE
bob_mismatched_choice_bits += [# COMPLETE THIS LINE
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
print("Key Length: " + str(len(bob_key)))
print("Number of Disagreeing Key Bits: " + str(sum([alice_key[i] != bob_key[i] for i in range(len(alice_key))])))
#========
# STEP 1
#========
n = 100
#========
# STEP 2
#========
#========
# STEP 3
#========
#========
# STEP 4
#========
#========
# STEP 5
#========
#======================
# SIMULATE THE CIRCUIT
#======================
#========
# STEP 6
#========
#========
# STEP 1
#========
n = 100
# COMPLETE THIS CODE WITH YOUR SOLUTION FROM PART 2
#================
# EVE INTERCEPTS!
#================
for i in range(# COMPLETE THIS LINE
alice_bob_qubits[i].measure(# COMPLETE THIS LINE
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
eve_alice_bits = []
eve_bob_bits = []
for # COMPLETE THIS LINE
# Looks at measurement results
bits = list(counts[i].keys())[0]
eve_alice_bits += [bits[0]]
eve_bob_bits += [# COMPLETE THIS LINE
# Prepares new qubits for Alice and Bob
alice_bob_qubits[i] = QuantumCircuit(# COMPLETE THIS LINE
# Makes sure they are in the same state she measured
if eve_alice_bits[i] == 1: alice_bob_qubits[i].# COMPLETE THIS LINE
if # COMPLETE THIS LINE
#========
# STEP 6
#========
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
eve_key = []
# COMPLETE THIS CODE
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
print("Eve's Key: " + str(eve_key))
print("Key Length: " + str(len(bob_key)))
print("Number of Disagreeing Key Bits between Alice and Bob: " + str(sum([alice_key[i] != bob_key[i] for i in range(len(alice_key))])))
print("Number of Disagreeing Key Bits between Alice and Eve: " + str(sum([alice_key[i] != eve_key[i] for i in range(len(alice_key))])))
print("Number of Disagreeing Key Bits between Bob and Eve: " + str(sum([bob_key[i] != eve_key[i] for i in range(len(alice_key))])))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
|
nahumsa
|
from qiskit import Aer
from qiskit.circuit.library import QFT
from qiskit.aqua import QuantumInstance, aqua_globals
from qiskit.quantum_info import state_fidelity
from qiskit.aqua.algorithms import HHL, NumPyLSsolver
from qiskit.aqua.components.eigs import EigsQPE
from qiskit.aqua.components.reciprocals import LookupRotation
from qiskit.aqua.operators import MatrixOperator
from qiskit.aqua.components.initial_states import Custom
import numpy as np
def create_eigs(matrix, num_ancillae, num_time_slices, negative_evals):
"""QPE for the eigenvalues estimation.
Parameters
-------------------------------------------------------------------
matrix(np.array): Unitary matrix for the QPE.
num_ancillae(int): Number of ancillas.
num_time_slices(float): An optional evolution time which should scale the
eigenvalue onto the range (0,1] (or (−0.5,0.5] for
negative eigenvalues).If None is internally computed.
negative_evals(Boolean): Set True to indicate negative eigenvalues need to be handled
"""
ne_qfts = [None, None]
if negative_evals:
num_ancillae += 1
ne_qfts = [QFT(num_ancillae - 1), QFT(num_ancillae - 1).inverse()]
return EigsQPE(MatrixOperator(matrix=matrix),
QFT(num_ancillae).inverse(),
num_time_slices=num_time_slices,
num_ancillae=num_ancillae,
expansion_mode='suzuki',
expansion_order=2,
evo_time=None,
negative_evals=negative_evals,
ne_qfts=ne_qfts)
def fidelity(hhl, ref):
""" Helper function for the fidelity comparing
the solution from the HHL and the classical solution.
"""
solution_hhl_normed = hhl / np.linalg.norm(hhl)
solution_ref_normed = ref / np.linalg.norm(ref)
fidelity = state_fidelity(solution_hhl_normed, solution_ref_normed)
return fidelity
A = [[1, 1/3], [1/3, 4]]
b = [1, 4]
orig_size = len(b)
A, b, truncate_powerdim, truncate_hermitian = HHL.matrix_resize(A, b)
# Initialize eigenvalue finding module
eigs = create_eigs(matrix=A, num_ancillae=3,
num_time_slices=50,
negative_evals=False)
num_q, num_a = eigs.get_register_sizes()
# Initialize initial state module
init_state = Custom(num_q, state_vector=b)
# Initialize reciprocal rotation module
reci = LookupRotation(negative_evals=eigs._negative_evals,
evo_time=eigs._evo_time,
scale=0.5)
algo = HHL(matrix=A, vector=b, truncate_powerdim=truncate_powerdim,
truncate_hermitian=truncate_hermitian, eigs=eigs,
init_state=init_state, reciprocal=reci,
num_q= num_q, num_a=num_a, orig_size=orig_size)
result = algo.run(QuantumInstance(Aer.get_backend('statevector_simulator')))
print(f"solution: {np.round(result['solution'], 5)}")
result_ref = NumPyLSsolver(A, b).run()
print(f"classical solution: {np.round(result_ref['solution'], 5)} ")
print(f"probability: {result['probability_result']}")
fidelity(result['solution'], result_ref['solution'])
orig_size = len(b)
A, b, truncate_powerdim, truncate_hermitian = HHL.matrix_resize(A, b)
# Initialize eigenvalue finding module
eigs = create_eigs(matrix=A, num_ancillae=3,
num_time_slices=50,
negative_evals=False)
num_q, num_a = eigs.get_register_sizes()
# Initialize initial state module
init_state = Custom(num_q, state_vector=b)
# Initialize reciprocal rotation module
reci = LookupRotation(negative_evals=eigs._negative_evals,
evo_time=eigs._evo_time,
scale=0.5)
algo = HHL(matrix=A, vector=b, truncate_powerdim=truncate_powerdim,
truncate_hermitian=truncate_hermitian, eigs=eigs,
init_state=init_state, reciprocal=reci,
num_q= num_q, num_a=num_a, orig_size=orig_size)
result = algo.run(QuantumInstance(Aer.get_backend('qasm_simulator')))
print(f"solution: {np.round(result['solution'], 5)}")
result_ref = NumPyLSsolver(A, b).run()
print(f"classical solution: {np.round(result_ref['solution'], 5)} ")
print(f"probability: {result['probability_result']}")
fidelity(result['solution'], result_ref['solution'])
from qiskit.tools.jupyter import *
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-bip-mapper
|
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.
"""Test the BIPMapping pass."""
import unittest
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit import Barrier
from qiskit.circuit.library.standard_gates import SwapGate
from qiskit.converters import circuit_to_dag
from qiskit.providers.fake_provider import FakeLima
from qiskit.transpiler import CouplingMap, Layout, PassManager
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import CheckMap, Collect2qBlocks, ConsolidateBlocks, UnitarySynthesis
from qiskit_bip_mapper.bip_mapping import BIPMapping
class TestBIPMapping(unittest.TestCase):
"""Tests the BIPMapping pass."""
def test_empty(self):
"""Returns the original circuit if the circuit is empty."""
coupling = CouplingMap([[0, 1]])
circuit = QuantumCircuit(2)
actual = BIPMapping(coupling)(circuit)
self.assertEqual(circuit, actual)
def test_no_two_qubit_gates(self):
"""Returns the original circuit if the circuit has no 2q-gates.
q0:--[H]--
q1:-------
CouplingMap map: [0]--[1]
"""
coupling = CouplingMap([[0, 1]])
circuit = QuantumCircuit(2)
circuit.h(0)
actual = BIPMapping(coupling)(circuit)
self.assertEqual(circuit, actual)
def test_trivial_case(self):
"""No need to have any swap, the CX are distance 1 to each other.
q0:--(+)-[H]-(+)-
| |
q1:---.-------|--
|
q2:-----------.--
CouplingMap map: [1]--[0]--[2]
"""
coupling = CouplingMap([[0, 1], [0, 2]])
circuit = QuantumCircuit(3)
circuit.cx(1, 0)
circuit.h(0)
circuit.cx(2, 0)
actual = BIPMapping(coupling)(circuit)
self.assertEqual(3, len(actual))
for inst, _, _ in actual.data: # there are no swaps
self.assertFalse(isinstance(inst, SwapGate))
def test_no_swap(self):
"""Adding no swap if not giving initial layout."""
coupling = CouplingMap([[0, 1], [0, 2]])
circuit = QuantumCircuit(3)
circuit.cx(1, 2)
actual = BIPMapping(coupling)(circuit)
q = QuantumRegister(3, name="q")
expected = QuantumCircuit(q)
expected.cx(q[0], q[1])
self.assertEqual(expected, actual)
def test_ignore_initial_layout(self):
"""Ignoring initial layout even when it is supplied."""
coupling = CouplingMap([[0, 1], [0, 2]])
circuit = QuantumCircuit(3)
circuit.cx(1, 2)
property_set = {"layout": Layout.generate_trivial_layout(*circuit.qubits)}
actual = BIPMapping(coupling)(circuit, property_set)
q = QuantumRegister(3, name="q")
expected = QuantumCircuit(q)
expected.cx(q[0], q[1])
self.assertEqual(expected, actual)
def test_can_map_measurements_correctly(self):
"""Verify measurement nodes are updated to map correct cregs to re-mapped qregs."""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[2])
circuit.measure(qr[1], cr[0])
circuit.measure(qr[2], cr[1])
actual = BIPMapping(coupling)(circuit)
q = QuantumRegister(3, "q")
expected = QuantumCircuit(q, cr)
expected.cx(q[0], q[1])
expected.measure(q[0], cr[0]) # <- changed due to initial layout change
expected.measure(q[1], cr[1]) # <- changed due to initial layout change
self.assertEqual(expected, actual)
def test_never_modify_mapped_circuit(self):
"""Test that the mapping is idempotent.
It should not modify a circuit which is already compatible with the
coupling map, and can be applied repeatedly without modifying the circuit.
"""
coupling = CouplingMap([[0, 1], [0, 2]])
circuit = QuantumCircuit(3, 2)
circuit.cx(1, 2)
circuit.measure(1, 0)
circuit.measure(2, 1)
dag = circuit_to_dag(circuit)
mapped_dag = BIPMapping(coupling).run(dag)
remapped_dag = BIPMapping(coupling).run(mapped_dag)
self.assertEqual(mapped_dag, remapped_dag)
def test_no_swap_multi_layer(self):
"""Can find the best layout for a circuit with multiple layers."""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, name="qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[3])
property_set = {}
actual = BIPMapping(coupling, objective="depth")(circuit, property_set)
self.assertEqual(2, actual.depth())
CheckMap(coupling)(actual, property_set)
self.assertTrue(property_set["is_swap_mapped"])
def test_unmappable_cnots_in_a_layer(self):
"""Test mapping of a circuit with 2 cnots in a layer which BIPMapping cannot map."""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.measure(qr, cr)
coupling = CouplingMap([[0, 1], [1, 2], [1, 3]]) # {0: [1], 1: [2, 3]}
actual = BIPMapping(coupling)(circuit)
# Fails to map and returns the original circuit
self.assertEqual(circuit, actual)
def test_multi_cregs(self):
"""Test for multiple ClassicalRegisters."""
# ┌───┐ ░ ┌─┐
# qr_0: ──■────────────┤ X ├─░─┤M├─────────
# ┌─┴─┐ ┌───┐└─┬─┘ ░ └╥┘┌─┐
# qr_1: ┤ X ├──■──┤ H ├──■───░──╫─┤M├──────
# └───┘┌─┴─┐└───┘ ░ ║ └╥┘┌─┐
# qr_2: ──■──┤ X ├───────────░──╫──╫─┤M├───
# ┌─┴─┐└───┘ ░ ║ ║ └╥┘┌─┐
# qr_3: ┤ X ├────────────────░──╫──╫──╫─┤M├
# └───┘ ░ ║ ║ ║ └╥┘
# c: 2/════════════════════════╩══╬══╩══╬═
# 0 ║ 1 ║
# ║ ║
# d: 2/═══════════════════════════╩═════╩═
# 0 1
qr = QuantumRegister(4, "qr")
cr1 = ClassicalRegister(2, "c")
cr2 = ClassicalRegister(2, "d")
circuit = QuantumCircuit(qr, cr1, cr2)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[1], qr[2])
circuit.h(qr[1])
circuit.cx(qr[1], qr[0])
circuit.barrier(qr)
circuit.measure(qr[0], cr1[0])
circuit.measure(qr[1], cr2[0])
circuit.measure(qr[2], cr1[1])
circuit.measure(qr[3], cr2[1])
coupling = CouplingMap([[0, 1], [0, 2], [2, 3]]) # linear [1, 0, 2, 3]
property_set = {}
actual = BIPMapping(coupling, objective="depth")(circuit, property_set)
self.assertEqual(5, actual.depth())
CheckMap(coupling)(actual, property_set)
self.assertTrue(property_set["is_swap_mapped"])
def test_swaps_in_dummy_steps(self):
"""Test the case when swaps are inserted in dummy steps."""
# ┌───┐ ░ ░
# q_0: ──■──┤ H ├─░───■────────░───■───────
# ┌─┴─┐├───┤ ░ │ ░ │
# q_1: ┤ X ├┤ H ├─░───┼────■───░───┼────■──
# └───┘├───┤ ░ │ ┌─┴─┐ ░ ┌─┴─┐ │
# q_2: ──■──┤ H ├─░───┼──┤ X ├─░─┤ X ├──┼──
# ┌─┴─┐├───┤ ░ ┌─┴─┐└───┘ ░ └───┘┌─┴─┐
# q_3: ┤ X ├┤ H ├─░─┤ X ├──────░──────┤ X ├
# └───┘└───┘ ░ └───┘ ░ └───┘
circuit = QuantumCircuit(4)
circuit.cx(0, 1)
circuit.cx(2, 3)
circuit.h([0, 1, 2, 3])
circuit.barrier()
circuit.cx(0, 3)
circuit.cx(1, 2)
circuit.barrier()
circuit.cx(0, 2)
circuit.cx(1, 3)
coupling = CouplingMap.from_line(4)
property_set = {}
actual = BIPMapping(coupling, objective="depth")(circuit, property_set)
self.assertEqual(7, actual.depth())
CheckMap(coupling)(actual, property_set)
self.assertTrue(property_set["is_swap_mapped"])
# no swaps before the first barrier
for inst, _, _ in actual.data:
if isinstance(inst, Barrier):
break
self.assertFalse(isinstance(inst, SwapGate))
def test_different_number_of_virtual_and_physical_qubits(self):
"""Test the case when number of virtual and physical qubits are different."""
# q_0: ──■────■───────
# ┌─┴─┐ │
# q_1: ┤ X ├──┼────■──
# └───┘ │ ┌─┴─┐
# q_2: ──■────┼──┤ X ├
# ┌─┴─┐┌─┴─┐└───┘
# q_3: ┤ X ├┤ X ├─────
# └───┘└───┘
circuit = QuantumCircuit(4)
circuit.cx(0, 1)
circuit.cx(2, 3)
circuit.cx(0, 3)
property_set = {}
coupling = CouplingMap.from_line(5)
actual = BIPMapping(coupling, objective="depth")(circuit, property_set)
self.assertEqual(2, actual.depth())
def test_qubit_subset(self):
"""Test if `qubit_subset` option works as expected."""
circuit = QuantumCircuit(3)
circuit.cx(0, 1)
circuit.cx(1, 2)
circuit.cx(0, 2)
coupling = CouplingMap([(0, 1), (1, 3), (3, 2)])
qubit_subset = [0, 1, 3]
actual = BIPMapping(coupling, qubit_subset=qubit_subset)(circuit)
# all used qubits are in qubit_subset
bit_indices = {bit: index for index, bit in enumerate(actual.qubits)}
for _, qargs, _ in actual.data:
for q in qargs:
self.assertTrue(bit_indices[q] in qubit_subset)
# ancilla qubits are set in the resulting qubit
idle = QuantumRegister(1, name="ancilla")
self.assertEqual(idle[0], actual._layout.initial_layout[2])
def test_unconnected_qubit_subset(self):
"""Fails if qubits in `qubit_subset` are not connected."""
circuit = QuantumCircuit(3)
circuit.cx(0, 1)
coupling = CouplingMap([(0, 1), (1, 3), (3, 2)])
with self.assertRaises(TranspilerError):
BIPMapping(coupling, qubit_subset=[0, 1, 2])(circuit)
def test_objective_function(self):
"""Test if ``objective`` functions prioritize metrics correctly."""
# ┌──────┐┌──────┐ ┌──────┐
# q_0: ┤0 ├┤0 ├─────┤0 ├
# │ Dcx ││ │ │ Dcx │
# q_1: ┤1 ├┤ Dcx ├──■──┤1 ├
# └──────┘│ │ │ └──────┘
# q_2: ───■────┤1 ├──┼─────■────
# ┌─┴─┐ └──────┘┌─┴─┐ ┌─┴─┐
# q_3: ─┤ X ├──────────┤ X ├─┤ X ├──
# └───┘ └───┘ └───┘
qc = QuantumCircuit(4)
qc.dcx(0, 1)
qc.cx(2, 3)
qc.dcx(0, 2)
qc.cx(1, 3)
qc.dcx(0, 1)
qc.cx(2, 3)
coupling = CouplingMap(FakeLima().configuration().coupling_map)
dep_opt = BIPMapping(coupling, objective="depth", qubit_subset=[0, 1, 3, 4])(qc)
err_opt = BIPMapping(
coupling,
objective="gate_error",
qubit_subset=[0, 1, 3, 4],
backend_prop=FakeLima().properties(),
)(qc)
# depth = number of su4 layers (mirrored gates have to be consolidated as single su4 gates)
pm_ = PassManager([Collect2qBlocks(), ConsolidateBlocks(basis_gates=["cx", "u"])])
dep_opt = pm_.run(dep_opt)
err_opt = pm_.run(err_opt)
self.assertLessEqual(dep_opt.depth(), err_opt.depth())
# count CNOTs after synthesized
dep_opt = UnitarySynthesis(basis_gates=["cx", "u"])(dep_opt)
err_opt = UnitarySynthesis(basis_gates=["cx", "u"])(err_opt)
self.assertGreater(dep_opt.count_ops()["cx"], err_opt.count_ops()["cx"])
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit.extensions import Initialize
from qiskit.quantum_info import random_statevector
from utility import *
#create_bell_pair(qc, a, b): coded in utility.py
def encode_message(qc, qubit, msg):
if msg == "00":
pass # To send 00 we do nothing
elif msg == "10":
qc.x(qubit) # To send 10 we apply an X-gate
elif msg == "01":
qc.z(qubit) # To send 01 we apply a Z-gate
elif msg == "11":
qc.z(qubit) # To send 11, we apply a Z-gate
qc.x(qubit) # followed by an X-gate
else:
print("Invalid Message: Sending '00'")
def decode_message(qc, a, b):
qc.cx(a,b)
qc.h(a)
#put everything together
qc = QuantumCircuit(2)
create_bell_pair(qc, 0, 1)
qc.barrier()
message = "10"
encode_message(qc, 0, message)
qc.barrier()
decode_message(qc, 0, 1)
qc.measure_all()
qc.draw(output = "mpl")
backend = Aer.get_backend('qasm_simulator')
res = execute(qc, backend, shots=1024).result()
measurement_result = res.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)
# Plotting our result
result = job.result()
plot_histogram(result.get_counts(qc))
correct_results = result.get_counts(qc)[message]
accuracy = (correct_results/shots)*100
print("Accuracy = %.2f%%" % accuracy)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
"""BasicProvider provider integration tests."""
import unittest
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile
from qiskit.result import Result
from qiskit.providers.basic_provider import BasicProviderError, BasicSimulator
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestBasicProviderIntegration(QiskitTestCase):
"""Qiskit BasicProvider simulator integration tests."""
def setUp(self):
super().setUp()
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
self._qc1 = QuantumCircuit(qr, cr, name="qc1")
self._qc2 = QuantumCircuit(qr, cr, name="qc2")
self._qc1.measure(qr[0], cr[0])
self.backend = BasicSimulator()
self._result1 = self.backend.run(transpile(self._qc1)).result()
def test_builtin_simulator_result_fields(self):
"""Test components of a result from a local simulator."""
self.assertEqual("basic_simulator", self._result1.backend_name)
self.assertIsInstance(self._result1.job_id, str)
self.assertEqual(self._result1.status, "COMPLETED")
self.assertEqual(self._result1.results[0].status, "DONE")
def test_basicprovider_execute(self):
"""Test Compiler and run."""
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
job = self.backend.run(qc)
result = job.result()
self.assertIsInstance(result, Result)
def test_basicprovider_execute_two(self):
"""Test Compiler and run."""
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
qc_extra = QuantumCircuit(qubit_reg, clbit_reg, name="extra")
qc_extra.measure(qubit_reg, clbit_reg)
job = self.backend.run([qc, qc_extra])
result = job.result()
self.assertIsInstance(result, Result)
def test_basicprovider_num_qubits(self):
"""Test BasicProviderError is raised if num_qubits too large to simulate."""
qc = QuantumCircuit(50, 1)
qc.x(0)
qc.measure(0, 0)
with self.assertRaises(BasicProviderError):
self.backend.run(qc)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
N = 2**10; th = asin(1/sqrt(N)); N, float(th), float(sin(th)), float(th*180/pi), sqrt(N)
my_list = [1,3,5,2,4,9,5,8,0,7,6]
def my_oracle(my_input):
solution = 2
if my_input == solution:
response = True
else:
response = False
return response
my_input = 7; res = my_oracle(my_input); print(res)
for j in range(0,len(my_list)):
if my_oracle(my_list[j]) == True:
print('Solução encontrada no índice',j, ', após ', j+1, ' consultas ao oráculo.')
from qiskit import *
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_belem')
from qiskit.tools.monitor import job_monitor
from qiskit.tools.visualization import plot_histogram
def qc_Uz(n): # 2|0><0| - I
qc = QuantumCircuit(n, name = 'Uz')
qrl = []
for j in range(0, n):
qrl.append(j)
qc.z(0); qc.x(0); qc.z(0); qc.x(0)
qc.x(qrl) # 00...0 -> 11...1
qc.h(n-1); qc.mcx(qrl[0:n-1],n-1); qc.h(n-1) # Cz multicontrolada. Multiplica 11...1 por -1
qc.x(qrl); # 11...1 -> 00...0
return qc
qc_Uz_ = qc_Uz(3); qc_Uz_.draw()
def qc_Uh(n): # 2|h><h| - I
qc = QuantumCircuit(n, name = 'Uh')
qrl = []
for j in range(0, n):
qrl.append(j)
qc.h(qrl) # transforma Uz em Uh
qc_Uz_ = qc_Uz(n); qc.append(qc_Uz_, qrl)
qc.h(qrl)
return qc
qc_Uh_ = qc_Uh(3); qc_Uh_.draw()
def qc_oracle(n):
# Nielsen & Chuang, Box 6.1 (N=4)
qc = QuantumCircuit(n+1, name = 'Oracle')
qc.ccx(0,1,2) # para a solução sendo o estado |11>
return qc
qc_oracle_ = qc_oracle(2)
qc_oracle_.draw('mpl')
def qc_grover_iteration(n):
qc = QuantumCircuit(n+1, name = 'G')
qrl = []
for j in range(0, n+1):
qrl.append(j)
qc_oracle_ = qc_oracle(n)
qc.append(qc_oracle_, qrl)
qc_Uh_ = qc_Uh(n); qc.append(qc_Uh_, qrl[0:n])
return qc
qc_grover_iteration_ = qc_grover_iteration(2)
qc_grover_iteration_.draw('mpl')
def qc_hadamard_state(n): # aplica a Hadamard em n qubits
qc = QuantumCircuit(n, name = 'H state') # começarei a não usar mais os qr[j]
qrl = [] # lista de registros quânticos
for j in range(0, n):
qrl.append(j)
qc.h(qrl) # aplica a hadamard em toda a lista de registros quânticos
return qc
qc_hadamard_state_ = qc_hadamard_state(3); qc_hadamard_state_.draw()
def qc_grover_search(n):
qc = QuantumCircuit(n+1, n)
qc.x(n)
qrl = [] # lista de registros quânticos
for j in range(0, n+1):
qrl.append(j)
qc_hadamard_state_ = qc_hadamard_state(n+1); qc.append(qc_hadamard_state_, qrl)
for j in range(0, int((math.pi*math.sqrt(2**n))/4 - 1/2)):
qc_grover_iteration_ = qc_grover_iteration(n); qc.append(qc_grover_iteration_, qrl)
qc.measure(qrl[0:n], qrl[0:n])
return qc
qc_grover_search_ = qc_grover_search(2); qc_grover_search_.draw()
qc_grover_search_ = qc_grover_search(2)
result = execute(qc_grover_search_, backend = simulator, shots = nshots).result()
plot_histogram(result.get_counts(qc_grover_search_))
job = execute(qc_grover_search_, backend = device, shots = nshots)
job_monitor(job)
plot_histogram(job.result().get_counts(qc_grover_search_))
|
https://github.com/abhik-99/Qiskit-Summer-School
|
abhik-99
|
# -*- 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/Dpbm/scientific-research-1-quantum-oracles
|
Dpbm
|
%matplotlib inline
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import array_to_latex, plot_histogram
from qiskit_aer import AerSimulator
from utils import get_image_path
sim = AerSimulator()
circuit = QuantumCircuit(4,3)
circuit.x(-1)
circuit.h(range(4))
circuit.barrier()
circuit.cx(0, -1)
circuit.cx(1, -1)
#circuit.cx(2, -1)
circuit.barrier()
circuit.h(range(3))
circuit.measure(range(3), range(3))
circuit.draw('mpl', filename=get_image_path("phase_oracle_1.png"))
result = sim.run(circuit).result().get_counts()
plot_histogram(result, filename=get_image_path("result_phase_oracle_plot.png"))
from math import pi
circuit2 = QuantumCircuit(3)
circuit2.x(-1)
circuit2.ccz(2, 1, 0)
circuit2.x(-1)
circuit2.draw('mpl')
circuit_tmp = circuit2.copy()
circuit_tmp.save_unitary()
unitary = sim.run(transpile(circuit_tmp, sim)).result().get_unitary()
array_to_latex(unitary, max_size=1000)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import LinearAmplitudeFunction
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits to represent the uncertainty
num_uncertainty_qubits = 3
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# construct circuit for uncertainty model
uncertainty_model = LogNormalDistribution(
num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high)
)
# plot probability distribution
x = uncertainty_model.values
y = uncertainty_model.probabilities
plt.bar(x, y, width=0.2)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.show()
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price_1 = 1.438
strike_price_2 = 2.584
# set the approximation scaling for the payoff function
rescaling_factor = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price_1, strike_price_2]
slopes = [0, 1, 0]
offsets = [0, 0, strike_price_2 - strike_price_1]
f_min = 0
f_max = strike_price_2 - strike_price_1
bull_spread_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
rescaling_factor=rescaling_factor,
)
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
bull_spread = bull_spread_objective.compose(uncertainty_model, front=True)
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = uncertainty_model.values
y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1)
plt.plot(x, y, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(uncertainty_model.probabilities, y)
exact_delta = sum(
uncertainty_model.probabilities[np.logical_and(x >= strike_price_1, x <= strike_price_2)]
)
print("exact expected value:\t%.4f" % exact_value)
print("exact delta value: \t%.4f" % exact_delta)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=bull_spread,
objective_qubits=[num_uncertainty_qubits],
post_processing=bull_spread_objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value:\t%.4f" % result.estimation_processed)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price_1, strike_price_2]
slopes = [0, 0, 0]
offsets = [0, 1, 0]
f_min = 0
f_max = 1
bull_spread_delta_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
) # no approximation necessary, hence no rescaling factor
# construct the A operator by stacking the uncertainty model and payoff function together
bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits]
)
# construct amplitude estimation
ae_delta = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_delta = ae_delta.estimate(problem)
conf_int = np.array(result_delta.confidence_interval)
print("Exact delta: \t%.4f" % exact_delta)
print("Estimated value:\t%.4f" % result_delta.estimation)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
secretnumber = '11100011'
circuit = QuantumCircuit(len(secretnumber)+1,len(secretnumber))
circuit.h(range(len(secretnumber)))
circuit.x(len(secretnumber))
circuit.h(len(secretnumber))
circuit.barrier()
for ii, yesno in enumerate(reversed(secretnumber)):
if yesno == '1':
circuit.cx(ii,len(secretnumber))
circuit.barrier()
circuit.h(range(len(secretnumber)))
circuit.barrier()
circuit.measure(range(len(secretnumber)),range(len(secretnumber)))
circuit.draw(output = 'mpl')
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
from mip import Model, INTEGER, xsum, OptimizationStatus, minimize
import numpy as np
from itertools import permutations
A = np.array([[0,1,2,3,4,1],
[2,1,4,1,0,2],
[1,5,2,3,1,1]])
var_type = INTEGER
max_gap = 0.05
max_seconds=10
c = np.array([1,2,1,-3,1,-1])
m, n = A.shape
def createModelAndCheck(A, b, var_type, max_gap, max_seconds):
m, n = A.shape
model = Model()
x = [model.add_var(var_type=var_type) for j in range(n)]
for i in range(m):
A_i = A[i]
b_i = b[i]
model += xsum(A_i[j]*x[j] for j in range(n)) == b_i
model.objective = minimize(xsum(c[j]*x[j] for j in range(n)))
model.max_gap = max_gap
status = model.optimize(max_seconds=max_seconds)
"""
if status != OptimizationStatus.INFEASIBLE:
print("Found b: ", b)
if status == OptimizationStatus.OPTIMAL:
print('optimal solution cost {} found'.format(model.objective_value))
elif status == OptimizationStatus.FEASIBLE:
print('sol.cost {} found, best possible: {}'.format(model.objective_value, model.objective_bound))
elif status == OptimizationStatus.NO_SOLUTION_FOUND:
print('no feasible solution found, lower bound is: {}'.format(model.objective_bound))
"""
if status == OptimizationStatus.OPTIMAL:# or status == OptimizationStatus.FEASIBLE:
print('solution:')
for v in model.vars:
if abs(v.x) > 1e-6: # only printing non-zeros
print('{} : {}'.format(v.name, v.x))
return model
else:
return None
brute_force_b = list(permutations([0,1,2,3,4,5,6,7,8],3))
goodB = []
for b in brute_force_b:
model = createModelAndCheck(A, np.array(b), var_type, max_gap, max_seconds)
if model is not None:
count = 0
good = False
for v in model.vars:
if abs(v.x) > 1e-6:
count += 1
if abs(v.x) > 1: good = True
if count > 2 and good:
goodB +=[b]
print(goodB)
for b in goodB :
createModelAndCheck(A, np.array(b), var_type, max_gap, max_seconds)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
input_3sat_instance = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
import os
import tempfile
from qiskit.exceptions import MissingOptionalLibraryError
from qiskit.circuit.library.phase_oracle import PhaseOracle
fp = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
fp.write(input_3sat_instance)
file_name = fp.name
fp.close()
oracle = None
try:
oracle = PhaseOracle.from_dimacs_file(file_name)
except MissingOptionalLibraryError as ex:
print(ex)
finally:
os.remove(file_name)
from qiskit.algorithms import AmplificationProblem
problem = None
if oracle is not None:
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
from qiskit.algorithms import Grover
from qiskit.primitives import Sampler
grover = Grover(sampler=Sampler())
result = None
if problem is not None:
result = grover.amplify(problem)
print(result.assignment)
from qiskit.tools.visualization import plot_histogram
if result is not None:
display(plot_histogram(result.circuit_results[0]))
expression = '(w ^ x) & ~(y ^ z) & (x & y & z)'
try:
oracle = PhaseOracle(expression)
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
display(plot_histogram(result.circuit_results[0]))
except MissingOptionalLibraryError as ex:
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/samuraigab/Quantum-Basic-Algorithms
|
samuraigab
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import *
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit_textbook.tools import array_to_latex
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
n = 2
qc = QuantumCircuit(n)
qc.h(0)
qc.h(1)
display(qc.draw())
'''
Executando o circuito acima em um simulador quântico.
O resultado irá mostrar a probabilidade de obter um dos 4 estados possivíveis:
00, 01, 10 e 11
Lembrando que o que conseguimos estrair de informação são os bits clássicos.
'''
backend = Aer.get_backend('statevector_simulator')
results = execute(qc,backend).result().get_counts()
state = execute(qc,backend).result().get_statevector()
#Gerando o histograma dos resultatos
display(plot_histogram(results, figsize = (3,3)))
#Mostrando vetor de estado
array_to_latex(state, pretext="\\vert \psi\\rangle = ")
n = 2 # número de qubits
c = 2 # número de bits (clássicos)
#iniciando o circuito com n qubit e c bits
qc = QuantumCircuit(n, c)
qc.h(0)
qc.h(1)
#medindo os qubits q0 e q1 e guarando o valor em c0 e c1 (respectivamente)
qc.measure(range(n), range(c))
display(qc.draw())
shots = 100 #quantidade de vezes que realizamos o experimento
plots = 1 #numero de plots
backend = Aer.get_backend('qasm_simulator')
for i in range(plots):
results = execute(qc,backend, shots = shots).result().get_counts()
#Gerando o histograma dos resultatos
display(plot_histogram(results, figsize = (3,3)))
print(f"O resultado 00 apareceu {results['00']}")
print(f"O resultado 01 apareceu {results['01']}")
print(f"O resultado 10 apareceu {results['10']}")
print(f"O resultado 11 apareceu {results['11']}")
n = 2 # número de qubits
c = 2 # número de bits (clássicos)
#iniciando o circuito com n qubit e c bits
qc = QuantumCircuit(n)
qc.h(0)
qc.cx(0,1)
qc.draw()
backend = Aer.get_backend('statevector_simulator')
results = execute(qc,backend).result().get_counts()
display(plot_histogram(results, figsize = (3,3)))
state = execute(qc,backend).result().get_statevector()
array_to_latex(state, pretext="\\vert \psi \\rangle = ")
n = 2 # número de qubits
c = 2 # número de bits (clássicos)
#iniciando o circuito com n qubit e c bits
qc = QuantumCircuit(n)
# qc.h(0)
# qc.z(0)
qc.x(0)
qc.h(0)
qc.cx(0,1)
qc.draw()
backend = Aer.get_backend('statevector_simulator')
results = execute(qc,backend).result().get_counts()
display(plot_histogram(results, figsize = (3,3)))
state = execute(qc,backend).result().get_statevector()
array_to_latex(state, pretext="\\vert \psi \\rangle = ")
n = 2 # número de qubits
c = 2 # número de bits (clássicos)
#iniciando o circuito com n qubit e c bits
qc = QuantumCircuit(n)
qc.h(0) #00 + 10
qc.x(1) #01 + 11 (0 + 1)* 1
qc.cx(0,1) #01 +10 (?)
qc.draw()
backend = Aer.get_backend('statevector_simulator')
results = execute(qc,backend).result().get_counts()
display(plot_histogram(results, figsize = (3,3)))
state = execute(qc,backend).result().get_statevector()
array_to_latex(state, pretext="\\vert \psi \\rangle = ")
n = 2 # número de qubits
c = 2 # número de bits (clássicos)
#iniciando o circuito com n qubit e c bits
qc = QuantumCircuit(n)
qc.x(0)
qc.h(0)
qc.x(1)
qc.cx(0,1)
display(qc.draw())
backend = Aer.get_backend('statevector_simulator')
results = execute(qc,backend).result().get_counts()
display(plot_histogram(results, figsize = (3,3)))
state = execute(qc,backend).result().get_statevector()
array_to_latex(state, pretext="\\vert \psi \\rangle = ")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc)
|
https://github.com/rochelleli165/qiskitfallfest2023
|
rochelleli165
|
########################################
# ENTER YOUR NAME AND WISC EMAIL HERE: #
########################################
# Name: Rochelle Li
# Email: rli484@wisc.edu
## Run this cell to make sure your grader is setup correctly
%set_env QC_GRADE_ONLY=true
%set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, 3)
## Write your code below this line ##
qc.h(0)
qc.h(2)
qc.cx(0,1)
## Do not change the code below here ##
answer1 = qc
qc.draw()
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2a
grade_ex2a(answer1)
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, 3)
qc.barrier(0, 1, 2)
## Write your code below this line ##
qc.cx(1,2)
qc.x(2)
qc.cx(2,0)
qc.x(2)
## Do not change the code below this line ##
answer2 = qc
qc.draw()
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2b
grade_ex2b(answer2)
answer3: bool
## Quiz: evaluate the results and decide if the following statement is True or False
q0 = 1
q1 = 0
q2 = 1
## Based on this, is it TRUE or FALSE that the Guard on the left is a liar?
## Assign your answer, either True or False, to answer3 below
answer3 = True
from qc_grader.challenges.fall_fest23 import grade_ex2c
grade_ex2c(answer3)
## Quiz: Fill in the correct numbers to make the following statement true:
## The treasure is on the right, and the Guard on the left is the liar
q0 = 0
q1 = 1
q2 = 1
## HINT - Remember that Qiskit uses little-endian ordering
answer4 = [q0, q1, q2]
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2d
grade_ex2d(answer4)
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
## in the code below, fill in the missing gates. Run the cell to see a drawing of the current circuit ##
qc.h(0)
qc.h(2)
qc.cx(0,1)
qc.barrier(0, 1, 2)
qc.cx(2, 1)
qc.x(2)
qc.cx(2, 0)
qc.x(2)
qc.barrier(0, 1, 2)
qc.swap(0,1)
qc.x(0)
qc.x(1)
qc.cx(2,1)
qc.x(2)
qc.cx(2,0)
qc.x(2)
## Do not change any of the code below this line ##
answer5 = qc
qc.draw(output="mpl")
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2e
grade_ex2e(answer5)
from qiskit import QuantumCircuit, Aer, transpile
from qiskit.visualization import plot_histogram
## This is the full version of the circuit. Run it to see the results ##
quantCirc = QuantumCircuit(3)
quantCirc.h(0), quantCirc.h(2), quantCirc.cx(0, 1), quantCirc.barrier(0, 1, 2), quantCirc.cx(2, 1), quantCirc.x(2), quantCirc.cx(2, 0), quantCirc.x(2)
quantCirc.barrier(0, 1, 2), quantCirc.swap(0, 1), quantCirc.x(1), quantCirc.cx(2, 1), quantCirc.x(0), quantCirc.x(2), quantCirc.cx(2, 0), quantCirc.x(2)
# Execute the circuit and draw the histogram
measured_qc = quantCirc.measure_all(inplace=False)
backend = Aer.get_backend('qasm_simulator') # the device to run on
result = backend.run(transpile(measured_qc, backend), shots=1000).result()
counts = result.get_counts(measured_qc)
plot_histogram(counts)
from qiskit.primitives import Sampler
from qiskit.visualization import plot_distribution
sampler = Sampler()
result = sampler.run(measured_qc, shots=1000).result()
probs = result.quasi_dists[0].binary_probabilities()
plot_distribution(probs)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Sampler
from qiskit.utils import algorithm_globals
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder, MinMaxScaler
from qiskit_machine_learning.algorithms.classifiers import VQC
from IPython.display import clear_output
algorithm_globals.random_seed = 42
sampler1 = Sampler()
sampler2 = Sampler()
num_samples = 40
num_features = 2
features = 2 * algorithm_globals.random.random([num_samples, num_features]) - 1
labels = 1 * (np.sum(features, axis=1) >= 0) # in { 0, 1}
features = MinMaxScaler().fit_transform(features)
features.shape
features[0:5, :]
labels = OneHotEncoder(sparse=False).fit_transform(labels.reshape(-1, 1))
labels.shape
labels[0:5, :]
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=30, random_state=algorithm_globals.random_seed
)
train_features.shape
def plot_dataset():
plt.scatter(
train_features[np.where(train_labels[:, 0] == 0), 0],
train_features[np.where(train_labels[:, 0] == 0), 1],
marker="o",
color="b",
label="Label 0 train",
)
plt.scatter(
train_features[np.where(train_labels[:, 0] == 1), 0],
train_features[np.where(train_labels[:, 0] == 1), 1],
marker="o",
color="g",
label="Label 1 train",
)
plt.scatter(
test_features[np.where(test_labels[:, 0] == 0), 0],
test_features[np.where(test_labels[:, 0] == 0), 1],
marker="o",
facecolors="w",
edgecolors="b",
label="Label 0 test",
)
plt.scatter(
test_features[np.where(test_labels[:, 0] == 1), 0],
test_features[np.where(test_labels[:, 0] == 1), 1],
marker="o",
facecolors="w",
edgecolors="g",
label="Label 1 test",
)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.plot([1, 0], [0, 1], "--", color="black")
plot_dataset()
plt.show()
maxiter = 20
objective_values = []
# callback function that draws a live plot when the .fit() method is called
def callback_graph(_, objective_value):
clear_output(wait=True)
objective_values.append(objective_value)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
stage1_len = np.min((len(objective_values), maxiter))
stage1_x = np.linspace(1, stage1_len, stage1_len)
stage1_y = objective_values[:stage1_len]
stage2_len = np.max((0, len(objective_values) - maxiter))
stage2_x = np.linspace(maxiter, maxiter + stage2_len - 1, stage2_len)
stage2_y = objective_values[maxiter : maxiter + stage2_len]
plt.plot(stage1_x, stage1_y, color="orange")
plt.plot(stage2_x, stage2_y, color="purple")
plt.show()
plt.rcParams["figure.figsize"] = (12, 6)
original_optimizer = COBYLA(maxiter=maxiter)
ansatz = RealAmplitudes(num_features)
initial_point = np.asarray([0.5] * ansatz.num_parameters)
original_classifier = VQC(
ansatz=ansatz, optimizer=original_optimizer, callback=callback_graph, sampler=sampler1
)
original_classifier.fit(train_features, train_labels)
print("Train score", original_classifier.score(train_features, train_labels))
print("Test score ", original_classifier.score(test_features, test_labels))
original_classifier.save("vqc_classifier.model")
loaded_classifier = VQC.load("vqc_classifier.model")
loaded_classifier.warm_start = True
loaded_classifier.neural_network.sampler = sampler2
loaded_classifier.optimizer = COBYLA(maxiter=80)
loaded_classifier.fit(train_features, train_labels)
print("Train score", loaded_classifier.score(train_features, train_labels))
print("Test score", loaded_classifier.score(test_features, test_labels))
train_predicts = loaded_classifier.predict(train_features)
test_predicts = loaded_classifier.predict(test_features)
# return plot to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
plot_dataset()
# plot misclassified data points
plt.scatter(
train_features[np.all(train_labels != train_predicts, axis=1), 0],
train_features[np.all(train_labels != train_predicts, axis=1), 1],
s=200,
facecolors="none",
edgecolors="r",
linewidths=2,
)
plt.scatter(
test_features[np.all(test_labels != test_predicts, axis=1), 0],
test_features[np.all(test_labels != test_predicts, axis=1), 1],
s=200,
facecolors="none",
edgecolors="r",
linewidths=2,
)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Piecewise-polynomially-controlled Pauli rotations."""
from __future__ import annotations
from typing import List, Optional
import numpy as np
from qiskit.circuit import QuantumRegister, AncillaRegister, QuantumCircuit
from qiskit.circuit.exceptions import CircuitError
from .functional_pauli_rotations import FunctionalPauliRotations
from .polynomial_pauli_rotations import PolynomialPauliRotations
from .integer_comparator import IntegerComparator
class PiecewisePolynomialPauliRotations(FunctionalPauliRotations):
r"""Piecewise-polynomially-controlled Pauli rotations.
This class implements a piecewise polynomial (not necessarily continuous) function,
:math:`f(x)`, on qubit amplitudes, which is defined through breakpoints and coefficients as
follows.
Suppose the breakpoints :math:`(x_0, ..., x_J)` are a subset of :math:`[0, 2^n-1]`, where
:math:`n` is the number of state qubits. Further on, denote the corresponding coefficients by
:math:`[a_{j,1},...,a_{j,d}]`, where :math:`d` is the highest degree among all polynomials.
Then :math:`f(x)` is defined as:
.. math::
f(x) = \begin{cases}
0, x < x_0 \\
\sum_{i=0}^{i=d}a_{j,i}/2 x^i, x_j \leq x < x_{j+1}
\end{cases}
where if given the same number of breakpoints as polynomials, we implicitly assume
:math:`x_{J+1} = 2^n`.
.. note::
Note the :math:`1/2` factor in the coefficients of :math:`f(x)`, this is consistent with
Qiskit's Pauli rotations.
Examples:
>>> from qiskit import QuantumCircuit
>>> from qiskit.circuit.library.arithmetic.piecewise_polynomial_pauli_rotations import\
... PiecewisePolynomialPauliRotations
>>> qubits, breakpoints, coeffs = (2, [0, 2], [[0, -1.2],[-1, 1, 3]])
>>> poly_r = PiecewisePolynomialPauliRotations(num_state_qubits=qubits,
...breakpoints=breakpoints, coeffs=coeffs)
>>>
>>> qc = QuantumCircuit(poly_r.num_qubits)
>>> qc.h(list(range(qubits)));
>>> qc.append(poly_r.to_instruction(), list(range(qc.num_qubits)));
>>> qc.draw()
┌───┐┌──────────┐
q_0: ┤ H ├┤0 ├
├───┤│ │
q_1: ┤ H ├┤1 ├
└───┘│ │
q_2: ─────┤2 ├
│ pw_poly │
q_3: ─────┤3 ├
│ │
q_4: ─────┤4 ├
│ │
q_5: ─────┤5 ├
└──────────┘
References:
[1]: Haener, T., Roetteler, M., & Svore, K. M. (2018).
Optimizing Quantum Circuits for Arithmetic.
`arXiv:1805.12445 <http://arxiv.org/abs/1805.12445>`_
[2]: Carrera Vazquez, A., Hiptmair, R., & Woerner, S. (2022).
Enhancing the Quantum Linear Systems Algorithm using Richardson Extrapolation.
`ACM Transactions on Quantum Computing 3, 1, Article 2 <https://doi.org/10.1145/3490631>`_
"""
def __init__(
self,
num_state_qubits: Optional[int] = None,
breakpoints: Optional[List[int]] = None,
coeffs: Optional[List[List[float]]] = None,
basis: str = "Y",
name: str = "pw_poly",
) -> None:
"""
Args:
num_state_qubits: The number of qubits representing the state.
breakpoints: The breakpoints to define the piecewise-linear function.
Defaults to ``[0]``.
coeffs: The coefficients of the polynomials for different segments of the
piecewise-linear function. ``coeffs[j][i]`` is the coefficient of the i-th power of x
for the j-th polynomial.
Defaults to linear: ``[[1]]``.
basis: The type of Pauli rotation (``'X'``, ``'Y'``, ``'Z'``).
name: The name of the circuit.
"""
# store parameters
self._breakpoints = breakpoints if breakpoints is not None else [0]
self._coeffs = coeffs if coeffs is not None else [[1]]
# store a list of coefficients as homogeneous polynomials adding 0's where necessary
self._hom_coeffs = []
self._degree = len(max(self._coeffs, key=len)) - 1
for poly in self._coeffs:
self._hom_coeffs.append(poly + [0] * (self._degree + 1 - len(poly)))
super().__init__(num_state_qubits=num_state_qubits, basis=basis, name=name)
@property
def breakpoints(self) -> List[int]:
"""The breakpoints of the piecewise polynomial function.
The function is polynomial in the intervals ``[point_i, point_{i+1}]`` where the last
point implicitly is ``2**(num_state_qubits + 1)``.
Returns:
The list of breakpoints.
"""
if (
self.num_state_qubits is not None
and len(self._breakpoints) == len(self.coeffs)
and self._breakpoints[-1] < 2**self.num_state_qubits
):
return self._breakpoints + [2**self.num_state_qubits]
return self._breakpoints
@breakpoints.setter
def breakpoints(self, breakpoints: List[int]) -> None:
"""Set the breakpoints.
Args:
breakpoints: The new breakpoints.
"""
self._invalidate()
self._breakpoints = breakpoints
if self.num_state_qubits and breakpoints:
self._reset_registers(self.num_state_qubits)
@property
def coeffs(self) -> List[List[float]]:
"""The coefficients of the polynomials.
Returns:
The polynomial coefficients per interval as nested lists.
"""
return self._coeffs
@coeffs.setter
def coeffs(self, coeffs: List[List[float]]) -> None:
"""Set the polynomials.
Args:
coeffs: The new polynomials.
"""
self._invalidate()
self._coeffs = coeffs
# update the homogeneous polynomials and degree
self._hom_coeffs = []
self._degree = len(max(self._coeffs, key=len)) - 1
for poly in self._coeffs:
self._hom_coeffs.append(poly + [0] * (self._degree + 1 - len(poly)))
if self.num_state_qubits and coeffs:
self._reset_registers(self.num_state_qubits)
@property
def mapped_coeffs(self) -> List[List[float]]:
"""The coefficients mapped to the internal representation, since we only compare
x>=breakpoint.
Returns:
The mapped coefficients.
"""
mapped_coeffs = []
# First polynomial
mapped_coeffs.append(self._hom_coeffs[0])
for i in range(1, len(self._hom_coeffs)):
mapped_coeffs.append([])
for j in range(0, self._degree + 1):
mapped_coeffs[i].append(self._hom_coeffs[i][j] - self._hom_coeffs[i - 1][j])
return mapped_coeffs
@property
def contains_zero_breakpoint(self) -> bool | np.bool_:
"""Whether 0 is the first breakpoint.
Returns:
True, if 0 is the first breakpoint, otherwise False.
"""
return np.isclose(0, self.breakpoints[0])
def evaluate(self, x: float) -> float:
"""Classically evaluate the piecewise polynomial rotation.
Args:
x: Value to be evaluated at.
Returns:
Value of piecewise polynomial function at x.
"""
y = 0
for i in range(0, len(self.breakpoints)):
y = y + (x >= self.breakpoints[i]) * (np.poly1d(self.mapped_coeffs[i][::-1])(x))
return y
def _check_configuration(self, raise_on_failure: bool = True) -> bool:
"""Check if the current configuration is valid."""
valid = True
if self.num_state_qubits is None:
valid = False
if raise_on_failure:
raise AttributeError("The number of qubits has not been set.")
if self.num_qubits < self.num_state_qubits + 1:
valid = False
if raise_on_failure:
raise CircuitError(
"Not enough qubits in the circuit, need at least "
"{}.".format(self.num_state_qubits + 1)
)
if len(self.breakpoints) != len(self.coeffs) + 1:
valid = False
if raise_on_failure:
raise ValueError("Mismatching number of breakpoints and polynomials.")
return valid
def _reset_registers(self, num_state_qubits: Optional[int]) -> None:
"""Reset the registers."""
self.qregs = []
if num_state_qubits:
qr_state = QuantumRegister(num_state_qubits)
qr_target = QuantumRegister(1)
self.qregs = [qr_state, qr_target]
# Calculate number of ancilla qubits required
num_ancillas = num_state_qubits + 1
if self.contains_zero_breakpoint:
num_ancillas -= 1
if num_ancillas > 0:
qr_ancilla = AncillaRegister(num_ancillas)
self.add_register(qr_ancilla)
def _build(self):
"""If not already built, build the circuit."""
if self._is_built:
return
super()._build()
circuit = QuantumCircuit(*self.qregs, name=self.name)
qr_state = circuit.qubits[: self.num_state_qubits]
qr_target = [circuit.qubits[self.num_state_qubits]]
# Ancilla for the comparator circuit
qr_ancilla = circuit.qubits[self.num_state_qubits + 1 :]
# apply comparators and controlled linear rotations
for i, point in enumerate(self.breakpoints[:-1]):
if i == 0 and self.contains_zero_breakpoint:
# apply rotation
poly_r = PolynomialPauliRotations(
num_state_qubits=self.num_state_qubits,
coeffs=self.mapped_coeffs[i],
basis=self.basis,
)
circuit.append(poly_r.to_gate(), qr_state[:] + qr_target)
else:
# apply Comparator
comp = IntegerComparator(num_state_qubits=self.num_state_qubits, value=point)
qr_state_full = qr_state[:] + [qr_ancilla[0]] # add compare qubit
qr_remaining_ancilla = qr_ancilla[1:] # take remaining ancillas
circuit.append(
comp.to_gate(), qr_state_full[:] + qr_remaining_ancilla[: comp.num_ancillas]
)
# apply controlled rotation
poly_r = PolynomialPauliRotations(
num_state_qubits=self.num_state_qubits,
coeffs=self.mapped_coeffs[i],
basis=self.basis,
)
circuit.append(
poly_r.to_gate().control(), [qr_ancilla[0]] + qr_state[:] + qr_target
)
# uncompute comparator
circuit.append(
comp.to_gate().inverse(),
qr_state_full[:] + qr_remaining_ancilla[: comp.num_ancillas],
)
self.append(circuit.to_gate(), self.qubits)
|
https://github.com/ctuning/ck-qiskit
|
ctuning
|
#!/usr/bin/env python3
"""
Example used in the readme. In this example a Bell state is made and then measured.
## Running this script using the "lightweight" CK infrastructure to import QISKit library...
# 1) on local simulator:
ck virtual env --tags=lib,qiskit --shell_cmd=quantum_coin_flip.py
# 2) on remote simulator (need the API Token from IBM QuantumExperience) :
CK_IBM_BACKEND=ibmq_qasm_simulator ck virtual `ck search env:* --tags=qiskit,lib` `ck search env:* --tags=ibmqx,login` --shell_cmd=quantum_coin_flip.py
# 3) on remote quantum hardware (need the API Token from IBM QuantumExperience) :
CK_IBM_BACKEND=ibmqx4 ck virtual `ck search env:* --tags=qiskit,lib` `ck search env:* --tags=ibmqx,login` --shell_cmd=quantum_coin_flip.py
"""
import sys
import os
# We don't know from where the user is running the example,
# so we need a relative position from this file path.
# TODO: Relative imports for intra-package imports are highly discouraged.
# http://stackoverflow.com/a/7506006
sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
from qiskit import QuantumProgram, QISKitError, available_backends, register
try:
import Qconfig
register(Qconfig.APItoken, Qconfig.config["url"], verify=False,
hub=Qconfig.config["hub"],
group=Qconfig.config["group"],
project=Qconfig.config["project"])
except:
print("""
WARNING: There's no connection with IBMQuantumExperience servers.
cannot test I/O intesive tasks, will only test CPU intensive tasks
running the jobs in the local simulator
""")
available_backends = available_backends()
print("The backends available for use are: {}\n".format(available_backends))
backend = os.environ.get('CK_IBM_BACKEND', 'local_qasm_simulator')
email = os.environ.get('CK_IBM_API_EMAIL', 'N/A')
print("User email: {}\n".format(email))
timeout = int( os.environ.get('CK_IBM_TIMEOUT', 120) )
shots = int( os.environ.get('CK_IBM_REPETITION', 10) )
# Create a QuantumProgram object instance.
Q_program = QuantumProgram()
try:
# Create a Quantum Register called "qr" with 2 qubits.
qr = Q_program.create_quantum_register("qr", 2)
# Create a Classical Register called "cr" with 2 bits.
cr = Q_program.create_classical_register("cr", 2)
# Create a Quantum Circuit called "qc" with the Quantum Register "qr"
# and the Classical Register "cr".
qc = Q_program.create_circuit("bell", [qr], [cr])
# Add an H gate to qubit 0, putting this qubit in superposition.
qc.h(qr[0])
# Add a CX gate to control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
qc.cx(qr[0], qr[1])
# Add a Measure gate to observe the state.
qc.measure(qr, cr)
# Compile and execute the Quantum Program using the given backend.
result = Q_program.execute(["bell"], backend=backend, shots=shots, seed=1, timeout=timeout)
# Show the results.
print(result) # 'COMPLETED'
q_execution_time = result.get_data().get('time')
if q_execution_time:
print("Quantum execution time: {} sec".format(q_execution_time) )
print(result.get_data("bell"))
except QISKitError as ex:
print('Error in the circuit! {}'.format(ex))
########################### Save output to CK format. ##############################
import json
import numpy as np
# See https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable
#
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
elif isinstance(obj, np.bool_):
return bool(obj)
elif isinstance(obj, np.complex):
return obj.real # if you care about the imaginary part, try (obj.real, obj.imag)
return json.JSONEncoder.default(self, obj)
output_dict = {
'backends': available_backends,
'email': email,
'result': result.get_data("bell"),
}
formatted_json = json.dumps(output_dict, cls=NumpyEncoder, sort_keys = True, indent = 4)
#print(formatted_json)
with open('tmp-ck-timer.json', 'w') as json_file:
json_file.write( formatted_json )
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
import qiskit
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
import json
import csv
# Gloabal _lambda variable
_LAMBDA = 10
_SHOTS = 10000
_UNIFORM_CONVERGENCE_SAMPLE = []
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def tsp_obj(x, G):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _LAMBDA)
cost = 0
# z term
for index in range(len(x)):
z = (int(x[index]) * 2 ) -1
cost += z_classic_term[index] * z
## zz term
for i in range(len(x)):
z_1 = (int(x[i]) * 2 ) -1
for j in range(len(x)):
z_2 = (int(x[j]) * 2 ) -1
cost += zz_classic_term[i][j] * z_1 * z_1
return cost
# Sample expectation value
def compute_tsp_energy(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj(meas, G)
energy += obj_for_meas*meas_count
total_counts += meas_count
return energy/total_counts
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, _LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_black_box_objective(G,p):
backend = Aer.get_backend('qasm_simulator')
def f(theta):
beta = theta[:p]
gamma = theta[p:]
_lambda = _LAMBDA # get global _lambda
qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
counts = execute(qc, backend, seed_simulator=10, shots=_SHOTS).result().get_counts()
return compute_tsp_energy(invert_counts(counts),G)
return f
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
def f(theta):
beta = theta[:p]
gamma = theta[p:]
#print(beta)
_lambda = _LAMBDA # get global _lambda
qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
#print(beta)
result = execute(qc, backend, seed_simulator=10, shots=_SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
# expected value
#print("prob-dict")
#print(state_vector.probabilities_dict())
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
# get cost from state
cost = tsp_obj_2(state, G, _LAMBDA)
expected_value += cost*probability
#print(probabilities)
counts = result.get_counts()
#qc.save_statevector() # Tell simulator to save statevector
#qobj = assemble(qc) # Create a Qobj from the circuit for the simulator to run
#state_vector = sim.run(qobj).result().get_statevector()
#state_vector = Statevector(state_vector)
#probabilities = state_vector.probabilities()
mean = compute_tsp_energy_2(invert_counts(counts),G)
global _UNIFORM_CONVERGENCE_SAMPLE
_UNIFORM_CONVERGENCE_SAMPLE.append({
"beta" : beta,
"gamma" : gamma,
"counts" : counts,
"mean" : mean,
"probabilities" : probabilities,
"expected_value" : expected_value
})
return mean
return f
def compute_tsp_min_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
min = 1000000000000000000000
index = 0
min_meas = ""
for meas, meas_count in counts.items():
index = index + 1
obj_for_meas = tsp_obj_2(meas, G, _LAMBDA)
if obj_for_meas < min:
min = obj_for_meas
min_meas = meas
return index, min, min_meas
def compute_tsp_min_energy_1(counts, G):
energy = 0
get_counts = 0
total_counts = 0
min = 1000000000000000000000
index = 0
min_meas = ""
for meas, meas_count in counts.items():
index = index + 1
obj_for_meas = tsp_obj(meas, G)
if obj_for_meas < min:
min = obj_for_meas
min_meas = meas
return index, min, min_meas
def test_counts_2(counts, G):
mean_energy2 = compute_tsp_energy_2(invert_counts(counts),G)
cantidad, min, min_meas = compute_tsp_min_energy_2(invert_counts(counts),G)
print("*************************")
print("En el algoritmo 2 (Marina) el valor esperado como resultado es " + str(mean_energy2))
print("El valor minimo de todos los evaluados es " + str(min) + " se evaluaron un total de " + str(cantidad))
print("El vector minimo es " + min_meas)
def test_counts_1(counts, G):
mean_energy1 = compute_tsp_energy(invert_counts(counts),G)
cantidad, min, min_meas = compute_tsp_min_energy_1(invert_counts(counts),G)
print("*************************")
print("En el algoritmo 1 (Pablo) el valor esperado como resultado es " + str(mean_energy1))
print("El valor minimo de todos los evaluados es " + str(min) + " se evaluaron un total de " + str(cantidad))
print("El vector minimo es " + min_meas)
def test_solution(grafo=None, p=7):
global _UNIFORM_CONVERGENCE_SAMPLE
_UNIFORM_CONVERGENCE_SAMPLE = []
if grafo == None:
cantidad_ciudades = 2
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
print(mejor_costo)
print(mejor_camino)
print(G.edges())
print(G.nodes())
else:
G = grafo
# beta [0,pi], gamma [0, 2pi]
# create bounds for beta [0,pi]
bounds = []
intial_random = []
for i in range(p):
bounds.append((0, np.pi))
intial_random.append(np.random.uniform(0,np.pi))
# create bounds for gamma [0,2*pi]
for i in range(p):
bounds.append((0, np.pi * 2))
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
# Pablo Solutions
#obj = get_black_box_objective(G,p)
#res_sample_1 = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
#print(res_sample_1)
# Marina Solutions
obj = get_black_box_objective_2(G,p)
res_sample_2 = minimize(obj, init_point, method="COBYLA", options={"maxiter":2500,"disp":True})
print(res_sample_2)
#theta_1 = res_sample_1.x
theta_2 = res_sample_2.x
#beta = theta_1[:p]
#gamma = theta_1[p:]
#_lambda = _LAMBDA # get global _lambda
#qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
#backend = Aer.get_backend('qasm_simulator')
#job_1 = execute(qc, backend, shots=_SHOTS)
#resutls_1 = job_1.result().get_counts()
#test_counts_1(resutls_1, G)
beta = theta_2[:p]
gamma = theta_2[p:]
_lambda = _LAMBDA # get global _lambda
qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
backend = Aer.get_backend('qasm_simulator')
job_2 = execute(qc, backend, shots=_SHOTS)
resutls_2 = job_2.result().get_counts()
test_counts_2(resutls_2, G)
#print( _UNIFORM_CONVERGENCE_SAMPLE)
return job_2, G, _UNIFORM_CONVERGENCE_SAMPLE
def create_multiple_p_mismo_grafo():
header = ['p', 'state', 'probability', 'mean']
length_p = 10
with open('qaoa_multiple_p.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
first_p = False
UNIFORM_CONVERGENCE_SAMPLE = []
for p in range(length_p):
p = p+1
if first_p == False:
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p)
first_p = True
else:
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p)
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
mean = UNIFORM_CONVERGENCE_SAMPLE[0]["mean"]
print(mean)
state = 0
for probability in UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"]:
state += 1
writer.writerow([p,state, probability,mean])
def create_multiple_p_mismo_grafo_multiples_instanncias():
header = ['instance','p','distance', 'mean']
length_p = 4
length_instances = 10
with open('qaoa_multiple_p_distance.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
instance_index = 0
for instance in range(length_instances):
instance_index += 1
first_p = False
UNIFORM_CONVERGENCE_P = []
UNIFORM_CONVERGENCE_SAMPLE = []
for p in range(length_p):
p = p+1
print("p es igual " + str(p))
if first_p == False:
print("Vuelve a llamar a test_solution")
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p)
first_p = True
else:
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p)
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["expected_value"])
convergence_min = UNIFORM_CONVERGENCE_SAMPLE[0]
UNIFORM_CONVERGENCE_P.append({
"mean":convergence_min["expected_value"],
"probabilities": convergence_min["probabilities"]
})
print("expected value min con p =" + str(p) + " : " + str(convergence_min["expected_value"]))
cauchy_function_nk = UNIFORM_CONVERGENCE_P[len(UNIFORM_CONVERGENCE_P) - 1]
p_index = 0
for p_state in UNIFORM_CONVERGENCE_P:
p_index += 1
print(p_index)
mean = p_state["mean"]
#print(p_state)
print("expected value min")
print(mean)
distance_p_cauchy_function_nk = np.max(np.abs(cauchy_function_nk["probabilities"] - p_state["probabilities"]))
writer.writerow([instance_index, p_index, distance_p_cauchy_function_nk, mean])
if __name__ == '__main__':
#create_multiple_p_mismo_grafo()
create_multiple_p_mismo_grafo_multiples_instanncias()
def defult_init():
cantidad_ciudades = 2
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
print(mejor_costo)
print(mejor_camino)
print(G.edges())
print(G.nodes())
print("labels")
labels = nx.get_edge_attributes(G,'weight')
#z_term, zz_term = get_classical_simplified_hamiltonian(G, 1)
#print("z term")
#print(z_term)
#print("*****************")
#print("zz term")
#print(zz_term)
#print(get_QAOA_circuit(G, beta = [2,3], gamma = [4,5], _lambda = 1))
p = 5
obj = get_black_box_objective(G,p)
init_point = np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1])
#res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
#print(res_sample)
# Marina Solutions
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
theta_2 = [0.72685401, 2.15678239, 0.86389827, 2.19403121, 0.26916675, 2.19832144, 7.06651453, 3.20333137, 3.81301611, 6.08893568]
theta_1 = [0.90644898, 2.15994212, 1.8609325 , 2.14042604, 1.49126214, 2.4127999, 6.10529434, 2.18238732, 3.84056674, 6.07097744]
beta = theta_1[:p]
gamma = theta_1[p:]
_lambda = _LAMBDA # get global _lambda
qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend)
print(plot_histogram(job.result().get_counts(), color='midnightblue', title="New Histogram"))
beta = theta_2[:p]
gamma = theta_2[p:]
_lambda = _LAMBDA # get global _lambda
qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend)
print(plot_histogram(job.result().get_counts(), color='midnightblue', title="New Histogram"))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Tests for Choi quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators.channel import Choi
from .channel_test_case import ChannelTestCase
class TestChoi(ChannelTestCase):
"""Tests for Choi channel representation."""
def test_init(self):
"""Test initialization"""
mat4 = np.eye(4) / 2.0
chan = Choi(mat4)
assert_allclose(chan.data, mat4)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
mat8 = np.eye(8) / 2.0
chan = Choi(mat8, input_dims=4)
assert_allclose(chan.data, mat8)
self.assertEqual(chan.dim, (4, 2))
self.assertIsNone(chan.num_qubits)
chan = Choi(mat8, input_dims=2)
assert_allclose(chan.data, mat8)
self.assertEqual(chan.dim, (2, 4))
self.assertIsNone(chan.num_qubits)
mat16 = np.eye(16) / 4
chan = Choi(mat16)
assert_allclose(chan.data, mat16)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan.num_qubits, 2)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Choi, mat8, input_dims=[4], output_dims=[4])
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Choi(circuit)
target = Choi(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Choi, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(4, 4)
self.assertEqual(Choi(mat), Choi(mat))
def test_copy(self):
"""Test copy method"""
mat = np.eye(2)
with self.subTest("Deep copy"):
orig = Choi(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Choi(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = Choi(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Choi(self.depol_choi(0.25)).is_cptp())
# Non-CPTP should return false
self.assertFalse(Choi(1.25 * self.choiI - 0.25 * self.depol_choi(1)).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
# Test channel measures in Z basis and prepares in Y basis
# Zp -> Yp, Zm -> Ym
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2
chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym))
# Conjugate channel swaps Y-basis states
targ = Choi(np.kron(Zp, Ym) + np.kron(Zm, Yp))
chan_conj = chan.conjugate()
self.assertEqual(chan_conj, targ)
def test_transpose(self):
"""Test transpose method."""
# Test channel measures in Z basis and prepares in Y basis
# Zp -> Yp, Zm -> Ym
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2
chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym))
# Transpose channel swaps basis
targ = Choi(np.kron(Yp, Zp) + np.kron(Ym, Zm))
chan_t = chan.transpose()
self.assertEqual(chan_t, targ)
def test_adjoint(self):
"""Test adjoint method."""
# Test channel measures in Z basis and prepares in Y basis
# Zp -> Yp, Zm -> Ym
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2
chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym))
# Ajoint channel swaps Y-basis elements and Z<->Y bases
targ = Choi(np.kron(Ym, Zp) + np.kron(Yp, Zm))
chan_adj = chan.adjoint()
self.assertEqual(chan_adj, targ)
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Choi(np.eye(4)).compose, Choi(np.eye(8)))
self.assertRaises(QiskitError, Choi(np.eye(4)).compose, 2)
def test_compose(self):
"""Test compose method."""
# UnitaryChannel evolution
chan1 = Choi(self.choiX)
chan2 = Choi(self.choiY)
chan = chan1.compose(chan2)
targ = Choi(self.choiZ)
self.assertEqual(chan, targ)
# 50% depolarizing channel
chan1 = Choi(self.depol_choi(0.5))
chan = chan1.compose(chan1)
targ = Choi(self.depol_choi(0.75))
self.assertEqual(chan, targ)
# Measure and rotation
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2
chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
chan2 = Choi(self.choiX)
# X-gate second does nothing
targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
self.assertEqual(chan1.compose(chan2), targ)
self.assertEqual(chan1 & chan2, targ)
# X-gate first swaps Z states
targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm))
self.assertEqual(chan2.compose(chan1), targ)
self.assertEqual(chan2 & chan1, targ)
# Compose different dimensions
chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4)
chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2)
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
chan = chan2.compose(chan1)
self.assertEqual(chan.dim, (4, 4))
def test_dot(self):
"""Test dot method."""
# UnitaryChannel evolution
chan1 = Choi(self.choiX)
chan2 = Choi(self.choiY)
targ = Choi(self.choiZ)
self.assertEqual(chan1.dot(chan2), targ)
self.assertEqual(chan1 @ chan2, targ)
# 50% depolarizing channel
chan1 = Choi(self.depol_choi(0.5))
targ = Choi(self.depol_choi(0.75))
self.assertEqual(chan1.dot(chan1), targ)
self.assertEqual(chan1 @ chan1, targ)
# Measure and rotation
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2
chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
chan2 = Choi(self.choiX)
# X-gate second does nothing
targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
self.assertEqual(chan2.dot(chan1), targ)
self.assertEqual(chan2 @ chan1, targ)
# X-gate first swaps Z states
targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm))
self.assertEqual(chan1.dot(chan2), targ)
self.assertEqual(chan1 @ chan2, targ)
# Compose different dimensions
chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4)
chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2)
chan = chan1.dot(chan2)
self.assertEqual(chan.dim, (4, 4))
chan = chan1 @ chan2
self.assertEqual(chan.dim, (4, 4))
chan = chan2.dot(chan1)
self.assertEqual(chan.dim, (2, 2))
chan = chan2 @ chan1
self.assertEqual(chan.dim, (2, 2))
def test_compose_front(self):
"""Test front compose method."""
# UnitaryChannel evolution
chan1 = Choi(self.choiX)
chan2 = Choi(self.choiY)
chan = chan1.compose(chan2, front=True)
targ = Choi(self.choiZ)
self.assertEqual(chan, targ)
# 50% depolarizing channel
chan1 = Choi(self.depol_choi(0.5))
chan = chan1.compose(chan1, front=True)
targ = Choi(self.depol_choi(0.75))
self.assertEqual(chan, targ)
# Measure and rotation
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2
chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
chan2 = Choi(self.choiX)
# X-gate second does nothing
chan = chan2.compose(chan1, front=True)
targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
self.assertEqual(chan, targ)
# X-gate first swaps Z states
chan = chan1.compose(chan2, front=True)
targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm))
self.assertEqual(chan, targ)
# Compose different dimensions
chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4)
chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2)
chan = chan1.compose(chan2, front=True)
self.assertEqual(chan.dim, (4, 4))
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Choi(self.choiI)
chan2 = Choi(self.choiX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = Choi(self.depol_choi(1))
chan = chan_dep.expand(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Choi(self.choiI)
chan2 = Choi(self.choiX)
# X \otimes I
rho_targ = DensityMatrix(np.kron(rho1, rho0))
chan = chan2.tensor(chan1)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan2 ^ chan1
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
rho_targ = DensityMatrix(np.kron(rho0, rho1))
chan = chan1.tensor(chan2)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 ^ chan2
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
chan_dep = Choi(self.depol_choi(1))
chan = chan_dep.tensor(chan_dep)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan_dep ^ chan_dep
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
p_id = 0.9
depol = Choi(self.depol_choi(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = depol.power(3)
targ3 = Choi(self.depol_choi(1 - p_id3))
self.assertEqual(chan3, targ3)
def test_add(self):
"""Test add method."""
mat1 = 0.5 * self.choiI
mat2 = 0.5 * self.depol_choi(1)
chan1 = Choi(mat1)
chan2 = Choi(mat2)
targ = Choi(mat1 + mat2)
self.assertEqual(chan1._add(chan2), targ)
self.assertEqual(chan1 + chan2, targ)
targ = Choi(mat1 - mat2)
self.assertEqual(chan1 - chan2, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = Choi(mat)
op0 = Choi(mat0)
op1 = Choi(mat1)
op01 = op1.tensor(op0)
eye = Choi(self.choiI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = Choi(mat)
op0 = Choi(mat0)
op1 = Choi(mat1)
op01 = op1.tensor(op0)
eye = Choi(self.choiI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_add_except(self):
"""Test add method raises exceptions."""
chan1 = Choi(self.choiI)
chan2 = Choi(np.eye(8))
self.assertRaises(QiskitError, chan1._add, chan2)
self.assertRaises(QiskitError, chan1._add, 5)
def test_multiply(self):
"""Test multiply method."""
chan = Choi(self.choiI)
val = 0.5
targ = Choi(val * self.choiI)
self.assertEqual(chan._multiply(val), targ)
self.assertEqual(val * chan, targ)
targ = Choi(self.choiI * val)
self.assertEqual(chan * val, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Choi(self.choiI)
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
chan = Choi(self.choiI)
targ = Choi(-1 * self.choiI)
self.assertEqual(-chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for the wrapper functionality."""
import sys
import unittest
from unittest.mock import patch
from unittest.mock import MagicMock
from io import StringIO
import qiskit
from qiskit import providers
from qiskit.tools.monitor import backend_overview, backend_monitor
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeProviderFactory, FakeBackend, FakeVigo
class TestBackendOverview(QiskitTestCase):
"""Tools test case."""
def _restore_ibmq(self):
if not self.import_error:
qiskit.IBMQ = self.ibmq_back
else:
del qiskit.IBMQ
if self.prov_backup:
providers.ibmq = self.prov_backup
else:
del providers.ibmq
def _restore_ibmq_mod(self):
if self.ibmq_module_backup is not None:
sys.modules["qiskit.providers.ibmq"] = self.ibmq_module_backup
else:
sys.modules.pop("qiskit.providers.ibmq")
def setUp(self):
super().setUp()
ibmq_mock = MagicMock()
ibmq_mock.IBMQBackend = FakeBackend
if "qiskit.providers.ibmq" in sys.modules:
self.ibmq_module_backup = sys.modules["qiskit.providers.ibmq"]
else:
self.ibmq_module_backup = None
sys.modules["qiskit.providers.ibmq"] = ibmq_mock
self.addCleanup(self._restore_ibmq_mod)
if hasattr(qiskit, "IBMQ"):
self.import_error = False
else:
self.import_error = True
qiskit.IBMQ = None
self.ibmq_back = qiskit.IBMQ
qiskit.IBMQ = FakeProviderFactory()
self.addCleanup(self._restore_ibmq)
if hasattr(providers, "ibmq"):
self.prov_backup = providers.ibmq
else:
self.prov_backup = None
providers.ibmq = MagicMock()
@patch("qiskit.tools.monitor.overview.get_unique_backends", return_value=[FakeVigo()])
def test_backend_overview(self, _):
"""Test backend_overview"""
with patch("sys.stdout", new=StringIO()) as fake_stdout:
backend_overview()
stdout = fake_stdout.getvalue()
self.assertIn("Operational:", stdout)
self.assertIn("Avg. T1:", stdout)
self.assertIn("Num. Qubits:", stdout)
@patch("qiskit.tools.monitor.overview.get_unique_backends", return_value=[FakeVigo()])
def test_backend_monitor(self, _):
"""Test backend_monitor"""
for back in [FakeVigo()]:
if not back.configuration().simulator:
backend = back
break
with patch("sys.stdout", new=StringIO()) as fake_stdout:
backend_monitor(backend)
stdout = fake_stdout.getvalue()
self.assertIn("Configuration", stdout)
self.assertIn("Qubits [Name / Freq / T1 / T2 / ", stdout)
for gate in backend.properties().gates:
if gate.gate not in ["id"] and len(gate.qubits) == 1:
self.assertIn(gate.gate.upper() + " err", stdout)
self.assertIn("Readout err", stdout)
self.assertIn("Multi-Qubit Gates [Name / Type / Gate Error]", stdout)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/agaviniv/qaoa-maxcut-qiskit
|
agaviniv
|
from qiskit import Aer, IBMQ, execute
from qiskit import transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
from qiskit.visualization import plot_histogram, plot_state_city
"""
Qiskit backends to execute the quantum circuit
"""
def simulator(qc):
"""
Run on local simulator
:param qc: quantum circuit
:return:
"""
backend = Aer.get_backend("qasm_simulator")
shots = 2048
tqc = transpile(qc, backend)
qobj = assemble(tqc, shots=shots)
job_sim = backend.run(qobj)
qc_results = job_sim.result()
return qc_results, shots
def simulator_state_vector(qc):
"""
Select the StatevectorSimulator from the Aer provider
:param qc: quantum circuit
:return:
statevector
"""
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(qc, simulator).result()
state_vector = result.get_statevector(qc)
return state_vector
def real_quantum_device(qc):
"""
Use the IBMQ essex device
:param qc: quantum circuit
:return:
"""
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_santiago')
shots = 2048
TQC = transpile(qc, backend)
qobj = assemble(TQC, shots=shots)
job_exp = backend.run(qobj)
job_monitor(job_exp)
QC_results = job_exp.result()
return QC_results, shots
def counts(qc_results):
"""
Get counts representing the wave-function amplitudes
:param qc_results:
:return: dict keys are bit_strings and their counting values
"""
return qc_results.get_counts()
def plot_results(qc_results):
"""
Visualizing wave-function amplitudes in a histogram
:param qc_results: quantum circuit
:return:
"""
plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False))
def plot_state_vector(state_vector):
"""Visualizing state vector in the density matrix representation"""
plt.show(plot_state_city(state_vector))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
state = Statevector(qc)
plot_bloch_multivector(state)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
from qiskit import QuantumCircuit, Aer, execute
from math import pi, sin
from qiskit.compiler import transpile, assemble
from grover_operator import GroverOperator
def qft(n): # returns circuit for inverse quantum fourier transformation for given n
circuit = QuantumCircuit(n)
def swap_registers(circuit, n):
for qubit in range(n // 2):
circuit.swap(qubit, n - qubit - 1)
return circuit
def qft_rotations(circuit, n):
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi / 2 ** (n - qubit), qubit, n)
qft_rotations(circuit, n)
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
class PhaseEstimation:
def get_control_gft(self, label="QFT †"):
qft_dagger = self.qft_circuit.to_gate().inverse()
qft_dagger.label = label
return qft_dagger
def get_main_circuit(self):
qc = QuantumCircuit(self.c_bits + self.s_bits, self.c_bits) # Circuit with n+t qubits and t classical bits
# Initialize all qubits to |+>
qc.h(range(self.c_bits + self.n_bits))
qc.h(self.c_bits + self.s_bits - 1)
qc.z(self.c_bits + self.s_bits - 1)
# Begin controlled Grover iterations
iterations = 1
for qubit in range(self.c_bits):
for i in range(iterations):
qc.append(self.c_grover, [qubit] + [*range(self.c_bits, self.s_bits + self.c_bits)])
iterations *= 2
# Do inverse QFT on counting qubits
qc.append(self.c_qft, range(self.c_bits))
# Measure counting qubits
qc.measure(range(self.c_bits), range(self.c_bits))
return qc
def simulate(self):
aer_sim = Aer.get_backend('aer_simulator')
transpiled_qc = transpile(self.main_circuit, aer_sim)
qobj = assemble(transpiled_qc)
job = aer_sim.run(qobj)
hist = job.result().get_counts()
# plot_histogram(hist)
measured_int = int(max(hist, key=hist.get), 2)
theta = (measured_int / (2 ** self.c_bits)) * pi * 2
N = 2 ** self.n_bits
M = N * (sin(theta / 2) ** 2)
# print(N - M, round(N - M))
return round(N - M)
def __init__(self, grover: GroverOperator, c_bits=5):
self.c_grover = grover.get_control_circuit()
self.c_bits = c_bits
self.n_bits = grover.n_bits
self.s_bits = grover.total_bits
self.qft_circuit = qft(c_bits)
self.c_qft = self.get_control_gft()
self.main_circuit = self.get_main_circuit()
self.M = self.simulate()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Maximum-Likelihood estimation quantum tomography fitter
"""
import logging
import itertools as it
from ast import literal_eval
import numpy as np
from qiskit import QiskitError
from qiskit import QuantumCircuit
from ..basis import TomographyBasis, default_basis
from ..data import marginal_counts, combine_counts, count_keys
from .cvx_fit import cvxpy, cvx_fit
from .lstsq_fit import lstsq_fit
# Create logger
logger = logging.getLogger(__name__)
class TomographyFitter:
"""Basse maximum-likelihood estimate tomography fitter class"""
def __init__(self,
result,
circuits,
meas_basis='Pauli',
prep_basis='Pauli'):
"""Initialize tomography fitter with experimental data.
Args:
result (Result): a Qiskit Result object obtained from executing
tomography circuits.
circuits (list): a list of circuits or circuit names to extract
count information from the result object.
meas_basis (TomographyBasis, str): A function to return
measurement operators corresponding to measurement
outcomes. See Additional Information
(default: 'Pauli')
prep_basis (TomographyBasis, str): A function to return
preparation operators. See Additional
Information (default: 'Pauli')
"""
# Set the measure and prep basis
self._meas_basis = None
self._prep_basis = None
self.set_measure_basis(meas_basis)
self.set_preparation_basis(prep_basis)
# Add initial data
self._data = {}
self.add_data(result, circuits)
def set_measure_basis(self, basis):
"""Set the measurement basis
Args:
basis (TomographyBasis or str): measurement basis
"""
self._meas_basis = default_basis(basis)
if isinstance(self._meas_basis, TomographyBasis):
if self._meas_basis.measurement is not True:
raise QiskitError("Invalid measurement basis")
def set_preparation_basis(self, basis):
"""Set the prepearation basis function
Args:
basis (TomographyBasis or str): preparation basis
"""
self._prep_basis = default_basis(basis)
if isinstance(self._prep_basis, TomographyBasis):
if self._prep_basis.preparation is not True:
raise QiskitError("Invalid preparation basis")
@property
def measure_basis(self):
"""Return the tomography measurement basis."""
return self._meas_basis
@property
def preparation_basis(self):
"""Return the tomography preperation basis."""
return self._prep_basis
def fit(self, method='auto', standard_weights=True, beta=0.5, **kwargs):
"""
Reconstruct a quantum state using CVXPY convex optimization.
Args:
method (str): The fitter method 'auto', 'cvx' or 'lstsq'.
standard_weights (bool, optional): Apply weights to
tomography data
based on count probability
(default: True)
beta (float): hedging parameter for converting counts
to probabilities
(default: 0.5)
PSD (bool, optional): Enforced the fitted matrix to be positive
semidefinite (default: True)
trace (int, optional): trace constraint for the fitted matrix
(default: None).
trace_preserving (bool, optional): Enforce the fitted matrix to be
trace preserving when fitting a Choi-matrix in quantum process
tomography. Note this method does not apply for 'lstsq' fitter
method (default: False).
**kwargs (optional): kwargs for fitter method.
Returns:
The fitted matrix rho that minimizes
||basis_matrix * vec(rho) - data||_2.
Additional Information:
Fitter method
-------------
The 'cvx' fitter method used CVXPY convex optimization package.
The 'lstsq' method uses least-squares fitting (linear inversion).
The 'auto' method will use 'cvx' if the CVXPY package is found on
the system, otherwise it will default to 'lstsq'.
Objective function
------------------
This fitter solves the constrained least-squares minimization:
minimize: ||a * x - b ||_2
subject to: x >> 0 (PSD, optional)
trace(x) = t (trace, optional)
partial_trace(x) = identity (trace_preserving,
optional)
where:
a is the matrix of measurement operators a[i] = vec(M_i).H
b is the vector of expectation value data for each projector
b[i] ~ Tr[M_i.H * x] = (a * x)[i]
x is the vectorized density matrix (or Choi-matrix)
to be fitted
PSD constraint
--------------
The PSD keyword constrains the fitted matrix to be
postive-semidefinite.
For the 'lstsq' fitter method the fitted matrix is rescaled
using the method proposed in Reference [1].
For the 'cvx' fitter method the convex constraint makes the
optimization problem a SDP. If PSD=False the fitted matrix
will still
be constrained to be Hermitian, but not PSD. In this case the
optimization problem becomes a SOCP.
Trace constraint
----------------
The trace keyword constrains the trace of the fitted matrix. If
trace=None there will be no trace constraint on the fitted matrix.
This constraint should not be used for process tomography and the
trace preserving constraint should be used instead.
Trace preserving (TP) constraint
--------------------------------
The trace_preserving keyword constrains the fitted matrix
to be TP. This should only be used for process tomography,
not state tomography.
Note that the TP constraint implicitly enforces
the trace of the fitted
matrix to be equal to the square-root of the matrix dimension.
If a trace constraint is also specified that
differs from this value the fit
will likely fail. Note that this can only be used
for the CVX method.
CVXPY Solvers:
-------
Various solvers can be called in CVXPY using the `solver` keyword
argument. Solvers included in CVXPY are:
'CVXOPT': SDP and SOCP (default solver)
'SCS' : SDP and SOCP
'ECOS' : SOCP only
See the documentation on CVXPY for more information on solvers.
References:
[1] J Smolin, JM Gambetta, G Smith, Phys. Rev. Lett. 108, 070502
(2012). Open access: arXiv:1106.5458 [quant-ph].
"""
# Get fitter data
data, basis_matrix, weights = self._fitter_data(standard_weights,
beta)
# Choose automatic method
if method == 'auto':
if cvxpy is None:
method = 'lstsq'
else:
method = 'cvx'
if method == 'lstsq':
return lstsq_fit(data, basis_matrix, weights=weights, **kwargs)
if method == 'cvx':
return cvx_fit(data, basis_matrix, weights=weights, **kwargs)
raise QiskitError('Unrecognised fit method {}'.format(method))
@property
def data(self):
"""
Return tomography data
"""
return self._data
def add_data(self, result, circuits):
"""Add tomography data from a Qiskit Result object.
Args:
result (Result): a Qiskit Result object obtained from executing
tomography circuits.
circuits (list): a list of circuits or circuit names to extract
count information from the result object.
"""
if len(circuits[0].cregs) == 1:
marginalize = False
else:
marginalize = True
# Process measurement counts into probabilities
for circ in circuits:
counts = result.get_counts(circ)
if isinstance(circ, str):
tup = literal_eval(circ)
elif isinstance(circ, QuantumCircuit):
tup = literal_eval(circ.name)
else:
tup = circ
if marginalize:
counts = marginal_counts(counts, range(len(tup[0])))
if tup in self._data:
self._data[tup] = combine_counts(self._data[tup], counts)
else:
self._data[tup] = counts
def _fitter_data(self, standard_weights, beta):
"""Generate tomography fitter data from a tomography data dictionary.
Args:
standard_weights (bool, optional): Apply weights to basis matrix
and data based on count probability
(default: True)
beta (float): hedging parameter for 0, 1
probabilities (default: 0.5)
Returns:
tuple: (data, basis_matrix, weights) where `data`
is a vector of the
probability values, and `basis_matrix`
is a matrix of the preparation
and measurement operator, and `weights`
is a vector of weights for the
given probabilities.
Additional Information
----------------------
standard_weights:
Weights are calculated from from binomial distribution standard
deviation
"""
# Get basis matrix functions
if self._meas_basis:
measurement = self._meas_basis.measurement_matrix
else:
measurement = None
if self._prep_basis:
preparation = self._prep_basis.preparation_matrix
else:
preparation = None
data = []
basis_blocks = []
if standard_weights:
weights = []
else:
weights = None
# Check if input data is state or process tomography data based
# on the label tuples
label = next(iter(self._data))
is_qpt = (isinstance(label, tuple) and len(label) == 2 and
isinstance(label[0], tuple) and isinstance(label[1], tuple))
# Generate counts keys for converting to np array
if is_qpt:
ctkeys = count_keys(len(label[1]))
else:
ctkeys = count_keys(len(label))
for label, cts in self._data.items():
# Convert counts dict to numpy array
if isinstance(cts, dict):
cts = np.array([cts.get(key, 0) for key in ctkeys])
# Get probabilities
shots = np.sum(cts)
probs = np.array(cts) / shots
data += list(probs)
# Compute binomial weights
if standard_weights is True:
wts = self._binomial_weights(cts, beta)
weights += list(wts)
# Get reconstruction basis operators
if is_qpt:
prep_label = label[0]
meas_label = label[1]
else:
prep_label = None
meas_label = label
prep_op = self._preparation_op(prep_label, preparation)
meas_ops = self._measurement_ops(meas_label, measurement)
block = self._basis_operator_matrix(
[np.kron(prep_op.T, mop) for mop in meas_ops])
basis_blocks.append(block)
return data, np.vstack(basis_blocks), weights
def _binomial_weights(self, counts, beta=0.5):
"""
Compute binomial weights for list or dictionary of counts.
Args:
counts (dict, vector): A set of measurement counts for
all outcomes of a given measurement
configuration.
beta (float >= 0): A hedging parameter used to bias probabilities
computed from input counts away from 0 or 1.
Returns:
A numpy array of binomial weights for the input counts and beta
parameter.
Additional Information:
The weights are determined by
w[i] = sqrt(shots / p[i] * (1 - p[i]))
p[i] = (counts[i] + beta) / (shots + K * beta)
where
`shots` is the sum of all counts in the input
`p` is the hedged probability computed for a count
`K` is the total number of possible measurement outcomes.
"""
# Sort counts if input is a dictionary
if isinstance(counts, dict):
mcts = marginal_counts(counts, pad_zeros=True)
ordered_keys = sorted(list(mcts))
counts = np.array([mcts[k] for k in ordered_keys])
# Assume counts are already sorted if a list
else:
counts = np.array(counts)
shots = np.sum(counts)
# If beta is 0 check if we would be dividing by zero
# If so change beta value and log warning.
if beta < 0:
raise ValueError('beta = {} must be non-negative.'.format(beta))
if beta == 0 and (shots in counts or 0 in counts):
beta = 0.5
msg = ("Counts result in probabilities of 0 or 1 "
"in binomial weights "
"calculation. Setting hedging "
"parameter beta={} to prevent "
"dividing by zero.".format(beta))
logger.warning(msg)
K = len(counts) # Number of possible outcomes.
# Compute hedged frequencies which are shifted to never be 0 or 1.
freqs_hedged = (counts + beta) / (shots + K * beta)
# Return gaussian weights for 2-outcome measurements.
return np.sqrt(shots / (freqs_hedged * (1 - freqs_hedged)))
def _basis_operator_matrix(self, basis):
"""
Return a basis measurement matrix of the input basis.
Args:
basis (list (array like)): a list of basis matrices.
Returns:
A numpy array of shape (n, col * row) where n is the number
of operators of shape (row, col) in `basis`.
"""
# Dimensions
num_ops = len(basis)
nrows, ncols = basis[0].shape
size = nrows * ncols
ret = np.zeros((num_ops, size), dtype=complex)
for j, b in enumerate(basis):
ret[j] = np.array(b).reshape((1, size), order='F').conj()
return ret
def _preparation_op(self, label, prep_matrix_fn):
"""
Return the multi-qubit matrix for a state preparation label.
Args:
label (tuple(str)): a preparation configuration label for a
tomography circuit.
prep_matrix_fn (function): a function that returns the matrix
corresponding to a single qubit preparation label.
The functions should have signature
prep_matrix_fn(str) -> np.array
Returns:
A Numpy array for the multi-qubit prepration operator specified
by label.
Additional Information:
See the Pauli and SIC-POVM preparation functions
`pauli_preparation_matrix` and `sicpovm_preparation_matrix` for
examples.
"""
# Trivial case
if label is None:
return np.eye(1, dtype=complex)
# Construct preparation matrix
op = np.eye(1, dtype=complex)
for l in label:
op = np.kron(prep_matrix_fn(l), op)
return op
def _measurement_ops(self, label, meas_matrix_fn):
"""
Return a list multi-qubit matrices for a measurement label.
Args:
label (tuple(str)): a measurement configuration label for a
tomography circuit.
meas_matrix_fn (function): a function that returns the matrix
corresponding to a single qubit measurement label
for a given outcome. The functions should have
signature meas_matrix_fn(str, int) -> np.array
Returns:
A list of Numpy array for the multi-qubit measurement operators
for all measurement outcomes for the measurement basis specified
by the label. These are ordered in increasing binary order. Eg for
2-qubits the returned matrices correspond to outcomes
[00, 01, 10, 11]
Additional Information:
See the Pauli measurement function `pauli_measurement_matrix`
for an example.
"""
num_qubits = len(label)
meas_ops = []
# Construct measurement POVM for all measurement outcomes for a given
# measurement label. This will be a list of 2 ** n operators.
for l in sorted(it.product((0, 1), repeat=num_qubits)):
op = np.eye(1, dtype=complex)
# Reverse label to correspond to QISKit bit ordering
for m, outcome in zip(reversed(label), l):
op = np.kron(op, meas_matrix_fn(m, outcome))
meas_ops.append(op)
return meas_ops
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
from qiskit.aqua.algorithms import Shor
from qiskit.aqua import QuantumInstance
import numpy as np
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1000)
my_shor=Shor(N=15, a=2, quantum_instance=quantum_instance)
Shor.run(my_shor)
def c_amod15(a,power):
U = QuantumCircuit(4)
for iteration in range(power):
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
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
a = 7
def qft_dagger(n):
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.cu1(-np.pi/float(2**(j-m)),m,j)
qc.h(j)
qc.name="QFT dagger"
return qc
# bringing it all together
qc = QuantumCircuit(n_count +4, n_count)
for q in range(n_count):
qc.h(q)
qc.x(3+n_count)
#MOdular expo
for q in range(n_count):
qc.append(c_amod15(a,2**q), [q]+[i+n_count for i in range(4)])
#QFT
qc.append(qft_dagger(n_count),range(n_count))
#Measure ckt
qc.measure(range(n_count),range(n_count))
qc.draw('text')
backend = Aer.get_backend('qasm_simulator')
results = execute(qc, backend, shots = 2048).result()
counts = results.get_counts()
plot_histogram(counts)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# Copyright 2022-2023 Ohad Lev.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0,
# or in the root directory of this package("LICENSE.txt").
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
`SATInterface` class.
"""
import os
import json
from typing import List, Tuple, Union, Optional, Dict, Any
from sys import stdout
from datetime import datetime
from hashlib import sha256
from qiskit import transpile, QuantumCircuit, qpy
from qiskit.result.counts import Counts
from qiskit.visualization.circuit.text import TextDrawing
from qiskit.providers.backend import Backend
from qiskit.transpiler.passes import RemoveBarriers
from IPython import display
from matplotlib.figure import Figure
from sat_circuits_engine.util import timer_dec, timestamp, flatten_circuit
from sat_circuits_engine.util.settings import DATA_PATH, TRANSPILE_KWARGS
from sat_circuits_engine.circuit import GroverConstraintsOperator, SATCircuit
from sat_circuits_engine.constraints_parse import ParsedConstraints
from sat_circuits_engine.interface.circuit_decomposition import decompose_operator
from sat_circuits_engine.interface.counts_visualization import plot_histogram
from sat_circuits_engine.interface.translator import ConstraintsTranslator
from sat_circuits_engine.classical_processing import (
find_iterations_unknown,
calc_iterations,
ClassicalVerifier,
)
from sat_circuits_engine.interface.interactive_inputs import (
interactive_operator_inputs,
interactive_solutions_num_input,
interactive_run_input,
interactive_backend_input,
interactive_shots_input,
)
# Local globlas for visualization of charts and diagrams
IFRAME_WIDTH = "100%"
IFRAME_HEIGHT = "700"
class SATInterface:
"""
An interface for building, running and mining data from n-SAT problems quantum circuits.
There are 2 options to use this class:
(1) Using an interactive interface (intuitive but somewhat limited) - for this
just initiate a bare instance of this class: `SATInterface()`.
(2) Using the API defined by this class, that includes the following methods:
* The following descriptions are partial, for full annotations see the methods' docstrings.
- `__init__`: an instance of `SATInterface must be initiated with exactly 1 combination:
(a) (high_level_constraints_string + high_level_vars) - for constraints
in a high-level format.
(b) (num_input_qubits + constraints_string) - for constraints
in a low-level foramt.
* For formats annotations see `constriants_format.ipynb` in the main directory.
- `obtain_grover_operator`: obtains the suitable grover operator for the constraints.
- `save_display_grover_operator`: saves and displays data generated
by the `obtain_grover_operator` method.
- `obtain_overall_circuit`: obtains the suitable overall SAT circuit.
- `save_display_overall_circuit: saves and displays data generated
by the `obtain_overall_circuit` method.
- `run_overall_circuit`: executes the overall SAT circuit.
- `save_display_results`: saves and displays data generated
by the `run_overall_circuit` method.
It is very recommended to go through `demos.ipynb` that demonstrates the various optional uses
of this class, in addition to reading `constraints_format.ipynb`, which is a must for using
this package properly. Both notebooks are in ther main directory.
"""
def __init__(
self,
num_input_qubits: Optional[int] = None,
constraints_string: Optional[str] = None,
high_level_constraints_string: Optional[str] = None,
high_level_vars: Optional[Dict[str, int]] = None,
name: Optional[str] = None,
save_data: Optional[bool] = True,
) -> None:
"""
Accepts the combination of paramters:
(high_level_constraints_string + high_level_vars) or (num_input_qubits + constraints_string).
Exactly one combination is accepted.
In other cases either an iteractive user interface will be called to take user's inputs,
or an exception will be raised due to misuse of the API.
Args:
num_input_qubits (Optional[int] = None): number of input qubits.
constraints_string (Optional[str] = None): a string of constraints in a low-level format.
high_level_constraints_string (Optional[str] = None): a string of constraints in a
high-level format.
high_level_vars (Optional[Dict[str, int]] = None): a dictionary that configures
the high-level variables - keys are names and values are bits-lengths.
name (Optional[str] = None): a name for this object, if None than the
generic name "SAT" is given automatically.
save_data (Optional[bool] = True): if True, saves all data and metadata generated by this
class to a unique data folder (by using the `save_XXX` methods of this class).
Raises:
SyntaxError - if a forbidden combination of arguments has been provided.
"""
if name is None:
name = "SAT"
self.name = name
# Creating a directory for data to be saved
if save_data:
self.time_created = timestamp(datetime.now())
self.dir_path = f"{DATA_PATH}{self.time_created}_{self.name}/"
os.mkdir(self.dir_path)
print(f"Data will be saved into '{self.dir_path}'.")
# Initial metadata, more to be added by this class' `save_XXX` methods
self.metadata = {
"name": self.name,
"datetime": self.time_created,
"num_input_qubits": num_input_qubits,
"constraints_string": constraints_string,
"high_level_constraints_string": high_level_constraints_string,
"high_level_vars": high_level_vars,
}
self.update_metadata()
# Identifying user's platform, for visualization purposes
self.identify_platform()
# In the case of low-level constraints format, that is the default value
self.high_to_low_map = None
# Case A - interactive interface
if (num_input_qubits is None or constraints_string is None) and (
high_level_constraints_string is None or high_level_vars is None
):
self.interactive_interface()
# Case B - API
else:
self.high_level_constraints_string = high_level_constraints_string
self.high_level_vars = high_level_vars
# Case B.1 - high-level format constraints inputs
if num_input_qubits is None or constraints_string is None:
self.num_input_qubits = sum(self.high_level_vars.values())
self.high_to_low_map, self.constraints_string = ConstraintsTranslator(
self.high_level_constraints_string, self.high_level_vars
).translate()
# Case B.2 - low-level format constraints inputs
elif num_input_qubits is not None and constraints_string is not None:
self.num_input_qubits = num_input_qubits
self.constraints_string = constraints_string
# Misuse
else:
raise SyntaxError(
"SATInterface accepts the combination of paramters:"
"(high_level_constraints_string + high_level_vars) or "
"(num_input_qubits + constraints_string). "
"Exactly one combination is accepted, not both."
)
self.parsed_constraints = ParsedConstraints(
self.constraints_string, self.high_level_constraints_string
)
def update_metadata(self, update_metadata: Optional[Dict[str, Any]] = None) -> None:
"""
Updates the metadata file (in the unique data folder of a given `SATInterface` instance).
Args:
update_metadata (Optional[Dict[str, Any]] = None):
- If None - just dumps `self.metadata` into the metadata JSON file.
- If defined - updates the `self.metadata` attribute and then dumps it.
"""
if update_metadata is not None:
self.metadata.update(update_metadata)
with open(f"{self.dir_path}metadata.json", "w") as metadata_file:
json.dump(self.metadata, metadata_file, indent=4)
def identify_platform(self) -> None:
"""
Identifies user's platform.
Writes True to `self.jupyter` for Jupyter notebook, False for terminal.
"""
# If True then the platform is a terminal/command line/shell
if stdout.isatty():
self.jupyter = False
# If False, we assume the platform is a Jupyter notebook
else:
self.jupyter = True
def output_to_platform(
self,
*,
title: str,
output_terminal: Union[TextDrawing, str],
output_jupyter: Union[Figure, str],
display_both_on_jupyter: Optional[bool] = False,
) -> None:
"""
Displays output to user's platform.
Args:
title (str): a title for the output.
output_terminal (Union[TextDrawing, str]): text to print for a terminal platform.
output_jupyter: (Union[Figure, str]): objects to display for a Jupyter notebook platform.
can handle `Figure` matplotlib objects or strings of paths to IFrame displayable file,
e.g PDF files.
display_both_on_jupyter (Optional[bool] = False): if True, displays both
`output_terminal` and `output_jupyter` in a Jupyter notebook platform.
Raises:
TypeError - in the case of misusing the `output_jupyter` argument.
"""
print()
print(title)
if self.jupyter:
if isinstance(output_jupyter, str):
display.display(display.IFrame(output_jupyter, width=IFRAME_WIDTH, height=IFRAME_HEIGHT))
elif isinstance(output_jupyter, Figure):
display.display(output_jupyter)
else:
raise TypeError("output_jupyter must be an str (path to image file) or a Figure object.")
if display_both_on_jupyter:
print(output_terminal)
else:
print(output_terminal)
def interactive_interface(self) -> None:
"""
An interactive CLI that allows exploiting most (but not all) of the package's features.
Uses functions of the form `interactive_XXX_inputs` from the `interactive_inputs.py` module.
Divided into 3 main stages:
1. Obtaining Grover's operator for the SAT problem.
2. Obtaining the overall SAT cirucit.
3. Executing the circuit and parsing the results.
The interface is built in a modular manner such that a user can halt at any stage.
The defualt settings for the interactive user intreface are:
1. `name = "SAT"`.
2. `save_data = True`.
3. `display = True`.
4. `transpile_kwargs = {'basis_gates': ['u', 'cx'], 'optimization_level': 3}`.
5. Backends are limited to those defined in the global-constant-like function `BACKENDS`:
- Those are the local `aer_simulator` and the remote `ibmq_qasm_simulator` for now.
Due to these default settings the interactive CLI is somewhat restrictive,
for full flexibility a user should use the API and not the CLI.
"""
# Handling operator part
operator_inputs = interactive_operator_inputs()
self.num_input_qubits = operator_inputs["num_input_qubits"]
self.high_to_low_map = operator_inputs["high_to_low_map"]
self.constraints_string = operator_inputs["constraints_string"]
self.high_level_constraints_string = operator_inputs["high_level_constraints_string"]
self.high_level_vars = operator_inputs["high_level_vars"]
self.parsed_constraints = ParsedConstraints(
self.constraints_string, self.high_level_constraints_string
)
self.update_metadata(
{
"num_input_qubits": self.num_input_qubits,
"constraints_string": self.constraints_string,
"high_level_constraints_string": self.high_level_constraints_string,
"high_level_vars": self.high_level_vars,
}
)
obtain_grover_operator_output = self.obtain_grover_operator()
self.save_display_grover_operator(obtain_grover_operator_output)
# Handling overall circuit part
solutions_num = interactive_solutions_num_input()
if solutions_num is not None:
backend = None
if solutions_num == -1:
backend = interactive_backend_input()
overall_circuit_data = self.obtain_overall_sat_circuit(
obtain_grover_operator_output["operator"], solutions_num, backend
)
self.save_display_overall_circuit(overall_circuit_data)
# Handling circuit execution part
if interactive_run_input():
if backend is None:
backend = interactive_backend_input()
shots = interactive_shots_input()
counts_parsed = self.run_overall_sat_circuit(
overall_circuit_data["circuit"], backend, shots
)
self.save_display_results(counts_parsed)
print()
print(f"Done saving data into '{self.dir_path}'.")
def obtain_grover_operator(
self, transpile_kwargs: Optional[Dict[str, Any]] = None
) -> Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]:
"""
Obtains the suitable `GroverConstraintsOperator` object for the constraints,
decomposes it using the `circuit_decomposition.py` module and transpiles it
according to `transpile_kwargs`.
Args:
transpile_kwargs (Optional[Dict[str, Any]]): kwargs for Qiskit's transpile function.
The defualt is set to the global constant `TRANSPILE_KWARGS`.
Returns:
(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit, Dict[str, List[int]]]]):
- 'operator' (GroverConstraintsOperator):the high-level blocks operator.
- 'decomposed_operator' (QuantumCircuit): decomposed to building-blocks operator.
* For annotations regarding the decomposition method see the
`circuit_decomposition` module.
- 'transpiled_operator' (QuantumCircuit): the transpiled operator.
*** The high-level operator and the decomposed operator are generated with barriers
between constraints as default for visualizations purposes. The barriers are stripped
off before transpiling so the the transpiled operator object contains no barriers. ***
- 'high_level_to_bit_indexes_map' (Optional[Dict[str, List[int]]] = None):
A map of high-level variables with their allocated bit-indexes in the input register.
"""
print()
print(
"The system synthesizes and transpiles a Grover's "
"operator for the given constraints. Please wait.."
)
if transpile_kwargs is None:
transpile_kwargs = TRANSPILE_KWARGS
self.transpile_kwargs = transpile_kwargs
operator = GroverConstraintsOperator(
self.parsed_constraints, self.num_input_qubits, insert_barriers=True
)
decomposed_operator = decompose_operator(operator)
no_baerriers_operator = RemoveBarriers()(operator)
transpiled_operator = transpile(no_baerriers_operator, **transpile_kwargs)
print("Done.")
return {
"operator": operator,
"decomposed_operator": decomposed_operator,
"transpiled_operator": transpiled_operator,
"high_level_to_bit_indexes_map": self.high_to_low_map,
}
def save_display_grover_operator(
self,
obtain_grover_operator_output: Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]],
display: Optional[bool] = True,
) -> None:
"""
Handles saving and displaying data generated by the `self.obtain_grover_operator` method.
Args:
obtain_grover_operator_output(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]):
the dictionary returned upon calling the `self.obtain_grover_operator` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
# Creating a directory to save operator's data
operator_dir_path = f"{self.dir_path}grover_operator/"
os.mkdir(operator_dir_path)
# Titles for displaying objects, by order of `obtain_grover_operator_output`
titles = [
"The operator diagram - high level blocks:",
"The operator diagram - decomposed:",
f"The transpiled operator diagram saved into '{operator_dir_path}'.\n"
f"It's not presented here due to its complexity.\n"
f"Please note that barriers appear in the high-level diagrams above only for convenient\n"
f"visual separation between constraints.\n"
f"Before transpilation all barriers are removed to avoid redundant inefficiencies.",
]
for index, (op_name, op_obj) in enumerate(obtain_grover_operator_output.items()):
# Generic path and name for files to be saved
files_path = f"{operator_dir_path}{op_name}"
# Generating a circuit diagrams figure
figure_path = f"{files_path}.pdf"
op_obj.draw("mpl", filename=figure_path, fold=-1)
# Generating a QPY serialization file for the circuit object
qpy_file_path = f"{files_path}.qpy"
with open(qpy_file_path, "wb") as qpy_file:
qpy.dump(op_obj, qpy_file)
# Original high-level operator and decomposed operator
if index < 2 and display:
# Displaying to user
self.output_to_platform(
title=titles[index], output_terminal=op_obj.draw("text"), output_jupyter=figure_path
)
# Transpiled operator
elif index == 2:
# Output to user, not including the circuit diagram
print()
print(titles[index])
print()
print(f"The transpilation kwargs are: {self.transpile_kwargs}.")
transpiled_operator_depth = op_obj.depth()
transpiled_operator_gates_count = op_obj.count_ops()
print(f"Transpiled operator depth: {transpiled_operator_depth}.")
print(f"Transpiled operator gates count: {transpiled_operator_gates_count}.")
print(f"Total number of qubits: {op_obj.num_qubits}.")
# Generating QASM 2.0 file only for the (flattened = no registers) tranpsiled operator
qasm_file_path = f"{files_path}.qasm"
flatten_circuit(op_obj).qasm(filename=qasm_file_path)
# Index 3 is 'high_level_to_bit_indexes_map' so it's time to break from the loop
break
# Mapping from high-level variables to bit-indexes will be displayed as well
mapping = obtain_grover_operator_output["high_level_to_bit_indexes_map"]
if mapping:
print()
print(f"The high-level variables mapping to bit-indexes:\n{mapping}")
print()
print(
f"Saved into '{operator_dir_path}':\n",
" Circuit diagrams for all levels.\n",
" QPY serialization exports for all levels.\n",
" QASM 2.0 export only for the transpiled level.",
)
with open(f"{operator_dir_path}operator.qpy", "rb") as qpy_file:
operator_qpy_sha256 = sha256(qpy_file.read()).hexdigest()
self.update_metadata(
{
"high_level_to_bit_indexes_map": self.high_to_low_map,
"transpile_kwargs": self.transpile_kwargs,
"transpiled_operator_depth": transpiled_operator_depth,
"transpiled_operator_gates_count": transpiled_operator_gates_count,
"operator_qpy_sha256": operator_qpy_sha256,
}
)
def obtain_overall_sat_circuit(
self,
grover_operator: GroverConstraintsOperator,
solutions_num: int,
backend: Optional[Backend] = None,
) -> Dict[str, SATCircuit]:
"""
Obtains the suitable `SATCircuit` object (= the overall SAT circuit) for the SAT problem.
Args:
grover_operator (GroverConstraintsOperator): Grover's operator for the SAT problem.
solutions_num (int): number of solutions for the SAT problem. In the case the number
of solutions is unknown, specific negative values are accepted:
* '-1' - for launching a classical iterative stochastic process that finds an adequate
number of iterations - by calling the `find_iterations_unknown` function (see its
docstrings for more information).
* '-2' - for generating a dynamic circuit that iterates over Grover's iterator until
a solution is obtained, using weak measurements. TODO - this feature isn't ready yet.
backend (Optional[Backend] = None): in the case of a '-1' value given to `solutions_num`,
a backend object to execute the depicted iterative prcess upon should be provided.
Returns:
(Dict[str, SATCircuit]):
- 'circuit' key for the overall SAT circuit.
- 'concise_circuit' key for the overall SAT circuit, with only 1 iteration over Grover's
iterator (operator + diffuser). Useful for visualization purposes.
*** The concise circuit is generated with barriers between segments as default
for visualizations purposes. In the actual circuit there no barriers. ***
"""
# -1 = Unknown number of solutions - iterative stochastic process
print()
if solutions_num == -1:
assert backend is not None, "Need to specify a backend if `solutions_num == -1`."
print("Please wait while the system checks various solutions..")
circuit, iterations = find_iterations_unknown(
self.num_input_qubits,
grover_operator,
self.parsed_constraints,
precision=10,
backend=backend,
)
print()
print(f"An adequate number of iterations found = {iterations}.")
# -2 = Unknown number of solutions - implement a dynamic circuit
# TODO this feature isn't fully implemented yet
elif solutions_num == -2:
print("The system builds a dynamic circuit..")
circuit = SATCircuit(self.num_input_qubits, grover_operator, iterations=None)
circuit.add_input_reg_measurement()
iterations = None
# Known number of solutions
else:
print("The system builds the overall circuit..")
iterations = calc_iterations(self.num_input_qubits, solutions_num)
print(f"\nFor {solutions_num} solutions, {iterations} iterations needed.")
circuit = SATCircuit(
self.num_input_qubits, grover_operator, iterations, insert_barriers=False
)
circuit.add_input_reg_measurement()
self.iterations = iterations
# Obtaining a SATCircuit object with one iteration for concise representation
concise_circuit = SATCircuit(
self.num_input_qubits, grover_operator, iterations=1, insert_barriers=True
)
concise_circuit.add_input_reg_measurement()
return {"circuit": circuit, "concise_circuit": concise_circuit}
def save_display_overall_circuit(
self, obtain_overall_sat_circuit_output: Dict[str, SATCircuit], display: Optional[bool] = True
) -> None:
"""
Handles saving and displaying data generated by the `self.obtain_overall_sat_circuit` method.
Args:
obtain_overall_sat_circuit_output(Dict[str, SATCircuit]):
the dictionary returned upon calling the `self.obtain_overall_sat_circuit` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
circuit = obtain_overall_sat_circuit_output["circuit"]
concise_circuit = obtain_overall_sat_circuit_output["concise_circuit"]
# Creating a directory to save overall circuit's data
overall_circuit_dir_path = f"{self.dir_path}overall_circuit/"
os.mkdir(overall_circuit_dir_path)
# Generating a figure of the overall SAT circuit with just 1 iteration (i.e "concise")
concise_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_1_iteration.pdf"
concise_circuit.draw("mpl", filename=concise_circuit_fig_path, fold=-1)
# Displaying the concise circuit to user
if display:
if self.iterations:
self.output_to_platform(
title=(
f"The high level circuit contains {self.iterations}"
f" iterations of the following form:"
),
output_terminal=concise_circuit.draw("text"),
output_jupyter=concise_circuit_fig_path,
)
# Dynamic circuit case - TODO NOT FULLY IMPLEMENTED YET
else:
dynamic_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_dynamic.pdf"
circuit.draw("mpl", filename=dynamic_circuit_fig_path, fold=-1)
self.output_to_platform(
title="The dynamic circuit diagram:",
output_terminal=circuit.draw("text"),
output_jupyter=dynamic_circuit_fig_path,
)
if self.iterations:
transpiled_overall_circuit = transpile(flatten_circuit(circuit), **self.transpile_kwargs)
print()
print(f"The transpilation kwargs are: {self.transpile_kwargs}.")
transpiled_overall_circuit_depth = transpiled_overall_circuit.depth()
transpiled_overall_circuit_gates_count = transpiled_overall_circuit.count_ops()
print(f"Transpiled overall-circuit depth: {transpiled_overall_circuit_depth}.")
print(f"Transpiled overall-circuit gates count: {transpiled_overall_circuit_gates_count}.")
print(f"Total number of qubits: {transpiled_overall_circuit.num_qubits}.")
print()
print("Exporting the full overall SAT circuit object..")
export_files_path = f"{overall_circuit_dir_path}overall_circuit"
with open(f"{export_files_path}.qpy", "wb") as qpy_file:
qpy.dump(circuit, qpy_file)
if self.iterations:
transpiled_overall_circuit.qasm(filename=f"{export_files_path}.qasm")
print()
print(
f"Saved into '{overall_circuit_dir_path}':\n",
" A concised (1 iteration) circuit diagram of the high-level overall SAT circuit.\n",
" QPY serialization export for the full overall SAT circuit object.",
)
if self.iterations:
print(" QASM 2.0 export for the transpiled full overall SAT circuit object.")
metadata_update = {
"num_total_qubits": circuit.num_qubits,
"num_iterations": circuit.iterations,
}
if self.iterations:
metadata_update["transpiled_overall_circuit_depth"] = (transpiled_overall_circuit_depth,)
metadata_update[
"transpiled_overall_circuit_gates_count"
] = transpiled_overall_circuit_gates_count
self.update_metadata(metadata_update)
@timer_dec("Circuit simulation execution time = ")
def run_overall_sat_circuit(
self, circuit: QuantumCircuit, backend: Backend, shots: int
) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]:
"""
Executes a `circuit` on `backend` transpiled w.r.t backend, `shots` times.
Args:
circuit (QuantumCircuit): `QuantumCircuit` object or child-object (a.k.a `SATCircuit`)
to execute.
backend (Backend): backend to execute `circuit` upon.
shots (int): number of execution shots.
Returns:
(Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]):
dict object returned by `self.parse_counts` - see this method's docstrings for annotations.
"""
# Defines also instance attributes to use in other methods
self.backend = backend
self.shots = shots
print()
print(f"The system is running the circuit {shots} times on {backend}, please wait..")
print("This process might take a while.")
job = backend.run(transpile(circuit, backend), shots=shots)
counts = job.result().get_counts()
print("Done.")
parsed_counts = self.parse_counts(counts)
return parsed_counts
def parse_counts(
self, counts: Counts
) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]:
"""
Parses a `Counts` object into several desired datas (see 'Returns' section).
Args:
counts (Counts): the `Counts` object to parse.
Returns:
(Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]):
'counts' (Counts) - the original `Counts` object.
'counts_sorted' (List[Tuple[Union[str, int]]]) - results sorted in a descending order.
'distilled_solutions' (List[str]): list of solutions (bitstrings).
'high_level_vars_values' (List[Dict[str, int]]): list of solutions (each solution is a
dictionary with variable-names as keys and their integer values as values).
"""
# Sorting results in an a descending order
counts_sorted = sorted(counts.items(), key=lambda x: x[1], reverse=True)
# Generating a set of distilled verified-only solutions
verifier = ClassicalVerifier(self.parsed_constraints)
distilled_solutions = set()
for count_item in counts_sorted:
if not verifier.verify(count_item[0]):
break
distilled_solutions.add(count_item[0])
# In the case of high-level format in use, translating `distilled_solutions` into integer values
high_level_vars_values = None
if self.high_level_constraints_string and self.high_level_vars:
# Container for dictionaries with variables integer values
high_level_vars_values = []
for solution in distilled_solutions:
# Keys are variable-names and values are their integer values
solution_vars = {}
for var, bits_bundle in self.high_to_low_map.items():
reversed_solution = solution[::-1]
var_bitstring = ""
for bit_index in bits_bundle:
var_bitstring += reversed_solution[bit_index]
# Translating to integer value
solution_vars[var] = int(var_bitstring, 2)
high_level_vars_values.append(solution_vars)
return {
"counts": counts,
"counts_sorted": counts_sorted,
"distilled_solutions": distilled_solutions,
"high_level_vars_values": high_level_vars_values,
}
def save_display_results(
self,
run_overall_sat_circuit_output: Dict[
str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]
],
display: Optional[bool] = True,
) -> None:
"""
Handles saving and displaying data generated by the `self.run_overall_sat_circuit` method.
Args:
run_overall_sat_circuit_output (Dict[str, Union[Counts, List[Tuple[Union[str, int]]],
List[str], List[Dict[str, int]]]]): the dictionary returned upon calling
the `self.run_overall_sat_circuit` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
counts = run_overall_sat_circuit_output["counts"]
counts_sorted = run_overall_sat_circuit_output["counts_sorted"]
distilled_solutions = run_overall_sat_circuit_output["distilled_solutions"]
high_level_vars_values = run_overall_sat_circuit_output["high_level_vars_values"]
# Creating a directory to save results data
results_dir_path = f"{self.dir_path}results/"
os.mkdir(results_dir_path)
# Defining custom dimensions for the custom `plot_histogram` of this package
histogram_fig_width = max((len(counts) * self.num_input_qubits * (10 / 72)), 7)
histogram_fig_height = 5
histogram_figsize = (histogram_fig_width, histogram_fig_height)
histogram_path = f"{results_dir_path}histogram.pdf"
plot_histogram(counts, figsize=histogram_figsize, sort="value_desc", filename=histogram_path)
if display:
# Basic output text
output_text = (
f"All counts:\n{counts_sorted}\n"
f"\nDistilled solutions ({len(distilled_solutions)} total):\n"
f"{distilled_solutions}"
)
# Additional outputs for a high-level constraints format
if high_level_vars_values:
# Mapping from high-level variables to bit-indexes will be displayed as well
output_text += (
f"\n\nThe high-level variables mapping to bit-indexes:" f"\n{self.high_to_low_map}"
)
# Actual integer solutions will be displayed as well
additional_text = ""
for solution_index, solution in enumerate(high_level_vars_values):
additional_text += f"Solution {solution_index + 1}: "
for var_index, (var, value) in enumerate(solution.items()):
additional_text += f"{var} = {value}"
if var_index != len(solution) - 1:
additional_text += ", "
else:
additional_text += "\n"
output_text += f"\n\nHigh-level format solutions: \n{additional_text}"
self.output_to_platform(
title=f"The results for {self.shots} shots are:",
output_terminal=output_text,
output_jupyter=histogram_path,
display_both_on_jupyter=True,
)
results_dict = {
"high_level_to_bit_indexes_map": self.high_to_low_map,
"solutions": list(distilled_solutions),
"high_level_solutions": high_level_vars_values,
"counts": counts_sorted,
}
with open(f"{results_dir_path}results.json", "w") as results_file:
json.dump(results_dict, results_file, indent=4)
self.update_metadata(
{
"num_solutions": len(distilled_solutions),
"backend": str(self.backend),
"shots": self.shots,
}
)
|
https://github.com/qBraid/qBraid
|
qBraid
|
'''
qiskitpool/job.py
Contains the QJob class
'''
from functools import partial
from qiskit import execute
class QJob():
'''
QJob
Job manager for asynch qiskit backends
'''
def __init__(self, *args, qjob_id=None, **kwargs):
'''
QJob.__init__
Initialiser for a qiksit job
:: *args :: Args for qiskit execute
:: **kwargs :: Kwargs for qiskit execute
'''
self.job_fn = partial(execute, *args, **kwargs)
self.job = None
self.done = False
self.test_count = 10
self.qjob_id = qjob_id
def __call__(self):
'''
QJob.__call__
Wrapper for QJob.run
'''
return self.run()
def run(self):
'''
QJob.run
Send async job to qiskit backend
'''
self.job = self.job_fn()
return self
def poll(self):
'''
QJob.poll
Poll qiskit backend for job completion status
'''
if self.job is not None:
return self.job.done()
return False
def cancel(self):
'''
QJob.cancel
Cancel job on backend
'''
if self.job is None:
return None
return self.job.cancel()
def position(self):
pos = self.job.queue_position()
if pos is None:
return 0
return pos
def status(self):
if self.job is None:
return 'LOCAL QUEUE'
else:
status = self.job.status().value
if 'running' in status:
return 'RUNNING'
if 'run' in status:
return 'COMPLETE'
if 'validated' in status:
return 'VALIDATING'
if 'queued' in status:
pos = self.position()
return f'QISKIT QUEUE: {self.position()}'
def status_short(self):
if self.job is None:
return ' '
else:
status = self.job.status().value
if 'running' in status:
return 'R'
if 'run' in status:
return 'C'
if 'validated' in status:
return 'V'
if 'queued' in status:
return str(self.position())
def result(self):
'''
QJob.result
Get result from backend
Non blocking - returns False if a job is not yet ready
'''
if self.poll():
return self.job.result()
return False
|
https://github.com/purvi1508/Quantum_Computing_Fundamentals
|
purvi1508
|
!pip install qiskit
#superpositon, entanglement and interference
my_list=[1,3,5,2,4,9,5,8,0,7,6]
#eracle is the black box at the disposal->we can call it and ask whether this number is a whinner or not
def the_oracle(my_input):
winner=7
if my_input is winner:
response=True
else:
response=False
return response
for index, trial_number in enumerate(my_list):
if the_oracle(trial_number)==True:
print('winner found at index %i'%index)
print('%i calls at the oracle used'%(index+1))
#oracle works here by flipping the sign of the input of the winner
#controlled Z gate -> |11> -> [CZ] -> -|11>
#amplitute amplification ->reflection operator
#Grovvers diffusion operator-> oracle+ Reflection
from qiskit import *
import matplotlib.pyplot as py
import numpy as np
#define oracle circuit
oracle = QuantumCircuit(2,name='oracle')
oracle.cz(0,1)
oracle.to_gate()#make oracle into its own gate
oracle.draw(initial_state = True)
#preparing a supepositon state of all the gates by applying the handmard gate on each one of them
#in this way each uery xould be simuntaneousky reached oracle
backend=Aer.get_backend('statevector_simulator')
# statevector_simulator backend is selected, which allows for simulation of the quantum state vector of the circuit.
grover_circ=QuantumCircuit(2,2)
#The first argument 2 specifies the number of qubits in the quantum registers, and the second argument 2 specifies the number of classical bits in the classical registers.
grover_circ.h([0,1])
#This line applies the Hadamard gate (H gate) to qubits 0 and 1 in the grover_circ circuit.
grover_circ.append(oracle,[0,1])
grover_circ.draw(initial_state = True)
job= execute(grover_circ,backend)
result=job.result()
sv=result.get_statevector()
np.around(sv,2)
#square the state vectors to get back the probabilities
reflection = QuantumCircuit(2,name="reflection")
reflection.h([0,1])
reflection.z([0,1])
reflection.cz(0,1)
reflection.h([0,1])
reflection.to_gate()
reflection.draw(initial_state = True)
backend=Aer.get_backend('statevector_simulator')
# statevector_simulator backend is selected, which allows for simulation of the quantum state vector of the circuit.
grover_circ=QuantumCircuit(2,2)
#The first argument 2 specifies the number of qubits in the quantum registers, and the second argument 2 specifies the number of classical bits in the classical registers.
grover_circ.h([0,1])
#This line applies the Hadamard gate (H gate) to qubits 0 and 1 in the grover_circ circuit.
grover_circ.append(oracle,[0,1])
grover_circ.append(reflection,[0,1])
grover_circ.measure([0,1],[0,1])
grover_circ.draw(initial_state = True)
job= execute(grover_circ,backend,shots=1)
result=job.result()
result.get_counts()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.