repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
|
JessicaJohnBritto
|
import pennylane as qml
from pennylane import numpy as np
import matplotlib.pyplot as plt
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev)
def apply_z_to_plus():
"""Write a circuit that applies PauliZ to the |+> state and returns
the state.
Returns:
array[complex]: The state of the qubit after the operations.
"""
##################
# YOUR CODE HERE #
##################
# CREATE THE |+> STATE
qml.Hadamard(wires=0)
# APPLY PAULI Z
qml.PauliZ(wires=0)
# RETURN THE STATE
return qml.state()
print(apply_z_to_plus())
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev)
def fake_z():
"""Use RZ to produce the same action as Pauli Z on the |+> state.
Returns:
array[complex]: The state of the qubit after the operations.
"""
##################
# YOUR CODE HERE #
##################
# CREATE THE |+> STATE
qml.Hadamard(wires=0)
# APPLY RZ
qml.RZ(np.pi, wires=0)
# RETURN THE STATE
return qml.state()
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev)
def many_rotations():
"""Implement the circuit depicted above and return the quantum state.
Returns:
array[complex]: The state of the qubit after the operations.
"""
##################
# YOUR CODE HERE #
##################
# IMPLEMENT THE CIRCUIT
qml.Hadamard(wires=0)
qml.S(wires=0)
qml.adjoint(qml.T)(wires=0)
qml.RZ(0.3, wires=0)
qml.adjoint(qml.S)(wires=0)
# RETURN THE STATE
return qml.state()
dev = qml.device('default.qubit', wires=3)
@qml.qnode(dev)
def too_many_ts():
"""You can implement the original circuit here as well, it may help you with
testing to ensure that the circuits have the same effect.
Returns:
array[float]: The measurement outcome probabilities.
"""
# qml.Hadamard(wires=[0,1,2])
qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
qml.T(wires=[0,1])
qml.adjoint(qml.T)(wires=2)
qml.T(wires=0)
# qml.Hadamard(wires=[0,1,2])
qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
qml.adjoint(qml.T)(wires=0)
qml.T(wires=1)
qml.adjoint(qml.T)(wires=2)
qml.adjoint(qml.T)(wires=0)
qml.T(wires=1)
qml.adjoint(qml.T)(wires=2)
qml.T(wires=1)
qml.adjoint(qml.T)(wires=2)
qml.T(wires=1)
# qml.Hadamard(wires=[0,1,2])
qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
return qml.probs(wires=[0, 1, 2])
@qml.qnode(dev)
def just_enough_ts():
"""Implement an equivalent circuit as the above with the minimum number of
T and T^\dagger gates required.
Returns:
array[float]: The measurement outcome probabilities.
"""
##################
# YOUR CODE HERE #
##################
qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
qml.S(wires=0)
qml.T(wires=1)
qml.adjoint(qml.T)(wires=2)
# qml.T(wires=0)
# qml.Hadamard(wires=[0,1,2])
qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
qml.adjoint(qml.S)(wires=0)
qml.S(wires=1)
qml.adjoint(qml.S)(wires=2)
# qml.adjoint(qml.T)(wires=0)
# qml.T(wires=1)
# qml.adjoint(qml.T)(wires=2)
qml.S(wires=1)
qml.adjoint(qml.T)(wires=2)
# qml.T(wires=1)
# qml.Hadamard(wires=[0,1,2])
qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
# IMPLEMENT THE CIRCUIT, BUT COMBINE AND OPTIMIZE THE GATES
# TO MINIMIZE THE NUMBER OF TS
return qml.probs(wires=[0, 1, 2])
##################
# YOUR CODE HERE #
##################
# FILL IN THE CORRECT VALUES FOR THE ORIGINAL CIRCUIT
original_depth = 8
original_t_count = 13
original_t_depth = 6
# FILL IN THE CORRECT VALUES FOR THE NEW, OPTIMIZED CIRCUIT
optimal_depth = 6
optimal_t_count = 3
optimal_t_depth = 2
dev = qml.device("default.qubit", wires=1)
##################
# YOUR CODE HERE #
##################
# ADJUST THE VALUES OF PHI, THETA, AND OMEGA
phi, theta, omega = np.pi/2, np.pi/2, np.pi/2
@qml.qnode(dev)
def hadamard_with_rz_rx():
qml.RZ(phi, wires=0)
qml.RX(theta, wires=0)
qml.RZ(omega, wires=0)
return qml.state()
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev)
def convert_to_rz_rx():
##################
# YOUR CODE HERE #
##################
# IMPLEMENT THE CIRCUIT IN THE PICTURE USING ONLY RZ AND RX
qml.RZ(np.pi/2, wires=0)
qml.RX(np.pi/2, wires=0)
qml.RZ(np.pi/2, wires=0)
qml.RZ(np.pi/2,wires=0)
qml.RZ(np.pi, wires=0)
qml.RZ(np.pi/2, wires=0)
qml.RZ(np.pi/4, wires=0)
qml.RZ(np.pi/2,wires=0)
qml.RX(np.pi, wires=0)
qml.RZ(np.pi, wires=0)
qml.RZ(np.pi/2, wires=0)
return qml.state()
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev)
def unitary_with_h_and_t():
##################
# YOUR CODE HERE #
##################
# APPLY ONLY H AND T TO PRODUCE A CIRCUIT THAT EFFECTS THE GIVEN MATRIX
# qml.T(wires=0)
qml.Hadamard(wires=0)
qml.T(wires=0)
qml.Hadamard(wires=0)
qml.T(wires=0)
qml.T(wires=0)
qml.Hadamard(wires=0)
# qml.T(wires=0)
return qml.state()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
|
https://github.com/jatin-47/QGSS-2021
|
jatin-47
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.sdg(0)
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.cx(0,1)
qc.x(0)
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
#
#
# FILL YOUR CODE IN HERE
#
#
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.y(1)
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
oraclenr = 4 # determines the oracle (can range from 1 to 5)
oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles
oracle.name = "DJ-Oracle"
def dj_classical(n, input_str):
# build a quantum circuit with n qubits and 1 classical readout bit
dj_circuit = QuantumCircuit(n+1,1)
# Prepare the initial state corresponding to your input bit string
for i in range(n):
if input_str[i] == '1':
dj_circuit.x(i)
# append oracle
dj_circuit.append(oracle, range(n+1))
# measure the fourth qubit
dj_circuit.measure(n,0)
return dj_circuit
n = 4 # number of qubits
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
dj_circuit.draw() # draw the circuit
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit, qasm_sim)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def lab1_ex7():
min_nr_inputs = 2
max_nr_inputs = 9
return [min_nr_inputs, max_nr_inputs]
from qc_grader import grade_lab1_ex7
# Note that the grading function is expecting a list of two integers
grade_lab1_ex7(lab1_ex7())
n=4
def psi_0(n):
qc = QuantumCircuit(n+1,n)
# Build the state (|00000> - |10000>)/sqrt(2)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(4)
qc.h(4)
return qc
dj_circuit = psi_0(n)
dj_circuit.draw()
def psi_1(n):
# obtain the |psi_0> = |00001> state
qc = psi_0(n)
# create the superposition state |psi_1>
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
#
#
qc.barrier()
return qc
dj_circuit = psi_1(n)
dj_circuit.draw()
def psi_2(oracle,n):
# circuit to obtain psi_1
qc = psi_1(n)
# append the oracle
qc.append(oracle, range(n+1))
return qc
dj_circuit = psi_2(oracle, n)
dj_circuit.draw()
def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25])
qc = psi_2(oracle, n)
# apply n-fold hadamard gate
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
# add the measurement by connecting qubits to classical bits
#
#
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
#
#
return qc
dj_circuit = lab1_ex8(oracle, n)
dj_circuit.draw()
from qc_grader import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit with measurements
grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n))
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/rigetti/qiskit-rigetti
|
rigetti
|
#In case you don't have qiskit, install it now
%pip install qiskit --quiet
#Installing/upgrading pylatexenc seems to have fixed my mpl issue
#If you try this and it doesn't work, try also restarting the runtime/kernel
%pip install pylatexenc --quiet
!pip install -Uqq ipdb
!pip install qiskit_optimization
import networkx as nx
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer
from qiskit.compiler import transpile
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit.quantum_info import process_fidelity
from qiskit.extensions.hamiltonian_gate import HamiltonianGate
from qiskit.extensions import RXGate, XGate, CXGate
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute
import numpy as np
from qiskit.visualization import plot_histogram
import ipdb
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
#quadratic optimization
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.converters import QuadraticProgramToQubo
%pdb on
# def ApplyCost(qc, gamma):
# Ix = np.array([[1,0],[0,1]])
# Zx= np.array([[1,0],[0,-1]])
# Xx = np.array([[0,1],[1,0]])
# Temp = (Ix-Zx)/2
# T = Operator(Temp)
# I = Operator(Ix)
# Z = Operator(Zx)
# X = Operator(Xx)
# FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T)
# ham = HamiltonianGate(FinalOp,gamma)
# qc.append(ham,[0,1,2])
task = QuadraticProgram(name = 'QUBO on QC')
task.binary_var(name = 'x')
task.binary_var(name = 'y')
task.binary_var(name = 'z')
task.minimize(linear = {"x":-1,"y":2,"z":-3}, quadratic = {("x", "z"): -2, ("y", "z"): -1})
qubo = QuadraticProgramToQubo().convert(task) #convert to QUBO
operator, offset = qubo.to_ising()
print(operator)
# ham = HamiltonianGate(operator,0)
# print(ham)
Ix = np.array([[1,0],[0,1]])
Zx= np.array([[1,0],[0,-1]])
Xx = np.array([[0,1],[1,0]])
Temp = (Ix-Zx)/2
T = Operator(Temp)
I = Operator(Ix)
Z = Operator(Zx)
X = Operator(Xx)
FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T)
ham = HamiltonianGate(FinalOp,0)
print(ham)
#define PYBIND11_DETAILED_ERROR_MESSAGES
def compute_expectation(counts):
"""
Computes expectation value based on measurement results
Args:
counts: dict
key as bitstring, val as count
G: networkx graph
Returns:
avg: float
expectation value
"""
avg = 0
sum_count = 0
for bitstring, count in counts.items():
x = int(bitstring[2])
y = int(bitstring[1])
z = int(bitstring[0])
obj = -2*x*z-y*z-x+2*y-3*z
avg += obj * count
sum_count += count
return avg/sum_count
# We will also bring the different circuit components that
# build the qaoa circuit under a single function
def create_qaoa_circ(theta):
"""
Creates a parametrized qaoa circuit
Args:
G: networkx graph
theta: list
unitary parameters
Returns:
qc: qiskit circuit
"""
nqubits = 3
n,m=3,3
p = len(theta)//2 # number of alternating unitaries
qc = QuantumCircuit(nqubits,nqubits)
Ix = np.array([[1,0],[0,1]])
Zx= np.array([[1,0],[0,-1]])
Xx = np.array([[0,1],[1,0]])
Temp = (Ix-Zx)/2
T = Operator(Temp)
I = Operator(Ix)
Z = Operator(Zx)
X = Operator(Xx)
FinalOp=-2*(Z^I^Z)-(I^Z^Z)-(Z^I^I)+2*(I^Z^I)-3*(I^I^Z)
beta = theta[:p]
gamma = theta[p:]
# initial_state
for i in range(0, nqubits):
qc.h(i)
for irep in range(0, p):
#ipdb.set_trace(context=6)
# problem unitary
# for pair in list(G.edges()):
# qc.rzz(2 * gamma[irep], pair[0], pair[1])
#ApplyCost(qc,2*0)
ham = HamiltonianGate(operator,2 * gamma[irep])
qc.append(ham,[0,1,2])
# mixer unitary
for i in range(0, nqubits):
qc.rx(2 * beta[irep], i)
qc.measure(qc.qubits[:n],qc.clbits[:m])
return qc
# Finally we write a function that executes the circuit on the chosen backend
def get_expectation(shots=512):
"""
Runs parametrized circuit
Args:
G: networkx graph
p: int,
Number of repetitions of unitaries
"""
backend = Aer.get_backend('qasm_simulator')
backend.shots = shots
def execute_circ(theta):
qc = create_qaoa_circ(theta)
# ipdb.set_trace(context=6)
counts = {}
job = execute(qc, backend, shots=1024)
result = job.result()
counts=result.get_counts(qc)
return compute_expectation(counts)
return execute_circ
from scipy.optimize import minimize
expectation = get_expectation()
res = minimize(expectation, [1, 1], method='COBYLA')
expectation = get_expectation()
res = minimize(expectation, res.x, method='COBYLA')
res
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('aer_simulator')
backend.shots = 512
qc_res = create_qaoa_circ(res.x)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc_res, backend, shots=1024)
result = job.result()
counts=result.get_counts(qc_res)
plot_histogram(counts)
|
https://github.com/Fergus-Hayes/qiskit_tools
|
Fergus-Hayes
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
import qiskit_tools as qt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
in_digit = np.pi
print(in_digit)
n = 20
nint = qt.get_nint(in_digit)
print(nint)
in_binary = qt.my_binary_repr(in_digit, n, nint=nint, phase=False)
print(in_binary)
out_digit = qt.bin_to_dec(in_binary, nint=nint, phase=False)
print(out_digit)
n-nint
in_digit = -3.25
print(in_digit)
nint = qt.get_nint(in_digit)
print(nint)
npres = qt.get_npres(in_digit)
print(npres)
n = npres + nint + 1
in_binary = qt.my_binary_repr(in_digit, n, nint=nint, phase=True)
print(in_binary)
out_digit = qt.bin_to_dec(in_binary, nint=nint, phase=True)
print(out_digit)
sm_binary = qt.my_binary_repr(in_digit, n, nint=nint, phase=True, signmag=True)
print(sm_binary, qt.bin_to_dec(sm_binary, nint=nint, phase=True, signmag=True))
qreg = QuantumRegister(n, 'bit')
circ = QuantumCircuit(qreg)
circ = qt.input_bits_to_qubits(in_binary, circ, qreg)
circ.draw(output="latex")
|
https://github.com/lynnlangit/learning-quantum
|
lynnlangit
|
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()
import math
import numpy as np
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit.algorithms import Shor
N = 15
backend = Aer.get_backend('aer_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
shor = Shor(quantum_instance=quantum_instance)
result = shor.factor(N)
print(f"The list of factors of {N} as computed by the Shor's algorithm is {result.factors[0]}.")
print(f'Computed of qubits for circuit: {4 * math.ceil(math.log(N, 2)) + 2}')
print(f'Actual number of qubits of circuit: {shor.construct_circuit(N).num_qubits}')
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_circuit_layout
from qiskit.tools.monitor import job_monitor
from qiskit.providers.fake_provider import FakeVigoV2
import matplotlib.pyplot as plt
ghz = QuantumCircuit(3, 3)
ghz.h(0)
for idx in range(1,3):
ghz.cx(0,idx)
ghz.measure(range(3), range(3))
backend = FakeVigoV2()
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/mlvqc/Byskit
|
mlvqc
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import *
# First princinple for two parent nodes and one child
class byskit():
def __init__(self, provider, backend, n, parents, child):
self.provider = provider
self.backend = backend
self.parents = parents
self.child = child
self.n = n
self.ctrl = QuantumRegister(self.n, 'ctrl')
self.anc = QuantumRegister(self.n - 1, 'anc')
self.tgt = QuantumRegister(1, 'tgt')
self.circ = QuantumCircuit(self.ctrl, self.anc, self.tgt)
self.parent_init()
self.child_init()
self.circ.draw(output='mpl')
plt.show()
def parent_init(self):
for i in range(self.n):
theta = self.calc_theta(self.parents[2*i], self.parents[2*i+1])
self.circ.ry(theta, i)
self.circ.barrier()
self.circ.x(self.ctrl)
def child_init(self):
self.a = np.arange(0, 2 ** self.n)
gates = []
for i in self.a:
s = str(np.binary_repr(i, width=self.n))
gates.append(s)
for i in range(2*self.n):
theta = self.calc_theta(self.child[2*i+1], self.child[2*i])
for index2,item2 in enumerate(gates[i]):
print(item2)
if int(item2) == 0:
self.circ.x(index2)
self.cn_ry(theta)
for index2,item2 in enumerate(gates[i]):
print(item2)
if int(item2) == 0:
self.circ.x(index2)
self.circ.barrier()
#RY gates
def cn_ry(self,theta):
# compute
self.circ.ccx(self.ctrl[0], self.ctrl[1], self.anc[0])
for i in range(2, self.n):
self.circ.ccx(self.ctrl[i], self.anc[i - 2], self.anc[i - 1])
# copy
self.circ.cry(theta,self.anc[self.n - 2], self.tgt[0])
# uncompute
for i in range(self.n - 1, 1, -1):
self.circ.ccx(self.ctrl[i], self.anc[i - 2], self.anc[i - 1])
self.circ.ccx(self.ctrl[0], self.ctrl[1], self.anc[0])
def calc_theta(self,p1,p0):
return 2 * np.arctan(np.sqrt((p1)/(p0)))
if __name__=='__main__':
from jupyterthemes import jtplot
jtplot.style(theme='monokai', context='notebook', ticks=True, grid=False)
from qiskit.tools.jupyter import *
from qiskit import IBMQ
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = IBMQ.get_provider(hub='ibm-q-oxford', group='on-boarding', project='on-boarding-proj')
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
a0 = 0.2
a1 = 0.8
b0 = 0.3
b1 = 0.7
c000 = 0.15
c001 = 0.3
c010 = 0.4
c011 = 0.1
c100 = 0.85
c101 = 0.7
c110 = 0.6
c111 = 0.9
parents = np.array([a0,a1,b0,b1])
child = np.array([c000,c100,c001,c101,c010,c110,c011,c111])
n = 2
b = byskit(provider,backend,n,parents,child)
print(np.shape(b.parents))
print(np.shape(b.child))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can set a color for all the bars.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import matplotlib.pyplot as plt
import qiskit
from qiskit.providers.aer.noise.errors.standard_errors import amplitude_damping_error
from qiskit.providers.aer.noise.errors.standard_errors import phase_damping_error
from qiskit.providers.aer.noise import NoiseModel
from qiskit.ignis.characterization.coherence import T1Fitter, T2StarFitter, T2Fitter
from qiskit.ignis.characterization.coherence import t1_circuits, t2_circuits, t2star_circuits
# 12 numbers ranging from 10 to 1000, logarithmically spaced
# extra point at 1500
num_of_gates = np.append((np.logspace(1, 3, 12)).astype(int), np.array([1500]))
gate_time = 0.1
# Select the qubits whose T1 are to be measured
qubits = [0]
# Generate experiments
circs, xdata = t1_circuits(num_of_gates, gate_time, qubits)
# Set the simulator with amplitude damping noise
t1 = 25.0
gamma = 1 - np.exp(-gate_time/t1)
error = amplitude_damping_error(gamma)
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'id', [0])
# Run the simulator
backend = qiskit.Aer.get_backend('qasm_simulator')
shots = 200
backend_result = qiskit.execute(circs, backend,
shots=shots, noise_model=noise_model).result()
%matplotlib inline
# Fit the data to an exponential
# The correct answers are a=1, and c=0, and t1=25/15 for qubit 0/2
# The user does not know the correct answer exactly,
# so starts the fit from a different but close location
initial_t1 = t1*1.2
initial_a = 1.0
initial_c = 0.0
fit = T1Fitter(backend_result, xdata, qubits,
fit_p0=[initial_a, initial_t1, initial_c],
fit_bounds=([0, 0, -1], [2, initial_t1*2, 1]))
fit.plot(0)
# 50 points linearly spaced in two regions (fine and coarse)
# 30 from 10->150, 20 from 160->450
num_of_gates = np.append((np.linspace(10, 150, 30)).astype(int), (np.linspace(160,450,20)).astype(int))
gate_time = 0.1
# Select the qubits whose T2* are to be measured
qubits = [0]
# Generate experiments
circs, xdata, osc_freq = t2star_circuits(num_of_gates, gate_time, qubits, nosc=5)
backend = qiskit.Aer.get_backend('qasm_simulator')
# Set the simulator with phase damping noise
t2 = 10
p = 1 - np.exp(-2*gate_time/t2)
error = phase_damping_error(p)
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'id', [0])
# Run the simulator
shots = 300
backend_result = qiskit.execute(circs, backend,
shots=shots, noise_model=noise_model).result()
%matplotlib inline
# Fit the data to an oscillator
# The correct answers are a=0.5, f=osc_freq, phi=0, c=0.5, and t2=10/5 for qubit 0/2
# The user does not know the correct answer exactly,
# so starts the fit from a different but close location
initial_t2 = t2*1.1
initial_a = 0.5
initial_c = 0.5
initial_f = osc_freq
initial_phi = -np.pi/20
fit = T2StarFitter(backend_result, xdata, qubits,
fit_p0=[initial_a, initial_t2, initial_f, initial_phi, initial_c],
fit_bounds=([-0.5, 0, 0, -np.pi, -0.5],
[1.5, 2*t2, 2*osc_freq, np.pi, 1.5]))
fit.plot(0)
# 50 points linearly spaced to 300
num_of_gates = (np.linspace(10, 300, 50)).astype(int)
gate_time = 0.1
# Select the qubits whose T2 are to be measured
qubits = [0]
# Generate experiments
circs, xdata = t2_circuits(num_of_gates, gate_time, qubits)
backend = qiskit.Aer.get_backend('qasm_simulator')
# Set the simulator with phase damping noise
t2 = 10
p = 1 - np.exp(-2*gate_time/t2)
error = phase_damping_error(p)
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'id', [0])
# Run the simulator
shots = 300
backend_result = qiskit.execute(circs, backend,
shots=shots, noise_model=noise_model).result()
%matplotlib inline
# Fit the data to an exponent
# The correct answers are a=1, c=0, and t2=10/5 for qubit 0/2
# The user does not know the correct answer exactly,
# so starts the fit from a different but close location
initial_t2 = t2*1.1
initial_a = 0.5
initial_c = 0.5
fit = T2Fitter(backend_result, xdata, qubits,
fit_p0=[initial_a, initial_t2, initial_c],
fit_bounds=([-0.5, 0, -0.5],
[1.5, 2*t2, 1.5]))
fit.plot(0)
num_of_gates = (np.linspace(1, 30, 30)).astype(int)
gate_time = 0.1
# Select the qubits whose T2 are to be measured
qubits = [0]
# Echo parameters
n_echos = 5
alt_phase_echo = True
# Generate experiments
circs, xdata = t2_circuits(num_of_gates, gate_time, qubits, n_echos, alt_phase_echo)
backend = qiskit.Aer.get_backend('qasm_simulator')
# Set the simulator with phase damping noise
t2 = 10
p = 1 - np.exp(-2*gate_time/t2)
error = phase_damping_error(p)
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'id', [0])
# Run the simulator
shots = 300
backend_result = qiskit.execute(circs, backend,
shots=shots, noise_model=noise_model).result()
%matplotlib inline
# Fit the data to an exponent
# The correct answers are a=1, c=0, and t2=10/5 for qubit 0/2
# The user does not know the correct answer exactly,
# so starts the fit from a different but close location
initial_t2 = t2*1.1
initial_a = 0.5
initial_c = 0.5
fit = T2Fitter(backend_result, xdata, qubits,
fit_p0=[initial_a, initial_t2, initial_c],
fit_bounds=([-0.5, 0, -0.5],
[1.5, 2*t2, 1.5]))
fit.plot(0)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, QuantumRegister, transpile, Aer, IBMQ, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.providers.aer import QasmSimulator
from tqdm.notebook import tqdm
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
import qiskit.quantum_info as qi
from qc_grader.challenges.spring_2022.helpers import generate_disordered_tb_instruction
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
import pylatexenc
import IPython
pop = [1,0]
Ne=0 # Sum of even populations.
No=0 # Sum of odd populations.
for j in range(0, len(pop), 2):
Ne += pop[j]
for j in range(1, len(pop), 2):
No += pop[j]
I = (Ne-No)/(Ne+No)
print(f"Ne={Ne}, No={No}, I={I}")
def get_imbalance(state):
###EDIT CODE BELOW
### HINT: MAKE SURE TO SKIP CALCULATING IMBALANCE OF THE |00...0> STATE
imbalance_val=0
def get_basis(i):
num_qubits = int(np.log2(len(state.probabilities())))
basis = []
for i in list(f'{i:0{num_qubits}b}'):
basis.append(int(i))
return basis # A list such as [1,0,0,0]
def imbalance(basis):
Ne=0 # Sum of even populations.
No=0 # Sum of odd populations.
for j in range(0, len(basis), 2):
Ne += basis[j]
for j in range(1, len(basis), 2):
No += basis[j]
return (Ne-No)/(Ne+No)
pop = state.probabilities() # List of probabilities of the state |\psi> for measuring all qubits.
for i in range(1, len(pop)): # Skipping i=0 corresponding to the |00...0> basis.
basis = get_basis(i)
prob_amp = pop[i] # float
imbalance_val += imbalance(basis)*prob_amp
###DO NOT EDIT BELOW
return imbalance_val
st1 = qi.Statevector.from_label('0111') # -1/3
st2 = np.sqrt(2/3)*qi.Statevector.from_label('0111') + np.sqrt(1/3)*qi.Statevector.from_label('1011') # -1/9
st3 = (qi.Statevector.from_label('1000')+qi.Statevector.from_label('1001'))*(1/np.sqrt(2)) # 0.5
for i in [st1, st2, st3]:
print(get_imbalance(i))
## Grade and submit your solution
from qc_grader.challenges.spring_2022 import grade_ex3a
grade_ex3a(get_imbalance)
bell_state = qi.Statevector(np.array([0,1,1,0])/np.sqrt(2))
rho_0 = qi.partial_trace(bell_state,[1]) # We trace out qubit 1
rho_1 = qi.partial_trace(bell_state,[0]) # We trace out qubit 0
print('QB0 vn entropy: ', qi.entropy(rho_0, base=np.exp(1)))
print('QB1 vn entropy: ', qi.entropy(rho_1, base=np.exp(1)))
t = Parameter('t')
num_qubits=12
deltas=[Parameter('delta_{:d}'.format(idx)) for idx in range(num_qubits)]
disorder_trot_step=generate_disordered_tb_instruction(t, deltas, num_qubits)
# Here we define the disorder pattern
beta=(np.sqrt(5)-1)/2 # DO NOT EDIT
AA_pattern=np.cos(2*np.pi*beta*np.arange(num_qubits)) # DO NOT EDIT
delta_t=0.1
time_steps=np.arange(0,21,2)
circuits={}
Ws=[1,4,10]
for W in Ws:
disorders=W*AA_pattern
circuits[W]=[]
for n_steps in time_steps:
qr = QuantumRegister(num_qubits)
qc = QuantumCircuit(qr)
###EDIT CODE BELOW
qc.x([0,4,8])
###DO NOT EDIT BELOW
for _ in range(n_steps):
qc.append(disorder_trot_step, [i for i in range(num_qubits)])
if n_steps!=0:
qc = qc.bind_parameters({t: delta_t})
qc = qc.bind_parameters({deltas[idx]: disorders[idx] for idx in range(num_qubits)})
circuits[W].append(qc)
from qiskit import transpile
# Use Aer's statevector simulator
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend_sim = Aer.get_backend('statevector_simulator')
probability_densities={}
state_vector_imbalances={}
vn_entropies={}
for W in tqdm(Ws):
probability_densities[W]=[]
state_vector_imbalances[W]=[]
vn_entropies[W]=[]
for circ in circuits[W]:
transpiled_circ=transpile(circ, backend_sim, optimization_level=3)
job_sim = backend_sim.run(transpiled_circ)
# Grab the results from the job.
result_sim = job_sim.result()
outputstate = result_sim.get_statevector(transpiled_circ, decimals=6)
ps=[]
for idx in range(num_qubits):
ps.append(np.abs(qi.partial_trace(outputstate,[i for i in range(num_qubits) if i!=idx]))[1,1]**2)
entropy=0
### EDIT CODE BELOW (extract the density matrix of qubit 0 by tracing out all other qubits)
rho0=qi.partial_trace(outputstate, [i for i in range(num_qubits) if i!=0]) # trace out qubit 0.
entropy=qi.entropy(rho0, base=np.exp(1))
###DO NOT EDIT BELOW
imbalance=get_imbalance(outputstate)
### EDIT CODE BELOW
###DO NOT EDIT BELOW
vn_entropies[W].append(entropy)
probability_densities[W].append(ps)
state_vector_imbalances[W].append(imbalance)
fig, axs = plt.subplots(1,3,figsize=(15,5), facecolor='white', sharey=True)
for i,W in enumerate(Ws):
ax=axs[i]
ax.pcolormesh(np.arange(0,num_qubits,1), time_steps*delta_t ,probability_densities[W])
ax.set_xlabel('Qubit index')
ax.set_xticks(np.arange(1,num_qubits+1,1))
axs[0].set_ylabel('Time (1/J)')
plt.show()
for W in Ws:
plt.plot(time_steps*delta_t,vn_entropies[W], '--o', label='W={:d}'.format(W))
plt.xlabel(r'Time (1/J)')
plt.ylabel(r'$\mathcal{S}_{\rm vn}(\rho_0)$')
plt.legend()
plt.show()
## Grade and submit your solution
from qc_grader.challenges.spring_2022 import grade_ex3b
grade_ex3b(vn_entropies)
for W in Ws:
plt.plot(time_steps*delta_t,state_vector_imbalances[W], '--o', label='W={:d}'.format(W))
plt.xlabel(r'Time (1/J)')
plt.ylabel(r'$\mathcal{I}$')
plt.legend()
plt.show()
## Grade and submit your solution
from qc_grader.challenges.spring_2022 import grade_ex3c
grade_ex3c(state_vector_imbalances)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.barrier()
circuit.h(0)
circuit = RemoveBarriers()(circuit)
circuit.draw('mpl')
|
https://github.com/vm6502q/qiskit-qrack-provider
|
vm6502q
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
QasmSimulator Integration Tests
"""
from test.terra.reference import ref_unitary_gate, ref_diagonal_gate
from qiskit import execute
from qiskit.providers.qrack import QasmSimulator
import numpy as np
class QasmUnitaryGateTests:
"""QasmSimulator unitary gate tests."""
SIMULATOR = QasmSimulator()
BACKEND_OPTS = {}
# ---------------------------------------------------------------------
# Test unitary gate qobj instruction
# ---------------------------------------------------------------------
def test_unitary_gate(self):
"""Test simulation with unitary gate circuit instructions."""
shots = 100
circuits = ref_unitary_gate.unitary_gate_circuits_deterministic(
final_measure=True)
targets = ref_unitary_gate.unitary_gate_counts_deterministic(
shots)
result = execute(circuits, self.SIMULATOR, shots=shots,
**self.BACKEND_OPTS).result()
self.assertSuccess(result)
self.compare_counts(result, circuits, targets, delta=0)
def test_random_unitary_gate(self):
"""Test simulation with random unitary gate circuit instructions."""
shots = 4000
circuits = ref_unitary_gate.unitary_random_gate_circuits_nondeterministic(final_measure=True)
targets = ref_unitary_gate.unitary_random_gate_counts_nondeterministic(shots)
result = execute(circuits, self.SIMULATOR, shots=shots,
**self.BACKEND_OPTS).result()
self.assertSuccess(result)
self.compare_counts(result, circuits, targets, delta=0.05 * shots)
class QasmDiagonalGateTests:
"""QasmSimulator diagonal gate tests."""
SIMULATOR = QasmSimulator()
BACKEND_OPTS = {}
# ---------------------------------------------------------------------
# Test unitary gate qobj instruction
# ---------------------------------------------------------------------
def test_diagonal_gate(self):
"""Test simulation with unitary gate circuit instructions."""
shots = 100
circuits = ref_diagonal_gate.diagonal_gate_circuits_deterministic(
final_measure=True)
targets = ref_diagonal_gate.diagonal_gate_counts_deterministic(
shots)
result = execute(circuits, self.SIMULATOR, shots=shots,
**self.BACKEND_OPTS).result()
self.assertSuccess(result)
self.compare_counts(result, circuits, targets, delta=0)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit import Parameter
from qiskit import QuantumCircuit
theta = Parameter('$\\theta$')
chsh_circuits_no_meas = QuantumCircuit(2)
chsh_circuits_no_meas.h(0)
chsh_circuits_no_meas.cx(0, 1)
chsh_circuits_no_meas.ry(theta, 0)
chsh_circuits_no_meas.draw('mpl')
import numpy as np
number_of_phases = 21
phases = np.linspace(0, 2*np.pi, number_of_phases)
# Phases need to be expressed as list of lists in order to work
individual_phases = [[ph] for ph in phases]
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit_ibm_runtime import Estimator, Session
from qiskit.quantum_info import SparsePauliOp
ZZ = SparsePauliOp.from_list([("ZZ", 1)])
ZX = SparsePauliOp.from_list([("ZX", 1)])
XZ = SparsePauliOp.from_list([("XZ", 1)])
XX = SparsePauliOp.from_list([("XX", 1)])
ops = [ZZ, ZX, XZ, XX]
chsh_est_sim = []
# Simulator
with Session(service=service, backend=backend):
estimator = Estimator()
for op in ops:
job = estimator.run(
circuits=[chsh_circuits_no_meas]*len(individual_phases),
observables=[op]*len(individual_phases),
parameter_values=individual_phases)
est_result = job.result()
chsh_est_sim.append(est_result)
# <CHSH1> = <AB> - <Ab> + <aB> + <ab>
chsh1_est_sim = chsh_est_sim[0].values - chsh_est_sim[1].values + chsh_est_sim[2].values + chsh_est_sim[3].values
# <CHSH2> = <AB> + <Ab> - <aB> + <ab>
chsh2_est_sim = chsh_est_sim[0].values + chsh_est_sim[1].values - chsh_est_sim[2].values + chsh_est_sim[3].values
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
fig, ax = plt.subplots(figsize=(10, 6))
# results from a simulator
ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Simulation')
ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Simulation')
# classical bound +-2
ax.axhline(y=2, color='r', linestyle='--')
ax.axhline(y=-2, color='r', linestyle='--')
# quantum bound, +-2√2
ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.')
ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.')
# set x tick labels to the unit of pi
ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5))
# set title, labels, and legend
plt.title('Violation of CHSH Inequality')
plt.xlabel('Theta')
plt.ylabel('CHSH witness')
plt.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
from hide_toggle import hide_toggle
#usage:
#1 create a cell with: hide_toggle(for_next=True)
#2 put the commented solution in the next cell
import qiskit as qk
import numpy as np
from scipy.linalg import expm
import matplotlib.pyplot as plt
import math
# definition of single qubit operators
sx = np.array([[0.0, 1.0],[1.0, 0.0]])
sy = np.array([[0.0, -1.0*1j],[1.0*1j, 0.0]])
sz = np.array([[1.0, 0.0],[0.0, -1.0]])
idt = np.array([[1.0, 0.0],[0.0, 1.0]])
psi0 = np.array([1.0, 0.0])
thetas = np.linspace(0,4*math.pi,200)
avg_sx_tot = np.zeros(len(thetas))
for i in range(len(thetas)):
psi_theta = expm(-1j*0.5*thetas[i]*(sx+sz)/math.sqrt(2)).dot(psi0)
avg_sx_tot[i] = np.real(psi_theta.conjugate().transpose().dot(sx.dot(psi_theta)))
plt.plot(thetas,avg_sx_tot)
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.show()
#solution
hide_toggle(for_next=True)
avg_sx_zx = np.zeros(len(thetas))
avg_sx_xz = np.zeros(len(thetas))
for i in range(len(thetas)):
psi_theta_zx = expm(-1j*0.5*thetas[i]*(sz)/math.sqrt(2)).dot(expm(-1j*0.5*thetas[i]*(sx)/math.sqrt(2)).dot(psi0))
psi_theta_xz = expm(-1j*0.5*thetas[i]*(sx)/math.sqrt(2)).dot(expm(-1j*0.5*thetas[i]*(sz)/math.sqrt(2)).dot(psi0))
avg_sx_zx[i] = np.real(psi_theta_zx.conjugate().transpose().dot(sx.dot(psi_theta_zx)))
avg_sx_xz[i] = np.real(psi_theta_xz.conjugate().transpose().dot(sx.dot(psi_theta_xz)))
plt.plot(thetas,avg_sx_tot)
plt.plot(thetas,avg_sx_zx)
plt.plot(thetas,avg_sx_xz)
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.legend(['Around x = z', 'x first', 'z first'],loc=1)
plt.show()
# Try this with e.g. ntrot = 1, 5, 10, 50.
# You can also try to do sx and sz slices in the reverse order: both choices will become good approximations for large n
ntrot = 8
avg_sx_n = np.zeros(len(thetas))
for i in range(len(thetas)):
rot = expm(-1j*0.5*thetas[i]*(sx)/(ntrot*math.sqrt(2))).dot(expm(-1j*0.5*thetas[i]*(sz)/(ntrot*math.sqrt(2))))
for j in range(ntrot-1):
rot = expm(-1j*0.5*thetas[i]*(sx)/(ntrot*math.sqrt(2))).dot(expm(-1j*0.5*thetas[i]*(sz)/(ntrot*math.sqrt(2)))).dot(rot)
psi_theta_n = rot.dot(psi0)
avg_sx_n[i] = np.real(psi_theta_n.conjugate().transpose().dot(sx.dot(psi_theta_n)))
plt.plot(thetas,avg_sx_tot)
plt.plot(thetas,avg_sx_n,'--')
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.legend(['Exact', 'ntrot = ' + str(ntrot)],loc=1)
plt.show()
#solution
hide_toggle(for_next=True)
# commutation function
def comm_check(a,b):
aa = np.kron(a,a)
bb = np.kron(b,b)
return (np.dot(aa,bb) - np.dot(bb,aa))
comm_check(sx,sy)
delta = 0.1
qr = qk.QuantumRegister(2,name='qr')
zz_example = qk.QuantumCircuit(qr)
zz_example.cx(qr[0],qr[1])
zz_example.u1(2*delta,qr[1])
zz_example.cx(qr[0],qr[1])
zz_example.draw(output='mpl')
#solution
J = 1
c_times = np.linspace(0,0.5*math.pi/abs(J),1000)
q_times = np.linspace(0,0.5*math.pi/abs(J),10)
### Classical simulation of the Heisenberg dimer model
psi0 = np.kron( np.array([0,1]), np.array([1,0]) )
H = J * ( np.kron(sx,sx) + np.kron(sy,sy) + np.kron(sz,sz) )
sz1_t = np.zeros(len(c_times))
sz2_t = np.zeros(len(c_times))
sz1 = np.kron(sz,idt)
sz2 = np.kron(idt,sz)
for i in range(len(c_times)):
t = c_times[i]
psi_t = expm(-1j*H*t).dot(psi0)
sz1_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
### Digital quantum simulation of the Heisenberg dimer model using qiskit
nshots = 1024
sz1q_t = np.zeros(len(q_times))
sz2q_t = np.zeros(len(q_times))
#Solution: try to write the circuit and the quantum evolution,
#hints: start with:
#for k in range(len(q_times)):
#delta =
#define QuantumRegister, ClassicalRegister and QuantumCircuit (Heis2)
#define initial state
#define each part of the circuit: ZZ, YY, XX
#measurement
# Post processing of outcomes to get sz expectation values
#sz1q = 0
#sz2q = 0
#for key,value in counts.items():
#if key == '00':
#sz1q += value
#sz2q += value
#elif key == '01':
#sz1q -= value
#sz2q += value
#elif key == '10':
#sz1q += value
#sz2q -= value
#elif key == '11':
#sz1q -= value
#sz2q -= value
#sz1q_t[k] = sz1q/nshots
#sz2q_t[k] = sz2q/nshots
# Run the quantum algorithm and colect the result, counts
hide_toggle(for_next=True)
for k in range(len(q_times)):
delta = J*q_times[k]
qr = qk.QuantumRegister(2,name='qr')
cr = qk.ClassicalRegister(2,name='cr')
Heis2 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis2.x(qr[0])
# ZZ
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
# YY
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[1])
# measure
Heis2.measure(qr,cr)
# Run the quantum algorithm
backend = qk.BasicAer.get_backend('qasm_simulator')
job = qk.execute(Heis2, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
# Post processing of outcomes to get sz expectation values
sz1q = 0
sz2q = 0
for key,value in counts.items():
if key == '00':
sz1q += value
sz2q += value
elif key == '01':
sz1q -= value
sz2q += value
elif key == '10':
sz1q += value
sz2q -= value
elif key == '11':
sz1q -= value
sz2q -= value
sz1q_t[k] = sz1q/nshots
sz2q_t[k] = sz2q/nshots
plt.plot(abs(J)*c_times,0.5*sz1_t,'b--')
plt.plot(abs(J)*c_times,0.5*sz2_t,'c')
plt.plot(abs(J)*q_times,0.5*sz1q_t,'rd')
plt.plot(abs(J)*q_times,0.5*sz2q_t,'ko')
plt.legend(['sz1','sz2','sz1q','sz2q'])
plt.xlabel(r'$\delta = |J|t$')
plt.show()
# WARNING: all these cells can take a few minutes to run!
ntrotter = 5
J12 = 1
J23 = 1
c_times = np.linspace(0,math.pi/abs(J12),1000)
q_times = np.linspace(0,math.pi/abs(J12),20)
### Classical simulation of the Heisenberg trimer model
psi0 = np.kron( np.kron( np.array([0,1]), np.array([1,0]) ) , np.array([1,0]) )
# SOLUTION:
#sxsx12 = np.kron(sx, np.kron(sx,idt))
#sysy12 =
#szsz12 =
#sxsx23 =
#sysy23 =
#szsz23 =
#H12 = J12 * ( sxsx12 + sysy12 + szsz12 )
#H23 =
#H = H12 + H23
hide_toggle(for_next=True)
sxsx12 = np.kron(sx, np.kron(sx,idt))
sysy12 = np.kron(sy, np.kron(sy,idt))
szsz12 = np.kron(sz, np.kron(sz,idt))
sxsx23 = np.kron(idt, np.kron(sx,sx))
sysy23 = np.kron(idt, np.kron(sy,sy))
szsz23 = np.kron(idt, np.kron(sz,sz))
H12 = J12 * ( sxsx12 + sysy12 + szsz12 )
H23 = J23 * ( sxsx23 + sysy23 + szsz23 )
H = H12 + H23
sz1_t = np.zeros(len(c_times))
sz2_t = np.zeros(len(c_times))
sz3_t = np.zeros(len(c_times))
sz1 = np.kron(sz, np.kron(idt,idt))
sz2 = np.kron(idt, np.kron(sz,idt))
sz3 = np.kron(idt, np.kron(idt,sz))
#SOLUTION:
#for i in range(len(c_times)):
#t = c_times[i]
#psi_t =
#sz1_t[i] =
#sz2_t[i] =
#sz3_t[i] =
hide_toggle(for_next=True)
for i in range(len(c_times)):
t = c_times[i]
psi_t = expm(-1j*H*t).dot(psi0)
sz1_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
sz3_t[i] = np.real(psi_t.conjugate().transpose().dot(sz3.dot(psi_t)))
### Classical simulation of the Heisenberg trimer model WITH SUZUKI TROTTER DIGITALIZATION
sz1st_t = np.zeros(len(c_times))
sz2st_t = np.zeros(len(c_times))
sz3st_t = np.zeros(len(c_times))
for i in range(len(c_times)):
t = c_times[i]
Ust = expm(-1j*H23*t/ntrotter).dot(expm(-1j*H12*t/ntrotter))
for j in range(ntrotter-1):
Ust = expm(-1j*H23*t/ntrotter).dot(expm(-1j*H12*t/ntrotter)).dot(Ust)
psi_t = Ust.dot(psi0)
sz1st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
sz3st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz3.dot(psi_t)))
### Digital quantum simulation of the Heisenberg model using qiskit
hide_toggle(for_next=True)
### Digital quantum simulation of the Heisenberg model using qiskit
nshots = 1024
sz1q_t = np.zeros(len(q_times))
sz2q_t = np.zeros(len(q_times))
sz3q_t = np.zeros(len(q_times))
for k in range(len(q_times)):
delta12n = J12*q_times[k]/ntrotter
delta23n = J23*q_times[k]/ntrotter
qr = qk.QuantumRegister(3,name='qr')
cr = qk.ClassicalRegister(3,name='cr')
Heis3 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis3.x(qr[0])
for n in range(ntrotter):
# 1-2 bond mapped on qubits 0 and 1 in the quantum register
# ZZ
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
# YY
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[1])
# 2-3 bond mapped on qubits 1 and 2 in the quantum register
# ZZ
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
# YY
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[2])
# XX
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[1])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[2])
# measure
Heis3.measure(qr,cr)
# Run the quantum algorithm
backend = qk.BasicAer.get_backend('qasm_simulator')
job = qk.execute(Heis3, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
# Post processing of outcomes to get sz expectation values
sz1q = 0
sz2q = 0
sz3q = 0
for key,value in counts.items():
if key == '000':
sz1q += value
sz2q += value
sz3q += value
elif key == '001':
sz1q -= value
sz2q += value
sz3q += value
elif key == '010':
sz1q += value
sz2q -= value
sz3q += value
elif key == '011':
sz1q -= value
sz2q -= value
sz3q += value
elif key == '100':
sz1q += value
sz2q += value
sz3q -= value
elif key == '101':
sz1q -= value
sz2q += value
sz3q -= value
elif key == '110':
sz1q += value
sz2q -= value
sz3q -= value
elif key == '111':
sz1q -= value
sz2q -= value
sz3q -= value
sz1q_t[k] = sz1q/nshots
sz2q_t[k] = sz2q/nshots
sz3q_t[k] = sz3q/nshots
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(abs(J12)*c_times,0.5*sz1_t,'b', label='sz1 full')
ax.plot(abs(J12)*c_times,0.5*sz2_t,'r', label='sz2 full')
ax.plot(abs(J12)*c_times,0.5*sz3_t,'g', label='sz3 full')
ax.plot(abs(J12)*c_times,0.5*sz1st_t,'b--',label='sz1 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*c_times,0.5*sz2st_t,'r--', label='sz2 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*c_times,0.5*sz3st_t,'g--', label='sz3 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*q_times,0.5*sz1q_t,'b*',label='sz1 n = ' + str(ntrotter) + ' (quantum)')
ax.plot(abs(J12)*q_times,0.5*sz2q_t,'ro', label='sz2 n = ' + str(ntrotter) + ' (quantum)')
ax.plot(abs(J12)*q_times,0.5*sz3q_t,'gd', label='sz3 n = ' + str(ntrotter) + ' (quantum)')
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.8), shadow=True, ncol=1)
plt.xlabel(r'$\delta_{12} = |J_{12}|t$')
plt.show()
Heis3.count_ops()
import Qconfig
from qiskit.tools.monitor import job_monitor
qk.IBMQ.enable_account(Qconfig.APItoken, **Qconfig.config)
delta = 0.5*math.pi
qr = qk.QuantumRegister(2,name='qr')
cr = qk.ClassicalRegister(2,name='cr')
Heis2 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis2.x(qr[0])
# ZZ
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
# YY
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[1])
# measure
Heis2.measure(qr,cr)
my_backend = qk.IBMQ.get_backend('ibmqx4')
job = qk.execute(Heis2, backend=my_backend, shots=1024)
job_monitor(job, interval=5)
result = job.result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
my_backend.configuration().coupling_map # In the output, the first entry in a pair [a,b] is a control, second is the
# corresponding target for a CNOT
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the TemplateOptimization pass."""
import unittest
from test.python.quantum_info.operators.symplectic.test_clifford import random_clifford_circuit
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.quantum_info import Operator
from qiskit.circuit.library.templates.nct import template_nct_2a_2, template_nct_5a_3
from qiskit.circuit.library.templates.clifford import (
clifford_2_1,
clifford_2_2,
clifford_2_3,
clifford_2_4,
clifford_3_1,
clifford_4_1,
clifford_4_2,
)
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.converters.circuit_to_dagdependency import circuit_to_dagdependency
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import TemplateOptimization
from qiskit.transpiler.passes.calibration.rzx_templates import rzx_templates
from qiskit.test import QiskitTestCase
from qiskit.transpiler.exceptions import TranspilerError
def _ry_to_rz_template_pass(parameter: Parameter = None, extra_costs=None):
"""Create a simple pass manager that runs a template optimisation with a single transformation.
It turns ``RX(pi/2).RY(parameter).RX(-pi/2)`` into the equivalent virtual ``RZ`` rotation, where
if ``parameter`` is given, it will be the instance used in the template."""
if parameter is None:
parameter = Parameter("_ry_rz_template_inner")
template = QuantumCircuit(1)
template.rx(-np.pi / 2, 0)
template.ry(parameter, 0)
template.rx(np.pi / 2, 0)
template.rz(-parameter, 0) # pylint: disable=invalid-unary-operand-type
costs = {"rx": 16, "ry": 16, "rz": 0}
if extra_costs is not None:
costs.update(extra_costs)
return PassManager(TemplateOptimization([template], user_cost_dict=costs))
class TestTemplateMatching(QiskitTestCase):
"""Test the TemplateOptimization pass."""
def test_pass_cx_cancellation_no_template_given(self):
"""
Check the cancellation of CX gates for the apply of the three basic
template x-x, cx-cx. ccx-ccx.
"""
qr = QuantumRegister(3)
circuit_in = QuantumCircuit(qr)
circuit_in.h(qr[0])
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[1], qr[0])
circuit_in.cx(qr[1], qr[0])
pass_manager = PassManager()
pass_manager.append(TemplateOptimization())
circuit_in_opt = pass_manager.run(circuit_in)
circuit_out = QuantumCircuit(qr)
circuit_out.h(qr[0])
circuit_out.h(qr[0])
self.assertEqual(circuit_in_opt, circuit_out)
def test_pass_cx_cancellation_own_template(self):
"""
Check the cancellation of CX gates for the apply of a self made template cx-cx.
"""
qr = QuantumRegister(2, "qr")
circuit_in = QuantumCircuit(qr)
circuit_in.h(qr[0])
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[1], qr[0])
circuit_in.cx(qr[1], qr[0])
dag_in = circuit_to_dag(circuit_in)
qrt = QuantumRegister(2, "qrc")
qct = QuantumCircuit(qrt)
qct.cx(0, 1)
qct.cx(0, 1)
template_list = [qct]
pass_ = TemplateOptimization(template_list)
dag_opt = pass_.run(dag_in)
circuit_expected = QuantumCircuit(qr)
circuit_expected.h(qr[0])
circuit_expected.h(qr[0])
dag_expected = circuit_to_dag(circuit_expected)
self.assertEqual(dag_opt, dag_expected)
def test_pass_cx_cancellation_template_from_library(self):
"""
Check the cancellation of CX gates for the apply of the library template cx-cx (2a_2).
"""
qr = QuantumRegister(2, "qr")
circuit_in = QuantumCircuit(qr)
circuit_in.h(qr[0])
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[1], qr[0])
circuit_in.cx(qr[1], qr[0])
dag_in = circuit_to_dag(circuit_in)
template_list = [template_nct_2a_2()]
pass_ = TemplateOptimization(template_list)
dag_opt = pass_.run(dag_in)
circuit_expected = QuantumCircuit(qr)
circuit_expected.h(qr[0])
circuit_expected.h(qr[0])
dag_expected = circuit_to_dag(circuit_expected)
self.assertEqual(dag_opt, dag_expected)
def test_pass_template_nct_5a(self):
"""
Verify the result of template matching and substitution with the template 5a_3.
q_0: ───────■─────────■────■──
┌─┴─┐ ┌─┴─┐ │
q_1: ──■──┤ X ├──■──┤ X ├──┼──
┌─┴─┐└───┘┌─┴─┐└───┘┌─┴─┐
q_2: ┤ X ├─────┤ X ├─────┤ X ├
└───┘ └───┘ └───┘
The circuit before optimization is:
┌───┐ ┌───┐
qr_0: ┤ X ├───────────────┤ X ├─────
└─┬─┘ ┌───┐┌───┐└─┬─┘
qr_1: ──┼────■──┤ X ├┤ Z ├──┼────■──
│ │ └─┬─┘└───┘ │ │
qr_2: ──┼────┼────■────■────■────┼──
│ │ ┌───┐┌─┴─┐ │ │
qr_3: ──■────┼──┤ H ├┤ X ├──■────┼──
│ ┌─┴─┐└───┘└───┘ ┌─┴─┐
qr_4: ──■──┤ X ├───────────────┤ X ├
└───┘ └───┘
The match is given by [0,1][1,2][2,7], after substitution the circuit becomes:
┌───┐ ┌───┐
qr_0: ┤ X ├───────────────┤ X ├
└─┬─┘ ┌───┐┌───┐└─┬─┘
qr_1: ──┼───────┤ X ├┤ Z ├──┼──
│ └─┬─┘└───┘ │
qr_2: ──┼────■────■────■────■──
│ │ ┌───┐┌─┴─┐ │
qr_3: ──■────┼──┤ H ├┤ X ├──■──
│ ┌─┴─┐└───┘└───┘
qr_4: ──■──┤ X ├───────────────
└───┘
"""
qr = QuantumRegister(5, "qr")
circuit_in = QuantumCircuit(qr)
circuit_in.ccx(qr[3], qr[4], qr[0])
circuit_in.cx(qr[1], qr[4])
circuit_in.cx(qr[2], qr[1])
circuit_in.h(qr[3])
circuit_in.z(qr[1])
circuit_in.cx(qr[2], qr[3])
circuit_in.ccx(qr[2], qr[3], qr[0])
circuit_in.cx(qr[1], qr[4])
dag_in = circuit_to_dag(circuit_in)
template_list = [template_nct_5a_3()]
pass_ = TemplateOptimization(template_list)
dag_opt = pass_.run(dag_in)
# note: cx(2, 1) commutes both with ccx(3, 4, 0) and with cx(2, 4),
# so there is no real difference with the circuit drawn on the picture above.
circuit_expected = QuantumCircuit(qr)
circuit_expected.cx(qr[2], qr[1])
circuit_expected.ccx(qr[3], qr[4], qr[0])
circuit_expected.cx(qr[2], qr[4])
circuit_expected.z(qr[1])
circuit_expected.h(qr[3])
circuit_expected.cx(qr[2], qr[3])
circuit_expected.ccx(qr[2], qr[3], qr[0])
dag_expected = circuit_to_dag(circuit_expected)
self.assertEqual(dag_opt, dag_expected)
def test_pass_template_wrong_type(self):
"""
If a template is not equivalent to the identity, it raises an error.
"""
qr = QuantumRegister(2, "qr")
circuit_in = QuantumCircuit(qr)
circuit_in.h(qr[0])
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[1], qr[0])
circuit_in.cx(qr[1], qr[0])
dag_in = circuit_to_dag(circuit_in)
qrt = QuantumRegister(2, "qrc")
qct = QuantumCircuit(qrt)
qct.cx(0, 1)
qct.x(0)
qct.h(1)
template_list = [qct]
pass_ = TemplateOptimization(template_list)
self.assertRaises(TranspilerError, pass_.run, dag_in)
def test_accept_dagdependency(self):
"""
Check that users can supply DAGDependency in the template list.
"""
circuit_in = QuantumCircuit(2)
circuit_in.cnot(0, 1)
circuit_in.cnot(0, 1)
templates = [circuit_to_dagdependency(circuit_in)]
pass_ = TemplateOptimization(template_list=templates)
circuit_out = PassManager(pass_).run(circuit_in)
# these are NOT equal if template optimization works
self.assertNotEqual(circuit_in, circuit_out)
# however these are equivalent if the operators are the same
self.assertTrue(Operator(circuit_in).equiv(circuit_out))
def test_parametric_template(self):
"""
Check matching where template has parameters.
┌───────────┐ ┌────────┐
q_0: ┤ P(-1.0*β) ├──■────────────■──┤0 ├
├───────────┤┌─┴─┐┌──────┐┌─┴─┐│ CU(2β)│
q_1: ┤ P(-1.0*β) ├┤ X ├┤ P(β) ├┤ X ├┤1 ├
└───────────┘└───┘└──────┘└───┘└────────┘
First test try match on
┌───────┐
q_0: ┤ P(-2) ├──■────────────■─────────────────────────────
├───────┤┌─┴─┐┌──────┐┌─┴─┐┌───────┐
q_1: ┤ P(-2) ├┤ X ├┤ P(2) ├┤ X ├┤ P(-3) ├──■────────────■──
├───────┤└───┘└──────┘└───┘└───────┘┌─┴─┐┌──────┐┌─┴─┐
q_2: ┤ P(-3) ├───────────────────────────┤ X ├┤ P(3) ├┤ X ├
└───────┘ └───┘└──────┘└───┘
Second test try match on
┌───────┐
q_0: ┤ P(-2) ├──■────────────■────────────────────────────
├───────┤┌─┴─┐┌──────┐┌─┴─┐┌──────┐
q_1: ┤ P(-2) ├┤ X ├┤ P(2) ├┤ X ├┤ P(3) ├──■────────────■──
└┬──────┤└───┘└──────┘└───┘└──────┘┌─┴─┐┌──────┐┌─┴─┐
q_2: ─┤ P(3) ├──────────────────────────┤ X ├┤ P(3) ├┤ X ├
└──────┘ └───┘└──────┘└───┘
"""
beta = Parameter("β")
template = QuantumCircuit(2)
template.p(-beta, 0)
template.p(-beta, 1)
template.cx(0, 1)
template.p(beta, 1)
template.cx(0, 1)
template.cu(0, 2.0 * beta, 0, 0, 0, 1)
def count_cx(qc):
"""Counts the number of CX gates for testing."""
return qc.count_ops().get("cx", 0)
circuit_in = QuantumCircuit(3)
circuit_in.p(-2, 0)
circuit_in.p(-2, 1)
circuit_in.cx(0, 1)
circuit_in.p(2, 1)
circuit_in.cx(0, 1)
circuit_in.p(-3, 1)
circuit_in.p(-3, 2)
circuit_in.cx(1, 2)
circuit_in.p(3, 2)
circuit_in.cx(1, 2)
pass_ = TemplateOptimization(
template_list=[template],
user_cost_dict={"cx": 6, "p": 0, "cu": 8},
)
circuit_out = PassManager(pass_).run(circuit_in)
np.testing.assert_almost_equal(Operator(circuit_out).data[3, 3], np.exp(-4.0j))
np.testing.assert_almost_equal(Operator(circuit_out).data[7, 7], np.exp(-10.0j))
self.assertEqual(count_cx(circuit_out), 0) # Two matches => no CX gates.
np.testing.assert_almost_equal(Operator(circuit_in).data, Operator(circuit_out).data)
circuit_in = QuantumCircuit(3)
circuit_in.p(-2, 0)
circuit_in.p(-2, 1)
circuit_in.cx(0, 1)
circuit_in.p(2, 1)
circuit_in.cx(0, 1)
circuit_in.p(3, 1)
circuit_in.p(3, 2)
circuit_in.cx(1, 2)
circuit_in.p(3, 2)
circuit_in.cx(1, 2)
pass_ = TemplateOptimization(
template_list=[template],
user_cost_dict={"cx": 6, "p": 0, "cu": 8},
)
circuit_out = PassManager(pass_).run(circuit_in)
# these are NOT equal if template optimization works
self.assertNotEqual(circuit_in, circuit_out)
# however these are equivalent if the operators are the same
self.assertTrue(Operator(circuit_in).equiv(circuit_out))
def test_optimizer_does_not_replace_unbound_partial_match(self):
"""
Test that partial matches with parameters will not raise errors.
This tests that if parameters are still in the temporary template after
_attempt_bind then they will not be used.
"""
beta = Parameter("β")
template = QuantumCircuit(2)
template.cx(1, 0)
template.cx(1, 0)
template.p(beta, 1)
template.cu(0, 0, 0, -beta, 0, 1)
circuit_in = QuantumCircuit(2)
circuit_in.cx(1, 0)
circuit_in.cx(1, 0)
pass_ = TemplateOptimization(
template_list=[template],
user_cost_dict={"cx": 6, "p": 0, "cu": 8},
)
circuit_out = PassManager(pass_).run(circuit_in)
# The template optimisation should not have replaced anything, because
# that would require it to leave dummy parameters in place without
# binding them.
self.assertEqual(circuit_in, circuit_out)
def test_unbound_parameters_in_rzx_template(self):
"""
Test that rzx template ('zz2') functions correctly for a simple
circuit with an unbound ParameterExpression. This uses the same
Parameter (theta) as the template, so this also checks that template
substitution handle this correctly.
"""
theta = Parameter("ϴ")
circuit_in = QuantumCircuit(2)
circuit_in.cx(0, 1)
circuit_in.p(2 * theta, 1)
circuit_in.cx(0, 1)
pass_ = TemplateOptimization(**rzx_templates(["zz2"]))
circuit_out = PassManager(pass_).run(circuit_in)
# these are NOT equal if template optimization works
self.assertNotEqual(circuit_in, circuit_out)
# however these are equivalent if the operators are the same
theta_set = 0.42
self.assertTrue(
Operator(circuit_in.bind_parameters({theta: theta_set})).equiv(
circuit_out.bind_parameters({theta: theta_set})
)
)
def test_two_parameter_template(self):
"""
Test a two-Parameter template based on rzx_templates(["zz3"]),
┌───┐┌───────┐┌───┐┌────────────┐»
q_0: ──■─────────────■──┤ X ├┤ Rz(φ) ├┤ X ├┤ Rz(-1.0*φ) ├»
┌─┴─┐┌───────┐┌─┴─┐└─┬─┘└───────┘└─┬─┘└────────────┘»
q_1: ┤ X ├┤ Rz(θ) ├┤ X ├──■─────────────■────────────────»
└───┘└───────┘└───┘
« ┌─────────┐┌─────────┐┌─────────┐┌───────────┐┌──────────────┐»
«q_0: ┤ Rz(π/2) ├┤ Rx(π/2) ├┤ Rz(π/2) ├┤ Rx(1.0*φ) ├┤1 ├»
« └─────────┘└─────────┘└─────────┘└───────────┘│ Rzx(-1.0*φ) │»
«q_1: ──────────────────────────────────────────────┤0 ├»
« └──────────────┘»
« ┌─────────┐ ┌─────────┐┌─────────┐ »
«q_0: ─┤ Rz(π/2) ├──┤ Rx(π/2) ├┤ Rz(π/2) ├────────────────────────»
« ┌┴─────────┴─┐├─────────┤├─────────┤┌─────────┐┌───────────┐»
«q_1: ┤ Rz(-1.0*θ) ├┤ Rz(π/2) ├┤ Rx(π/2) ├┤ Rz(π/2) ├┤ Rx(1.0*θ) ├»
« └────────────┘└─────────┘└─────────┘└─────────┘└───────────┘»
« ┌──────────────┐
«q_0: ┤0 ├─────────────────────────────────
« │ Rzx(-1.0*θ) │┌─────────┐┌─────────┐┌─────────┐
«q_1: ┤1 ├┤ Rz(π/2) ├┤ Rx(π/2) ├┤ Rz(π/2) ├
« └──────────────┘└─────────┘└─────────┘└─────────┘
correctly template matches into a unique circuit, but that it is
equivalent to the input circuit when the Parameters are bound to floats
and checked with Operator equivalence.
"""
theta = Parameter("θ")
phi = Parameter("φ")
template = QuantumCircuit(2)
template.cx(0, 1)
template.rz(theta, 1)
template.cx(0, 1)
template.cx(1, 0)
template.rz(phi, 0)
template.cx(1, 0)
template.rz(-phi, 0)
template.rz(np.pi / 2, 0)
template.rx(np.pi / 2, 0)
template.rz(np.pi / 2, 0)
template.rx(phi, 0)
template.rzx(-phi, 1, 0)
template.rz(np.pi / 2, 0)
template.rz(-theta, 1)
template.rx(np.pi / 2, 0)
template.rz(np.pi / 2, 1)
template.rz(np.pi / 2, 0)
template.rx(np.pi / 2, 1)
template.rz(np.pi / 2, 1)
template.rx(theta, 1)
template.rzx(-theta, 0, 1)
template.rz(np.pi / 2, 1)
template.rx(np.pi / 2, 1)
template.rz(np.pi / 2, 1)
alpha = Parameter("$\\alpha$")
beta = Parameter("$\\beta$")
circuit_in = QuantumCircuit(2)
circuit_in.cx(0, 1)
circuit_in.rz(2 * alpha, 1)
circuit_in.cx(0, 1)
circuit_in.cx(1, 0)
circuit_in.rz(3 * beta, 0)
circuit_in.cx(1, 0)
pass_ = TemplateOptimization(
[template],
user_cost_dict={"cx": 6, "rz": 0, "rx": 1, "rzx": 0},
)
circuit_out = PassManager(pass_).run(circuit_in)
# these are NOT equal if template optimization works
self.assertNotEqual(circuit_in, circuit_out)
# however these are equivalent if the operators are the same
alpha_set = 0.37
beta_set = 0.42
self.assertTrue(
Operator(circuit_in.bind_parameters({alpha: alpha_set, beta: beta_set})).equiv(
circuit_out.bind_parameters({alpha: alpha_set, beta: beta_set})
)
)
def test_exact_substitution_numeric_parameter(self):
"""Test that a template match produces the expected value for numeric parameters."""
circuit_in = QuantumCircuit(1)
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(1.45, 0)
circuit_in.rx(np.pi / 2, 0)
circuit_out = _ry_to_rz_template_pass().run(circuit_in)
expected = QuantumCircuit(1)
expected.rz(1.45, 0)
self.assertEqual(circuit_out, expected)
def test_exact_substitution_symbolic_parameter(self):
"""Test that a template match produces the expected value for numeric parameters."""
a_circuit = Parameter("a")
circuit_in = QuantumCircuit(1)
circuit_in.h(0)
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(a_circuit, 0)
circuit_in.rx(np.pi / 2, 0)
circuit_out = _ry_to_rz_template_pass(extra_costs={"h": 1}).run(circuit_in)
expected = QuantumCircuit(1)
expected.h(0)
expected.rz(a_circuit, 0)
self.assertEqual(circuit_out, expected)
def test_naming_clash(self):
"""Test that the template matching works and correctly replaces a template if there is a
naming clash between it and the circuit. This should include binding a partial match with a
parameter."""
# Two instances of parameters with the same name---this is how naming clashes might occur.
a_template = Parameter("a")
a_circuit = Parameter("a")
circuit_in = QuantumCircuit(1)
circuit_in.h(0)
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(a_circuit, 0)
circuit_in.rx(np.pi / 2, 0)
circuit_out = _ry_to_rz_template_pass(a_template, extra_costs={"h": 1}).run(circuit_in)
expected = QuantumCircuit(1)
expected.h(0)
expected.rz(a_circuit, 0)
self.assertEqual(circuit_out, expected)
# Ensure that the bound parameter in the output is referentially the same as the one we put
# in the input circuit..
self.assertEqual(len(circuit_out.parameters), 1)
self.assertIs(circuit_in.parameters[0], a_circuit)
self.assertIs(circuit_out.parameters[0], a_circuit)
def test_naming_clash_in_expression(self):
"""Test that the template matching works and correctly replaces a template if there is a
naming clash between it and the circuit. This should include binding a partial match with a
parameter."""
a_template = Parameter("a")
a_circuit = Parameter("a")
circuit_in = QuantumCircuit(1)
circuit_in.h(0)
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(2 * a_circuit, 0)
circuit_in.rx(np.pi / 2, 0)
circuit_out = _ry_to_rz_template_pass(a_template, extra_costs={"h": 1}).run(circuit_in)
expected = QuantumCircuit(1)
expected.h(0)
expected.rz(2 * a_circuit, 0)
self.assertEqual(circuit_out, expected)
# Ensure that the bound parameter in the output is referentially the same as the one we put
# in the input circuit..
self.assertEqual(len(circuit_out.parameters), 1)
self.assertIs(circuit_in.parameters[0], a_circuit)
self.assertIs(circuit_out.parameters[0], a_circuit)
def test_template_match_with_uninvolved_parameter(self):
"""Test that the template matching algorithm succeeds at matching a circuit that contains an
unbound parameter that is not involved in the subcircuit that matches."""
b_circuit = Parameter("b")
circuit_in = QuantumCircuit(2)
circuit_in.rz(b_circuit, 0)
circuit_in.rx(-np.pi / 2, 1)
circuit_in.ry(1.45, 1)
circuit_in.rx(np.pi / 2, 1)
circuit_out = _ry_to_rz_template_pass().run(circuit_in)
expected = QuantumCircuit(2)
expected.rz(b_circuit, 0)
expected.rz(1.45, 1)
self.assertEqual(circuit_out, expected)
def test_multiple_numeric_matches_same_template(self):
"""Test that the template matching will change both instances of a partial match within a
longer circuit."""
circuit_in = QuantumCircuit(2)
# Qubit 0
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(1.32, 0)
circuit_in.rx(np.pi / 2, 0)
# Qubit 1
circuit_in.rx(-np.pi / 2, 1)
circuit_in.ry(2.54, 1)
circuit_in.rx(np.pi / 2, 1)
circuit_out = _ry_to_rz_template_pass().run(circuit_in)
expected = QuantumCircuit(2)
expected.rz(1.32, 0)
expected.rz(2.54, 1)
self.assertEqual(circuit_out, expected)
def test_multiple_symbolic_matches_same_template(self):
"""Test that the template matching will change both instances of a partial match within a
longer circuit."""
a, b = Parameter("a"), Parameter("b")
circuit_in = QuantumCircuit(2)
# Qubit 0
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(a, 0)
circuit_in.rx(np.pi / 2, 0)
# Qubit 1
circuit_in.rx(-np.pi / 2, 1)
circuit_in.ry(b, 1)
circuit_in.rx(np.pi / 2, 1)
circuit_out = _ry_to_rz_template_pass().run(circuit_in)
expected = QuantumCircuit(2)
expected.rz(a, 0)
expected.rz(b, 1)
self.assertEqual(circuit_out, expected)
def test_template_match_multiparameter(self):
"""Test that the template matching works on instructions that take more than one
parameter."""
a = Parameter("a")
b = Parameter("b")
template = QuantumCircuit(1)
template.u(0, a, b, 0)
template.rz(-a - b, 0)
circuit_in = QuantumCircuit(1)
circuit_in.u(0, 1.23, 2.45, 0)
pm = PassManager(TemplateOptimization([template], user_cost_dict={"u": 16, "rz": 0}))
circuit_out = pm.run(circuit_in)
expected = QuantumCircuit(1)
expected.rz(1.23 + 2.45, 0)
self.assertEqual(circuit_out, expected)
def test_naming_clash_multiparameter(self):
"""Test that the naming clash prevention mechanism works with instructions that take
multiple parameters."""
a_template = Parameter("a")
b_template = Parameter("b")
template = QuantumCircuit(1)
template.u(0, a_template, b_template, 0)
template.rz(-a_template - b_template, 0)
a_circuit = Parameter("a")
b_circuit = Parameter("b")
circuit_in = QuantumCircuit(1)
circuit_in.u(0, a_circuit, b_circuit, 0)
pm = PassManager(TemplateOptimization([template], user_cost_dict={"u": 16, "rz": 0}))
circuit_out = pm.run(circuit_in)
expected = QuantumCircuit(1)
expected.rz(a_circuit + b_circuit, 0)
self.assertEqual(circuit_out, expected)
def test_consecutive_templates_apply(self):
"""Test the scenario where one template optimization creates an opportunity for
another template optimization.
This is the original circuit:
┌───┐
q_0: ┤ X ├──■───X───────■─
└─┬─┘┌─┴─┐ │ ┌───┐ │
q_1: ──■──┤ X ├─X─┤ H ├─■─
└───┘ └───┘
The clifford_4_1 template allows to replace the two CNOTs followed by the SWAP by a
single CNOT:
q_0: ──■────────■─
┌─┴─┐┌───┐ │
q_1: ┤ X ├┤ H ├─■─
└───┘└───┘
At these point, the clifford_4_2 template allows to replace the circuit by a single
Hadamard gate:
q_0: ─────
┌───┐
q_1: ┤ H ├
└───┘
The second optimization would not have been possible without the applying the first
optimization.
"""
qc = QuantumCircuit(2)
qc.cx(1, 0)
qc.cx(0, 1)
qc.swap(0, 1)
qc.h(1)
qc.cz(0, 1)
qc_expected = QuantumCircuit(2)
qc_expected.h(1)
costs = {"h": 1, "cx": 2, "cz": 2, "swap": 3}
# Check that consecutively applying both templates leads to the expected circuit.
qc_opt = TemplateOptimization(
template_list=[clifford_4_1(), clifford_4_2()], user_cost_dict=costs
)(qc)
self.assertEqual(qc_opt, qc_expected)
# Also check that applying the second template by itself does not do anything.
qc_non_opt = TemplateOptimization(template_list=[clifford_4_2()], user_cost_dict=costs)(qc)
self.assertEqual(qc, qc_non_opt)
def test_consecutive_templates_do_not_apply(self):
"""Test that applying one template optimization does not allow incorrectly
applying other templates (which could happen if the DagDependency graph is
not constructed correctly after the optimization).
"""
template_list = [
clifford_2_2(),
clifford_2_3(),
]
pm = PassManager(TemplateOptimization(template_list=template_list))
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.cx(0, 1)
qc.h(0)
qc.swap(0, 1)
qc.h(0)
qc_opt = pm.run(qc)
self.assertTrue(Operator(qc) == Operator(qc_opt))
def test_clifford_templates(self):
"""Tests TemplateOptimization pass on several larger examples."""
template_list = [
clifford_2_1(),
clifford_2_2(),
clifford_2_3(),
clifford_2_4(),
clifford_3_1(),
]
pm = PassManager(TemplateOptimization(template_list=template_list))
for seed in range(10):
qc = random_clifford_circuit(
num_qubits=5,
num_gates=100,
gates=["x", "y", "z", "h", "s", "sdg", "cx", "cz", "swap"],
seed=seed,
)
qc_opt = pm.run(qc)
self.assertTrue(Operator(qc) == Operator(qc_opt))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Core module of the timeline drawer.
This module provides the `DrawerCanvas` which is a collection of drawings.
The canvas instance is not just a container of drawing objects, as it also performs
data processing like binding abstract coordinates.
Initialization
~~~~~~~~~~~~~~
The `DataCanvas` is not exposed to users as they are implicitly initialized in the
interface function. It is noteworthy that the data canvas is agnostic to plotters.
This means once the canvas instance is initialized we can reuse this data
among multiple plotters. The canvas is initialized with a stylesheet.
```python
canvas = DrawerCanvas(stylesheet=stylesheet)
canvas.load_program(sched)
canvas.update()
```
Once all properties are set, `.update` method is called to apply changes to drawings.
Update
~~~~~~
To update the image, a user can set new values to canvas and then call the `.update` method.
```python
canvas.set_time_range(2000, 3000)
canvas.update()
```
All stored drawings are updated accordingly. The plotter API can access to
drawings with `.collections` property of the canvas instance. This returns
an iterator of drawings with the unique data key.
If a plotter provides object handler for plotted shapes, the plotter API can manage
the lookup table of the handler and the drawings by using this data key.
"""
from __future__ import annotations
import warnings
from collections.abc import Iterator
from copy import deepcopy
from functools import partial
from enum import Enum
import numpy as np
from qiskit import circuit
from qiskit.visualization.exceptions import VisualizationError
from qiskit.visualization.timeline import drawings, types
from qiskit.visualization.timeline.stylesheet import QiskitTimelineStyle
class DrawerCanvas:
"""Data container for drawings."""
def __init__(self, stylesheet: QiskitTimelineStyle):
"""Create new data container."""
# stylesheet
self.formatter = stylesheet.formatter
self.generator = stylesheet.generator
self.layout = stylesheet.layout
# drawings
self._collections: dict[str, drawings.ElementaryData] = {}
self._output_dataset: dict[str, drawings.ElementaryData] = {}
# vertical offset of bits
self.bits: list[types.Bits] = []
self.assigned_coordinates: dict[types.Bits, float] = {}
# visible controls
self.disable_bits: set[types.Bits] = set()
self.disable_types: set[str] = set()
# time
self._time_range = (0, 0)
# graph height
self.vmax = 0
self.vmin = 0
@property
def time_range(self) -> tuple[int, int]:
"""Return current time range to draw.
Calculate net duration and add side margin to edge location.
Returns:
Time window considering side margin.
"""
t0, t1 = self._time_range
duration = t1 - t0
new_t0 = t0 - duration * self.formatter["margin.left_percent"]
new_t1 = t1 + duration * self.formatter["margin.right_percent"]
return new_t0, new_t1
@time_range.setter
def time_range(self, new_range: tuple[int, int]):
"""Update time range to draw."""
self._time_range = new_range
@property
def collections(self) -> Iterator[tuple[str, drawings.ElementaryData]]:
"""Return currently active entries from drawing data collection.
The object is returned with unique name as a key of an object handler.
When the horizontal coordinate contains `AbstractCoordinate`,
the value is substituted by current time range preference.
"""
yield from self._output_dataset.items()
def add_data(self, data: drawings.ElementaryData):
"""Add drawing to collections.
If the given object already exists in the collections,
this interface replaces the old object instead of adding new entry.
Args:
data: New drawing to add.
"""
if not self.formatter["control.show_clbits"]:
data.bits = [b for b in data.bits if not isinstance(b, circuit.Clbit)]
self._collections[data.data_key] = data
# pylint: disable=cyclic-import
def load_program(self, program: circuit.QuantumCircuit):
"""Load quantum circuit and create drawing..
Args:
program: Scheduled circuit object to draw.
Raises:
VisualizationError: When circuit is not scheduled.
"""
not_gate_like = (circuit.Barrier,)
if getattr(program, "_op_start_times") is None:
# Run scheduling for backward compatibility
from qiskit import transpile
from qiskit.transpiler import InstructionDurations, TranspilerError
warnings.warn(
"Visualizing un-scheduled circuit with timeline drawer has been deprecated. "
"This circuit should be transpiled with scheduler though it consists of "
"instructions with explicit durations.",
DeprecationWarning,
)
try:
program = transpile(
program,
scheduling_method="alap",
instruction_durations=InstructionDurations(),
optimization_level=0,
)
except TranspilerError as ex:
raise VisualizationError(
f"Input circuit {program.name} is not scheduled and it contains "
"operations with unknown delays. This cannot be visualized."
) from ex
for t0, instruction in zip(program.op_start_times, program.data):
bits = list(instruction.qubits) + list(instruction.clbits)
for bit_pos, bit in enumerate(bits):
if not isinstance(instruction.operation, not_gate_like):
# Generate draw object for gates
gate_source = types.ScheduledGate(
t0=t0,
operand=instruction.operation,
duration=instruction.operation.duration,
bits=bits,
bit_position=bit_pos,
)
for gen in self.generator["gates"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(gate_source):
self.add_data(datum)
if len(bits) > 1 and bit_pos == 0:
# Generate draw object for gate-gate link
line_pos = t0 + 0.5 * instruction.operation.duration
link_source = types.GateLink(
t0=line_pos, opname=instruction.operation.name, bits=bits
)
for gen in self.generator["gate_links"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(link_source):
self.add_data(datum)
if isinstance(instruction.operation, circuit.Barrier):
# Generate draw object for barrier
barrier_source = types.Barrier(t0=t0, bits=bits, bit_position=bit_pos)
for gen in self.generator["barriers"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(barrier_source):
self.add_data(datum)
self.bits = list(program.qubits) + list(program.clbits)
for bit in self.bits:
for gen in self.generator["bits"]:
# Generate draw objects for bit
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(bit):
self.add_data(datum)
# update time range
t_end = max(program.duration, self.formatter["margin.minimum_duration"])
self.set_time_range(t_start=0, t_end=t_end)
def set_time_range(self, t_start: int, t_end: int):
"""Set time range to draw.
Args:
t_start: Left boundary of drawing in units of cycle time.
t_end: Right boundary of drawing in units of cycle time.
"""
self.time_range = (t_start, t_end)
def set_disable_bits(self, bit: types.Bits, remove: bool = True):
"""Interface method to control visibility of bits.
Specified object in the blocked list will not be shown.
Args:
bit: A qubit or classical bit object to disable.
remove: Set `True` to disable, set `False` to enable.
"""
if remove:
self.disable_bits.add(bit)
else:
self.disable_bits.discard(bit)
def set_disable_type(self, data_type: types.DataTypes, remove: bool = True):
"""Interface method to control visibility of data types.
Specified object in the blocked list will not be shown.
Args:
data_type: A drawing data type to disable.
remove: Set `True` to disable, set `False` to enable.
"""
if isinstance(data_type, Enum):
data_type_str = str(data_type.value)
else:
data_type_str = data_type
if remove:
self.disable_types.add(data_type_str)
else:
self.disable_types.discard(data_type_str)
def update(self):
"""Update all collections.
This method should be called before the canvas is passed to the plotter.
"""
self._output_dataset.clear()
self.assigned_coordinates.clear()
# update coordinate
y0 = -self.formatter["margin.top"]
for bit in self.layout["bit_arrange"](self.bits):
# remove classical bit
if isinstance(bit, circuit.Clbit) and not self.formatter["control.show_clbits"]:
continue
# remove idle bit
if not self._check_bit_visible(bit):
continue
offset = y0 - 0.5
self.assigned_coordinates[bit] = offset
y0 = offset - 0.5
self.vmax = 0
self.vmin = y0 - self.formatter["margin.bottom"]
# add data
temp_gate_links = {}
temp_data = {}
for data_key, data in self._collections.items():
# deep copy to keep original data hash
new_data = deepcopy(data)
new_data.xvals = self._bind_coordinate(data.xvals)
new_data.yvals = self._bind_coordinate(data.yvals)
if data.data_type == str(types.LineType.GATE_LINK.value):
temp_gate_links[data_key] = new_data
else:
temp_data[data_key] = new_data
# update horizontal offset of gate links
temp_data.update(self._check_link_overlap(temp_gate_links))
# push valid data
for data_key, data in temp_data.items():
if self._check_data_visible(data):
self._output_dataset[data_key] = data
def _check_data_visible(self, data: drawings.ElementaryData) -> bool:
"""A helper function to check if the data is visible.
Args:
data: Drawing object to test.
Returns:
Return `True` if the data is visible.
"""
_barriers = [str(types.LineType.BARRIER.value)]
_delays = [str(types.BoxType.DELAY.value), str(types.LabelType.DELAY.value)]
def _time_range_check(_data):
"""If data is located outside the current time range."""
t0, t1 = self.time_range
if np.max(_data.xvals) < t0 or np.min(_data.xvals) > t1:
return False
return True
def _associated_bit_check(_data):
"""If any associated bit is not shown."""
if all(bit not in self.assigned_coordinates for bit in _data.bits):
return False
return True
def _data_check(_data):
"""If data is valid."""
if _data.data_type == str(types.LineType.GATE_LINK.value):
active_bits = [bit for bit in _data.bits if bit not in self.disable_bits]
if len(active_bits) < 2:
return False
elif _data.data_type in _barriers and not self.formatter["control.show_barriers"]:
return False
elif _data.data_type in _delays and not self.formatter["control.show_delays"]:
return False
return True
checks = [_time_range_check, _associated_bit_check, _data_check]
if all(check(data) for check in checks):
return True
return False
def _check_bit_visible(self, bit: types.Bits) -> bool:
"""A helper function to check if the bit is visible.
Args:
bit: Bit object to test.
Returns:
Return `True` if the bit is visible.
"""
_gates = [str(types.BoxType.SCHED_GATE.value), str(types.SymbolType.FRAME.value)]
if bit in self.disable_bits:
return False
if self.formatter["control.show_idle"]:
return True
for data in self._collections.values():
if bit in data.bits and data.data_type in _gates:
return True
return False
def _bind_coordinate(self, vals: Iterator[types.Coordinate]) -> np.ndarray:
"""A helper function to bind actual coordinates to an `AbstractCoordinate`.
Args:
vals: Sequence of coordinate objects associated with a drawing.
Returns:
Numpy data array with substituted values.
"""
def substitute(val: types.Coordinate):
if val == types.AbstractCoordinate.LEFT:
return self.time_range[0]
if val == types.AbstractCoordinate.RIGHT:
return self.time_range[1]
if val == types.AbstractCoordinate.TOP:
return self.vmax
if val == types.AbstractCoordinate.BOTTOM:
return self.vmin
raise VisualizationError(f"Coordinate {val} is not supported.")
try:
return np.asarray(vals, dtype=float)
except TypeError:
return np.asarray(list(map(substitute, vals)), dtype=float)
def _check_link_overlap(
self, links: dict[str, drawings.GateLinkData]
) -> dict[str, drawings.GateLinkData]:
"""Helper method to check overlap of bit links.
This method dynamically shifts horizontal position of links if they are overlapped.
"""
duration = self.time_range[1] - self.time_range[0]
allowed_overlap = self.formatter["margin.link_interval_percent"] * duration
# return y coordinates
def y_coords(link: drawings.GateLinkData):
return np.array([self.assigned_coordinates.get(bit, np.nan) for bit in link.bits])
# group overlapped links
overlapped_group: list[list[str]] = []
data_keys = list(links.keys())
while len(data_keys) > 0:
ref_key = data_keys.pop()
overlaps = set()
overlaps.add(ref_key)
for key in data_keys[::-1]:
# check horizontal overlap
if np.abs(links[ref_key].xvals[0] - links[key].xvals[0]) < allowed_overlap:
# check vertical overlap
y0s = y_coords(links[ref_key])
y1s = y_coords(links[key])
v1 = np.nanmin(y0s) - np.nanmin(y1s)
v2 = np.nanmax(y0s) - np.nanmax(y1s)
v3 = np.nanmin(y0s) - np.nanmax(y1s)
v4 = np.nanmax(y0s) - np.nanmin(y1s)
if not (v1 * v2 > 0 and v3 * v4 > 0):
overlaps.add(data_keys.pop(data_keys.index(key)))
overlapped_group.append(list(overlaps))
# renew horizontal offset
new_links = {}
for overlaps in overlapped_group:
if len(overlaps) > 1:
xpos_mean = np.mean([links[key].xvals[0] for key in overlaps])
# sort link key by y position
sorted_keys = sorted(overlaps, key=lambda x: np.nanmax(y_coords(links[x])))
x0 = xpos_mean - 0.5 * allowed_overlap * (len(overlaps) - 1)
for ind, key in enumerate(sorted_keys):
data = links[key]
data.xvals = [x0 + ind * allowed_overlap]
new_links[key] = data
else:
key = overlaps[0]
new_links[key] = links[key]
return {key: new_links[key] for key in links.keys()}
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
import os
import sys
from IPython.display import Image
from qiskit import QuantumProgram
from qiskit.tools.visualization import plot_histogram
def show_image(img_name):
"""Display an image in the notebook.
This is set to the default path of the root of the tutorials repo
images directory in the sub-folder 'intro_img'.
Args:
img_name (str): file name to display
"""
return Image(filename=os.path.join("..", "images", "intro_img", img_name))
def execute_and_plot(qp, circuits):
"""Execute and plot the histograms with default settings.
Args:
qp: QuantumProgram containing the circuits
circuits (list): list of circuits to execute
"""
results = qp.execute(circuits)
for circuit in circuits:
print(circuit)
plot_histogram(results.get_counts(circuit))
qp = QuantumProgram()
n = 1 # number of qubits
q = qp.create_quantum_register("q", n)
c = qp.create_classical_register("c", n)
show_image("single_q_x_gate.png")
single_x = qp.create_circuit("single_x", [q], [c])
single_x.x(q[0])
single_x.measure(q[0], c[0])
execute_and_plot(qp, ["single_x"])
show_image("single_q_h_gate_0.png")
single_h = qp.create_circuit("single_h", [q], [c])
single_h.h(q[0])
single_h.measure(q[0], c[0])
execute_and_plot(qp, ["single_h"])
show_image("single_q_h_gate_1.png")
single_xh = qp.create_circuit("single_xh", [q], [c])
single_xh.x(q[0])
single_xh.h(q[0])
single_xh.measure(q[0], c[0])
execute_and_plot(qp, ["single_xh"])
show_image("single_q_h_gate_2.png")
# This is the |+> state
single_hh = qp.create_circuit("single_hh", [q], [c])
single_hh.h(q[0])
single_hh.h(q[0])
single_hh.measure(q[0], c[0])
execute_and_plot(qp, ["single_hh"])
show_image("single_q_h_gate_3.png")
# This is the |-> state
single_xhh = qp.create_circuit("single_xhh", [q], [c])
single_xhh.x(q[0])
single_xhh.h(q[0])
single_xhh.h(q[0])
single_xhh.measure(q[0],c[0])
execute_and_plot(qp, ["single_xhh"])
show_image("single_q_z_gate_0.png")
single_z = qp.create_circuit("single_z", [q], [c])
single_z.z(q[0])
single_z.measure(q[0],c[0])
execute_and_plot(qp, ["single_z"])
show_image("single_q_z_gate_1.png")
single_zh = qp.create_circuit("single_zh", [q], [c])
single_zh.h(q[0])
single_zh.z(q[0])
single_zh.measure(q[0],c[0])
execute_and_plot(qp, ["single_zh"])
show_image("single_q_z_gate_tbl.png")
# 0 rotation around z, Pr(0) = 1.0
phs_0 = qp.create_circuit("phs_0", [q], [c])
phs_0.h(q[0])
phs_0.h(q[0]) # for x-basis measurement
phs_0.measure(q[0], c[0])
# pi/4 rotation around z, Pr(0) = 0.85
phs_pi4 = qp.create_circuit("phs_pi4", [q], [c])
phs_pi4.h(q[0])
phs_pi4.t(q[0])
phs_pi4.h(q[0]) # for x-basis measurement
phs_pi4.measure(q[0], c[0])
# pi/2 rotation around z, Pr(0) = 0.5
phs_pi2 = qp.create_circuit("phs_pi2", [q], [c])
phs_pi2.h(q[0])
phs_pi2.s(q[0])
# Alternate example gate:
#phs_pi2.sdg(q[0]) #rotation -pi/2 using sdg instead of s
phs_pi2.h(q[0]) # for x-basis measurement
phs_pi2.measure(q[0], c[0])
# 3pi/4 rotation around z, Pr(0) = 0.15
phs_3pi4 = qp.create_circuit("phs_3pi4", [q], [c])
phs_3pi4.h(q[0])
phs_3pi4.s(q[0])
phs_3pi4.t(q[0])
phs_3pi4.h(q[0]) # for x-basis measurement
phs_3pi4.measure(q[0], c[0])
# pi rotation around z, Pr(0) = 0
phs_pi = qp.create_circuit("phs_pi", [q], [c])
phs_pi.h(q[0])
phs_pi.z(q[0])
phs_pi.h(q[0]) # for measurement
phs_pi.measure(q[0], c[0])
execute_and_plot(qp, ["phs_0", "phs_pi4", "phs_pi2",
"phs_3pi4", "phs_pi"])
n = 2 # number of qubits
q2 = qp.create_quantum_register("q2", n)
c2 = qp.create_classical_register("c2", n)
show_image("multi_q_0.png")
# |00> -- |00>
cnot_00 = qp.create_circuit("cnot_00", [q2], [c2])
cnot_00.cx(q2[0], q2[1])
cnot_00.measure(q2[0], c2[0])
cnot_00.measure(q2[1], c2[1])
execute_and_plot(qp, ["cnot_00"])
show_image("multi_q_1.png")
# |01> -- |11>
cnot_01 = qp.create_circuit("cnot_01", [q2], [c2])
cnot_01.x(q2[0])
cnot_01.cx(q2[0], q2[1])
cnot_01.measure(q2[0], c2[0])
cnot_01.measure(q2[1], c2[1])
execute_and_plot(qp, ["cnot_01"])
show_image("multi_q_2.png")
# |10> -- |10>
cnot_10 = qp.create_circuit("cnot_10", [q2], [c2])
cnot_10.x(q2[1])
cnot_10.cx(q2[0], q2[1])
cnot_10.measure(q2[0], c2[0])
cnot_10.measure(q2[1], c2[1])
execute_and_plot(qp, ["cnot_10"])
show_image("multi_q_3.png")
# |11> -- |01>
cnot_11 = qp.create_circuit("cnot_11", [q2], [c2])
cnot_11.x(q2[0])
cnot_11.x(q2[1])
cnot_11.cx(q2[0], q2[1])
cnot_11.measure(q2[0], c2[0])
cnot_11.measure(q2[1], c2[1])
execute_and_plot(qp, ["cnot_11"])
show_image("ent_q_0.png")
e0 = qp.create_circuit("e0", [q2], [c2])
e0.h(q2[0]) # apply H-gate for superposition to q0
e0.cx(q2[0], q2[1]) # apply CNOT control from q0 to q1
e0.measure(q2[0], c2[0])
e0.measure(q2[1], c2[1])
execute_and_plot(qp, ["e0"])
show_image("ent_q_1.png")
e1 = qp.create_circuit("e1", [q2], [c2])
e1.h(q2[0]) # apply H-gate on q0 for superposition
e1.x(q2[1]) # apply x-gate on q1
e1.cx(q2[0], q2[1]) # apply CNOT control from q0 to q1
e1.measure(q2[0], c2[0])
e1.measure(q2[1], c2[1])
execute_and_plot(qp, ["e1"])
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
# Importing standard Qiskit libraries
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import Aer, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector, plot_state_qsphere, plot_state_city, plot_state_paulivec, plot_state_hinton
# Ignore warnings
import warnings
warnings.filterwarnings('ignore')
# Define backend
sim = Aer.get_backend('aer_simulator')
def createBellStates(inp1, inp2):
qc = QuantumCircuit(2)
qc.reset(range(2))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.save_statevector()
qobj = assemble(qc)
result = sim.run(qobj).result()
state = result.get_statevector()
return qc, state, result
print('Note: Since these qubits are in entangled state, their state cannot be written as two separate qubit states. This also means that we lose information when we try to plot our state on separate Bloch spheres as seen below.\n')
inp1 = 0
inp2 = 1
qc, state, result = createBellStates(inp1, inp2)
display(plot_bloch_multivector(state))
# Uncomment below code in order to explore other states
#for inp2 in ['0', '1']:
#for inp1 in ['0', '1']:
#qc, state, result = createBellStates(inp1, inp2)
#print('For inputs',inp2,inp1,'Representation of Entangled States are:')
# Uncomment any of the below functions to visualize the resulting quantum states
# Draw the quantum circuit
#display(qc.draw())
# Plot states on QSphere
#display(plot_state_qsphere(state))
# Plot states on Bloch Multivector
#display(plot_bloch_multivector(state))
# Plot histogram
#display(plot_histogram(result.get_counts()))
# Plot state matrix like a city
#display(plot_state_city(state))
# Represent state matix using Pauli operators as the basis
#display(plot_state_paulivec(state))
# Plot state matrix as Hinton representation
#display(plot_state_hinton(state))
#print('\n')'''
from qiskit import IBMQ, execute
from qiskit.providers.ibmq import least_busy
from qiskit.tools import job_monitor
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
def createBSRealDevice(inp1, inp2):
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.reset(range(2))
if inp1 == 1:
qc.x(0)
if inp2 == 1:
qc.x(1)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.measure(qr, cr)
job = execute(qc, backend=backend, shots=100)
job_monitor(job)
result = job.result()
return qc, result
inp1 = 0
inp2 = 0
print('For inputs',inp2,inp1,'Representation of Entangled States are,')
#first results
qc, first_result = createBSRealDevice(inp1, inp2)
first_counts = first_result.get_counts()
# Draw the quantum circuit
display(qc.draw())
#second results
qc, second_result = createBSRealDevice(inp1, inp2)
second_counts = second_result.get_counts()
# Plot results on histogram with legend
legend = ['First execution', 'Second execution']
plot_histogram([first_counts, second_counts], legend=legend)
def ghzCircuit(inp1, inp2, inp3):
qc = QuantumCircuit(3)
qc.reset(range(3))
if inp1 == 1:
qc.x(0)
if inp2 == 1:
qc.x(1)
if inp3 == 1:
qc.x(2)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.save_statevector()
qobj = assemble(qc)
result = sim.run(qobj).result()
state = result.get_statevector()
return qc, state, result
print('Note: Since these qubits are in entangled state, their state cannot be written as two separate qubit states. This also means that we lose information when we try to plot our state on separate Bloch spheres as seen below.\n')
inp1 = 0
inp2 = 1
inp3 = 1
qc, state, result = ghzCircuit(inp1, inp2, inp3)
display(plot_bloch_multivector(state))
# Uncomment below code in order to explore other states
#for inp3 in ['0','1']:
#for inp2 in ['0','1']:
#for inp1 in ['0','1']:
#qc, state, result = ghzCircuit(inp1, inp2, inp3)
#print('For inputs',inp3,inp2,inp1,'Representation of GHZ States are:')
# Uncomment any of the below functions to visualize the resulting quantum states
# Draw the quantum circuit
#display(qc.draw())
# Plot states on QSphere
#display(plot_state_qsphere(state))
# Plot states on Bloch Multivector
#display(plot_bloch_multivector(state))
# Plot histogram
#display(plot_histogram(result.get_counts()))
# Plot state matrix like a city
#display(plot_state_city(state))
# Represent state matix using Pauli operators as the basis
#display(plot_state_paulivec(state))
# Plot state matrix as Hinton representation
#display(plot_state_hinton(state))
#print('\n')
def ghz5QCircuit(inp1, inp2, inp3, inp4, inp5):
qc = QuantumCircuit(5)
#qc.reset(range(5))
if inp1 == 1:
qc.x(0)
if inp2 == 1:
qc.x(1)
if inp3 == 1:
qc.x(2)
if inp4 == 1:
qc.x(3)
if inp5 == 1:
qc.x(4)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.cx(0,3)
qc.cx(0,4)
qc.save_statevector()
qobj = assemble(qc)
result = sim.run(qobj).result()
state = result.get_statevector()
return qc, state, result
# Explore GHZ States for input 00010. Note: the input has been stated in little-endian format.
inp1 = 0
inp2 = 1
inp3 = 0
inp4 = 0
inp5 = 0
qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
display(plot_state_qsphere(state))
print('\n')
# Explore GHZ States for input 11001. Note: the input has been stated in little-endian format.
inp1 = 1
inp2 = 0
inp3 = 0
inp4 = 1
inp5 = 1
qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
display(plot_state_qsphere(state))
print('\n')
# Explore GHZ States for input 01010. Note: the input has been stated in little-endian format.
inp1 = 0
inp2 = 1
inp3 = 0
inp4 = 1
inp5 = 0
qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
display(plot_state_qsphere(state))
print('\n')
# Uncomment below code in order to explore other states
#for inp5 in ['0','1']:
#for inp4 in ['0','1']:
#for inp3 in ['0','1']:
#for inp2 in ['0','1']:
#for inp1 in ['0','1']:
#qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
#print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
# Uncomment any of the below functions to visualize the resulting quantum states
# Draw the quantum circuit
#display(qc.draw())
# Plot states on QSphere
#display(plot_state_qsphere(state))
# Plot states on Bloch Multivector
#display(plot_bloch_multivector(state))
# Plot histogram
#display(plot_histogram(result.get_counts()))
# Plot state matrix like a city
#display(plot_state_city(state))
# Represent state matix using Pauli operators as the basis
#display(plot_state_paulivec(state))
# Plot state matrix as Hinton representation
#display(plot_state_hinton(state))
#print('\n')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 5
and not x.configuration().simulator
and x.status().operational==True))
def create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5):
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.reset(range(5))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
if inp3=='1':
qc.x(1)
if inp4=='1':
qc.x(1)
if inp5=='1':
qc.x(1)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.cx(0,3)
qc.cx(0,4)
qc.measure(qr, cr)
job = execute(qc, backend=backend, shots=1000)
job_monitor(job)
result = job.result()
return qc, result
inp1 = 0
inp2 = 0
inp3 = 0
inp4 = 0
inp5 = 0
#first results
qc, first_result = create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5)
first_counts = first_result.get_counts()
# Draw the quantum circuit
display(qc.draw())
#second results
qc, second_result = create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5)
second_counts = second_result.get_counts()
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ circuit states are,')
# Plot results on histogram with legend
legend = ['First execution', 'Second execution']
plot_histogram([first_counts, second_counts], legend=legend)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 12345
from qiskit_machine_learning.datasets import ad_hoc_data
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=20,
test_size=5,
n=adhoc_dimension,
gap=0.3,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
import matplotlib.pyplot as plt
import numpy as np
def plot_features(ax, features, labels, class_label, marker, face, edge, label):
# A train plot
ax.scatter(
# x coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 0],
# y coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 1],
marker=marker,
facecolors=face,
edgecolors=edge,
label=label,
)
def plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total):
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
# A train plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "A train")
# B train plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B train")
# A test plot
plot_features(plt, test_features, test_labels, 0, "s", "b", "w", "A test")
# B test plot
plot_features(plt, test_features, test_labels, 1, "o", "r", "w", "B test")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset")
plt.show()
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
from qiskit.circuit.library import ZZFeatureMap
from qiskit.primitives import Sampler
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit_machine_learning.kernels import FidelityQuantumKernel
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
sampler = Sampler()
fidelity = ComputeUncompute(sampler=sampler)
adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map)
from sklearn.svm import SVC
adhoc_svc = SVC(kernel=adhoc_kernel.evaluate)
adhoc_svc.fit(train_features, train_labels)
adhoc_score_callable_function = adhoc_svc.score(test_features, test_labels)
print(f"Callable kernel classification test score: {adhoc_score_callable_function}")
adhoc_matrix_train = adhoc_kernel.evaluate(x_vec=train_features)
adhoc_matrix_test = adhoc_kernel.evaluate(x_vec=test_features, y_vec=train_features)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(
np.asmatrix(adhoc_matrix_train), interpolation="nearest", origin="upper", cmap="Blues"
)
axs[0].set_title("Ad hoc training kernel matrix")
axs[1].imshow(np.asmatrix(adhoc_matrix_test), interpolation="nearest", origin="upper", cmap="Reds")
axs[1].set_title("Ad hoc testing kernel matrix")
plt.show()
adhoc_svc = SVC(kernel="precomputed")
adhoc_svc.fit(adhoc_matrix_train, train_labels)
adhoc_score_precomputed_kernel = adhoc_svc.score(adhoc_matrix_test, test_labels)
print(f"Precomputed kernel classification test score: {adhoc_score_precomputed_kernel}")
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=adhoc_kernel)
qsvc.fit(train_features, train_labels)
qsvc_score = qsvc.score(test_features, test_labels)
print(f"QSVC classification test score: {qsvc_score}")
print(f"Classification Model | Accuracy Score")
print(f"---------------------------------------------------------")
print(f"SVC using kernel as a callable function | {adhoc_score_callable_function:10.2f}")
print(f"SVC using precomputed kernel matrix | {adhoc_score_precomputed_kernel:10.2f}")
print(f"QSVC | {qsvc_score:10.2f}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=0,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
# A label plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "B")
# B label plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for clustering")
plt.show()
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
adhoc_kernel = FidelityQuantumKernel(feature_map=adhoc_feature_map)
adhoc_matrix = adhoc_kernel.evaluate(x_vec=train_features)
plt.figure(figsize=(5, 5))
plt.imshow(np.asmatrix(adhoc_matrix), interpolation="nearest", origin="upper", cmap="Greens")
plt.title("Ad hoc clustering kernel matrix")
plt.show()
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score
adhoc_spectral = SpectralClustering(2, affinity="precomputed")
cluster_labels = adhoc_spectral.fit_predict(adhoc_matrix)
cluster_score = normalized_mutual_info_score(cluster_labels, train_labels)
print(f"Clustering score: {cluster_score}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=10,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement="linear")
qpca_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=feature_map)
matrix_train = qpca_kernel.evaluate(x_vec=train_features)
matrix_test = qpca_kernel.evaluate(x_vec=test_features, y_vec=test_features)
from sklearn.decomposition import KernelPCA
kernel_pca_rbf = KernelPCA(n_components=2, kernel="rbf")
kernel_pca_rbf.fit(train_features)
train_features_rbf = kernel_pca_rbf.transform(train_features)
test_features_rbf = kernel_pca_rbf.transform(test_features)
kernel_pca_q = KernelPCA(n_components=2, kernel="precomputed")
train_features_q = kernel_pca_q.fit_transform(matrix_train)
test_features_q = kernel_pca_q.fit_transform(matrix_test)
from sklearn.linear_model import LogisticRegression
logistic_regression = LogisticRegression()
logistic_regression.fit(train_features_q, train_labels)
logistic_score = logistic_regression.score(test_features_q, test_labels)
print(f"Logistic regression score: {logistic_score}")
fig, (q_ax, rbf_ax) = plt.subplots(1, 2, figsize=(10, 5))
plot_features(q_ax, train_features_q, train_labels, 0, "s", "w", "b", "A train")
plot_features(q_ax, train_features_q, train_labels, 1, "o", "w", "r", "B train")
plot_features(q_ax, test_features_q, test_labels, 0, "s", "b", "w", "A test")
plot_features(q_ax, test_features_q, test_labels, 1, "o", "r", "w", "A test")
q_ax.set_ylabel("Principal component #1")
q_ax.set_xlabel("Principal component #0")
q_ax.set_title("Projection of training and test data\n using KPCA with Quantum Kernel")
# Plotting the linear separation
h = 0.01 # step size in the mesh
# create a mesh to plot in
x_min, x_max = train_features_q[:, 0].min() - 1, train_features_q[:, 0].max() + 1
y_min, y_max = train_features_q[:, 1].min() - 1, train_features_q[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
predictions = logistic_regression.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
predictions = predictions.reshape(xx.shape)
q_ax.contourf(xx, yy, predictions, cmap=plt.cm.RdBu, alpha=0.2)
plot_features(rbf_ax, train_features_rbf, train_labels, 0, "s", "w", "b", "A train")
plot_features(rbf_ax, train_features_rbf, train_labels, 1, "o", "w", "r", "B train")
plot_features(rbf_ax, test_features_rbf, test_labels, 0, "s", "b", "w", "A test")
plot_features(rbf_ax, test_features_rbf, test_labels, 1, "o", "r", "w", "A test")
rbf_ax.set_ylabel("Principal component #1")
rbf_ax.set_xlabel("Principal component #0")
rbf_ax.set_title("Projection of training data\n using KernelPCA")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/W-Bernau/QiskitAlgorithms
|
W-Bernau
|
from qiskit.circuit.library import TwoLocal, ZZFeatureMap
from qiskit_algorithms.optimizers import COBYLA
from qiskit_algorithms.utils import algorithm_globals
from sklearn.datasets import load_breast_cancer
from sklearn.preprocessing import MinMaxScaler
from qiskit_machine_learning.algorithms import VQC
from qiskit.circuit.library import ZZFeatureMap
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
seed = 1376
algorithm_globals.random_seed = seed
cancerData = load_breast_cancer()
print(cancerData.DESCR)
import pandas as pd
import seaborn as sns
from sklearn.decomposition import PCA
from sklearn.svm import SVC
features = cancerData.data
labels = cancerData.target
features = MinMaxScaler().fit_transform(features)
num_features = features.shape[1]
feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1)
feature_map.decompose().draw(style="clifford")
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Sampler
from IPython.display import clear_output
ansatz = RealAmplitudes(num_qubits=num_features, reps=3)
optimizer = COBYLA(maxiter=100)
sampler = Sampler()
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
df = pd.DataFrame(cancerData.data, columns=cancerData.feature_names)
df["class"] = pd.Series(cancerData.target)
sns.pairplot(df, hue="class", palette="tab10")
import time
from qiskit_machine_learning.algorithms.classifiers import VQC
algorithm_globals.random_seed = 12
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=0.8, random_state=algorithm_globals.random_seed
)
svc = SVC()
_ = svc.fit(train_features, train_labels) # suppress printing the return value
train_score_c4 = svc.score(train_features, train_labels)
test_score_c4 = svc.score(test_features, test_labels)
print(f"Classical SVC on the training dataset: {train_score_c4:.2f}")
print(f"Classical SVC on the test dataset: {test_score_c4:.2f}")
vqc = VQC(
sampler=sampler,
feature_map=feature_map,
ansatz=ansatz,
optimizer=optimizer,
callback=callback_graph,
)
# clear objective value history
objective_func_vals = []
start = time.time()
vqc.fit(train_features, train_labels)
train_score_q4 = vqc.score(train_features, train_labels)
test_score_q4 = vqc.score(test_features, test_labels)
print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}")
print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}")
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
from matplotlib import pyplot
from qiskit import *
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua
from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector
from qiskit.quantum_info import Statevector
from qiskit.extensions import *
provider = IBMQ.load_account()
from qiskit.quantum_info import random_unitary
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
from math import pi, sqrt
from scipy.special import rel_entr
from random import seed
from random import random
import cmath
#Possible Bin
bins_list=[];
for i in range(76):
bins_list.append((i)/75)
#Center of the Bean
bins_x=[]
for i in range(75):
bins_x.append(bins_list[1]+bins_list[i])
def P_harr(l,u,N):
return (1-l)**(N-1)-(1-u)**(N-1)
#Harr historgram
P_harr_hist=[]
for i in range(75):
P_harr_hist.append(P_harr(bins_list[i],bins_list[i+1],2))
#Imaginary
j=(-1)**(1/2)
backend = Aer.get_backend('qasm_simulator')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
print(nshot,'shots per simulation',nparam,'distribution size')
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_qasm.txt",qasm)
qasm
backend = QasmSimulator(method='density_matrix')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
print(nshot,'shots per simulation',nparam,'distribution size KL=',sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
density_mat=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_density_mat.txt",density_mat)
density_mat
backend = QasmSimulator(method='statevector')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
print(nshot,'shots per simulation',nparam,'distribution size KL=',sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
statevector1=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_statevector.txt",statevector1)
statevector1
backend = QasmSimulator(method='matrix_product_state')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
print(nshot,'shots per simulation',nparam,'distribution size KL=',sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
matrix_product1=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_matrix_product1.txt",matrix_product1)
matrix_product1
def plotdata(i,data):
klll=np.transpose(data)
x=[];
y=[];
for nsh in range(0,9,1):
x.append(int(round(1000*(nsh)**1.5,0)))
y.append(klll[nsh][i])
return [x,y]
#loading dataset
fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(20, 5))
datalist=[density_mat,statevector1,matrix_product1,qasm]
datalistn=['density_mat','statevector','matrix_product','qasm']
indx=0;
for indx in range(4):
data=datalist[indx];
axes[indx].plot(plotdata(0,data)[0],plotdata(0,data)[1], color='red', label='npram=1000');
axes[indx].plot(plotdata(1,data)[0],plotdata(1,data)[1], color='blue', label='npram=2000');
axes[indx].plot(plotdata(2,data)[0],plotdata(2,data)[1], color='black', label='npram=3000');
axes[indx].plot(plotdata(3,data)[0],plotdata(3,data)[1], color='green', label='npram=4000');
axes[indx].plot(plotdata(4,data)[0],plotdata(4,data)[1], color='purple', label='npram=5000');
axes[indx].plot(plotdata(5,data)[0],plotdata(5,data)[1], color='gray', label='npram=6000');
axes[indx].plot(plotdata(6,data)[0],plotdata(6,data)[1], color='black', label='npram=7000');
axes[indx].plot(plotdata(7,data)[0],plotdata(7,data)[1], color='yellow', label='npram=8000');
axes[indx].plot(plotdata(8,data)[0],plotdata(8,data)[1], color='pink', label='npram=9000');
axes[indx].set_ylim([0.003, 0.05])
axes[indx].legend(loc='upper right')
axes[indx].set_title(datalistn[indx])
axes[indx].set_yscale('log',base=10)
axes[indx].set_ylabel('Expressibility')
from matplotlib import pyplot as plt
fig.savefig('ExpressibilitybySimulator.png')
fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(20, 5))
indx=0
for indx in range(4):
data=density_mat;
axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='red', label='density_mat');
data=statevector1;
axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='blue', label='statevector');
data=matrix_product1;
axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='green', label='matrix_product1');
data=qasm;
axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='pink', label='qasm');
axes[indx].set_title('nparam='+str((indx+1)*1000))
axes[indx].set_yscale('log',base=10)
axes[indx].set_ylim([0.003, 0.05])
axes[indx].set_ylabel('Expressibility')
axes[indx].legend(['density_mat','statevector','matrix_product1','qasm'])
axes[indx].set_xlabel('iteration')
fig.savefig('ExpressibilitybySimulatornparam1.png')
fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(20, 5))
indx=0
for indx1 in range(4,8,1):
indx=indx1-4
data=density_mat;
axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='red', label='density_mat');
data=statevector1;
axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='blue', label='statevector');
data=matrix_product1;
axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='green', label='matrix_product1');
data=qasm;
axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='pink', label='qasm');
axes[indx].set_title('nparam='+str((indx1+1)*1000))
axes[indx].set_yscale('log',base=10)
axes[indx].set_ylabel('Expressibility')
axes[indx].set_ylim([0.003, 0.05])
axes[indx].legend(['density_mat','statevector','matrix_product1','qasm'])
axes[indx].set_xlabel('iteration')
fig.savefig('ExpressibilitybySimulatornparam2.png')
|
https://github.com/Heisenbug-s-Dog/qnn_visualization
|
Heisenbug-s-Dog
|
from google.colab import drive
drive.mount('/content/drive')
!pip install torch==1.3.1
!pip install torchvision==0.4.2
!pip install Pillow==6.2.1
!pip install pennylane==0.7.0
# 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 = False # If set to "False", the dressed quantum circuit is replaced by
# An enterily classical net (defined by the next parameter).
classical_model = '512_nq_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
'''
filtered_classes = ['plane', 'car'] # 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.0007 # Learning rate
batch_size = 8 # Number of samples for each training step
num_epochs = 3 # Number of training epochs
q_depth = 4 # Depth of the quantum circuit (number of variational layers)
gamma_lr_scheduler = 0.1 # Learning rate reduction applied every 3 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
'''
dev = qml.device('default.qubit', wires=n_qubits)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Fixed pre-processing operations
data_transforms = {
'train': transforms.Compose([
#transforms.RandomResizedCrop(224), # uncomment for data augmentation
#transforms.RandomHorizontalFlip(), # uncomment for data augmentation
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
# Normalize input channels using mean values and standard deviations of ImageNet.
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
# =================== begin CIFAR dataset loading ===================
trainset_full = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=data_transforms['train'])
testset_full = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=data_transforms['val'])
image_datasets_full={'train': trainset_full, 'val': testset_full}
# CIFAR classes
class_names = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
# Get indices of samples associated to filtered_classes
filtered_labels=[class_names.index(cl) for cl in filtered_classes]
sub_indices={'train': [], 'val': []}
for phase in ['train', 'val']:
for idx, label in enumerate(image_datasets_full[phase].targets):
if label in filtered_labels:
sub_indices[phase].append(idx)
# Initialize sub-datasets according to filtered indices
image_datasets = {x: torch.utils.data.Subset(image_datasets_full[x], sub_indices[x])
for x in ['train', 'val']}
def labels_to_filtered(labels):
"""Maps CIFAR labels (0,1,2,3,4,5,6,7,8,9) to the index of filtered_labels"""
return [filtered_labels.index(label) for label in labels]
# =================== end CIFAR dataset loading ==========================
# Number of samples
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
# Initialize dataloader
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x],
batch_size=batch_size, shuffle=True, num_workers=0) for x in ['train', 'val']}
# Function to plot images from tensors
def imshow(inp, title=None):
"""Imshow for Tensor."""
inp = inp.numpy().transpose((1, 2, 0))
# We apply the inverse of the initial normalization operation.
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
inp = std * inp + mean
inp = np.clip(inp, 0, 1)
plt.imshow(inp)
if title is not None:
plt.title(title)
# Get a batch of training data
inputs, classes = next(iter(dataloaders['val']))
# Make a grid from batch
out = torchvision.utils.make_grid(inputs)
imshow(out, title=[class_names[x] for x in classes])
torch.manual_seed(rng_seed)
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x],
batch_size=batch_size, shuffle=True, num_workers=0) for x in ['train', 'val']}
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)
model_hybrid = torchvision.models.resnet18(pretrained=True)
for param in model_hybrid.parameters():
param.requires_grad = False
if quantum:
model_hybrid.fc = Quantumnet()
elif classical_model == '512_n':
model_hybrid.fc = nn.Linear(512,len(filtered_classes))
elif classical_model == '512_nq_n':
model_hybrid.fc = nn.Sequential(nn.Linear(512, n_qubits),torch.nn.ReLU(),nn.Linear(n_qubits, len(filtered_classes)))
elif classical_model == '551_512_n':
model_hybrid.fc = nn.Sequential(nn.Linear(512, 512), torch.nn.ReLU(), nn.Linear(512, len(filtered_classes)))
# Use CUDA or CPU according to the "device" object.
model_hybrid = model_hybrid.to(device)
criterion = nn.CrossEntropyLoss()
optimizer_hybrid = optim.Adam(model_hybrid.fc.parameters(), lr=step)
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_hybrid, step_size=3, gamma=gamma_lr_scheduler)
def train_model(model, criterion, optimizer, scheduler, num_epochs):
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
best_loss = 10000.0 # Large arbitrary number
best_acc_train = 0.0
best_loss_train = 10000.0 # Large arbitrary number
print('Training started:')
for epoch in range(num_epochs):
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
# Set model to training mode
scheduler.step()
model.train()
else:
# Set model to evaluate mode
model.eval()
# Iteration loop
running_loss = 0.0
running_corrects = 0
n_batches = dataset_sizes[phase] // batch_size
it = 0
for inputs, cifar_labels in dataloaders[phase]:
since_batch = time.time()
batch_size_ = len(inputs)
inputs = inputs.to(device)
labels = torch.tensor(labels_to_filtered(cifar_labels))
labels = labels.to(device)
optimizer.zero_grad()
# Track/compute gradient and make an optimization step only when training
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
if phase == 'train':
loss.backward()
optimizer.step()
# Print iteration results
running_loss += loss.item() * batch_size_
batch_corrects = torch.sum(preds == labels.data).item()
running_corrects += batch_corrects
print('Phase: {} Epoch: {}/{} Iter: {}/{} Batch time: {:.4f}'.format(phase, epoch + 1, num_epochs, it + 1, n_batches + 1, time.time() - since_batch), end='\r', flush=True)
it += 1
# Print epoch results
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects / dataset_sizes[phase]
print('Phase: {} Epoch: {}/{} Loss: {:.4f} Acc: {:.4f} '.format('train' if phase == 'train' else 'val ', epoch + 1, num_epochs, epoch_loss, epoch_acc))
# Check if this is the best model wrt previous epochs
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
best_model_wts = copy.deepcopy(model.state_dict())
if phase == 'val' and epoch_loss < best_loss:
best_loss = epoch_loss
if phase == 'train' and epoch_acc > best_acc_train:
best_acc_train = epoch_acc
if phase == 'train' and epoch_loss < best_loss_train:
best_loss_train = epoch_loss
# Print final results
model.load_state_dict(best_model_wts)
time_elapsed = time.time() - since
print('Training completed in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))
print('Best test loss: {:.4f} | Best test accuracy: {:.4f}'.format(best_loss, best_acc))
return model
model_hybrid = train_model(model_hybrid, criterion, optimizer_hybrid, exp_lr_scheduler, num_epochs=num_epochs)
path = '/content/drive/MyDrive/Qiskit-Hackathon-Korea/qnn-visualization/'
if quantum:
torch.save(model_hybrid.state_dict(),
path+'quantum_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt'
)
else:
torch.save(model_hybrid.state_dict(),
path+'classical_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt'
)
print("Model state_dict saved.")
if quantum:
model_hybrid.load_state_dict(torch.load(
path+'quantum_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt'
)
)
else:
model_hybrid.load_state_dict(torch.load(
path+'classical_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt'
)
)
criterion = nn.CrossEntropyLoss()
running_loss = 0.0
running_corrects = 0
n_batches = dataset_sizes['val'] // batch_size
it = 0
model_hybrid.eval()
# Testing loop
for inputs, cifar_labels in dataloaders['val']:
inputs = inputs.to(device)
labels = torch.tensor(labels_to_filtered(cifar_labels))
labels = labels.to(device)
batch_size_ = len(inputs)
with torch.set_grad_enabled(False):
outputs = model_hybrid(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
running_loss += loss.item() * batch_size_
batch_corrects = torch.sum(preds == labels.data).item()
running_corrects += batch_corrects
print('Iter: {}/{}'.format(it+1,n_batches+1), end='\r', flush=True)
it += 1
# Print final results
epoch_loss = running_loss / dataset_sizes['val']
epoch_acc = running_corrects / dataset_sizes['val']
print('\nTest Loss: {:.4f} Test Acc: {:.4f} '.format(epoch_loss, epoch_acc))
def visualize_model(model, num_images=6, fig_name='Predictions'):
images_so_far = 0
fig = plt.figure(fig_name)
model.eval()
with torch.no_grad():
for i, (inputs, cifar_labels) in enumerate(dataloaders['val']):
inputs = inputs.to(device)
labels = torch.tensor(labels_to_filtered(cifar_labels))
labels = labels.to(device)
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
for j in range(inputs.size()[0]):
images_so_far += 1
ax = plt.subplot(num_images // 2, 2, images_so_far)
ax.axis('off')
ax.set_title('[{}]'.format(filtered_classes[preds[j]]))
imshow(inputs.cpu().data[j])
if images_so_far == num_images:
return
visualize_model(model_hybrid, num_images=4)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
|
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
from qiskit.transpiler.passes import RemoveBarriers
# 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")
def make_initial_state(qc, initial_state):
"""
logical qubit index
little endian
"""
for i, state in enumerate(initial_state):
if state == "1":
qc.x(i)
qc = QuantumCircuit(3)
make_initial_state(qc, "101")
qc.draw("mpl")
def subspace_encoder(qc, targets):
"""
naive method, can be optimized for init state |110>
little endian
"""
n = qc.num_qubits
qc.cx(targets[2],targets[1])
qc.cx(targets[1],targets[0])
def subspace_encoder_init110(qc, targets):
"""
optimized encoder for init state |110>
endian: |q_0, q_1, q_2> (little endian)
encode |110> to |0>|10>
"""
n = qc.num_qubits
qc.x(targets[0])
def subspace_decoder(qc, targets):
"""
naive method
little endian
"""
n = qc.num_qubits
qc.cx(targets[1], targets[0])
qc.cx(targets[2], targets[1])
qc = QuantumCircuit(3)
make_initial_state(qc, "110")
subspace_encoder_init110(qc, targets=[0,1,2])
qc.draw("mpl")
def trotterize(qc, trot_gate, num_steps, targets):
for _ in range(num_steps):
qc.append(trot_gate, qargs = targets)
qc = QuantumCircuit(3)
make_initial_state(qc, "110")
subspace_encoder_init110(qc, targets=[0,1,2])
qc.barrier()
trotterize(qc, trotter_gate(np.pi / 6), 1, targets=[1, 2])
qc = transpile(qc, optimization_level = 3, basis_gates=["sx", "rz", "cx"])
qc.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)
# initial layout
initial_layout = [5,3,1]
st_qcs_list = []
# Number of trotter steps
max_trotter_step = 50 ### CAN BE >= 4
trotter_steps = list(range(1, max_trotter_step + 1, 3))
for num_steps in trotter_steps:
print("trotter step: ", num_steps)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "101") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder(qc, targets=[0,1,2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
st_qcs_list.append(t3_st_qcs)
st_qcs_list[-1][-1].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")
jobs = []
shots = 1 << 13
# Number of trotter steps
for i, num_steps in enumerate(trotter_steps):
print("trotter step: ", num_steps)
# execute: reps = 1
job = execute(st_qcs_list[i], backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
print()
# 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, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
results = []
for job in jobs:
results.append( job.result() )
mit_results = []
for job in jobs:
mit_results.append( meas_fitter.filter.apply(job.result()) )
print(len(results), len(mit_results))
# 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^Zero^One).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
raw_fids = []
for result in results:
fid = state_tomo(result, st_qcs)
raw_fids.append(fid)
# print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
# 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)))
plt.clf()
plt.style.use('ggplot')
plt.figure(dpi=200)
plt.title("state fidelity from Trotter step 1 to "+str(trotter_steps))
plt.plot(trotter_steps, raw_fids, label="raw fidelity")
plt.plot(trotter_steps, fids, label="fidelity after QREM")
plt.xlabel("number of trotter steps")
plt.ylabel("fidelity")
plt.grid(linestyle='dotted')
for step, fid in zip(trotter_steps, raw_fids):
print(step, fid)
for step, fid in zip(trotter_steps, fids):
print(step, fid)
|
https://github.com/jeevesh2002/QuantumKatasQiskit
|
jeevesh2002
|
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise, create_empty_matrix
from typing import List
import math, cmath
Matrix = List[List[complex]]
@exercise
def matrix_add(a : Matrix, b : Matrix) -> Matrix:
# You can get the size of a matrix like this:
rows = len(a)
columns = len(a[0])
# You can use the following function to initialize a rows×columns matrix filled with 0s to store your answer
c = create_empty_matrix(rows, columns)
# You can use a for loop to execute its body several times;
# in this loop variable i will take on each value from 0 to n-1, inclusive
for i in range(rows):
# Loops can be nested
for j in range(columns):
# You can access elements of a matrix like this:
x = a[i][j]
y = b[i][j]
# You can modify the elements of a matrix like this:
c[i][j] = ...
return c
@exercise
def scalar_mult(x : complex, a : Matrix) -> Matrix:
# Fill in the missing code and run the cell to check your work.
return ...
@exercise
def matrix_mult(a : Matrix, b : Matrix) -> Matrix:
return ...
@exercise
def matrix_inverse(a : Matrix) -> Matrix:
return ...
@exercise
def transpose(a : Matrix) -> Matrix:
return ...
@exercise
def conjugate(a : Matrix) -> Matrix:
return ...
@exercise
def adjoint(a : Matrix) -> Matrix:
return ...
from pytest import approx
@exercise
def is_matrix_unitary(a : Matrix) -> bool:
return ...
@exercise
def inner_prod(v : Matrix, w : Matrix) -> complex:
return ...
@exercise
def normalize(v : Matrix) -> Matrix:
return ...
@exercise
def outer_prod(v : Matrix, w : Matrix) -> Matrix:
return ...
@exercise
def tensor_product(a : Matrix, b : Matrix) -> Matrix:
return ...
@exercise
def find_eigenvalue(a : Matrix, v : Matrix) -> float:
return ...
@exercise
def find_eigenvector(a : Matrix, x : float) -> Matrix:
return ...
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
|
bayesian-randomized-benchmarking
|
#Import general libraries (needed for functions)
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
#Import Qiskit classes
import qiskit
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error
#Import the RB Functions
import qiskit.ignis.verification.randomized_benchmarking as rb
import copy
# import the bayesian packages
import pymc3 as pm
import arviz as az
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
from qiskit.tools.monitor import job_monitor
device = provider.get_backend('ibmq_lima')
# initialize the Bayesian extension
%config InlineBackend.figure_format = 'retina'
# Initialize random number generator
RANDOM_SEED = 8927
np.random.seed(RANDOM_SEED)
az.style.use("arviz-darkgrid")
def obtain_priors_and_data_from_fitter(printout = True):
m_gates = copy.deepcopy(nCliffs)
# We choose the count matrix corresponding to 2 Qubit RB
Y = (np.array(rbfit._raw_data[0])*shots).astype(int)
# alpha prior and bounds
alpha_ref = rbfit._fit[0]['params'][1]
alpha_lower = alpha_ref - 2*rbfit._fit[0]['params_err'][1] # modified for real
alpha_upper = alpha_ref + 2*rbfit._fit[0]['params_err'][1] # modified for real
# priors for A anbd B
mu_AB = np.delete(rbfit._fit[0]['params'],1)
cov_AB=np.delete(rbfit._fit[0]['params_err'],1)**2
# prior for sigmatheta:
sigma_theta = 0.004
if printout:
print("priors:\nalpha_ref",alpha_ref)
print("alpha_lower", alpha_lower, "alpha_upper", alpha_upper)
print("A,B", mu_AB, "\ncov A,B", cov_AB)
print("sigma_theta", sigma_theta)
return m_gates, Y, alpha_ref, alpha_lower, alpha_upper, mu_AB, cov_AB, sigma_theta
def get_bayesian_model(model_type):
# Bayesian model
# from https://iopscience.iop.org/article/10.1088/1367-2630/17/1/013042/pdf
# see https://docs.pymc.io/api/model.html
RB_model = pm.Model()
with RB_model:
#Priors for unknown model parameters
alpha = pm.Uniform("alpha",lower=alpha_lower,
upper=alpha_upper, testval = alpha_ref)
BoundedMvNormal = pm.Bound(pm.MvNormal, lower=0.0)
AB = BoundedMvNormal("AB", mu=mu_AB,testval = mu_AB,
cov= np.diag(cov_AB),
shape = (2))
# Expected value of outcome
GSP = AB[0]*alpha**m_gates + AB[1]
if model_type == "pooled":
total_shots = np.full(Y.shape, shots)
theta = GSP
elif model_type == "hierarchical":
total_shots = np.full(Y.shape, shots)
theta = pm.Beta("GSP",
mu=GSP,
sigma = sigma_theta,
shape = Y.shape[1])
# Likelihood (sampling distribution) of observations
p = pm.Binomial("Counts", p=theta, observed=Y,
n = total_shots)
return RB_model
def get_trace(RB_model):
# Gradient-based sampling methods
# see also: https://docs.pymc.io/notebooks/sampler-stats.html
# and https://docs.pymc.io/notebooks/api_quickstart.html
with RB_model:
trace= pm.sample(draws = 2000, tune= 10000, target_accept=0.9, return_inferencedata=True)
with RB_model:
az.plot_trace(trace);
return trace
def get_summary(RB_model, trace, hdi_prob=.94, kind='all'):
with RB_model:
# (hdi_prob=.94 is default)
az_summary = az.summary(trace, round_to=4, hdi_prob=hdi_prob, kind=kind )
return az_summary
# obtain EPC from alpha (used by plot_posterior)
def alpha_to_EPC(alpha):
return 3*(1-alpha)/4
def get_EPC_and_legends(azs):
EPC_Bayes = alpha_to_EPC(azs['mean']['alpha'])
EPC_Bayes_err = EPC_Bayes - alpha_to_EPC(azs['mean']['alpha']+azs['sd']['alpha'])
Bayes_legend ="EPC Bayes {0:.5f} ({1:.5f})".format(EPC_Bayes, EPC_Bayes_err)
Fitter_legend ="EPC Fitter {0:.5f} ({1:.5f})".format(rbfit.fit[0]['epc']\
,rbfit._fit[0]['epc_err'])
pred_epc_legend = "EPC predicted {0:.5f}".format(pred_epc)
return EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend, pred_epc_legend
def EPC_compare_fitter_to_bayes(RB_model, azs, trace):
EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend, pred_epc_legend = get_EPC_and_legends(azs)
with RB_model:
az.plot_posterior(trace, var_names=['alpha'], round_to=4,
transform = alpha_to_EPC, point_estimate=None)
plt.title("Error per Clifford")
plt.axvline(x=alpha_to_EPC(alpha_ref),color='red')
#plt.axvline(x=pred_epc,color='green') # WIP
#plt.legend((Bayes_legend, "Higher density interval",Fitter_legend, pred_epc_legend), fontsize=10 )# WIP
plt.legend((Bayes_legend, "Higher density interval",Fitter_legend), fontsize=10 )
plt.show()
def GSP_compare_fitter_to_bayes(RB_model, azs):
EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend,_ = get_EPC_and_legends(azs)
# plot ground state population ~ Clifford length
fig, axes = plt.subplots(1, 1, sharex=True, figsize=(10, 6))
axes.set_ylabel("Ground State Population")
axes.set_xlabel("Clifford Length")
axes.plot(m_gates, np.mean(Y/shots,axis=0), 'r.')
axes.plot(m_gates,azs['mean']['AB[0]']*azs['mean']['alpha']**m_gates+azs['mean']['AB[1]'],'--')
#axes.plot(m_gates,azs['mean']['GSP'],'--') # WIP
#axes.errorbar(m_gates, azs['mean']['GSP'], azs['sd']['GSP'], linestyle='None', marker='^') # WIP
axes.plot(m_gates,mu_AB[0]*np.power(alpha_ref,m_gates)+mu_AB[1],':')
for i_seed in range(nseeds):
plt.scatter(m_gates-0.25, Y[i_seed,:]/shots, label = "data", marker="x")
axes.legend(["Mean Observed Frequencies",
"Bayesian Model\n"+Bayes_legend,
"Fitter Model\n"+Fitter_legend],fontsize=12)
#axes.set_title('2 Qubit RB with T1/T2 Noise', fontsize=18) # WIP
def get_predicted_EPC(error_source):
#Count the number of single and 2Q gates in the 2Q Cliffords
gates_per_cliff = rb.rb_utils.gates_per_clifford(transpile_list,xdata[0],basis_gates,rb_opts['rb_pattern'][0])
for basis_gate in basis_gates:
print("Number of %s gates per Clifford: %f "%(basis_gate ,
np.mean([gates_per_cliff[rb_pattern[0][0]][basis_gate],
gates_per_cliff[rb_pattern[0][1]][basis_gate]])))
# Calculate the predicted epc
# from the known depolarizing errors on the simulation
if error_source == "depolarization":
# Error per gate from noise model
epgs_1q = {'u1': 0, 'u2': p1Q/2, 'u3': 2*p1Q/2}
epg_2q = p2Q*3/4
pred_epc = rb.rb_utils.calculate_2q_epc(
gate_per_cliff=gates_per_cliff,
epg_2q=epg_2q,
qubit_pair=[0, 2],
list_epgs_1q=[epgs_1q, epgs_1q])
# using the predicted primitive gate errors from the coherence limit
if error_source == "from_T1_T2":
# Predicted primitive gate errors from the coherence limit
u2_error = rb.rb_utils.coherence_limit(1,[t1],[t2],gate1Q)
u3_error = rb.rb_utils.coherence_limit(1,[t1],[t2],2*gate1Q)
epg_2q = rb.rb_utils.coherence_limit(2,[t1,t1],[t2,t2],gate2Q)
epgs_1q = {'u1': 0, 'u2': u2_error, 'u3': u3_error}
pred_epc = rb.rb_utils.calculate_2q_epc(
gate_per_cliff=gates_per_cliff,
epg_2q=epg_2q,
qubit_pair=[0, 1],
list_epgs_1q=[epgs_1q, epgs_1q])
return pred_epc
def get_count_data(result_list):
### another way to obtain the observed counts
Y_list = []
for rbseed, result in enumerate(result_list):
row_list = []
for c_index, c_value in enumerate(nCliffs):
if nQ == 2:
list_bitstring = ['00']
elif nQ == 3:
list_bitstring = ['000', '100'] # because q2 measured in c1
total_counts = 0
for bitstring in list_bitstring:
total_counts += result.get_counts()[c_index][bitstring]
row_list.append(total_counts)
Y_list.append(row_list)
return np.array(Y_list)
#Number of qubits
nQ = 2
#There are 2 qubits: Q0,Q1.
#Number of seeds (random sequences)
nseeds = 10 # more data for the Rev. Mr. Bayes
#Number of Cliffords in the sequence (start, stop, steps)
nCliffs = np.arange(1,200,20)
#2Q RB Q0,Q1
rb_pattern = [[0,1]]
length_multiplier = 1
rb_opts = {}
rb_opts ['length_vector'] = nCliffs
rb_opts ['nseeds'] = nseeds
rb_opts ['rb_pattern'] = rb_pattern
rb_opts ['length_multiplier'] = length_multiplier
rb_circs , xdata = rb.randomized_benchmarking_seq(**rb_opts )
backend = device
basis_gates = ['u1','u2','u3','cx'] # use U,CX for now
shots = 1024
result_list = []
transpile_list = []
import time
for rb_seed,rb_circ_seed in enumerate(rb_circs):
print('Compiling seed %d'%rb_seed)
rb_circ_transpile = qiskit.transpile(rb_circ_seed,
optimization_level=0,
basis_gates=basis_gates)
print('Runing seed %d'%rb_seed)
job = qiskit.execute(rb_circ_transpile,
shots=shots,
backend=backend)
job_monitor(job)
result_list.append(job.result())
transpile_list.append(rb_circ_transpile)
print("Finished Real Jobs")
print(rb_circs[0][0])
#Create an RBFitter object
rbfit = rb.RBFitter(result_list, xdata, rb_opts['rb_pattern'])
m_gates, Y, alpha_ref, alpha_lower, alpha_upper, mu_AB, cov_AB, sigma_theta =\
obtain_priors_and_data_from_fitter(printout = True)
### a check of the count matrix
np.sum((Y == (get_count_data(result_list)))*1) == Y.size
pooled = get_bayesian_model("pooled")
pm.model_to_graphviz(pooled)
trace_p = get_trace(pooled)
azp_summary = get_summary(pooled, trace_p)
azp_summary
hierarchical = get_bayesian_model("hierarchical")
pm.model_to_graphviz(hierarchical)
trace_h = get_trace(hierarchical)
azh_summary = get_summary(hierarchical, trace_h)
azh_summary
# Leave-one-out Cross-validation (LOO) comparison
df_comp_loo = az.compare({"hierarchical": trace_h, "pooled": trace_p})
df_comp_loo
az.plot_compare(df_comp_loo, insample_dev=False);
# predict EPC from the noisy model
#pred_epc = get_predicted_EPC(error_source = 'from_T1_T2') # this was for a noise model
pred_epc = 0.0165 # will not appear on graphs for real device but at this point functions need value (WIP)
print("Fake 2Q Error per Clifford: %e"%pred_epc)
EPC_compare_fitter_to_bayes(pooled, azp_summary, trace_p)
EPC_compare_fitter_to_bayes(hierarchical, azh_summary, trace_h)
GSP_compare_fitter_to_bayes(pooled, azp_summary)
GSP_compare_fitter_to_bayes(hierarchical, azh_summary)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
%load_ext watermark
%watermark -n -u -v -iv -w
|
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/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.
"""
Functions used for the analysis of randomized benchmarking results.
"""
from scipy.optimize import curve_fit
import numpy as np
from qiskit import QiskitError
from ..tomography import marginal_counts
from ...characterization.fitters import build_counts_dict_from_list
try:
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
class RBFitter:
"""
Class for fitters for randomized benchmarking
"""
def __init__(self, backend_result, cliff_lengths,
rb_pattern=None):
"""
Args:
backend_result: list of results (qiskit.Result).
cliff_lengths: the Clifford lengths, 2D list i x j where i is the
number of patterns, j is the number of cliffords lengths
rb_pattern: the pattern for the rb sequences.
"""
if rb_pattern is None:
rb_pattern = [[0]]
self._cliff_lengths = cliff_lengths
self._rb_pattern = rb_pattern
self._raw_data = []
self._ydata = []
self._fit = []
self._nseeds = 0
self._result_list = []
self.add_data(backend_result)
@property
def raw_data(self):
"""Return raw data."""
return self._raw_data
@property
def cliff_lengths(self):
"""Return clifford lengths."""
return self.cliff_lengths
@property
def ydata(self):
"""Return ydata (means and std devs)."""
return self._ydata
@property
def fit(self):
"""Return fit."""
return self._fit
@property
def seeds(self):
"""Return the number of loaded seeds."""
return self._nseeds
@property
def results(self):
"""Return all the results."""
return self._result_list
def add_data(self, new_backend_result, rerun_fit=True):
"""
Add a new result. Re calculate the raw data, means and
fit.
Args:
new_backend_result: list of rb results
rerun_fit: re caculate the means and fit the result
Additional information:
Assumes that 'result' was executed is
the output of circuits generated by randomized_becnhmarking_seq,
"""
if new_backend_result is None:
return
if not isinstance(new_backend_result, list):
new_backend_result = [new_backend_result]
for result in new_backend_result:
self._result_list.append(result)
# update the number of seeds *if* new ones
# added. Note, no checking if we've done all the
# cliffords
for rbcirc in result.results:
nseeds_circ = int(rbcirc.header.name.split('_')[-1])
if (nseeds_circ+1) > self._nseeds:
self._nseeds = nseeds_circ+1
for result in self._result_list:
if not len(result.results) == len(self._cliff_lengths[0]):
raise ValueError(
"The number of clifford lengths must match the number of "
"results")
if rerun_fit:
self.calc_data()
self.calc_statistics()
self.fit_data()
@staticmethod
def _rb_fit_fun(x, a, alpha, b):
"""Function used to fit rb."""
# pylint: disable=invalid-name
return a * alpha ** x + b
def calc_data(self):
"""
Retrieve probabilities of success from execution results. Outputs
results into an internal variable _raw_data which is a 3-dimensional
list, where item (i,j,k) is the probability to measure the ground state
for the set of qubits in pattern "i" for seed no. j and vector length
self._cliff_lengths[i][k].
Additional information:
Assumes that 'result' was executed is
the output of circuits generated by randomized_becnhmarking_seq,
"""
circ_counts = {}
circ_shots = {}
for seedidx in range(self._nseeds):
for circ, _ in enumerate(self._cliff_lengths[0]):
circ_name = 'rb_length_%d_seed_%d' % (circ, seedidx)
count_list = []
for result in self._result_list:
try:
count_list.append(result.get_counts(circ_name))
except (QiskitError, KeyError):
pass
circ_counts[circ_name] = \
build_counts_dict_from_list(count_list)
circ_shots[circ_name] = sum(circ_counts[circ_name].values())
self._raw_data = []
startind = 0
for patt_ind in range(len(self._rb_pattern)):
string_of_0s = ''
string_of_0s = string_of_0s.zfill(len(self._rb_pattern[patt_ind]))
self._raw_data.append([])
endind = startind+len(self._rb_pattern[patt_ind])
for i in range(self._nseeds):
self._raw_data[-1].append([])
for k, _ in enumerate(self._cliff_lengths[patt_ind]):
circ_name = 'rb_length_%d_seed_%d' % (k, i)
counts_subspace = marginal_counts(
circ_counts[circ_name],
np.arange(startind, endind))
self._raw_data[-1][i].append(
counts_subspace.get(string_of_0s, 0)
/ circ_shots[circ_name])
startind += (endind)
def calc_statistics(self):
"""
Extract averages and std dev from the raw data (self._raw_data).
Assumes that self._calc_data has been run. Output into internal
_ydata variable:
ydata is a list of dictionaries (length number of patterns).
Dictionary ydata[i]:
ydata[i]['mean'] is a numpy_array of length n;
entry j of this array contains the mean probability of
success over seeds, for vector length
self._cliff_lengths[i][j].
And ydata[i]['std'] is a numpy_array of length n;
entry j of this array contains the std
of the probability of success over seeds,
for vector length self._cliff_lengths[i][j].
"""
self._ydata = []
for patt_ind in range(len(self._rb_pattern)):
self._ydata.append({})
self._ydata[-1]['mean'] = np.mean(self._raw_data[patt_ind], 0)
if len(self._raw_data[patt_ind]) == 1: # 1 seed
self._ydata[-1]['std'] = None
else:
self._ydata[-1]['std'] = np.std(self._raw_data[patt_ind], 0)
def fit_data(self):
"""
Fit the RB results to an exponential curve.
Fit each of the patterns
Puts the results into a list of fit dictionaries:
where each dictionary corresponds to a pattern and has fields:
'params' - three parameters of rb_fit_fun. The middle one is the
exponent.
'err' - the error limits of the parameters.
'epc' - error per Clifford
"""
self._fit = []
for patt_ind, (lens, qubits) in enumerate(zip(self._cliff_lengths,
self._rb_pattern)):
# if at least one of the std values is zero, then sigma is replaced
# by None
if not self._ydata[patt_ind]['std'] is None:
sigma = self._ydata[patt_ind]['std'].copy()
if len(sigma) - np.count_nonzero(sigma) > 0:
sigma = None
else:
sigma = None
params, pcov = curve_fit(self._rb_fit_fun, lens,
self._ydata[patt_ind]['mean'],
sigma=sigma,
p0=(1.0, 0.95, 0.0),
bounds=([-2, 0, -2], [2, 1, 2]))
alpha = params[1] # exponent
params_err = np.sqrt(np.diag(pcov))
alpha_err = params_err[1]
nrb = 2 ** len(qubits)
epc = (nrb-1)/nrb*(1-alpha)
epc_err = epc*alpha_err/alpha
self._fit.append({'params': params, 'params_err': params_err,
'epc': epc, 'epc_err': epc_err})
def plot_rb_data(self, pattern_index=0, ax=None,
add_label=True, show_plt=True):
"""
Plot randomized benchmarking data of a single pattern.
Args:
pattern_index: which RB pattern to plot
ax (Axes or None): plot axis (if passed in).
add_label (bool): Add an EPC label
show_plt (bool): display the plot.
Raises:
ImportError: If matplotlib is not installed.
"""
fit_function = self._rb_fit_fun
if not HAS_MATPLOTLIB:
raise ImportError('The function plot_rb_data needs matplotlib. '
'Run "pip install matplotlib" before.')
if ax is None:
plt.figure()
ax = plt.gca()
xdata = self._cliff_lengths[pattern_index]
# Plot the result for each sequence
for one_seed_data in self._raw_data[pattern_index]:
ax.plot(xdata, one_seed_data, color='gray', linestyle='none',
marker='x')
# Plot the mean with error bars
ax.errorbar(xdata, self._ydata[pattern_index]['mean'],
yerr=self._ydata[pattern_index]['std'],
color='r', linestyle='--', linewidth=3)
# Plot the fit
ax.plot(xdata,
fit_function(xdata, *self._fit[pattern_index]['params']),
color='blue', linestyle='-', linewidth=2)
ax.tick_params(labelsize=14)
ax.set_xlabel('Clifford Length', fontsize=16)
ax.set_ylabel('Ground State Population', fontsize=16)
ax.grid(True)
if add_label:
bbox_props = dict(boxstyle="round,pad=0.3",
fc="white", ec="black", lw=2)
ax.text(0.6, 0.9,
"alpha: %.3f(%.1e) EPC: %.3e(%.1e)" %
(self._fit[pattern_index]['params'][1],
self._fit[pattern_index]['params_err'][1],
self._fit[pattern_index]['epc'],
self._fit[pattern_index]['epc_err']),
ha="center", va="center", size=14,
bbox=bbox_props, transform=ax.transAxes)
if show_plt:
plt.show()
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
# importa o qiskit, cujas funcoes podemos entao usar
import qiskit
# para ver que versoes das ferramentas do qiskit temos instaladas
qiskit.__qiskit_version__
# determina o API token a ser usado
qiskit.IBMQ.save_account('76cefda2ab77d95541b7cf7a52dc060ae5552c2c67297b954cb056ea1dbf4cc2de3428fc8156cfa85ce0816608b323bf8b9134d8567bcebd3d84d2c4d9473bb9',
overwrite = True)
# conecta meu computador com minha conta IBMQ na nuvem
qiskit.IBMQ.load_account()
# determina qual das minhas "contas" vou usar.
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
# mostra quais beckends posso utilizar
provider.backends()
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
# para ter um panorama do tipo e status dos backends disponiveis
#from qiskit.tools.monitor import backend_overview, backend_monitor
#backend_overview()
# utilizado para obter informacoes sobre um determinado backend
#simulator = provider.get_backend('ibmq_qasm_simulator')
#device = provider.get_backend('ibmq_oslo')
# informacao detalhada sobre um determinado backend
#chip_info = backend_monitor(device); print(chip_info)
|
https://github.com/MuhammadMiqdadKhan/Solution-of-IBM-s-Global-Quantum-Challenge-2020
|
MuhammadMiqdadKhan
|
# Cell 1
import numpy as np
from qiskit import Aer, QuantumCircuit, execute
from qiskit.visualization import plot_histogram
from IPython.display import display, Math, Latex
from may4_challenge import plot_state_qsphere
from may4_challenge.ex1 import minicomposer
from may4_challenge.ex1 import check1, check2, check3, check4, check5, check6, check7, check8
from may4_challenge.ex1 import return_state, vec_in_braket, statevec
# Cell 2
# press shift + return to run this code cell
# then, click on the gate that you want to apply to your qubit
# next, you have to choose the qubit that you want to apply it to (choose '0' here)
# click on clear to restart
minicomposer(1, dirac=True, qsphere=True)
# Cell 3
def create_circuit():
qc = QuantumCircuit(1)
qc.x(0)
return qc
# check solution
qc = create_circuit()
state = statevec(qc)
check1(state)
plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True)
# Cell 4
def create_circuit2():
qc = QuantumCircuit(1)
qc.h(0)
return qc
qc = create_circuit2()
state = statevec(qc)
check2(state)
plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True)
# Cell 5
def create_circuit3():
qc = QuantumCircuit(1)
qc.x(0)
qc.h(0)
return qc
qc = create_circuit3()
state = statevec(qc)
check3(state)
plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True)
# Cell 6
def create_circuit4():
qc = QuantumCircuit(1)
qc.h(0)
qc.sdg(0)
return qc
qc = create_circuit4()
state = statevec(qc)
check4(state)
plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True)
# Cell 7
# press shift + return to run this code cell
# then, click on the gate that you want to apply followed by the qubit(s) that you want it to apply to
# for controlled gates, the first qubit you choose is the control qubit and the second one the target qubit
# click on clear to restart
minicomposer(2, dirac = True, qsphere = True)
# Cell 8
def create_circuit():
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
return qc
qc = create_circuit()
state = statevec(qc) # determine final state after running the circuit
display(Math(vec_in_braket(state.data)))
check5(state)
qc.draw(output='mpl') # we draw the circuit
# Cell 9
def create_circuit6():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also
# two classical bits for the measurement later
qc.h(0)
qc.x(1)
qc.cx(0, 1)
qc.z(0)
return qc
qc = create_circuit6()
state = statevec(qc) # determine final state after running the circuit
display(Math(vec_in_braket(state.data)))
check6(state)
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
qc.draw(output='mpl') # we draw the circuit
# Cell 10
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 1000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc)
print(counts)
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
# Cell 11
def create_circuit7():
qc = QuantumCircuit(2)
qc.rx(np.pi/3,0)
qc.x(1)
qc.swap(0, 1)
return qc
qc = create_circuit7()
def create_circuit():
qc.x(0)
qc.h(1)
qc.sdg(1)
qc.swap(0, 1)
state = statevec(qc) # determine final state after running the circuit
display(Math(vec_in_braket(state.data)))
check7(state)
plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True)
# Cell 12
#
#
# FILL YOUR CODE IN HERE
def create_circuit8():
qc = QuantumCircuit(3,3) # this time, we not only want two qubits, but also
# two classical bits for the measurement later
def create_circuit():
qc = QuantumCircuit(3)
qc.h(2)
qc.cx(2, 1)
qc.cx(1, 0)
return qc
qc = create_circuit8()
state = statevec(qc) # determine final state after running the circuit
display(Math(vec_in_braket(state.data)))
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
qc.measure(2, 2)
qc.draw(output='mpl') # we draw the circuit
plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True)
#
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 2000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc)
#
print(counts)
check8(counts)
plot_histogram(counts)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import Aer, QuantumCircuit
from qiskit.circuit.library import PhaseEstimation
qc= QuantumCircuit(3,3)
# dummy unitary circuit
unitary_circuit = QuantumCircuit(1)
unitary_circuit.h(0)
# QPE
qc.append(PhaseEstimation(2, unitary_circuit), list(range(3)))
qc.measure(list(range(3)), list(range(3)))
backend = Aer.get_backend('qasm_simulator')
result = backend.run(qc, shots = 8192).result()
|
https://github.com/SanNare/qiskit-notebooks
|
SanNare
|
! pip install qiskit
from qiskit import QuantumCircuit, Aer, IBMQ, execute
from qiskit.tools.monitor import job_monitor
import math
def superpose(n):
circuit = QuantumCircuit(n,n)
for i in range(0,n):
circuit.h(i)
circuit.measure(range(n),range(n))
return circuit
sample = superpose(6)
sample.draw('mpl')
def qrandom_sim(a,b):
n = math.ceil(math.log2(b))
circuit = superpose(n)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit,backend = simulator, shots = 1).result()
v = int(list(result.get_counts(circuit).keys())[0],2)
return v%(b-a+1)+a
r = qrandom_sim(2,20)
print(r)
IBMQ.load_account()
def qrandom(a,b):
n = math.ceil(math.log2(b))
circuit = superpose(n)
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmq_16_melbourne')
job = execute(circuit,backend = qcomp,shots = 1)
job_monitor(job)
result = job.result()
v = int(list(result.get_counts(circuit).keys())[0],2)
return v%(b-a+1)+a
r = qrandom(20,40)
print(r)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/ryanlevy/shadow-tutorial
|
ryanlevy
|
import numpy as np
import matplotlib.pyplot as plt
import qiskit
pauli_list = [
np.eye(2),
np.array([[0.0, 1.0], [1.0, 0.0]]),
np.array([[0, -1.0j], [1.0j, 0.0]]),
np.array([[1.0, 0.0], [0.0, -1.0]]),
]
s_to_pauli = {
"I": pauli_list[0],
"X": pauli_list[1],
"Y": pauli_list[2],
"Z": pauli_list[3],
}
def channel(N,qc):
'''create an N qubit GHZ state '''
qc.h(0)
if N>=2: qc.cx(0,1)
if N>=3: qc.cx(0,2)
if N>=4: qc.cx(1,3)
if N>4: raise NotImplementedError(f"{N} not implemented!")
def bitGateMap(qc,g,qi):
'''Map X/Y/Z string to qiskit ops'''
if g=="X":
qc.h(qi)
elif g=="Y":
qc.sdg(qi)
qc.h(qi)
elif g=="Z":
pass
else:
raise NotImplementedError(f"Unknown gate {g}")
def Minv(N,X):
'''inverse shadow channel'''
return ((2**N+1.))*X - np.eye(2**N)
def trace_dist(lam_exact,rho):
''' returns normalized trace distance between lam_exact and rho'''
mid = (lam_exact-rho).conj().T@(lam_exact-rho)
N = 2**int(np.log2(lam_exact.shape[0])/2)
# svd mid and apply sqrt to singular values
# based on qiskit internals function
U1,d,U2 = np.linalg.svd(mid)
sqrt_mid = U1@np.diag(np.sqrt(d))@U2
dist = np.trace(sqrt_mid)/2
return dist/N
qc = qiskit.QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
choi_actual = qiskit.quantum_info.Choi(qc)
qc.draw(output='mpl')
plt.imshow(choi_actual.data.real)
qiskit.visualization.state_visualization.plot_state_city(choi_actual.data)
N = 2
qc = qiskit.QuantumCircuit(2*N)
for i in range(N):
qc.h(i+N)
qc.cx(i+N,i)
qc.barrier()
channel(N,qc)
qc.draw(output='mpl')
choi_state = qiskit.quantum_info.DensityMatrix(qc)
# this is the same up to normalization
# Tr[lambda] = 2^N
np.allclose(choi_state.data*2**N,choi_actual)
nShadows = 1_000
reps = 50
N = 2
rng = np.random.default_rng(1717)
cliffords = [qiskit.quantum_info.random_clifford(N*2,seed=rng) for _ in range(nShadows)]
N = 2
qc = qiskit.QuantumCircuit(2*N)
for i in range(N):
qc.h(i+N)
qc.cx(i+N,i)
channel(N,qc)
results = []
for cliff in cliffords:
qc_c = qc.compose(cliff.to_circuit())
counts = qiskit.quantum_info.Statevector(qc_c).sample_counts(reps)
results.append(counts)
rho_shadow = 0.+0j
for cliff,res in zip(cliffords,results):
mat = cliff.adjoint().to_matrix()
for bit,count in res.items():
Ub = mat[:,int(bit,2)] # this is Udag|b>
rho_shadow += (Minv(N*2,np.outer(Ub,Ub.conj()))*count)
rho_shadow /=( nShadows*reps)
rho_shadow *= 2**N
assert np.allclose(rho_shadow.trace(),2**N)
plt.subplot(121)
plt.suptitle("Correct")
plt.imshow(choi_actual.data.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(choi_actual.data.imag,vmax=0.7,vmin=-0.7)
plt.show()
print("---")
plt.subplot(121)
plt.suptitle("Shadow(Full Clifford)")
plt.imshow(rho_shadow.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(rho_shadow.imag,vmax=0.7,vmin=-0.7)
plt.show()
qiskit.visualization.state_visualization.plot_state_city(choi_actual.data,title="Correct")
qiskit.visualization.state_visualization.plot_state_city(rho_shadow,title="Shadow (clifford)")
_,vs = np.linalg.eigh(rho_shadow)
rho_shadow_pure = np.outer(vs[:,-1],vs[:,-1].conj().T)*2**N
print(f"original trace distance = {trace_dist(choi_actual.data,rho_shadow).real:0.4f}")
print(f"Purified trace distance = {trace_dist(choi_actual.data,rho_shadow_pure).real:0.4f}")
nShadows = 1_000
reps = 50
N = 2
rng = np.random.default_rng(1717)
front_cliffords = [qiskit.quantum_info.random_clifford(N,seed=rng) for _ in range(nShadows)]
back_cliffords = [qiskit.quantum_info.random_clifford(N,seed=rng) for _ in range(nShadows)]
N = 2
qc = qiskit.QuantumCircuit(N)
results = []
for front,back in zip(front_cliffords,back_cliffords):
qc_c = qc.compose(front.adjoint().to_circuit())
channel(N,qc_c)
qc_c = qc_c.compose(back.to_circuit())
counts = qiskit.quantum_info.Statevector(qc_c).sample_counts(reps)
results.append(counts)
rho_shadow2 = 0.+0j
for front, back, res in zip(front_cliffords, back_cliffords, results):
mat_front = front.to_matrix()
mat_back = back.adjoint().to_matrix()
U0_front = mat_front.T[:, 0] # this is <0|U or U^T|0>
M_front = Minv(N, np.outer(U0_front, U0_front.conj()))
for bit, count in res.items():
Ub = mat_back[:, int(bit, 2)] # this is Udag|b>
M_back = Minv(N, np.outer(Ub, Ub.conj()))
rho_shadow2 += np.kron(M_front, M_back) * count
rho_shadow2 /= nShadows * reps
rho_shadow2 *= 2**N
assert np.allclose(rho_shadow2.trace(),2**N)
plt.subplot(121)
plt.suptitle("Correct")
plt.imshow(choi_actual.data.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(choi_actual.data.imag,vmax=0.7,vmin=-0.7)
plt.show()
print("---")
plt.subplot(121)
plt.suptitle("Shadow(Full Clifford, 2 sided)")
plt.imshow(rho_shadow2.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(rho_shadow2.imag,vmax=0.7,vmin=-0.7)
plt.show()
print(f"ancilla trace distance = {trace_dist(choi_actual.data,rho_shadow).real:0.4f}")
print(f"two sided trace distance = {trace_dist(choi_actual.data,rho_shadow2).real:0.4f}")
plt.subplot(121)
plt.title("Shadow(Full Clifford, Ancilla)")
plt.imshow(rho_shadow.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.title("Shadow(Full Clifford, 2 sided)")
plt.imshow(rho_shadow2.real,vmax=0.7,vmin=-0.7)
plt.show()
N = 2
# Channel
qc = qiskit.QuantumCircuit(N)
channel(N,qc)
# test state
sigma = qiskit.QuantumCircuit(N)
sigma.ry(1.23,0)
sigma.ry(2.34,1)
# input to channel to predict
qc_in = qiskit.QuantumCircuit(N)
qc_in.rx(.11,0)
qc_in.rx(.22,1)
rho_in = qiskit.quantum_info.DensityMatrix(qc_in)
rho_sigma = qiskit.quantum_info.DensityMatrix(sigma)
# Version 1, run the circuit above and measure P(00) state
qc_all = qc_in.compose(qc)
# now apple inverse(sigmaa)
qc_all.ry(-1.23,0)
qc_all.ry(-2.34,1)
qc_all.draw()
overlap_full = np.abs(qiskit.quantum_info.Statevector(qc_all)[0])**2
# version 2, evolve via the true choi matrix
overlap_trace = np.trace(np.kron(rho_in.data.T,rho_sigma.data)@choi_actual.data).real
# version 3, qiskit formalism
rho_evolve = choi_actual._evolve(rho_in)
overlap_evolve = rho_sigma.expectation_value(rho_evolve).real
print(f"trace circuit={overlap_full:0.4f}")
print(f"trace ={overlap_trace:0.4f}")
print(f"evolution ={overlap_evolve:0.4f}")
shadow_overlap = np.trace(np.kron(rho_in.data.T,rho_sigma.data)@rho_shadow).real
shadow_overlap2 = np.trace(np.kron(rho_in.data.T,rho_sigma.data)@rho_shadow2).real
print(f"ancilla shadow ={shadow_overlap:0.4f} (prediction)")
print(f"two sided shadow ={shadow_overlap2:0.4f} (prediction)")
rho_out = qiskit.quantum_info.Choi(rho_shadow2)._evolve(rho_in)
print(f"Tr[rho_out]={rho_out.trace().real:0.4f}")
eigs = np.linalg.eigvalsh(rho_out.data)
print(f"sum of eigenvalues below 0 ={np.sum(eigs[eigs<0]):0.4f}")
def purify(N,lam):
_,vs = np.linalg.eigh(lam)
lam_pure = np.outer(vs[:,-1],vs[:,-1].conj().T) * 2**N
return lam_pure
shadow_overlap_pure = np.trace(np.kron(rho_in.data.T,rho_sigma.data)@purify(N,rho_shadow)).real
shadow_overlap2_pure = np.trace(np.kron(rho_in.data.T,rho_sigma.data)@purify(N,rho_shadow2)).real
print(f"trace circuit = {overlap_full:0.4f}")
print(f"ancilla shadow = {shadow_overlap_pure:0.4f} (prediction)")
print(f"two sided shadow = {shadow_overlap2_pure:0.4f} (prediction)")
rho_out = qiskit.quantum_info.Choi(purify(N,rho_shadow2))._evolve(rho_in)
print(f"Tr[rho_out]={rho_out.trace().real:0.4f}")
eigs = np.linalg.eigvalsh(rho_out.data)
print(f"sum of eigenvalues below 0 ={np.sum(eigs[eigs<0]):0.4f}")
import scipy.sparse as sps
def partial_trace_super(dim1, dim2):
"""
From Qiskit internals
Return the partial trace superoperator in the column-major basis.
This returns the superoperator S_TrB such that:
S_TrB * vec(rho_AB) = vec(rho_A)
for rho_AB = kron(rho_A, rho_B)
Args:
dim1: the dimension of the system not being traced
dim2: the dimension of the system being traced over
Returns:
A Numpy array of the partial trace superoperator S_TrB.
"""
iden = sps.identity(dim1)
ptr = sps.csr_matrix((dim1 * dim1, dim1 * dim2 * dim1 * dim2))
for j in range(dim2):
v_j = sps.coo_matrix(([1], ([0], [j])), shape=(1, dim2))
tmp = sps.kron(iden, v_j.tocsr())
ptr += sps.kron(tmp, tmp)
return ptr
def make_tp(rho, validate=True,
MtM=None, Mb=None):
'''
Projects a 4^N x 4^N choi matrix into the space of TP matrices
Citation: 10.1103/PhysRevA.98.062336
'''
dim = rho.shape[0]
sdim = int(np.sqrt(dim))
if MtM==None and Mb==None:
M = partial_trace_super(sdim, sdim) # M*vec[rho] should be identity
MdagM = M.conj().T@M
MdagI = M.conj().T@np.eye(sdim).ravel('F')
# vec[rho] operation
vec_rho = rho.ravel('F')
new_rho = vec_rho - 1/sdim * MdagM@vec_rho + 1/sdim * MdagI
new_rho = new_rho.reshape(dim,dim,order='F')
if validate:
if abs(rho.trace().real-new_rho.trace().real) > 1e-4:
print(rho.trace(),new_rho.trace())
assert abs(rho.trace().real-new_rho.trace().real) < 1e-4
return new_rho
rho_out_tp = qiskit.quantum_info.Choi(make_tp(purify(N,rho_shadow2)))._evolve(rho_in)
print(f"Tr[rho_out]={rho_out_tp.trace().real:0.4f}")
eigs = np.linalg.eigvalsh(rho_out_tp.data)
print(f"sum of eigenvalues below 0 ={np.sum(eigs[eigs<0]):0.4f}")
print(f"trace circuit = {overlap_full:0.4f}")
print("---")
print(f"two sided shadow = {shadow_overlap2:0.4f} (prediction)")
print(f"two sided shadow = {shadow_overlap2_pure:0.4f} (prediction purified)")
print(f"two sided shadow = {np.trace(rho_out_tp.data@rho_sigma.data).real:0.4f} (prediction TP(purified))")
|
https://github.com/h-rathee851/Pulse_application_qiskit
|
h-rathee851
|
from calibration import *
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-research', group='iserc-1', project='main')
"""
Object to calibrate pulse of backend and qubit of interest.
"""
# Importing required python packages
from warnings import warn
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.signal import find_peaks
from sklearn.model_selection import train_test_split
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
# Importing standard Qiskit libraries
from qiskit import IBMQ, execute, pulse
from qiskit.providers.ibmq import IBMQBackend
from qiskit.pulse import DriveChannel, Schedule, Play
from qiskit.pulse import library as pulse_lib
from qiskit.pulse.library import Waveform, Gaussian
from qiskit.tools.monitor import job_monitor
from qiskit.providers.exceptions import QiskitBackendNotFoundError, BackendConfigurationError
# Loading your IBM Q account(s)
#IBMQ.load_account()
#provider = IBMQ.get_provider()
class PulseCalibration():
"""Creates an object that is used for pulse calibration.
Args:
backend (IBMQBackend) : The IBMQBackend for which pulse calibration needs to be done.
qubit (int) : The qubit for which the pulse calibration is done.
qubit_freq_ground (float) : Custom frequency for 0->1 transition.
qubit_freq_excited (float) : Custom frequency for 1->2 transition.
pi_amp_ground (float) : Custom pi amplitude for 0->1 transition.
The value should be between 0 and 1.
pi_amp_excited (float) : Custom pi amplitude for 1->2 transition.
The value should be between 0 and 1.
pulse_dur (int) : The duration of the pi pulse to be used for calibration.
pulse_sigma (int) : The standard deviation of the pi pulse to be used for calibration.
"""
def __init__(self, backend, qubit, qubit_freq_ground=None, qubit_freq_excited=None,
pi_amp_ground=None, pi_amp_excited=None, pulse_dur=None, pulse_sigma=None):
# pylint: disable=too-many-locals
# pylint: disable=too-many-arguments
if not isinstance(backend, IBMQBackend):
raise QiskitBackendNotFoundError("Provided backend not available." +
"Please provide backend after obtaining from IBMQ.")
self._backend = backend
self._back_config = backend.configuration()
if qubit >= self._back_config.n_qubits:
raise BackendConfigurationError(f"Qubit {qubit} not present in the provided backend.")
self._qubit = qubit
self._back_defaults = backend.defaults()
self._qubit_anharmonicity = backend.properties().qubit_property(self._qubit)['anharmonicity'][0]
self._dt = self._back_config.dt
self._qubit_freq = self._back_defaults.qubit_freq_est[self._qubit]
self._inst_sched_map = self._back_defaults.instruction_schedule_map
self._drive_chan = DriveChannel(qubit)
if pulse_sigma:
self._pulse_sigma = pulse_sigma
else:
if self._backend.name() == 'ibmq_armonk':
self._pulse_sigma = 80
else:
self._pulse_sigma = 40
if pulse_dur:
self._pulse_duration = pulse_dur
else:
self._pulse_duration = (4*self._pulse_sigma)-((4*self._pulse_sigma) % 16)
self._qubit_freq_ground = qubit_freq_ground
self._qubit_freq_excited = qubit_freq_excited
self._pi_amp_ground = pi_amp_ground
self._pi_amp_excited = pi_amp_excited
self._state_discriminator_012 = None
# Find out which measurement map index is needed for this qubit
meas_map_idx = None
for i, measure_group in enumerate(self._back_config.meas_map):
if qubit in measure_group:
meas_map_idx = i
break
assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!"
# The measurement pulse for measuring the qubit of interest.
self._measure = self._inst_sched_map.get('measure',
qubits=self._back_config.meas_map[meas_map_idx])
def create_cal_circuit(self, amp):
"""Constructs and returns a schedule containing Gaussian pulse with amplitude as 'amp',
sigma as 'pulse_sigma' and duration as 'pulse_duration'."""
sched = Schedule()
sched += Play(Gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma,
amp=amp), self._drive_chan)
sched += self._measure << sched.duration
return sched
def create_cal_circuit_excited(self, base_pulse, freq):
""" Constructs and returns a schedule containing a pi pulse for 0->1 transition followed by
a sidebanded pulse which corresponds to applying 'base_pulse' at frequency 'freq'."""
sched = Schedule()
sched += Play(Gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma,
amp=self._pi_amp_ground), self._drive_chan)
sched += Play(self.apply_sideband(base_pulse, freq), self._drive_chan)
sched += self._measure << sched.duration
return sched
@staticmethod
def _fit_function(x_values, y_values, function, init_params):
""" A function fitter. Returns the fit parameters of 'function'."""
fitparams, _ = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
@staticmethod
def _baseline_remove(values):
"""Centering data around zero."""
return np.array(values) - np.mean(values)
def apply_sideband(self, pulse, frequency):
"""Apply a sine sideband to 'pulse' at frequency 'freq'.
Args:
pulse (Waveform): The pulse to which sidebanding is to be applied.
frequency (float): LO frequency at which the pulse is to be applied.
Returns:
Waveform: The sidebanded pulse.
"""
t_samples = np.linspace(0, self._dt*self._pulse_duration, self._pulse_duration)
sine_pulse = np.sin(2*np.pi*(frequency-self._qubit_freq_ground)*t_samples)
sideband_pulse = Waveform(np.multiply(np.real(pulse.samples), sine_pulse),
name='sideband_pulse')
return sideband_pulse
def get_job_data(self, job, average):
"""Retrieve data from a job that has already run.
Args:
job (Job): The job whose data you want.
average (bool): If True, gets the data assuming data is an average.
If False, gets the data assuming it is for single shots.
Return:
list: List containing job result data.
"""
scale_factor = 1e-14
job_results = job.result(timeout=120) # timeout parameter set to 120 s
result_data = []
for i in range(len(job_results.results)):
if average: # get avg data
result_data.append(job_results.get_memory(i)[self._qubit]*scale_factor)
else: # get single data
result_data.append(job_results.get_memory(i)[:, self._qubit]*scale_factor)
return result_data
# Prints out relative maxima frequencies in output_data; height gives lower bound (abs val)
@staticmethod
def _rel_maxima(freqs, output_data, height, distance):
"""Prints out relative maxima frequencies in output_data (can see peaks);
height gives upper bound (abs val). Be sure to set the height properly or
the peak will be ignored!
Args:
freqs (list): frequency list
output_data (list): list of resulting signals
height (float): upper bound (abs val) on a peak
width (float):
Returns:
list: List containing relative maxima frequencies
"""
peaks, _ = find_peaks(x=output_data, height=height, distance=distance)
return freqs[peaks]
def find_freq_ground(self, verbose=False, visual=False):
"""Sets and returns the calibrated frequency corresponding to 0->1 transition."""
# pylint: disable=too-many-locals
sched_list = [self.create_cal_circuit(0.5)]*75
freq_list = np.linspace(self._qubit_freq-(45*1e+6), self._qubit_freq+(45*1e+6), 75)
sweep_job = execute(sched_list, backend=self._backend, meas_level=1, meas_return='avg',
shots=1024, schedule_los = [{self._drive_chan: freq} for freq in freq_list])
jid = sweep_job.job_id()
if verbose:
print("Executing the Frequency sweep job for 0->1 transition.")
print('Job Id : ', jid)
# job_monitor(sweep_job)
sweep_job = self._backend.retrieve_job(jid)
sweep_result = sweep_job.result()
sweep_values = []
for i in range(len(sweep_result.results)):
# Get the results from the ith experiment
res = sweep_result.get_memory(i)*1e-14
# Get the results for `qubit` from this experiment
sweep_values.append(res[self._qubit])
freq_list_GHz = freq_list/1e+9
if visual:
print("The frequency-signal plot for frequency sweep: ")
plt.scatter(freq_list_GHz, np.real(sweep_values), color='black')
plt.xlim([min(freq_list_GHz), max(freq_list_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
# def find_init_params(freq_list, res_values):
# hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0]
# hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0]
# if hmin_index < hmax_index:
# est_baseline = min(res_values)
# est_slope = (res_values[hmax_index] - res_values[hmin_index])/(freq_list[hmax_index] - freq_list[hmin_index])
# else:
# est_baseline = max(res_values)
# est_slope = (res_values[hmin_index] - res_values[hmax_index])/(freq_list[hmin_index] - freq_list[hmax_index])
# return [est_slope, self._qubit_freq/1e9, 1, est_baseline]
def find_init_params_gauss(freq_list, res_values):
hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0]
hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0]
mean_est = freq_list[hmax_index]
var_est = np.abs(freq_list[hmax_index]-freq_list[hmin_index])/2
scale_est = max(res_values)-min(res_values)
shift_est = min(res_values)
return [mean_est, var_est, scale_est, shift_est]
def gauss(x, mean, var, scale, shift):
return (scale*(1/var*np.sqrt(2*np.pi))*np.exp(-(1/2)*(((x-mean)/var)**2)))+shift
def lorentzian(xval, scale, q_freq, hwhm, shift):
return (scale / np.pi) * (hwhm / ((xval - q_freq)**2 + hwhm**2)) + shift
# do fit in Hz
init_params = find_init_params_gauss(freq_list_GHz, np.real(sweep_values))
# init_params = find_init_params(freq_list_GHz, np.real(sweep_values))
print('ground freq init params : ', init_params)
# Obtain the optimal paramters that fit the result data.
# fit_params, y_fit = self._fit_function(freq_list_GHz,
# np.real(sweep_values),
# lorentzian,
# init_params # init parameters for curve_fit
# )
fit_params, y_fit = self._fit_function(freq_list_GHz,
np.real(sweep_values),
gauss,
init_params # init parameters for curve_fit
)
if visual:
print("The frequency-signal plot for frequency sweep: ")
plt.scatter(freq_list_GHz, np.real(sweep_values), color='black')
plt.plot(freq_list_GHz, y_fit, color='red')
plt.xlim([min(freq_list_GHz), max(freq_list_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
qubit_freq_new, _, _, _ = fit_params
self._qubit_freq_ground = qubit_freq_new*1e9
if verbose:
print(f"The calibrate frequency for the 0->1 transition is {self._qubit_freq_ground}")
return [self._qubit_freq_ground, freq_list_GHz, sweep_values]
def find_pi_amp_ground(self, verbose=False, visual=False):
"""Sets and returns the amplitude of the pi pulse corresponding to 0->1 transition."""
# pylint: disable=too-many-locals
if not self._qubit_freq_ground:
warn("ground_qubit_freq not computed yet and custom qubit freq not provided." +
"Computing ground_qubit_freq now.")
self._qubit_freq_ground = self.find_freq_ground(verbose, visual)
amp_list = np.linspace(0, 1, 75)
rabi_sched_list = [self.create_cal_circuit(amp) for amp in amp_list]
rabi_list_len = len(rabi_sched_list)
rabi_job = execute(rabi_sched_list,backend=self._backend, meas_level=1, meas_return='avg',
shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*len(rabi_sched_list))
jid = rabi_job.job_id()
if verbose:
print("Executing the rabi oscillation job to get Pi pulse for 0->1 transition.")
print('Job Id : ', jid)
# job_monitor(rabi_job)
rabi_job = self._backend.retrieve_job(jid)
rabi_results = rabi_job.result()
scale_factor = 1e-14
rabi_values = []
for i in range(75):
# Get the results for `qubit` from the ith experiment
rabi_values.append(rabi_results.get_memory(i)[self._qubit]*scale_factor)
rabi_values = np.real(self._baseline_remove(rabi_values))
def find_init_params_amp(amp_list, rabi_values):
min_index = np.where(rabi_values==min(rabi_values))[0][0]
max_index = np.where(rabi_values==max(rabi_values))[0][0]
scale_est = (max(rabi_values) - min(rabi_values))/2
shift_est = (max(rabi_values) + min(rabi_values))/2
shift_est = np.mean(rabi_values)
period_est = 0.5
if ((max(rabi_values)-rabi_values[0])/(2*scale_est)) < 0.5:
phi_est = np.pi/2
else:
phi_est = -np.pi/2
return [scale_est, shift_est, period_est, phi_est]
# Obtain the optimal paramters that fit the result data.
init_params = find_init_params_amp(amp_list,rabi_values)
fit_params, y_fit = self._fit_function(amp_list,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B),
init_params)
drive_period = fit_params[2]
self._pi_amp_ground = drive_period/2
if verbose:
print(f"The Pi amplitude of 0->1 transition is {self._pi_amp_ground}.")
if visual:
print("The amplitude-signal plot for rabi oscillation for 0->1 transition.")
plt.figure()
plt.scatter(amp_list, rabi_values, color='black')
plt.plot(amp_list, y_fit, color='red')
plt.axvline(drive_period/2, color='red', linestyle='--')
plt.axvline(drive_period, color='red', linestyle='--')
plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2, 0),
arrowprops=dict(arrowstyle="<->", color='red'))
#plt.annotate("$\pi$", xy=(drive_period/2-0.03, 0.1), color='red')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
return [self._pi_amp_ground, amp_list, rabi_values]
def find_freq_excited(self, verbose=False, visual=False):
"""Sets and returns the frequency corresponding to 1->2 transition."""
# pylint: disable=too-many-locals
if not self._qubit_freq_ground:
raise ValueError("The qubit_freq_ground is not determined. Please determine" +
"qubit_freq_ground first.")
if not self._pi_amp_ground:
raise ValueError("The pi_amp_ground is not determined.\
Please determine pi_amp_ground first.")
base_pulse = pulse_lib.gaussian(duration=self._pulse_duration,
sigma=self._pulse_sigma, amp=0.3)
sched_list = []
# Here we assume that the anharmocity is about 8% for all qubits.
excited_freq_list = self._qubit_freq_ground + self._qubit_anharmonicity + np.linspace(-30*1e+6, 30*1e+6, 75)
for freq in excited_freq_list:
sched_list.append(self.create_cal_circuit_excited(base_pulse, freq))
excited_sweep_job = execute(sched_list, backend=self._backend,
meas_level=1, meas_return='avg', shots=1024,
schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*len(excited_freq_list)
)
jid = excited_sweep_job.job_id()
excited_freq_list_GHz = excited_freq_list/1e+9
if verbose:
print("Executing the Frequency sweep job for 1->2 transition.")
print('Job Id : ', jid)
# job_monitor(excited_sweep_job)
excited_sweep_job = self._backend.retrieve_job(jid)
excited_sweep_data = self.get_job_data(excited_sweep_job, average=True)
if visual:
print("The frequency-signal plot of frequency sweep for 1->2 transition.")
# Note: we are only plotting the real part of the signal
plt.scatter(excited_freq_list_GHz, excited_sweep_data, color='black')
plt.xlim([min(excited_freq_list_GHz), max(excited_freq_list_GHz)])
plt.xlabel("Frequency [GHz]", fontsize=15)
plt.ylabel("Measured Signal [a.u.]", fontsize=15)
plt.title("1->2 Frequency Sweep", fontsize=15)
plt.show()
def find_init_params_gauss(freq_list, res_values):
hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0]
hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0]
mean_est = freq_list[hmax_index]
var_est = np.abs(freq_list[hmax_index]-freq_list[hmin_index])/2
scale_est = max(res_values)-min(res_values)
shift_est = min(res_values)
return [mean_est, var_est, scale_est, shift_est]
def gauss(x, mean, var, scale, shift):
return (scale*(1/var*np.sqrt(2*np.pi))*np.exp(-(1/2)*(((x-mean)/var)**2)))+shift
def lorentzian(xval, scale, q_freq, hwhm, shift):
return (scale / np.pi) * (hwhm / ((xval - q_freq)**2 + hwhm**2)) + shift
# do fit in Hz
# init_params = find_init_params(excited_freq_list_GHz, np.real(excited_sweep_data))
init_params = find_init_params_gauss(excited_freq_list_GHz, np.real(excited_sweep_data))
print("Init params : ", init_params)
excited_sweep_fit_params, excited_sweep_y_fit = self._fit_function(excited_freq_list_GHz,
excited_sweep_data,
gauss,
init_params
)
if visual:
print("The frequency-signal plot of frequency sweep for 1->2 transition.")
# Note: we are only plotting the real part of the signal
plt.scatter(excited_freq_list/1e+9, excited_sweep_data, color='black')
plt.plot(excited_freq_list/1e+9, excited_sweep_y_fit, color='red')
plt.xlim([min(excited_freq_list/1e+9), max(excited_freq_list/1e+9)])
plt.xlabel("Frequency [GHz]", fontsize=15)
plt.ylabel("Measured Signal [a.u.]", fontsize=15)
plt.title("1->2 Frequency Sweep", fontsize=15)
plt.show()
qubit_freq_12, _, _, _ = excited_sweep_fit_params
self._qubit_freq_excited = qubit_freq_12*1e+9
if verbose:
print(f"The calibrated frequency for the 1->2 transition\
is {self._qubit_freq_excited}.")
return [self._qubit_freq_excited, excited_freq_list, excited_sweep_data]
def find_pi_amp_excited(self, verbose=False, visual=False):
"""Sets and returns the amplitude of the pi pulse corresponding to 1->2 transition."""
if not self._qubit_freq_excited:
warn("ground_qubit_freq not computed yet and custom qubit freq not provided." +
"Computing ground_qubit_freq now.")
self._qubit_freq_ground = self.find_freq_excited(verbose, visual)
amp_list = np.linspace(0, 1.0, 75)
rabi_sched_list = []
for amp in amp_list:
base_pulse = pulse_lib.gaussian(duration=self._pulse_duration,
sigma=self._pulse_sigma, amp=amp)
rabi_sched_list.append(self.create_cal_circuit_excited(base_pulse,
self._qubit_freq_excited))
rabi_job = execute(rabi_sched_list, backend=self._backend,
meas_level=1, meas_return='avg', shots=1024,
schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*75
)
jid = rabi_job.job_id()
if verbose:
print("Executing the rabi oscillation job for 1->2 transition.")
print('Job Id : ', jid)
# job_monitor(rabi_job)
rabi_job = self._backend.retrieve_job(jid)
rabi_data = self.get_job_data(rabi_job, average=True)
rabi_data = np.real(self._baseline_remove(rabi_data))
if visual:
print("The amplitude-signal plot of rabi oscillation for 1->2 transition.")
plt.figure()
plt.scatter(amp_list, rabi_data, color='black')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.title('Rabi Experiment (1->2)', fontsize=20)
plt.show()
def find_init_params_amp(amp_list, rabi_values):
min_index = np.where(rabi_values==min(rabi_values))[0][0]
max_index = np.where(rabi_values==max(rabi_values))[0][0]
scale_est = (max(rabi_values) - min(rabi_values))/2
shift_est = (max(rabi_values) + min(rabi_values))/2
shift_est = np.mean(rabi_values)
period_est = 0.5
if ((max(rabi_values)-rabi_values[0])/(2*scale_est)) < 0.5:
phi_est = np.pi/2
else:
phi_est = -np.pi/2
return [scale_est, shift_est, period_est, phi_est]
init_params = find_init_params_amp(amp_list, rabi_data)
print('Init params for 01 amp : ', init_params)
(rabi_fit_params,
rabi_y_fit) = self._fit_function(amp_list,
rabi_data,
lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B),
init_params)
drive_period_excited = rabi_fit_params[2]
pi_amp_excited = (drive_period_excited/2/np.pi) * (np.pi+rabi_fit_params[3])
self._pi_amp_excited = pi_amp_excited
if visual:
print("The amplitude-signal plot of rabi oscillation for 1->2 transition.")
plt.figure()
plt.scatter(amp_list, rabi_data, color='black')
plt.plot(amp_list, rabi_y_fit, color='red')
# account for phi in computing pi amp
plt.axvline(self._pi_amp_excited, color='red', linestyle='--')
plt.axvline(self._pi_amp_excited+drive_period_excited/2, color='red', linestyle='--')
plt.annotate("", xy=(self._pi_amp_excited+drive_period_excited/2, 0),
xytext=(self._pi_amp_excited, 0),
arrowprops=dict(arrowstyle="<->", color='red'))
#plt.annotate("$\\pi$", xy=(self._pi_amp_excited-0.03, 0.1), color='red')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.title('Rabi Experiment (1->2)', fontsize=20)
plt.show()
return [self._pi_amp_excited, amp_list, rabi_data]
def get_pi_pulse_ground(self):
"""Returns a pi pulse of the 0->1 transition."""
pulse = pulse_lib.gaussian(duration=self._pulse_duration,
sigma=self._pulse_sigma, amp=self._pi_amp_ground)
return pulse
def get_pi_pulse_excited(self):
"""Returns a pi pulse of the 1->2 transition."""
pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma,
amp=self._pi_amp_excited)
excited_pulse = self.apply_sideband(pulse, self._qubit_freq_excited)
return excited_pulse
def get_x90_pulse_ground(self):
"""Returns a pi/2 pulse of the 0->1 transition."""
pulse = pulse_lib.gaussian(duration=self._pulse_duration,
sigma=self._pulse_sigma, amp=self._pi_amp_ground/2)
return pulse
def get_x90_pulse_excited(self):
"""Returns a pi/2 pulse of the 1->2 transition."""
pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma,
amp=self._pi_amp_excited/2)
excited_pulse = self.apply_sideband(pulse, self._qubit_freq_excited)
return excited_pulse
def get_zero_sched(self):
"""Returns a schedule that performs only a measurement."""
zero_sched = Schedule()
zero_sched += self._measure
return zero_sched
def get_one_sched(self):
"""Returns a schedule that creates a |1> state from |0> by applying
a pi pulse of 0->1 transition and performs a measurement."""
one_sched = Schedule()
one_sched += Play(self.get_pi_pulse_ground(), self._drive_chan)
one_sched += self._measure << one_sched.duration
return one_sched
def get_two_sched(self):
"""Returns a schedule that creates a |2> state from |0> by applying
a pi pulse of 0->1 transition followed by applying a pi pulse
of 1->2 transition and performs a measurement."""
two_sched = Schedule()
two_sched += Play(self.get_pi_pulse_ground(), self._drive_chan)
two_sched += Play(self.get_pi_pulse_excited(), self._drive_chan)
two_sched += self._measure << two_sched.duration
return two_sched
@staticmethod
def _create_iq_plot(zero_data, one_data, two_data):
"""Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given
as arguments."""
# zero data plotted in blue
plt.scatter(np.real(zero_data), np.imag(zero_data),
s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$')
# one data plotted in red
plt.scatter(np.real(one_data), np.imag(one_data),
s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$')
# two data plotted in green
plt.scatter(np.real(two_data), np.imag(two_data),
s=5, cmap='viridis', c='green', alpha=0.5, label=r'$|2\rangle$')
x_min = np.min(np.append(np.real(zero_data), np.append(np.real(one_data),
np.real(two_data))))-5
x_max = np.max(np.append(np.real(zero_data), np.append(np.real(one_data),
np.real(two_data))))+5
y_min = np.min(np.append(np.imag(zero_data), np.append(np.imag(one_data),
np.imag(two_data))))-5
y_max = np.max(np.append(np.imag(zero_data), np.append(np.imag(one_data),
np.imag(two_data))))+5
# Plot a large dot for the average result of the 0, 1 and 2 states.
mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts
mean_one = np.mean(one_data)
mean_two = np.mean(two_data)
plt.scatter(np.real(mean_zero), np.imag(mean_zero),
s=200, cmap='viridis', c='black', alpha=1.0)
plt.scatter(np.real(mean_one), np.imag(mean_one),
s=200, cmap='viridis', c='black', alpha=1.0)
plt.scatter(np.real(mean_two), np.imag(mean_two),
s=200, cmap='viridis', c='black', alpha=1.0)
# plt.xlim(x_min, x_max)
# plt.ylim(y_min, y_max)
plt.legend()
plt.ylabel('I [a.u.]', fontsize=15)
plt.xlabel('Q [a.u.]', fontsize=15)
plt.title("0-1-2 discrimination", fontsize=15)
return x_min, x_max, y_min, y_max
@staticmethod
def reshape_complex_vec(vec):
"""Take in complex vector vec and return 2d array w/ real, imag entries.
This is needed for the learning.
Args:
vec (list): complex vector of data
Returns:
list: vector w/ entries given by (real(vec], imag(vec))
"""
length = len(vec)
vec_reshaped = np.zeros((length, 2))
for i, item in enumerate(vec):
vec_reshaped[i] = [np.real(item), np.imag(item)]
return vec_reshaped
def find_three_level_discriminator(self, verbose=False, visual=False):
"""Returns a discriminator for discriminating 0-1-2 states."""
# pylint: disable=too-many-locals
zero_sched = self.get_zero_sched()
one_sched = self.get_one_sched()
two_sched = self.get_two_sched()
iq_job = execute([zero_sched, one_sched, two_sched], backend=self._backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*3
)
jid = iq_job.job_id()
if verbose:
print('Job Id : ', jid)
# job_monitor(iq_job)
iq_job = self._backend.retrieve_job(jid)
iq_data = self.get_job_data(iq_job, average=False)
zero_data = iq_data[0]
one_data = iq_data[1]
two_data = iq_data[2]
if visual:
print("The discriminator plot for 0-1-2 discrimination.")
x_min, x_max, y_min, y_max = self._create_iq_plot(zero_data, one_data, two_data)
# Create IQ vector (split real, imag parts)
zero_data_reshaped = self.reshape_complex_vec(zero_data)
one_data_reshaped = self.reshape_complex_vec(one_data)
two_data_reshaped = self.reshape_complex_vec(two_data)
iq_data = np.concatenate((zero_data_reshaped, one_data_reshaped, two_data_reshaped))
# construct vector w/ 0's, 1's and 2's (for testing)
state_012 = np.zeros(1024) # shots gives number of experiments
state_012 = np.concatenate((state_012, np.ones(1024)))
state_012 = np.concatenate((state_012, 2*np.ones(1024)))
# Shuffle and split data into training and test sets
iq_012_train, iq_012_test, state_012_train, state_012_test = train_test_split(iq_data,
state_012,
test_size=0.5)
classifier_lda_012 = LinearDiscriminantAnalysis()
classifier_lda_012.fit(iq_012_train, state_012_train)
score_012 = classifier_lda_012.score(iq_012_test, state_012_test)
if verbose:
print('The accuracy score of the discriminator is: ', score_012)
self._state_discriminator_012 = classifier_lda_012
if visual:
self._separatrix_plot(classifier_lda_012, x_min, x_max, y_min, y_max, 1024)
return self._state_discriminator_012
@staticmethod
def _separatrix_plot(lda, x_min, x_max, y_min, y_max, shots):
"""Returns a sepratrix plot for the classifier."""
# pylint: disable=too-many-arguments
num_x, num_y = shots, shots
xvals, vals = np.meshgrid(np.linspace(x_min, x_max, num_x),
np.linspace(y_min, y_max, num_y))
predict_prob = lda.predict_proba(np.c_[xvals.ravel(), vals.ravel()])
predict_prob = predict_prob[:, 1].reshape(xvals.shape)
plt.contour(xvals, vals, predict_prob, [0.5], linewidths=2., colors='black')
def get_qubit_freq_ground(self):
"""Returns the set 0->1 transition frequency."""
return self._qubit_freq_ground
def get_qubit_freq_excited(self):
"""Returns the set 1->2 transition frequency."""
return self._qubit_freq_excited
def get_pi_amp_ground(self):
"""Returns the set 0->1 transition pi pulse amplitude."""
return self._pi_amp_ground
def get_pi_amp_excited(self):
"""Returns the set 1->2 transition pi pulse amplitude."""
return self._pi_amp_excited
def get_three_level_discriminator(self):
"""Returns the set 0-1-2 state discriminator."""
return self._state_discriminator_012
def calibrate_all(self, verbose=False, visual=False):
"""Calibrates and sets both the ground and excited transition frequencies and
corresponding pi pulse amplitudes. Also constructs a 0-1-2 state discriminator."""
ground_freq = self.find_freq_ground(verbose, visual)
ground_amp = self.find_pi_amp_ground(verbose, visual)
excited_freq = self.find_freq_excited(verbose, visual)
excited_amp = self.find_pi_amp_excited(verbose, visual)
state_discriminator = self.find_three_level_discriminator(verbose, visual)
return ground_freq, ground_amp, excited_freq, excited_amp, state_discriminator
anharmon = backend.properties().qubit_property(qubit)['anharmonicity'][0]
qu_freq = backend.properties().qubit_property(qubit)['frequency'][0]
print(qu_freq)
print(anharmon)
print(qu_freq+anharmon)
# backend = provider.get_backend('ibmq_casablanca')
# backend = provider.get_backend('ibmq_jakarta')
backend = provider.get_backend('ibmq_rome')
qubit = 0
cal_object = PulseCalibration(backend, qubit)
visual = True
verbose = True
ground_freq_list = cal_object.find_freq_ground(verbose, visual)
[ground_freq, freq_list, sweep_vals] = ground_freq_list
print(ground_freq)
ground_amp_list = cal_object.find_pi_amp_ground(verbose, visual)
pi_amp_ground = ground_amp_list[0]
amp_list = ground_amp_list[1]
rabi_values = ground_amp_list[2]
print(ground_freq)
print(pi_amp_ground)
excited_list = cal_object.find_freq_excited(verbose, visual)
excited_freq = excited_list[0]
excited_freq_list = excited_list[1]
excited_sweep_data = excited_list[2]
excited_freq_list_GHz = excited_freq_list/1e+9
excited_freq
pi_amp_excited_list = cal_object.find_pi_amp_excited(verbose, visual)
[excited_amp, amp_list, rabi_data] = pi_amp_excited_list
pi_amp_excited = excited_amp
pi_amp_excited
print(ground_freq)
print(pi_amp_ground)
print(excited_freq)
print(pi_amp_excited)
discrim = cal_object.find_three_level_discriminator(verbose, visual)
def create_iq_plot(zero_data, one_data, two_data):
"""Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given
as arguments."""
# zero data plotted in blue
plt.scatter(np.real(zero_data), np.imag(zero_data),
s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$')
# one data plotted in red
plt.scatter(np.real(one_data), np.imag(one_data),
s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$')
# two data plotted in green
plt.scatter(np.real(two_data), np.imag(two_data),
s=5, cmap='viridis', c='green', alpha=0.5, label=r'$|2\rangle$')
x_min = np.min(np.append(np.real(zero_data), np.append(np.real(one_data),
np.real(two_data))))-5
x_max = np.max(np.append(np.real(zero_data), np.append(np.real(one_data),
np.real(two_data))))+5
y_min = np.min(np.append(np.imag(zero_data), np.append(np.imag(one_data),
np.imag(two_data))))-5
y_max = np.max(np.append(np.imag(zero_data), np.append(np.imag(one_data),
np.imag(two_data))))+5
# Plot a large dot for the average result of the 0, 1 and 2 states.
mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts
mean_one = np.mean(one_data)
mean_two = np.mean(two_data)
plt.scatter(np.real(mean_zero), np.imag(mean_zero),
s=200, cmap='viridis', c='black', alpha=1.0)
plt.scatter(np.real(mean_one), np.imag(mean_one),
s=200, cmap='viridis', c='black', alpha=1.0)
plt.scatter(np.real(mean_two), np.imag(mean_two),
s=200, cmap='viridis', c='black', alpha=1.0)
# plt.xlim(x_min, x_max)
# plt.ylim(y_min, y_max)
plt.legend()
plt.ylabel('I [a.u.]', fontsize=15)
plt.xlabel('Q [a.u.]', fontsize=15)
plt.title("0-1-2 discrimination", fontsize=15)
return x_min, x_max, y_min, y_max
def reshape_complex_vec(vec):
"""Take in complex vector vec and return 2d array w/ real, imag entries.
This is needed for the learning.
Args:
vec (list): complex vector of data
Returns:
list: vector w/ entries given by (real(vec], imag(vec))
"""
length = len(vec)
vec_reshaped = np.zeros((length, 2))
for i, item in enumerate(vec):
vec_reshaped[i] = [np.real(item), np.imag(item)]
return vec_reshaped
def separatrix_plot(lda, x_min, x_max, y_min, y_max, shots):
"""Returns a sepratrix plot for the classifier."""
# pylint: disable=too-many-arguments
num_x, num_y = shots, shots
xvals, vals = np.meshgrid(np.linspace(x_min-4, x_max+4, num_x),
np.linspace(y_min-4, y_max+4, num_y))
predict_prob = lda.predict_proba(np.c_[xvals.ravel(), vals.ravel()])
predict_prob = predict_prob[:, 1].reshape(xvals.shape)
plt.contour(xvals, vals, predict_prob, [0.5], linewidths=2., colors='black')
def get_job_data(job, average):
"""Retrieve data from a job that has already run.
Args:
job (Job): The job whose data you want.
average (bool): If True, gets the data assuming data is an average.
If False, gets the data assuming it is for single shots.
Return:
list: List containing job result data.
"""
scale_factor = 1e-14
job_results = job.result(timeout=120) # timeout parameter set to 120 s
result_data = []
for i in range(len(job_results.results)):
if average: # get avg data
result_data.append(job_results.get_memory(i)[qubit]*scale_factor)
else: # get single data
result_data.append(job_results.get_memory(i)[:, qubit]*scale_factor)
return result_data
iq_job = backend.retrieve_job('60b501ab4a088c8310c55ebd')
iq_data = get_job_data(iq_job, average=False)
zero_data = iq_data[0]
one_data = iq_data[1]
two_data = iq_data[2]
if visual:
print("The discriminator plot for 0-1-2 discrimination.")
x_min, x_max, y_min, y_max = create_iq_plot(zero_data, one_data, two_data)
newcalobject = PulseCalibration(backend, qubit)
output_list = newcalobject.calibrate_all(verbose, visual)
[new_ground_freq, new_pi_amp_ground, new_excited_freq, new_pi_amp_excited, new_discrim] = output_list
print(new_ground_freq[0])
print(new_pi_amp_ground[0])
print(new_excited_freq[0])
print(new_pi_amp_excited[0])
back_config = backend.configuration()
back_defaults = backend.defaults()
inst_sched_map = back_defaults.instruction_schedule_map
meas_map_idx = None
for i, measure_group in enumerate(back_config.meas_map):
if qubit in measure_group:
meas_map_idx = i
break
assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!"
# The measurement pulse for measuring the qubit of interest.
measure = inst_sched_map.get('measure', qubits=back_config.meas_map[meas_map_idx])
# Should be getting |2> ideally.
sigma = 40
duration = 4*40
chan = DriveChannel(0)
with pulse.build(backend) as test_0:
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground), chan)
pulse.set_frequency(excited_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited), chan)
test_0 += measure << test_0.duration
test_0.draw()
test0_job = execute(test_0, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test0 = test0_job.job_id()
print(jid_test0)
test0_job = backend.retrieve_job(jid_test0)
res = get_job_data(test0_job, average=False)
res[0]
reshaped_res = reshape_complex_vec(res[0])
plt.scatter(np.real(res[0]), np.imag(res[0]))
plt.show()
output = discrim.predict(reshaped_res)
arr = [0,0,0]
for i in output:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a 0-1 pi pulse.
# Should be ideally getting |1>
with pulse.build(backend) as test_00:
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground), chan)
test_00 += measure << test_00.duration
test_00.draw()
test00_job = execute(test_00, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test00 = test00_job.job_id()
print(jid_test00)
test00_job = backend.retrieve_job(jid_test00)
res00 = get_job_data(test00_job, average=False)
res00[0]
reshaped_res00 = reshape_complex_vec(res00[0])
plt.scatter(np.real(res00[0]), np.imag(res00[0]))
plt.show()
output00 = discrim.predict(reshaped_res00)
arr = [0,0,0]
for i in output00:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H then Z then H gate on 0-1
# Should get |1> ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_1:
# Setting 0-1 frequency for channel and applying H gate
pulse.set_frequency(ground_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
# Applying a Z pulse
pulse.shift_phase(np.pi, chan)
# Applying H gate on 0-1
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_1 += measure << test_pulse_1.duration
test_pulse_1.draw()
test1_job = execute(test_pulse_1, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test1 = test1_job.job_id()
print(jid_test1)
test1_job = backend.retrieve_job(jid_test1)
res1 = get_job_data(test1_job, average=False)
reshaped_res1 = reshape_complex_vec(res1[0])
plt.scatter(np.real(res1[0]), np.imag(res1[0]))
plt.show()
output1 = discrim.predict(reshaped_res1)
arr = [0,0,0]
for i in output1:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H then Z then H gate on 1-2
# Should get |2> ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_2:
# Exciting the qubit to |1> state
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan)
# Setting 1-2 frequency for channel and applying H gate
pulse.set_frequency(excited_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
# Applying a Z pulse
pulse.shift_phase(np.pi, chan)
# Applying H gate on 1-2
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_2 += measure << test_pulse_2.duration
test_pulse_2.draw()
test2_job = execute(test_pulse_2, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test2 = test2_job.job_id()
print(jid_test2)
test2_job = backend.retrieve_job(jid_test2)
res2 = get_job_data(test2_job, average=False)
reshaped_res2 = reshape_complex_vec(res2[0])
plt.scatter(np.real(res2[0]), np.imag(res2[0]))
plt.show()
output2 = discrim.predict(reshaped_res2)
arr = [0,0,0]
for i in output2:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H on 0-1, then H on 1-2
# then Z on 1-2 followed by H on 1-2
# Should get |0>/sqrt(2) + |2>/sqrt(2)
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_3:
# Setting 0-1 frequency for channel and applying H gate
pulse.set_frequency(ground_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
# Undoing phase appied during 0-1 transitions
pulse.shift_phase(np.pi, chan)
# Setting 1-2 frequency for channel and applying H gate
pulse.set_frequency(excited_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
# Applying a Z pulse
pulse.shift_phase(np.pi, chan)
# Applying H gate on 1-2
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_3 += measure << test_pulse_3.duration
test_pulse_3.draw()
test3_job = execute(test_pulse_3, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test3 = test3_job.job_id()
print(jid_test3)
test3_job = backend.retrieve_job(jid_test3)
res3 = get_job_data(test3_job, average=False)
reshaped_res3 = reshape_complex_vec(res3[0])
plt.scatter(np.real(res3[0]), np.imag(res3[0]))
plt.show()
output3 = discrim.predict(reshaped_res3)
arr = [0,0,0]
for i in output3:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H on 1-2
# Should get |1>/sqrt(2) + |2>/sqrt(2) ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_4:
# Exciting the qubit to |1> state
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan)
# Setting 1-2 frequency for channel and applying H gate
pulse.set_frequency(excited_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_4 += measure << test_pulse_4.duration
test_pulse_4.draw()
test4_job = execute(test_pulse_4, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test4 = test4_job.job_id()
print(jid_test4)
test4_job = backend.retrieve_job(jid_test4)
res4 = get_job_data(test4_job, average=False)
reshaped_res4 = reshape_complex_vec(res4[0])
plt.scatter(np.real(res4[0]), np.imag(res4[0]))
plt.show()
output4 = discrim.predict(reshaped_res4)
arr = [0,0,0]
for i in output4:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H on 0-1
# Should get |0>/sqrt(2) + |1>/sqrt(2) ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_5:
# Setting 0-1 frequency for channel and applying H gate
pulse.set_frequency(ground_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_5 += measure << test_pulse_5.duration
test_pulse_5.draw()
test5_job = execute(test_pulse_5, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test5 = test5_job.job_id()
print(jid_test5)
test5_job = backend.retrieve_job(jid_test5)
res5 = get_job_data(test5_job, average=False)
reshaped_res5 = reshape_complex_vec(res5[0])
plt.scatter(np.real(res5[0]), np.imag(res5[0]))
plt.show()
output5 = discrim.predict(reshaped_res5)
arr = [0,0,0]
for i in output5:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a X on 0-1
# Should get |1> ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_6:
# Setting 0-1 frequency for channel and applying X gate
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan)
test_pulse_6 += measure << test_pulse_6.duration
test_pulse_6.draw()
test6_job = execute(test_pulse_6, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test6 = test6_job.job_id()
print(jid_test6)
test6_job = backend.retrieve_job(jid_test6)
res6 = get_job_data(test6_job, average=False)
reshaped_res6 = reshape_complex_vec(res6[0])
plt.scatter(np.real(res6[0]), np.imag(res6[0]))
plt.show()
output6 = discrim.predict(reshaped_res6)
arr = [0,0,0]
for i in output6:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a X on 1-2
# Should get |2> ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_7:
# Setting 0-1 frequency for channel and applying 0-1 pi pulse
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan)
# Setting 1-2 frequency for channel and applying 1-2 pi pulse
pulse.set_frequency(excited_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited, name='X(pi)'), chan)
test_pulse_7 += measure << test_pulse_7.duration
test_pulse_7.draw()
test7_job = execute(test_pulse_7, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test7 = test7_job.job_id()
print(jid_test7)
test7_job = backend.retrieve_job(jid_test7)
res7 = get_job_data(test7_job, average=False)
reshaped_res7 = reshape_complex_vec(res7[0])
plt.scatter(np.real(res7[0]), np.imag(res7[0]))
plt.show()
output7 = discrim.predict(reshaped_res7)
arr = [0,0,0]
for i in output7:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
back_config = backend.configuration()
print("Supported kernels: ", back_config.meas_kernels)
print("Supported discriminators: ", back_config.discriminators)
qc = QuantumCircuit(2)
qc.cx(0,1)
with pulse.build(backend) as cnot_pulse:
pulse.call(qc)
cnot_pulse += measure << cnot_pulse.duration
cnot_pulse.draw()
cnot_job = execute(cnot_pulse, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_cnot = cnot_job.job_id()
print(jid_cnot)
cnot_job = backend.retrieve_job(jid_cnot)
cnot_job.result().to_dict()
cnot_res = get_job_data(cnot_job, average=False)
reshaped_cnot_res = reshape_complex_vec(cnot_res[0])
plt.scatter(np.real(cnot_res[0]), np.imag(cnot_res[0]))
plt.show()
cnot_output = discrim.predict(reshaped_cnot_res)
arr = [0,0,0]
for i in cnot_output:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
qc = QuantumCircuit(1)
qc.y(0)
with pulse.build(backend) as ypulse:
pulse.call(qc)
ypulse += measure << ypulse.duration
ypulse.draw()
|
https://github.com/ShabaniLab/q-camp
|
ShabaniLab
|
import numpy as np
n = 4
dimension = 2**n
v = np.zeros(dimension, dtype=np.complex128)
print(np.shape(v))
real = np.random.rand(dimension)
imag = np.random.rand(dimension)
v = real + 1j*imag
# calculate norm of v
def norm(v):
norm = np.sqrt(np.dot(np.conjugate(v), v))
return norm
print(norm(v))
v_normalized = v/norm(v)
print(v)
print(v_normalized)
print(norm(v))
print(norm(v_normalized))
def print_probabilities(v):
sum = 0
for i in range(len(v)):
p = abs(np.conjugate(v[i])*v[i])
sum = sum + p
print("state: {0:04b}".format(i) + ", p = {0:.4f}".format(p))
print("total probability = {0:.4f}".format(sum))
print_probabilities(v_normalized)
import matplotlib.pyplot as plt
states = []
for i in range(len(v)):
s = "{0:04b}".format(i)
states.append(s)
prob = list(np.real(np.conjugate(v_normalized)*v_normalized))
plt.bar(states, v)
plt.xticks(rotation=45)
v = np.zeros(dimension, dtype=np.complex128)
v[0] = 1/np.sqrt(2)
v[-1] = 1/np.sqrt(2)
import matplotlib.pyplot as plt
v_normalized = v
states = []
for i in range(len(v)):
s = "{0:04b}".format(i)
states.append(s)
prob = list(np.real(np.conjugate(v_normalized)*v_normalized))
plt.bar(states, prob)
plt.xticks(rotation=45)
def tensor_product(u, v):
prod = np.zeros(len(u)*len(v))
for i in range(len(u)):
prod[i*len(v):(i+1)*len(v)] = u[i]*v
return prod
u = np.array([1, -1, 2])
v = np.array([0.6, 0.7, 0.8])
print(tensor_product(u, v))
def tensor_product(A, B):
m = np.shape(A)[0]
n = np.shape(A)[1]
r = np.shape(B)[0]
p = np.shape(B)[1]
prod = np.zeros((m*r, n*p))
for i in range(m):
for j in range(n):
prod[i*r:(i+1)*r, j*p:(j+1)*p] = A[i, j]*B
return prod
X = np.array([[0, 1], [1, 0]])
Z = np.array([[1, 0], [0, -1]])
print(tensor_product(X, Z))
import numpy as np
def print_pauli(A):
c1 = (A[0, 1] + A[1, 0])/2
c2 = (A[0, 1] - A[1, 0])/(2j)
c3 = (A[0, 0] + A[1, 1])/2
c4 = (A[0, 0] - A[1, 1])/2
print(f"{c1}X + {c2}Y + {c3}Z + {c4}I")
M = np.array([[1, 1], [-1, 3]])
print_pauli(M)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.algorithms import AmplificationProblem
# the state we desire to find is '11'
good_state = ['11']
# specify the oracle that marks the state '11' as a good solution
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
# define Grover's algorithm
problem = AmplificationProblem(oracle, is_good_state=good_state)
# now we can have a look at the Grover operator that is used in running the algorithm
# (Algorithm circuits are wrapped in a gate to appear in composition as a block
# so we have to decompose() the op to see it expanded into its component gates.)
problem.grover_operator.decompose().draw(output='mpl')
from qiskit.algorithms import Grover
from qiskit.primitives import Sampler
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Result type:', type(result))
print()
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
from qiskit.quantum_info import Statevector
oracle = Statevector.from_label('11')
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Result type:', type(result))
print()
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
problem.grover_operator.oracle.decompose().draw(output='mpl')
from qiskit.circuit.library.phase_oracle import PhaseOracle
from qiskit.exceptions import MissingOptionalLibraryError
# `Oracle` (`PhaseOracle`) as the `oracle` argument
expression = '(a & b)'
try:
oracle = PhaseOracle(expression)
problem = AmplificationProblem(oracle)
display(problem.grover_operator.oracle.decompose().draw(output='mpl'))
except MissingOptionalLibraryError as ex:
print(ex)
import numpy as np
# Specifying `state_preparation`
# to prepare a superposition of |01>, |10>, and |11>
oracle = QuantumCircuit(3)
oracle.ccz(0, 1, 2)
theta = 2 * np.arccos(1 / np.sqrt(3))
state_preparation = QuantumCircuit(3)
state_preparation.ry(theta, 0)
state_preparation.ch(0,1)
state_preparation.x(1)
state_preparation.h(2)
# we only care about the first two bits being in state 1, thus add both possibilities for the last qubit
problem = AmplificationProblem(oracle, state_preparation=state_preparation, is_good_state=['110', '111'])
# state_preparation
print('state preparation circuit:')
problem.grover_operator.state_preparation.draw(output='mpl')
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
oracle = QuantumCircuit(5)
oracle.ccz(0, 1, 2)
oracle.draw(output='mpl')
from qiskit.circuit.library import GroverOperator
grover_op = GroverOperator(oracle, insert_barriers=True)
grover_op.decompose().draw(output='mpl')
grover_op = GroverOperator(oracle, reflection_qubits=[0, 1, 2], insert_barriers=True)
grover_op.decompose().draw(output='mpl')
# a list of binary strings good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = ['11', '00']
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# a list of integer good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = [0, 1]
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
from qiskit.quantum_info import Statevector
# `Statevector` good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = Statevector.from_label('11')
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# Callable good state
def callable_good_state(bitstr):
if bitstr == "11":
return True
return False
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# integer iteration
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=1)
# list iteration
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=[1, 2, 3])
# using sample_from_iterations
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=[1, 2, 3], sample_from_iterations=True)
iterations = Grover.optimal_num_iterations(num_solutions=1, num_qubits=8)
iterations
def to_DIAMACS_CNF_format(bit_rep):
return [index+1 if val==1 else -1 * (index + 1) for index, val in enumerate(bit_rep)]
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'], post_processing=to_DIAMACS_CNF_format)
problem.post_processing([1, 0, 1])
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
|
Sanjay-995
|
from qiskit import IBMQ, QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
import numpy as np
from numpy import pi
import math
from math import sqrt
import matplotlib as mpl
%matplotlib inline
qc = QuantumCircuit(1)
qc.draw(output="mpl")
# Bloch Sphere
simulator_statevector = Aer.get_backend('statevector_simulator')
job_statevector = execute(qc, simulator_statevector)
result_statevector = job_statevector.result()
outputstate = result_statevector.get_statevector(qc)
plot_bloch_multivector(outputstate)
qc.ry(3 * math.pi/4, 0)
qc.draw(output="mpl")
qc = QuantumCircuit(2)
qc.ry(3 * math.pi/4, 1)
qc.draw(output="mpl")
# Bloch Sphere
simulator_statevector = Aer.get_backend('statevector_simulator')
job_statevector = execute(qc, simulator_statevector)
result_statevector = job_statevector.result()
outputstate = result_statevector.get_statevector(qc)
plot_bloch_multivector(outputstate)
qc_rotate = QuantumCircuit(1, 1)
qc_rotate.ry(3 * math.pi/4, 0)
qc_rotate.measure([0], [0])
qc_rotate.draw(output="mpl")
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(qc_rotate, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(qc_rotate)
print("\nTotal count for 0 and 1 are:",counts)
# Plot a histogram
plot_histogram(counts)
qc_rotate = QuantumCircuit(1, 1)
qc_rotate.ry(math.pi/4, 0)
qc_rotate.measure([0], [0])
qc_rotate.draw(output="mpl")
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(qc_rotate, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(qc_rotate)
print("\nTotal count for 0 and 1 are:",counts)
# Plot a histogram
plot_histogram(counts)
qc_rotate = QuantumCircuit(1, 1)
qc_rotate.ry(math.pi/2, 0)
qc_rotate.measure([0], [0])
qc_rotate.draw(output="mpl")
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(qc_rotate, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(qc_rotate)
print("\nTotal count for 0 and 1 are:",counts)
# Plot a histogram
plot_histogram(counts)
qc_rotate = QuantumCircuit(1, 1)
qc_rotate.ry(3 * math.pi/4, 0)
qc_rotate.measure([0], [0])
qc_rotate.draw(output="mpl")
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(qc_rotate, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(qc_rotate)
print("\nTotal count for 0 and 1 are:",counts)
# Plot a histogram
plot_histogram(counts)
qc_rotate = QuantumCircuit(1, 1)
qc_rotate.ry(math.pi, 0)
qc_rotate.measure([0], [0])
qc_rotate.draw(output="mpl")
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(qc_rotate, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(qc_rotate)
print("\nTotal count for 0 and 1 are:",counts)
# Plot a histogram
plot_histogram(counts)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
"""Quantum Operation Mixin."""
from abc import ABC, abstractmethod
class Operation(ABC):
"""Quantum Operation Interface Class.
For objects that can be added to a :class:`~qiskit.circuit.QuantumCircuit`.
These objects include :class:`~qiskit.circuit.Gate`, :class:`~qiskit.circuit.Reset`,
:class:`~qiskit.circuit.Barrier`, :class:`~qiskit.circuit.Measure`,
and operators such as :class:`~qiskit.quantum_info.Clifford`.
The main purpose is to add an :class:`~qiskit.circuit.Operation` to a
:class:`~qiskit.circuit.QuantumCircuit` without synthesizing it before the transpilation.
Example:
Add a Clifford and a Toffoli gate to a QuantumCircuit.
.. plot::
:include-source:
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford, random_clifford
qc = QuantumCircuit(3)
cliff = random_clifford(2)
qc.append(cliff, [0, 1])
qc.ccx(0, 1, 2)
qc.draw('mpl')
"""
__slots__ = ()
@property
@abstractmethod
def name(self):
"""Unique string identifier for operation type."""
raise NotImplementedError
@property
@abstractmethod
def num_qubits(self):
"""Number of qubits."""
raise NotImplementedError
@property
@abstractmethod
def num_clbits(self):
"""Number of classical bits."""
raise NotImplementedError
|
https://github.com/MAI-cyber/QIT
|
MAI-cyber
|
from qiskit import QuantumCircuit
from qiskit.circuit.library import QFT
from qiskit import Aer, execute
from qiskit.visualization import plot_histogram
import numpy as np
import math
# For factorizign the number, N= 15
N = 15
n = 4
m = 4
#Using, period root
a = 7
# Making the unitary U = 7^(1) mod 15
U= QuantumCircuit(m)
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
U.barrier()
for q in range(4):
U.x(q)
U.draw('mpl')
# Making the controlled gate con_U = 7^(1) mod 15 ... or 8^(1) mod 15
def con_amodN(m):
U = QuantumCircuit(m)
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
for q in range(m):
U.x(q) # Comment out for a = 8
U = U.to_gate()
U.name = "U"
con_U = U.control()
return con_U
# Shors algorithm
qc = QuantumCircuit(n+m, n)
#Initialiaing the proper states
qc.h(range(n))
#qc.x(range(n, n+m))
qc.x(n+m-1)
qc.barrier()
# Applyign the Unitary U for a = 7
for i in range(n):
for j in range(2**i):
qc.append(con_amodN(m), [i] + [*range(n, n+m)]) # [i] is the contol qubit and [4,5,6.. n+m] are the target qubits
# Applying inverse of Fourier
qc.append(QFT(n, do_swaps= False).inverse(), range(n))
#Measurining the controll qubits
for i in range(n):
qc.measure(i,i)
qc.draw('mpl')
# Simulating the circuit
simulator = Aer.get_backend('qasm_simulator')
counts = execute(qc, backend=simulator, shots=10000).result().get_counts()
plot_histogram(counts)
# USing the ststaes measured, finding the periodic roots (r)
for i in counts:
measured_value = int(i[::-1], 2)
if measured_value % 2 != 0:
#print("Measured value not even")
continue #measured value should be even as we are doing a^(r/2) mod N and r/2 should be int
x = int((a ** (measured_value/2)) % N)
if (x + 1) % N == 0:
continue
# FInding the factors using gcd arguments
factor_one = math.gcd(x + 1, N)
factor_two = math.gcd(x - 1, N)
# removing trivial factors
if factor_one == N:
continue
if factor_two == N:
continue
if factor_one == 1 and factor_two == 1:
continue
if factor_one != 1:
factor_two = N//factor_one
if factor_two != 1:
factor_one = N//factor_two
print("Measured value = ", measured_value, " leads to the factors =", factor_one, factor_two)
# Refer to QCI pg 235
|
https://github.com/daimurat/qiskit-implementation
|
daimurat
|
from qiskit import Aer
from qiskit.circuit.library import TwoLocal
from qiskit.aqua import QuantumInstance
from qiskit.finance import QiskitFinanceError
from qiskit.finance.applications.ising import portfolio
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.finance.data_providers import *
from qiskit.aqua.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import COBYLA
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import datetime
import pandas as pd
import pandas_datareader.data as web
from pandas.plotting import register_matplotlib_converters
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
register_matplotlib_converters()
# set number of assets (= number of qubits)
num_assets = 4
# # Generate expected return and covariance matrix from (random) time-series
# stocks = [("TICKER%s" % i) for i in range(num_assets)]
# data = RandomDataProvider(tickers=stocks,
# start=datetime.datetime(2016,1,1),
# end=datetime.datetime(2016,1,30))
# data.run()
# mu = data.get_period_return_mean_vector() # 平均期待リターン
# sigma = data.get_period_return_covariance_matrix() # 共分散行列
# print(mu)
# print(sigma)
# print("The underlying evolution of stock prices:")
# for (cnt, s) in enumerate(data._tickers):
# plt.plot(data._data[cnt], label=s)
# plt.legend()
# plt.xticks(rotation=90)
# plt.show()
# for (cnt, s) in enumerate(data._tickers):
# time_data = [(data._data[cnt][i] - data._data[cnt][i-1])/data._data[cnt][i-1] for i in range(1, len(data._data[cnt]))]
# print(sum(time_data)/len(data._data[cnt]))
stocks = ["GOOG", "AAPL", "FB", "AMZN"]
token = "" # API KEYを入れる
try:
wiki = WikipediaDataProvider(
token = token,
tickers = stocks,
start = datetime.datetime(2016,1,1),
end = datetime.datetime(2016,1,30))
wiki.run()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
if wiki._data:
if wiki._n <= 1:
print("Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers.")
else:
mu = wiki.get_period_return_mean_vector()
print("A return mean vector:")
print(mu)
sigma = wiki.get_covariance_matrix()
print("A covariance matrix:")
print(sigma)
plt.imshow(sigma)
plt.show()
else:
print('No wiki data loaded.')
if wiki._data:
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6))
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(stocks):
axis = 0 if s in ("GOOG","AMZN") else 1
wiki._data[cnt].plot(ax=axes[axis], label=s, legend=True)
else:
print('No wiki data loaded.')
q = 0.5 # set risk factor
budget = num_assets // 2 # set budget (the number of assets to be selected out of n)
penalty = num_assets # set parameter to scale the budget penalty term
qubitOp, offset = portfolio.get_operator(mu, sigma, q, budget, penalty)
def index_to_selection(i, num_assets):
s = "{0:b}".format(i).rjust(num_assets)
x = np.array([1 if s[i]=='1' else 0 for i in reversed(range(num_assets))])
return x
def print_result(result):
selection = sample_most_likely(result.eigenstate)
value = portfolio.portfolio_value(selection, mu, sigma, q, budget, penalty)
np.set_printoptions(formatter={'float': '{:.4f}'.format})
print('Optimal: selection {}, value {}'.format(selection, value))
eigenvector = result.eigenstate if isinstance(result.eigenstate, np.ndarray) else result.eigenstate.to_matrix()
probabilities = np.abs(eigenvector)**2
i_sorted = reversed(np.argsort(probabilities))
print('\n----------------- Full result ---------------------')
print('selection\tvalue\t\tprobability')
print('---------------------------------------------------')
for i in i_sorted:
x = index_to_selection(i, num_assets)
value = portfolio.portfolio_value(x, mu, sigma, q, budget, penalty)
probability = probabilities[i]
print('%10s\t%.4f\t\t%.4f' %(x, value, probability))
exact_eigensolver = NumPyMinimumEigensolver(qubitOp)
result_classical = exact_eigensolver.run()
print_result(result_classical)
backend = Aer.get_backend('statevector_simulator')
seed = 50
cobyla = COBYLA()
cobyla.set_options(maxiter=500)
ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=3, entanglement='full')
vqe = VQE(qubitOp, ry, cobyla)
vqe.random_seed = seed
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
result_vqe = vqe.run(quantum_instance)
print_result(result_vqe)
backend = Aer.get_backend('statevector_simulator')
seed = 50
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa = QAOA(qubitOp, cobyla, 3)
qaoa.random_seed = seed
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
result_qaoa = qaoa.run(quantum_instance)
print_result(result_qaoa)
try:
wiki = WikipediaDataProvider(
token = token,
tickers = stocks,
start = datetime.datetime(2016,1,31),
end = datetime.datetime(2016,12,31))
wiki.run()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
if wiki._data:
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6))
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(stocks):
axis = 0 if s in ("GOOG","AMZN") else 1
wiki._data[cnt].plot(ax=axes[axis], label=s, legend=True)
else:
print('No wiki data loaded.')
selection_classical = sample_most_likely(result_classical.eigenstate)
selection_vqe = sample_most_likely(result_vqe.eigenstate)
selection_qaoa = sample_most_likely(result_qaoa.eigenstate)
selection_cheat = [0,0,0,1]
selection_all = {'classical':selection_classical, 'VQE':selection_vqe, 'QAOA':selection_qaoa, 'cheat':selection_cheat}
if wiki._data:
print("back test")
for label, selection in selection_all.items():
total_price = 0
initial_price = 0
for (cnt, s) in enumerate(stocks):
if selection[cnt] == 1:
total_price += wiki._data[cnt]
initial_price += wiki._data[cnt][0]
plt.plot(total_price/initial_price, label=label)
plt.legend()
plt.xticks(rotation=90)
plt.show()
else:
print('No wiki data loaded.')
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
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
# 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
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="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
t3_st_qcs = transpile(t3_st_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_st_qcs), ")")
t3_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("ibmq_jakarta")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(t3_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, initial_layout=initial_layout)
print('Job ID', cal_job.job_id())
dt_now = datetime.datetime.now()
print(dt_now)
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()
print("retrieved cal_results")
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = []
for i, job in enumerate(jobs):
mit_results.append( meas_fitter.filter.apply(job.result()) )
print("retrieved", i, "th results")
# 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/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/Juan-Varela11/BNL_2020_Summer_Internship
|
Juan-Varela11
|
import numpy as np
import pylab
from qiskit import Aer, IBMQ
from qiskit.aqua import QuantumInstance, aqua_globals
from qiskit.aqua.algorithms.adaptive import VQE
from qiskit.aqua.algorithms.classical import ExactEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua.components.variational_forms import RY
from qiskit.aqua.operators import WeightedPauliOperator
import matplotlib.pyplot as plt
import numpy as np
from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.quantum_info.operators import Kraus, SuperOp
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.visualization import plot_histogram
# Qiskit Aer noise module imports
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import QuantumError, ReadoutError
from qiskit.providers.aer.noise.errors import pauli_error
from qiskit.providers.aer.noise.errors import depolarizing_error
from qiskit.providers.aer.noise.errors import thermal_relaxation_error
from qiskit.providers.aer import noise
provider = IBMQ.load_account()
pauli_dict = {
'paulis': [{"coeff": {"imag": 0.0, "real": -1.052373245772859}, "label": "II"},
{"coeff": {"imag": 0.0, "real": 0.39793742484318045}, "label": "ZI"},
{"coeff": {"imag": 0.0, "real": -0.39793742484318045}, "label": "IZ"},
{"coeff": {"imag": 0.0, "real": -0.01128010425623538}, "label": "ZZ"},
{"coeff": {"imag": 0.0, "real": 0.18093119978423156}, "label": "XX"}
]
}
qubit_op = WeightedPauliOperator.from_dict(pauli_dict)
num_qubits = qubit_op.num_qubits
print('Number of qubits: {}'.format(num_qubits))
ee = ExactEigensolver(qubit_op.copy())
result = ee.run()
ref = result['energy']
print('Reference value: {}'.format(ref))
# T1 and T2 values for qubits 0-3
T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
# Truncate random T2s <= T1s
T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)])
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_reset[j], "reset", [j])
noise_thermal.add_quantum_error(errors_measure[j], "measure", [j])
noise_thermal.add_quantum_error(errors_u1[j], "u1", [j])
noise_thermal.add_quantum_error(errors_u2[j], "u2", [j])
noise_thermal.add_quantum_error(errors_u3[j], "u3", [j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k])
print(noise_thermal)
device = provider.get_backend('ibmq_essex')
coupling_map = device.configuration().coupling_map
noise_model = noise.device.basic_device_noise_model(device.properties())
basis_gates = noise_model.basis_gates
print(noise_model)
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend=backend, seed_simulator=167, seed_transpiler=167,
noise_model=noise_thermal)
counts1 = []
values1 = []
def store_intermediate_result1(eval_count, parameters, mean, std):
counts1.append(eval_count)
values1.append(mean)
aqua_globals.random_seed = 167
optimizer = SPSA(max_trials=200)
var_form = RY(num_qubits)
vqe = VQE(qubit_op, var_form, optimizer, callback=store_intermediate_result1)
vqe_result1 = vqe.run(quantum_instance)
print('VQE on Aer qasm simulator (with noise): {}'.format(vqe_result1['energy']))
print('Delta from reference: {}'.format(vqe_result1['energy']-ref))
plt.figure(figsize=[10,5])
plt.plot(counts1, values1)
plt.xlabel('Eval count')
plt.ylabel('Energy')
plt.title('Convergence with noise');
plt.axhline(ref)
# T1 and T2 values for qubits 0-3
T1s = np.random.normal(5e3, 1e3, 4) # Sampled from normal distribution mean 50 microsec
T2s = np.random.normal(7e3, 1e3, 4) # Sampled from normal distribution mean 50 microsec
# Truncate random T2s <= T1s
T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)])
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_reset[j], "reset", [j])
noise_thermal.add_quantum_error(errors_measure[j], "measure", [j])
noise_thermal.add_quantum_error(errors_u1[j], "u1", [j])
noise_thermal.add_quantum_error(errors_u2[j], "u2", [j])
noise_thermal.add_quantum_error(errors_u3[j], "u3", [j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k])
print(noise_thermal)
device = provider.get_backend('ibmq_essex')
coupling_map = device.configuration().coupling_map
noise_model = noise.device.basic_device_noise_model(device.properties())
basis_gates = noise_model.basis_gates
print(noise_model)
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend=backend, seed_simulator=167, seed_transpiler=167,
noise_model=noise_thermal)
counts = []
values = []
def store_intermediate_result1(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
aqua_globals.random_seed = 167
optimizer = SPSA(max_trials=200)
var_form = RY(num_qubits)
vqe = VQE(qubit_op, var_form, optimizer, callback=store_intermediate_result1)
vqe_result1 = vqe.run(quantum_instance)
print('VQE on Aer qasm simulator (with noise): {}'.format(vqe_result1['energy']))
print('Delta from reference: {}'.format(vqe_result1['energy']-ref))
plt.figure(figsize=[10,5])
plt.plot(counts, values)
plt.xlabel('Eval count')
plt.ylabel('Energy')
plt.title('Convergence with noise');
plt.axhline(ref)
qiskit.__qiskit_version__
import qiskit
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The molecule tested is H2.
The shadow is vanilla, i.e. uses randomized basis change operations.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from predicting_quantum_properties.data_acquisition_shadow import randomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
# taking care of deprecation issues
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = mapper.map(second_q_op)
print(bkencoded_hamiltonian)
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = False)
system_size, observables_xyze, hamiltonian_coefficients = hamiltonian_data
#print('HAMILTONIAN\n', observables_xyze)
'''
VARIATIONAL ANSATZ
Note that for molecules other than H_2 you may need to specify a different number of reps.
'''
reps = 5
ansatz = TwoLocal(num_qubits=system_size, reps=reps, rotation_blocks=['ry', 'rz'],
entanglement_blocks='cz', skip_final_rotation_layer=False)
ansatz.decompose().draw('mpl')
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
estimator.set_options(shots = None)
vqe_solver = VQE(estimator, ansatz, SPSA(maxiter=3000))
calc = GroundStateEigensolver(mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
'''
EXPERIMENTS
'''
start_time = time.time()
rmse_errors = []
print('NUMBER OF RANDOM OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
randomized_basis_change = randomized_classical_shadow(num_operators, system_size)
tuples = (tuple(pauli) for pauli in randomized_basis_change)
counts = Counter(tuples)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(randomized_basis_change, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_randomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_randomised_cs)
print('{} | {}'.format(num_operators, rmse_randomised_cs))
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
points = measurement_range
num_points = len(measurement_range)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='randomized classical shadow')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
%matplotlib inline
from qiskit_finance import QiskitFinanceError
from qiskit_finance.data_providers import *
import datetime
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
data = RandomDataProvider(
tickers=["TICKER1", "TICKER2"],
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=1,
)
data.run()
means = data.get_mean_vector()
print("Means:")
print(means)
rho = data.get_similarity_matrix()
print("A time-series similarity measure:")
print(rho)
plt.imshow(rho)
plt.show()
cov = data.get_covariance_matrix()
print("A covariance matrix:")
print(cov)
plt.imshow(cov)
plt.show()
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
for (cnt, s) in enumerate(data._tickers):
print(s)
print(data._data[cnt])
data = RandomDataProvider(
tickers=["CompanyA", "CompanyB", "CompanyC"],
start=datetime.datetime(2015, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=1,
)
data.run()
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
stocks = ["GOOG", "AAPL"]
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
wiki = WikipediaDataProvider(
token=token,
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
)
wiki.run()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
if token != "REPLACE-ME":
if wiki._data:
if wiki._n <= 1:
print(
"Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers."
)
else:
rho = wiki.get_similarity_matrix()
print("A time-series similarity measure:")
print(rho)
plt.imshow(rho)
plt.show()
cov = wiki.get_covariance_matrix()
print("A covariance matrix:")
print(cov)
plt.imshow(cov)
plt.show()
else:
print("No wiki data loaded.")
if token != "REPLACE-ME":
if wiki._data:
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(stocks):
plt.plot(wiki._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
for (cnt, s) in enumerate(stocks):
print(s)
print(wiki._data[cnt])
else:
print("No wiki data loaded.")
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
nasdaq = DataOnDemandProvider(
token=token,
tickers=["GOOG", "AAPL"],
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 2),
)
nasdaq.run()
for (cnt, s) in enumerate(nasdaq._tickers):
plt.plot(nasdaq._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
lse = ExchangeDataProvider(
token=token,
tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"],
stockmarket=StockMarket.LONDON,
start=datetime.datetime(2018, 1, 1),
end=datetime.datetime(2018, 12, 31),
)
lse.run()
for (cnt, s) in enumerate(lse._tickers):
plt.plot(lse._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
try:
data = YahooDataProvider(
tickers=["MSFT", "AAPL", "GOOG"],
start=datetime.datetime(2021, 1, 1),
end=datetime.datetime(2021, 12, 31),
)
data.run()
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3)
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
data = None
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
import sys
sys.path[1:1] = ["_common", "_common/qiskit"]
sys.path[1:1] = ["../../_common", "../../_common/qiskit"]
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import time
import math
import os
import numpy as np
np.random.seed(0)
import execute as ex
import metrics as metrics
from collections import defaultdict
from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule
from qiskit_nature.circuit.library import HartreeFock as HF
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.transformers import ActiveSpaceTransformer
from qiskit_nature.operators.second_quantization import FermionicOp
from qiskit.opflow import PauliTrotterEvolution, CircuitStateFn, Suzuki
from qiskit.opflow.primitive_ops import PauliSumOp
# Function that converts a list of single and double excitation operators to Pauli operators
def readPauliExcitation(norb, circuit_id=0):
# load pre-computed data
filename = os.path.join(os.getcwd(), f'../qiskit/ansatzes/{norb}_qubit_{circuit_id}.txt')
with open(filename) as f:
data = f.read()
ansatz_dict = json.loads(data)
# initialize Pauli list
pauli_list = []
# current coefficients
cur_coeff = 1e5
# current Pauli list
cur_list = []
# loop over excitations
for ext in ansatz_dict:
if cur_coeff > 1e4:
cur_coeff = ansatz_dict[ext]
cur_list = [(ext, ansatz_dict[ext])]
elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4:
pauli_list.append(PauliSumOp.from_list(cur_list))
cur_coeff = ansatz_dict[ext]
cur_list = [(ext, ansatz_dict[ext])]
else:
cur_list.append((ext, ansatz_dict[ext]))
# add the last term
pauli_list.append(PauliSumOp.from_list(cur_list))
# return Pauli list
return pauli_list
# Get the Hamiltonian by reading in pre-computed file
def ReadHamiltonian(nqubit):
# load pre-computed data
filename = os.path.join(os.getcwd(), f'../qiskit/Hamiltonians/{nqubit}_qubit.txt')
with open(filename) as f:
data = f.read()
ham_dict = json.loads(data)
# pauli list
pauli_list = []
for p in ham_dict:
pauli_list.append( (p, ham_dict[p]) )
# build Hamiltonian
ham = PauliSumOp.from_list(pauli_list)
# return Hamiltonian
return ham
def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1):
'''
Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz
:param n_spin_orbs:The number of spin orbitals
:return: return a Qiskit circuit for this VQE ansatz
'''
# allocate qubits
num_qubits = n_spin_orbs
qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name="main")
# number of alpha spin orbitals
norb_a = int(n_spin_orbs / 2)
# number of beta spin orbitals
norb_b = norb_a
# construct the Hamiltonian
qubit_op = ReadHamiltonian(n_spin_orbs)
# initialize the HF state
qc = HartreeFock(n_spin_orbs, na, nb)
# form the list of single and double excitations
singles = []
doubles = []
for occ_a in range(na):
for vir_a in range(na, norb_a):
singles.append((occ_a, vir_a))
for occ_b in range(norb_a, norb_a+nb):
for vir_b in range(norb_a+nb, n_spin_orbs):
singles.append((occ_b, vir_b))
for occ_a in range(na):
for vir_a in range(na, norb_a):
for occ_b in range(norb_a, norb_a+nb):
for vir_b in range(norb_a+nb, n_spin_orbs):
doubles.append((occ_a, vir_a, occ_b, vir_b))
# get cluster operators in Paulis
pauli_list = readPauliExcitation(n_spin_orbs, circuit_id)
# loop over the Pauli operators
for index, PauliOp in enumerate(pauli_list):
# get circuit for exp(-iP)
cluster_qc = ClusterOperatorCircuit(PauliOp)
# add to ansatz
qc.compose(cluster_qc, inplace=True)
# method 2, only compute the last term in the Hamiltonian
if method == 2:
# last term in Hamiltonian
qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits)
# return the circuit
return qc_with_mea
# now we need to add the measurement parts to the circuit
# circuit list
qc_list = []
diag = []
off_diag = []
for p in qubit_op:
# get the circuit with expectation measurements
qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits)
# add to circuit list
qc_list.append(qc_with_mea)
# diagonal term
if is_diag:
diag.append(p)
# off-diagonal term
else:
off_diag.append(p)
return qc_list
def ClusterOperatorCircuit(pauli_op):
# compute exp(-iP)
exp_ip = pauli_op.exp_i()
# Trotter approximation
qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip)
# convert to circuit
qc = qc_op.to_circuit()
# return this circuit
return qc
# Function that adds expectation measurements to the raw circuits
def ExpectationCircuit(qc, pauli, nqubit, method=1):
# a flag that tells whether we need to perform rotation
need_rotate = False
# copy the unrotated circuit
raw_qc = qc.copy()
# whether this term is diagonal
is_diag = True
# primitive Pauli string
PauliString = pauli.primitive.to_list()[0][0]
# coefficient
coeff = pauli.coeffs[0]
# basis rotation
for i, p in enumerate(PauliString):
target_qubit = nqubit - i - 1
if (p == "X"):
need_rotate = True
is_diag = False
raw_qc.h(target_qubit)
elif (p == "Y"):
raw_qc.sdg(target_qubit)
raw_qc.h(target_qubit)
need_rotate = True
is_diag = False
# perform measurements
raw_qc.measure_all()
# name of this circuit
raw_qc.name = PauliString + " " + str(np.real(coeff))
return raw_qc, is_diag
# Function that implements the Hartree-Fock state
def HartreeFock(norb, na, nb):
# initialize the quantum circuit
qc = QuantumCircuit(norb)
# alpha electrons
for ia in range(na):
qc.x(ia)
# beta electrons
for ib in range(nb):
qc.x(ib+int(norb/2))
# return the circuit
return qc
import json
from qiskit import execute, Aer
backend = Aer.get_backend("qasm_simulator")
precalculated_data = {}
def run(min_qubits=4, max_qubits=4, max_circuits=3, num_shots=4092 * 2**8, method=2):
print(f"... using circuit method {method}")
# validate parameters (smallest circuit is 4 qubits)
max_qubits = max(4, max_qubits)
min_qubits = min(max(4, min_qubits), max_qubits)
if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even
if method == 1: max_circuits = 1
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
for input_size in range(min_qubits, max_qubits + 1, 2):
# determine the number of circuits to execute fo this group
num_circuits = max_circuits
num_qubits = input_size
# decides number of electrons
na = int(num_qubits/4)
nb = int(num_qubits/4)
# decides number of unoccupied orbitals
nvira = int(num_qubits/2) - na
nvirb = int(num_qubits/2) - nb
# determine the size of t1 and t2 amplitudes
t1_size = na * nvira + nb * nvirb
t2_size = na * nb * nvira * nvirb
# random seed
np.random.seed(0)
# create the circuit for given qubit size and simulation parameters, store time metric
ts = time.time()
# circuit list
qc_list = []
# method 1 (default)
if method == 1:
# sample t1 and t2 amplitude
t1 = np.random.normal(size=t1_size)
t2 = np.random.normal(size=t2_size)
# construct all circuits
qc_list = VQEEnergy(num_qubits, na, nb, 0, method)
else:
# loop over circuits
for circuit_id in range(num_circuits):
# sample t1 and t2 amplitude
t1 = np.random.normal(size=t1_size)
t2 = np.random.normal(size=t2_size)
# construct circuit
qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method)
qc_single.name = qc_single.name + " " + str(circuit_id)
# add to list
qc_list.append(qc_single)
print(f"************\nExecuting VQE with num_qubits {num_qubits}")
for qc in qc_list:
# get circuit id
if method == 1:
circuit_id = qc.name.split()[0]
else:
circuit_id = qc.name.split()[2]
# collapse the sub-circuits used in this benchmark (for qiskit)
qc2 = qc.decompose()
# submit circuit for execution on target (simulator, cloud simulator, or hardware)
job = execute(qc, backend, shots=num_shots)
# executation result
result = job.result()
# get measurement counts
counts = result.get_counts(qc)
# initialize empty dictionary
dist = {}
for key in counts.keys():
prob = counts[key] / num_shots
dist[key] = prob
# add dist values to precalculated data for use in fidelity calculation
precalculated_data[f"{circuit_id}"] = dist
with open(f'precalculated_data_qubit_{num_qubits}_method1.json', 'w') as f:
f.write(json.dumps(
precalculated_data,
sort_keys=True,
indent=4,
separators=(',', ': ')
))
run()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
# TODO: This example should use a real mock backend.
backend = FakeOpenPulse3Q()
d2 = pulse.DriveChannel(2)
with pulse.build(backend) as bell_prep:
pulse.u2(0, math.pi, 0)
pulse.cx(0, 1)
with pulse.build(backend) as decoupled_bell_prep_and_measure:
# We call our bell state preparation schedule constructed above.
with pulse.align_right():
pulse.call(bell_prep)
pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2)
pulse.barrier(0, 1, 2)
registers = pulse.measure_all()
decoupled_bell_prep_and_measure.draw()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Unit tests for pulse instructions."""
import numpy as np
from qiskit import pulse, circuit
from qiskit.pulse import channels, configuration, instructions, library, exceptions
from qiskit.pulse.transforms import inline_subroutines, target_qobj_transform
from qiskit.test import QiskitTestCase
class TestAcquire(QiskitTestCase):
"""Acquisition tests."""
def test_can_construct_valid_acquire_command(self):
"""Test if valid acquire command can be constructed."""
kernel_opts = {"start_window": 0, "stop_window": 10}
kernel = configuration.Kernel(name="boxcar", **kernel_opts)
discriminator_opts = {
"neighborhoods": [{"qubits": 1, "channels": 1}],
"cal": "coloring",
"resample": False,
}
discriminator = configuration.Discriminator(
name="linear_discriminator", **discriminator_opts
)
acq = instructions.Acquire(
10,
channels.AcquireChannel(0),
channels.MemorySlot(0),
kernel=kernel,
discriminator=discriminator,
name="acquire",
)
self.assertEqual(acq.duration, 10)
self.assertEqual(acq.discriminator.name, "linear_discriminator")
self.assertEqual(acq.discriminator.params, discriminator_opts)
self.assertEqual(acq.kernel.name, "boxcar")
self.assertEqual(acq.kernel.params, kernel_opts)
self.assertIsInstance(acq.id, int)
self.assertEqual(acq.name, "acquire")
self.assertEqual(
acq.operands,
(
10,
channels.AcquireChannel(0),
channels.MemorySlot(0),
None,
kernel,
discriminator,
),
)
def test_instructions_hash(self):
"""Test hashing for acquire instruction."""
acq_1 = instructions.Acquire(
10,
channels.AcquireChannel(0),
channels.MemorySlot(0),
name="acquire",
)
acq_2 = instructions.Acquire(
10,
channels.AcquireChannel(0),
channels.MemorySlot(0),
name="acquire",
)
hash_1 = hash(acq_1)
hash_2 = hash(acq_2)
self.assertEqual(hash_1, hash_2)
class TestDelay(QiskitTestCase):
"""Delay tests."""
def test_delay(self):
"""Test delay."""
delay = instructions.Delay(10, channels.DriveChannel(0), name="test_name")
self.assertIsInstance(delay.id, int)
self.assertEqual(delay.name, "test_name")
self.assertEqual(delay.duration, 10)
self.assertIsInstance(delay.duration, int)
self.assertEqual(delay.operands, (10, channels.DriveChannel(0)))
self.assertEqual(delay, instructions.Delay(10, channels.DriveChannel(0)))
self.assertNotEqual(delay, instructions.Delay(11, channels.DriveChannel(1)))
self.assertEqual(repr(delay), "Delay(10, DriveChannel(0), name='test_name')")
# Test numpy int for duration
delay = instructions.Delay(np.int32(10), channels.DriveChannel(0), name="test_name2")
self.assertEqual(delay.duration, 10)
self.assertIsInstance(delay.duration, np.integer)
def test_operator_delay(self):
"""Test Operator(delay)."""
from qiskit.circuit import QuantumCircuit
from qiskit.quantum_info import Operator
circ = QuantumCircuit(1)
circ.delay(10)
op_delay = Operator(circ)
expected = QuantumCircuit(1)
expected.i(0)
op_identity = Operator(expected)
self.assertEqual(op_delay, op_identity)
class TestSetFrequency(QiskitTestCase):
"""Set frequency tests."""
def test_freq(self):
"""Test set frequency basic functionality."""
set_freq = instructions.SetFrequency(4.5e9, channels.DriveChannel(1), name="test")
self.assertIsInstance(set_freq.id, int)
self.assertEqual(set_freq.duration, 0)
self.assertEqual(set_freq.frequency, 4.5e9)
self.assertEqual(set_freq.operands, (4.5e9, channels.DriveChannel(1)))
self.assertEqual(
set_freq, instructions.SetFrequency(4.5e9, channels.DriveChannel(1), name="test")
)
self.assertNotEqual(
set_freq, instructions.SetFrequency(4.5e8, channels.DriveChannel(1), name="test")
)
self.assertEqual(repr(set_freq), "SetFrequency(4500000000.0, DriveChannel(1), name='test')")
def test_freq_non_pulse_channel(self):
"""Test set frequency constructor with illegal channel"""
with self.assertRaises(exceptions.PulseError):
instructions.SetFrequency(4.5e9, channels.RegisterSlot(1), name="test")
def test_parameter_expression(self):
"""Test getting all parameters assigned by expression."""
p1 = circuit.Parameter("P1")
p2 = circuit.Parameter("P2")
expr = p1 + p2
instr = instructions.SetFrequency(expr, channel=channels.DriveChannel(0))
self.assertSetEqual(instr.parameters, {p1, p2})
class TestShiftFrequency(QiskitTestCase):
"""Shift frequency tests."""
def test_shift_freq(self):
"""Test shift frequency basic functionality."""
shift_freq = instructions.ShiftFrequency(4.5e9, channels.DriveChannel(1), name="test")
self.assertIsInstance(shift_freq.id, int)
self.assertEqual(shift_freq.duration, 0)
self.assertEqual(shift_freq.frequency, 4.5e9)
self.assertEqual(shift_freq.operands, (4.5e9, channels.DriveChannel(1)))
self.assertEqual(
shift_freq, instructions.ShiftFrequency(4.5e9, channels.DriveChannel(1), name="test")
)
self.assertNotEqual(
shift_freq, instructions.ShiftFrequency(4.5e8, channels.DriveChannel(1), name="test")
)
self.assertEqual(
repr(shift_freq), "ShiftFrequency(4500000000.0, DriveChannel(1), name='test')"
)
def test_freq_non_pulse_channel(self):
"""Test shift frequency constructor with illegal channel"""
with self.assertRaises(exceptions.PulseError):
instructions.ShiftFrequency(4.5e9, channels.RegisterSlot(1), name="test")
def test_parameter_expression(self):
"""Test getting all parameters assigned by expression."""
p1 = circuit.Parameter("P1")
p2 = circuit.Parameter("P2")
expr = p1 + p2
instr = instructions.ShiftFrequency(expr, channel=channels.DriveChannel(0))
self.assertSetEqual(instr.parameters, {p1, p2})
class TestSetPhase(QiskitTestCase):
"""Test the instruction construction."""
def test_default(self):
"""Test basic SetPhase."""
set_phase = instructions.SetPhase(1.57, channels.DriveChannel(0))
self.assertIsInstance(set_phase.id, int)
self.assertEqual(set_phase.name, None)
self.assertEqual(set_phase.duration, 0)
self.assertEqual(set_phase.phase, 1.57)
self.assertEqual(set_phase.operands, (1.57, channels.DriveChannel(0)))
self.assertEqual(
set_phase, instructions.SetPhase(1.57, channels.DriveChannel(0), name="test")
)
self.assertNotEqual(
set_phase, instructions.SetPhase(1.57j, channels.DriveChannel(0), name="test")
)
self.assertEqual(repr(set_phase), "SetPhase(1.57, DriveChannel(0))")
def test_set_phase_non_pulse_channel(self):
"""Test shift phase constructor with illegal channel"""
with self.assertRaises(exceptions.PulseError):
instructions.SetPhase(1.57, channels.RegisterSlot(1), name="test")
def test_parameter_expression(self):
"""Test getting all parameters assigned by expression."""
p1 = circuit.Parameter("P1")
p2 = circuit.Parameter("P2")
expr = p1 + p2
instr = instructions.SetPhase(expr, channel=channels.DriveChannel(0))
self.assertSetEqual(instr.parameters, {p1, p2})
class TestShiftPhase(QiskitTestCase):
"""Test the instruction construction."""
def test_default(self):
"""Test basic ShiftPhase."""
shift_phase = instructions.ShiftPhase(1.57, channels.DriveChannel(0))
self.assertIsInstance(shift_phase.id, int)
self.assertEqual(shift_phase.name, None)
self.assertEqual(shift_phase.duration, 0)
self.assertEqual(shift_phase.phase, 1.57)
self.assertEqual(shift_phase.operands, (1.57, channels.DriveChannel(0)))
self.assertEqual(
shift_phase, instructions.ShiftPhase(1.57, channels.DriveChannel(0), name="test")
)
self.assertNotEqual(
shift_phase, instructions.ShiftPhase(1.57j, channels.DriveChannel(0), name="test")
)
self.assertEqual(repr(shift_phase), "ShiftPhase(1.57, DriveChannel(0))")
def test_shift_phase_non_pulse_channel(self):
"""Test shift phase constructor with illegal channel"""
with self.assertRaises(exceptions.PulseError):
instructions.ShiftPhase(1.57, channels.RegisterSlot(1), name="test")
def test_parameter_expression(self):
"""Test getting all parameters assigned by expression."""
p1 = circuit.Parameter("P1")
p2 = circuit.Parameter("P2")
expr = p1 + p2
instr = instructions.ShiftPhase(expr, channel=channels.DriveChannel(0))
self.assertSetEqual(instr.parameters, {p1, p2})
class TestSnapshot(QiskitTestCase):
"""Snapshot tests."""
def test_default(self):
"""Test default snapshot."""
snapshot = instructions.Snapshot(label="test_name", snapshot_type="state")
self.assertIsInstance(snapshot.id, int)
self.assertEqual(snapshot.name, "test_name")
self.assertEqual(snapshot.type, "state")
self.assertEqual(snapshot.duration, 0)
self.assertNotEqual(snapshot, instructions.Delay(10, channels.DriveChannel(0)))
self.assertEqual(repr(snapshot), "Snapshot(test_name, state, name='test_name')")
class TestPlay(QiskitTestCase):
"""Play tests."""
def setUp(self):
"""Setup play tests."""
super().setUp()
self.duration = 4
self.pulse_op = library.Waveform([1.0] * self.duration, name="test")
def test_play(self):
"""Test basic play instruction."""
play = instructions.Play(self.pulse_op, channels.DriveChannel(1))
self.assertIsInstance(play.id, int)
self.assertEqual(play.name, self.pulse_op.name)
self.assertEqual(play.duration, self.duration)
self.assertEqual(
repr(play),
"Play(Waveform(array([1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]), name='test'),"
" DriveChannel(1), name='test')",
)
def test_play_non_pulse_ch_raises(self):
"""Test that play instruction on non-pulse channel raises a pulse error."""
with self.assertRaises(exceptions.PulseError):
instructions.Play(self.pulse_op, channels.AcquireChannel(0))
class TestDirectives(QiskitTestCase):
"""Test pulse directives."""
def test_relative_barrier(self):
"""Test the relative barrier directive."""
a0 = channels.AcquireChannel(0)
d0 = channels.DriveChannel(0)
m0 = channels.MeasureChannel(0)
u0 = channels.ControlChannel(0)
mem0 = channels.MemorySlot(0)
reg0 = channels.RegisterSlot(0)
chans = (a0, d0, m0, u0, mem0, reg0)
name = "barrier"
barrier = instructions.RelativeBarrier(*chans, name=name)
self.assertEqual(barrier.name, name)
self.assertEqual(barrier.duration, 0)
self.assertEqual(barrier.channels, chans)
self.assertEqual(barrier.operands, chans)
class TestCall(QiskitTestCase):
"""Test call instruction."""
def setUp(self):
super().setUp()
with pulse.build() as _subroutine:
pulse.delay(10, pulse.DriveChannel(0))
self.subroutine = _subroutine
self.param1 = circuit.Parameter("amp1")
self.param2 = circuit.Parameter("amp2")
with pulse.build() as _function:
pulse.play(pulse.Gaussian(160, self.param1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, self.param2, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, self.param1, 40), pulse.DriveChannel(0))
self.function = _function
def test_call(self):
"""Test basic call instruction."""
with self.assertWarns(DeprecationWarning):
call = instructions.Call(subroutine=self.subroutine)
self.assertEqual(call.duration, 10)
self.assertEqual(call.subroutine, self.subroutine)
def test_parameterized_call(self):
"""Test call instruction with parameterized subroutine."""
with self.assertWarns(DeprecationWarning):
call = instructions.Call(subroutine=self.function)
self.assertTrue(call.is_parameterized())
self.assertEqual(len(call.parameters), 2)
def test_assign_parameters_to_call(self):
"""Test create schedule by calling subroutine and assign parameters to it."""
init_dict = {self.param1: 0.1, self.param2: 0.5}
with pulse.build() as test_sched:
pulse.call(self.function)
test_sched = test_sched.assign_parameters(value_dict=init_dict)
test_sched = inline_subroutines(test_sched)
with pulse.build() as ref_sched:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
self.assertEqual(target_qobj_transform(test_sched), target_qobj_transform(ref_sched))
def test_call_initialize_with_parameter(self):
"""Test call instruction with parameterized subroutine with initial dict."""
init_dict = {self.param1: 0.1, self.param2: 0.5}
with self.assertWarns(DeprecationWarning):
call = instructions.Call(subroutine=self.function, value_dict=init_dict)
with pulse.build() as ref_sched:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
self.assertEqual(
target_qobj_transform(call.assigned_subroutine()), target_qobj_transform(ref_sched)
)
def test_call_subroutine_with_different_parameters(self):
"""Test call subroutines with different parameters in the same schedule."""
init_dict1 = {self.param1: 0.1, self.param2: 0.5}
init_dict2 = {self.param1: 0.3, self.param2: 0.7}
with pulse.build() as test_sched:
pulse.call(self.function, value_dict=init_dict1)
pulse.call(self.function, value_dict=init_dict2)
with pulse.build() as ref_sched:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.3, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.7, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.3, 40), pulse.DriveChannel(0))
self.assertEqual(target_qobj_transform(test_sched), target_qobj_transform(ref_sched))
|
https://github.com/C2QA/bosonic-qiskit
|
C2QA
|
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa.
import os
import sys
module_path = os.path.abspath(os.path.join("../.."))
if module_path not in sys.path:
sys.path.append(module_path)
# Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv
module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages"))
if module_path not in sys.path:
sys.path.append(module_path)
import math
import c2qa
import c2qa.util
import c2qa.wigner
import matplotlib.pyplot
import numpy
import qiskit
import qiskit_aer
def calibration_circuit(dist, num_qumodes = 1, num_qubits_per_qumode = 4):
qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=num_qubits_per_qumode)
qr = qiskit.QuantumRegister(size=1)
cr = qiskit.ClassicalRegister(size=1)
circuit = c2qa.CVCircuit(qmr, qr, cr)
circuit.initialize([1,0], qr[0])
circuit.cv_initialize(0, qmr[0])
circuit.h(qr[0])
circuit.cv_c_d(dist, qmr[0], qr[0])
circuit.cv_d(1j * dist, qmr[0])
circuit.cv_c_d(-dist, qmr[0], qr[0])
circuit.cv_d(-1j * dist, qmr[0])
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
return circuit, qr[0], cr[0]
circuit, _, _ = calibration_circuit(numpy.sqrt(numpy.pi) / numpy.sqrt(2))
state, result, fock_counts = c2qa.util.simulate(circuit)
counts = result.get_counts(circuit)
print("Simulated statevector:")
print(state)
print("Simulated result counts:")
print(counts)
# Plot Fock state Wigner function
c2qa.wigner.plot_wigner(circuit, state)
# Run the simulations
backend = qiskit_aer.Aer.get_backend("qasm_simulator")
up = numpy.linspace(numpy.sqrt(2), 2, 20)
down = numpy.linspace(2, numpy.sqrt(2), 20)
steps = []
for _ in range(2):
steps.extend(up[0:19])
steps.extend(down[0:19])
x = []
y = []
for i, step in enumerate(steps):
dist = numpy.sqrt(numpy.pi) / step
circuit, _, _ = calibration_circuit(dist)
state, result, fock_counts = c2qa.util.simulate(circuit, shots=32)
counts = result.get_counts(circuit)
x.append(i)
y.append(counts.get("0", 0) - counts.get("1", 0))
print(f"{i}: {counts}")
# Plot the results
matplotlib.pyplot.scatter(x, y)
matplotlib.pyplot.show()
circuit, qubit, cbit = calibration_circuit(dist=numpy.sqrt(numpy.pi) / numpy.sqrt(2))
anim = c2qa.animate.animate_wigner(circuit, qubit=qubit, cbit=cbit, animation_segments=10, shots=10)
from IPython.display import HTML
HTML(anim.to_html5_video())
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 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 Conditional Value at Risk (CVaR) measurement."""
import unittest
from test.python.opflow import QiskitOpflowTestCase
import numpy as np
from ddt import ddt, data
from qiskit import QuantumCircuit
from qiskit.utils import algorithm_globals
from qiskit.opflow import (
CVaRMeasurement,
StateFn,
Z,
I,
X,
Y,
Plus,
PauliSumOp,
PauliExpectation,
MatrixExpectation,
CVaRExpectation,
ListOp,
CircuitOp,
AerPauliExpectation,
MatrixOp,
OpflowError,
)
class TestCVaRMeasurement(QiskitOpflowTestCase):
"""Test the CVaR measurement."""
def expected_cvar(self, statevector, operator, alpha):
"""Compute the expected CVaR expected value."""
probabilities = statevector * np.conj(statevector)
# get energies
num_bits = int(np.log2(len(statevector)))
energies = []
for i, _ in enumerate(probabilities):
basis_state = np.binary_repr(i, num_bits)
energies += [operator.eval(basis_state).eval(basis_state)]
# sort ascending
i_sorted = np.argsort(energies)
energies = [energies[i] for i in i_sorted]
probabilities = [probabilities[i] for i in i_sorted]
# add up
result = 0
accumulated_probabilities = 0
for energy, probability in zip(energies, probabilities):
accumulated_probabilities += probability
if accumulated_probabilities <= alpha:
result += probability * energy
else: # final term
result += (alpha - accumulated_probabilities + probability) * energy
break
return result / alpha
def cleanup_algorithm_globals(self, massive):
"""Method used to reset the values of algorithm_globals."""
algorithm_globals.massive = massive
def test_cvar_simple(self):
"""Test a simple case with a single Pauli."""
theta = 1.2
qc = QuantumCircuit(1)
qc.ry(theta, 0)
statefn = StateFn(qc)
for alpha in [0.2, 0.4, 1]:
with self.subTest(alpha=alpha):
cvar = (CVaRMeasurement(Z, alpha) @ statefn).eval()
ref = self.expected_cvar(statefn.to_matrix(), Z, alpha)
self.assertAlmostEqual(cvar, ref)
def test_cvar_simple_with_coeff(self):
"""Test a simple case with a non-unity coefficient"""
theta = 2.2
qc = QuantumCircuit(1)
qc.ry(theta, 0)
statefn = StateFn(qc)
alpha = 0.2
cvar = ((-1 * CVaRMeasurement(Z, alpha)) @ statefn).eval()
ref = self.expected_cvar(statefn.to_matrix(), Z, alpha)
self.assertAlmostEqual(cvar, -1 * ref)
def test_add(self):
"""Test addition."""
theta = 2.2
qc = QuantumCircuit(1)
qc.ry(theta, 0)
statefn = StateFn(qc)
alpha = 0.2
cvar = -1 * CVaRMeasurement(Z, alpha)
ref = self.expected_cvar(statefn.to_matrix(), Z, alpha)
other = ~StateFn(I)
# test add in both directions
res1 = ((cvar + other) @ statefn).eval()
res2 = ((other + other) @ statefn).eval()
self.assertAlmostEqual(res1, 1 - ref)
self.assertAlmostEqual(res2, 1 - ref)
def invalid_input(self):
"""Test invalid input raises an error."""
op = Z
with self.subTest("alpha < 0"):
with self.assertRaises(ValueError):
_ = CVaRMeasurement(op, alpha=-0.2)
with self.subTest("alpha > 1"):
with self.assertRaises(ValueError):
_ = CVaRMeasurement(op, alpha=12.3)
with self.subTest("Single pauli operator not diagonal"):
op = Y
with self.assertRaises(OpflowError):
_ = CVaRMeasurement(op)
with self.subTest("Summed pauli operator not diagonal"):
op = X ^ Z + Z ^ I
with self.assertRaises(OpflowError):
_ = CVaRMeasurement(op)
with self.subTest("List operator not diagonal"):
op = ListOp([X ^ Z, Z ^ I])
with self.assertRaises(OpflowError):
_ = CVaRMeasurement(op)
with self.subTest("Matrix operator not diagonal"):
op = MatrixOp([[1, 1], [0, 1]])
with self.assertRaises(OpflowError):
_ = CVaRMeasurement(op)
def test_unsupported_operations(self):
"""Assert unsupported operations raise an error."""
cvar = CVaRMeasurement(Z)
attrs = ["to_matrix", "to_matrix_op", "to_density_matrix", "to_circuit_op", "sample"]
for attr in attrs:
with self.subTest(attr):
with self.assertRaises(NotImplementedError):
_ = getattr(cvar, attr)()
with self.subTest("adjoint"):
with self.assertRaises(OpflowError):
cvar.adjoint()
def test_cvar_on_paulisumop(self):
"""Test a large PauliSumOp is checked for diagonality efficiently.
Regression test for Qiskit/qiskit-terra#7573.
"""
op = PauliSumOp.from_list([("Z" * 30, 1)])
# assert global algorithm settings do not have massive calculations turned on
# -- which is the default, but better to be sure in the test!
# also add a cleanup so we're sure to reset to the original value after the test, even if
# the test would fail
self.addCleanup(self.cleanup_algorithm_globals, algorithm_globals.massive)
algorithm_globals.massive = False
cvar = CVaRMeasurement(op, alpha=0.1)
fake_probabilities = [0.2, 0.8]
fake_energies = [1, 2]
expectation = cvar.compute_cvar(fake_energies, fake_probabilities)
self.assertEqual(expectation, 1)
@ddt
class TestCVaRExpectation(QiskitOpflowTestCase):
"""Test the CVaR expectation object."""
def test_construction(self):
"""Test the correct operator expression is constructed."""
alpha = 0.5
base_expecation = PauliExpectation()
cvar_expecation = CVaRExpectation(alpha=alpha, expectation=base_expecation)
with self.subTest("single operator"):
op = ~StateFn(Z) @ Plus
expected = CVaRMeasurement(Z, alpha) @ Plus
cvar = cvar_expecation.convert(op)
self.assertEqual(cvar, expected)
with self.subTest("list operator"):
op = ~StateFn(ListOp([Z ^ Z, I ^ Z])) @ (Plus ^ Plus)
expected = ListOp(
[
CVaRMeasurement((Z ^ Z), alpha) @ (Plus ^ Plus),
CVaRMeasurement((I ^ Z), alpha) @ (Plus ^ Plus),
]
)
cvar = cvar_expecation.convert(op)
self.assertEqual(cvar, expected)
def test_unsupported_expectation(self):
"""Assert passing an AerPauliExpectation raises an error."""
expecation = AerPauliExpectation()
with self.assertRaises(NotImplementedError):
_ = CVaRExpectation(alpha=1, expectation=expecation)
@data(PauliExpectation(), MatrixExpectation())
def test_underlying_expectation(self, base_expecation):
"""Test the underlying expectation works correctly."""
cvar_expecation = CVaRExpectation(alpha=0.3, expectation=base_expecation)
circuit = QuantumCircuit(2)
circuit.z(0)
circuit.cp(0.5, 0, 1)
circuit.t(1)
op = ~StateFn(CircuitOp(circuit)) @ (Plus ^ 2)
cvar = cvar_expecation.convert(op)
expected = base_expecation.convert(op)
# test if the operators have been transformed in the same manner
self.assertEqual(cvar.oplist[0].primitive, expected.oplist[0].primitive)
def test_compute_variance(self):
"""Test if the compute_variance method works"""
alphas = [0, 0.3, 0.5, 0.7, 1]
correct_vars = [0, 0, 0, 0.8163, 1]
for i, alpha in enumerate(alphas):
base_expecation = PauliExpectation()
cvar_expecation = CVaRExpectation(alpha=alpha, expectation=base_expecation)
op = ~StateFn(Z ^ Z) @ (Plus ^ Plus)
cvar_var = cvar_expecation.compute_variance(op)
np.testing.assert_almost_equal(cvar_var, correct_vars[i], decimal=3)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can choose different colors for the real and imaginary parts of the density matrix.
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = DensityMatrix(qc)
plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
|
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.
"""
Arbitrary unitary circuit instruction.
"""
import numpy
from qiskit.circuit import Gate, ControlledGate
from qiskit.circuit import QuantumCircuit
from qiskit.circuit import QuantumRegister, Qubit
from qiskit.circuit.exceptions import CircuitError
from qiskit.circuit._utils import _compute_control_matrix
from qiskit.circuit.library.standard_gates import UGate
from qiskit.extensions.quantum_initializer import isometry
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.quantum_info.operators.predicates import is_unitary_matrix
from qiskit.quantum_info.synthesis.one_qubit_decompose import OneQubitEulerDecomposer
from qiskit.quantum_info.synthesis.two_qubit_decompose import two_qubit_cnot_decompose
from qiskit.extensions.exceptions import ExtensionError
_DECOMPOSER1Q = OneQubitEulerDecomposer("U")
class UnitaryGate(Gate):
"""Class quantum gates specified by a unitary matrix.
Example:
We can create a unitary gate from a unitary matrix then add it to a
quantum circuit. The matrix can also be directly applied to the quantum
circuit, see :meth:`.QuantumCircuit.unitary`.
.. code-block:: python
from qiskit import QuantumCircuit
from qiskit.extensions import UnitaryGate
matrix = [[0, 0, 0, 1],
[0, 0, 1, 0],
[1, 0, 0, 0],
[0, 1, 0, 0]]
gate = UnitaryGate(matrix)
circuit = QuantumCircuit(2)
circuit.append(gate, [0, 1])
"""
def __init__(self, data, label=None):
"""Create a gate from a numeric unitary matrix.
Args:
data (matrix or Operator): unitary operator.
label (str): unitary name for backend [Default: None].
Raises:
ExtensionError: if input data is not an N-qubit unitary operator.
"""
if hasattr(data, "to_matrix"):
# If input is Gate subclass or some other class object that has
# a to_matrix method this will call that method.
data = data.to_matrix()
elif hasattr(data, "to_operator"):
# If input is a BaseOperator subclass this attempts to convert
# the object to an Operator so that we can extract the underlying
# numpy matrix from `Operator.data`.
data = data.to_operator().data
# Convert to numpy array in case not already an array
data = numpy.array(data, dtype=complex)
# Check input is unitary
if not is_unitary_matrix(data):
raise ExtensionError("Input matrix is not unitary.")
# Check input is N-qubit matrix
input_dim, output_dim = data.shape
num_qubits = int(numpy.log2(input_dim))
if input_dim != output_dim or 2**num_qubits != input_dim:
raise ExtensionError("Input matrix is not an N-qubit operator.")
# Store instruction params
super().__init__("unitary", num_qubits, [data], label=label)
def __eq__(self, other):
if not isinstance(other, UnitaryGate):
return False
if self.label != other.label:
return False
# Should we match unitaries as equal if they are equal
# up to global phase?
return matrix_equal(self.params[0], other.params[0], ignore_phase=True)
def __array__(self, dtype=None):
"""Return matrix for the unitary."""
# pylint: disable=unused-argument
return self.params[0]
def inverse(self):
"""Return the adjoint of the unitary."""
return self.adjoint()
def conjugate(self):
"""Return the conjugate of the unitary."""
return UnitaryGate(numpy.conj(self.to_matrix()))
def adjoint(self):
"""Return the adjoint of the unitary."""
return self.transpose().conjugate()
def transpose(self):
"""Return the transpose of the unitary."""
return UnitaryGate(numpy.transpose(self.to_matrix()))
def _define(self):
"""Calculate a subcircuit that implements this unitary."""
if self.num_qubits == 1:
q = QuantumRegister(1, "q")
qc = QuantumCircuit(q, name=self.name)
theta, phi, lam, global_phase = _DECOMPOSER1Q.angles_and_phase(self.to_matrix())
qc._append(UGate(theta, phi, lam), [q[0]], [])
qc.global_phase = global_phase
self.definition = qc
elif self.num_qubits == 2:
self.definition = two_qubit_cnot_decompose(self.to_matrix())
else:
from qiskit.quantum_info.synthesis.qsd import ( # pylint: disable=cyclic-import
qs_decomposition,
)
self.definition = qs_decomposition(self.to_matrix())
def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None):
"""Return controlled version of gate
Args:
num_ctrl_qubits (int): number of controls to add to gate (default=1)
label (str): optional gate label
ctrl_state (int or str or None): The control state in decimal or as a
bit string (e.g. '1011'). If None, use 2**num_ctrl_qubits-1.
Returns:
UnitaryGate: controlled version of gate.
Raises:
QiskitError: Invalid ctrl_state.
ExtensionError: Non-unitary controlled unitary.
"""
mat = self.to_matrix()
cmat = _compute_control_matrix(mat, num_ctrl_qubits, ctrl_state=None)
iso = isometry.Isometry(cmat, 0, 0)
return ControlledGate(
"c-unitary",
num_qubits=self.num_qubits + num_ctrl_qubits,
params=[mat],
label=label,
num_ctrl_qubits=num_ctrl_qubits,
definition=iso.definition,
ctrl_state=ctrl_state,
base_gate=self.copy(),
)
def _qasm2_decomposition(self):
"""Return an unparameterized version of ourselves, so the OQ2 exporter doesn't choke on the
non-standard things in our `params` field."""
out = self.definition.to_gate()
out.name = self.name
return out
def validate_parameter(self, parameter):
"""Unitary gate parameter has to be an ndarray."""
if isinstance(parameter, numpy.ndarray):
return parameter
else:
raise CircuitError(f"invalid param type {type(parameter)} in gate {self.name}")
def unitary(self, obj, qubits, label=None):
"""Apply unitary gate specified by ``obj`` to ``qubits``.
Args:
obj (matrix or Operator): unitary operator.
qubits (Union[int, Tuple[int]]): The circuit qubits to apply the
transformation to.
label (str): unitary name for backend [Default: None].
Returns:
QuantumCircuit: The quantum circuit.
Raises:
ExtensionError: if input data is not an N-qubit unitary operator.
Example:
Apply a gate specified by a unitary matrix to a quantum circuit
.. code-block:: python
from qiskit import QuantumCircuit
matrix = [[0, 0, 0, 1],
[0, 0, 1, 0],
[1, 0, 0, 0],
[0, 1, 0, 0]]
circuit = QuantumCircuit(2)
circuit.unitary(matrix, [0, 1])
"""
gate = UnitaryGate(obj, label=label)
if isinstance(qubits, QuantumRegister):
qubits = qubits[:]
# for single qubit unitary gate, allow an 'int' or a 'list of ints' as qubits.
if gate.num_qubits == 1:
if isinstance(qubits, (int, Qubit)) or len(qubits) > 1:
qubits = [qubits]
return self.append(gate, qubits, [])
QuantumCircuit.unitary = unitary
|
https://github.com/qiskit-community/qiskit-hackathon-korea-22
|
qiskit-community
|
## import essential libraries
import numpy as np
from qiskit import *
from qiskit.tools.monitor import job_monitor
from qiskit import assemble,pulse,QuantumCircuit,schedule,transpile
from qiskit.pulse.channels import ControlChannel, DriveChannel
from qiskit.circuit import Gate
from qiskit.providers.aer import PulseSimulator
from qiskit.providers.aer.pulse import PulseSystemModel
from qiskit.test.mock import FakeValencia
from qiskit.visualization import plot_histogram
from qiskit.visualization.pulse_v2 import draw, IQXSimple, IQXDebugging,IQXStandard
IBMQ.load_account()
provider = IBMQ.get_provider(group='open')
#check open_pulse ibmq device that you can use
provider.backends(simulator=False, open_pulse=True)
#define pulsesimulator from the backend profile
backend = FakeValencia()
# setting for build pulse simulation
model = PulseSystemModel.from_backend(backend)
qubit_lo_freq = model.hamiltonian.get_qubit_lo_from_drift()
backend_sim = PulseSimulator(system_model = model)
backend_sim.set_options(qubit_lo_freq=backend.defaults().qubit_freq_est)
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.measure_all()
qc.draw('mpl')
qc_t = transpile(qc, backend)
pulse_sched_qc = schedule(qc_t, backend)
draw(pulse_sched_qc, backend=backend)
from qiskit import pulse
dc = pulse.DriveChannel
d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4)
with pulse.build(name='QHK2022_Pulse') as QHK2022:
pulse.play([1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 ], d0)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 ], d1)
pulse.play([1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0 ], d2)
pulse.play([1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0 ], d3)
pulse.play([1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1], d4)
draw(QHK2022)
with pulse.build(backend) as drive_sched_check:
for i in range(5):
print("The driveing channel of qubit{} is {}".format(i, pulse.drive_channel(i)))
from qiskit.tools.jupyter import *
backend
#check the control channel btw 0-1
with pulse.build(backend) as control_sched_check:
print("The control channel of qubit btw qubit (0,1) is {}".format(0, pulse.control_channels(0,1)))
with pulse.build(backend) as control_sched_check:
print("The control channel of qubit btw qubit (0,2) is {}".format(0, pulse.control_channels(0,2)))
with pulse.build(backend) as drive_sched_check:
for i in range(5):
print("The acquire channel of qubit{} is {}".format(i, pulse.acquire_channel(i)))
print("The measurement channel of qubit{} is {}".format(i, pulse.measure_channel(i)))
with pulse.build(backend) as actual_playing:
d0 = pulse.drive_channel(0)
a0 = pulse.acquire_channel(0)
#play square constant pulse at drive channel 0 with the duration 10 (computational duration) amplitude 1.0
pulse.play(pulse.library.Constant(64, 1.0), d0)
#give 20 steps of delay to the d0
pulse.delay(20, d0)
#give pi/2 phase shift to the d0
pulse.shift_phase(2, d0)
pulse.play(pulse.library.Constant(64, 1.0), d0)
#set phase of d0 as pi
pulse.set_phase(0.5, d0)
pulse.play(pulse.library.Constant(64, 1), d0)
#define inner pulse schedule inside of the pulse builder
with pulse.build() as inner_sched:
#play a gaussian pulse with duration 20, amplitude 1, sigma 3.0 to d0
pulse.play(pulse.library.Gaussian(64, 0.2, 3.0), d0)
#play inner schedule at the main schedule
pulse.call(inner_sched)
draw(actual_playing, backend = backend)
with pulse.build(backend) as actual_playing:
#with pulse.build(backend, default_alignment='left') as actual_playing:
#with pulse.build(backend, default_alignment='right') as actual_playing:
#with pulse.build(backend, default_alignment='sequential') as actual_playing_two:
d0 = pulse.drive_channel(0)
d1 = pulse.drive_channel(1)
a0 = pulse.acquire_channel(0)
#play square constant pulse at drive channel 0 with the duration 10 (computational duration) amplitude 1.0
pulse.play(pulse.library.Constant(64, 1.0), d0)
pulse.play(pulse.library.Constant(64, 1.0), d1)
#give 20 steps of delay to the d0
pulse.delay(20, d0)
#give pi/2 phase shift to the d0
pulse.shift_phase(2, d0)
pulse.play(pulse.library.Constant(10, 1.0), d0)
#set phase of d0 as pi
pulse.set_phase(0.5, d0)
pulse.play(pulse.library.Constant(64, 1.0), d0)
#define inner pulse schedule inside of the pulse builder
with pulse.build() as inner_sched:
#play a gaussian pulse with duration 20, amplitude 1, sigma 3.0 to d0
pulse.play(pulse.library.Gaussian(64, 1.0, 3.0), d0)
#play inner schedule at the main schedule
pulse.call(inner_sched)
draw(actual_playing_two, backend = backend)
with pulse.build(backend, default_alignment='sequential') as meas:
pulse.call(actual_playing)
with pulse.align_left():
pulse.measure(0)
draw(meas, style=IQXDebugging(), backend = backend)
result = backend.run(meas, shots=8192).result()
result.get_counts()
with pulse.build(backend, default_alignment='sequential') as entangle_circ:
pulse.u2(0, np.pi, 0)
pulse.cx(0,1)
with pulse.align_left():
pulse.measure(0)
pulse.measure(1)
draw(entangle_circ, style=IQXDebugging(), backend=backend)
with pulse.build(backend, default_alignment='sequential') as example1:
d0 = pulse.drive_channel(0)
#play square constant pulse at drive channel 0 with the duration 200 (computational duration) amplitude 0.5
pulse.play(pulse.library.Constant(200, 0.5), d0)
draw(example1, backend = backend)
with pulse.build(backend, default_alignment='sequential') as example2:
d0 = pulse.drive_channel(0)
#play square constant pulse at drive channel 0 with the duration 189 (computational duration) amplitude 0.5
pulse.play(pulse.library.Constant(189, 0.5), d0)
draw(example2, backend = backend)
with pulse.build(backend, default_alignment='sequential') as example3:
d0 = pulse.drive_channel(0)
#play gaussian pulse at drive channel 0 with the duration 160 (computational duration) amplitude 0.2 with sigma=40
pulse.play(pulse.library.Gaussian(duration=160, amp=(0.2), sigma=40), d0)
draw(example3, backend = backend)
with pulse.build(backend, default_alignment='sequential') as example4:
d0 = pulse.drive_channel(0)
#play gaussian pulse at drive channel 0 with the duration 160 (computational duration) amplitude 0.4 with sigma=40
pulse.play(pulse.library.Gaussian(duration=160, amp=(0.5), sigma=40), d0)
draw(example4, backend = backend)
with pulse.build(backend, default_alignment='sequential') as measure:
a0 = pulse.acquire_channel(0)
m0 = pulse.MeasureChannel(0)
#commenting out and insert pulse schedule you want to play ex:pulse.call(test_pulse1)
#pulse.call()
pulse.acquire(500, m0, pulse.MemorySlot(0))
result = backend.run(measure, shots=8192).result()
result.get_counts()
|
https://github.com/bagmk/qiskit-quantum-state-classifier
|
bagmk
|
import numpy as np
import copy
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer, execute, transpile, assemble
from qiskit.tools.visualization import *
from qiskit.ignis.mitigation.measurement import (complete_meas_cal, tensored_meas_cal,
CompleteMeasFitter, TensoredMeasFitter)
import json
import time
from qiskit.tools.monitor import job_monitor
from c_utils import new_cut # circuit building utilities
data_directory = "data2_files/" # this directory for 2d pilot project data
def json_dic_loader(dic_name):
f = open(data_directory+dic_name+'.json')
return json.load(f)
def json_dic_dumper(dic, dic_name):
with open(data_directory+dic_name+'.json', 'w') as f:
json.dump(dic,f)
simulator = Aer.get_backend('qasm_simulator')
#specify the layout of the devices
used_qubits = 5
qubit_list = [0,1,2,3,4]
program_name="AL2" # This for a mix of W/Psi+ and W_bar/Phi+ separable states (2d pilot project)
Flag_char = "DS" # use the joint set
if len(Flag_char) >= 2:
unique_char = "M" # for "mixed"
else:
unique_char = Flag_char
# These dictionaries for the devices used in the study
QV_dic = {'ibmq_athens': 32.0, 'ibmq_valencia': 16.0, 'ibmq_ourense': 8.0,
"ibmqx2": 8.0, 'ibmq_santiago': 32.0, 'ibmq_vigo': 16.0, 'ideal_device': np.inf}
dev_dic = {'ibmq_santiago': "San",'ibmq_athens': "Ath", 'ibmq_valencia': "Val", 'ibmq_vigo': 'Vig','ibmq_ourense': "Our",
"ibmqx2": 'Yor', 'ideal_device': "Ide"}
# specify the device: here first the ideal noise-free device
project_device = 'ideal_device'
device_name = dev_dic[project_device]
# specify the nb of id gates between state creation and measurements
# zero for the ideal device of course
id_gates = 0
str_nb_id = str(id_gates)
zfilled = str_nb_id.zfill(4-len(str_nb_id))
# tail of the file names for RAM storage
mitig_name = program_name + "_" + device_name
project_name = mitig_name + "_" + unique_char + zfilled
print(mitig_name)
print(project_name)
# establish the result label list
# meas_calibs will be used for mitigation in the real device section
qr = QuantumRegister(used_qubits) #
meas_calibs, label_list = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal')
nb_labels=len(label_list)
print(nb_labels,label_list)
len(meas_calibs)
# permutation list
# here it is simple to write down the list,
# but a version using itertools will be wellcome for >5 qubits projects
q_perm = [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 1, 4, 2, 3], [0, 2, 3, 1, 4], [0, 2, 4, 1, 3],
[0, 3, 4, 1, 2], [1, 2, 3, 0, 4], [1, 2, 4, 0, 3], [1, 3, 4, 0, 2], [2, 3, 4, 0, 1]]
# define the two subsets of 10 separable states
if program_name == "QAD":
state_1a = ["W","Phi+"]
state_1b = ["GHZ","Psi+"]
elif program_name == "ALT" or "AL2":
state_1a = ["W","Psi+"]
state_1b = ["Wbar","Phi+"]
l_states = state_1a+state_1b
l_states
# version 20 circuits for demonstration
# (in the version run on real devices: two batches of 10 circuits)
# these circuits limited to state creation are ready to be saved
# for ultimately building circuits adapted to noisy simulator and real devices
# as option, these circuits will include a row of id gates between creation and measurements
circ_ori = []
for i_s in range(0,len(l_states),2):
for perm in q_perm:
mycircuit = QuantumCircuit(used_qubits, used_qubits)
mycircuit = new_cut.circuit_builder(mycircuit, perm, l_states[i_s],l_states[i_s+1])
circ_ori.append(mycircuit)
# add measurement section to the circuit set newly created:
nb_states = len(circ_ori)
circ_ideal = copy.deepcopy(circ_ori)
for i_state in range(nb_states):
new_cut.add_barrier_and_measure(circ_ideal[i_state],qubit_list)
# execute on noise free simulator
s_sim = 12000
job_simul = execute(circ_ideal, backend=simulator, shots=s_sim)
tot_results_simul = job_simul.result()
# establish a dictionary of count results on noise free simulator:
# (this step is only useful if ram storage is performed)
void_counts = dict(zip(label_list, np.full(2**used_qubits,0.0))) #, dtype=int)))
tot_results_sim_dic = {}
ideal_dic = {}
for i_state in range(nb_states):
counts_simul = copy.deepcopy(void_counts)
counts_simul.update(tot_results_simul.get_counts(i_state))
ideal_dic[str(i_state)]=counts_simul
i_state_test = 0
print(device_name, "circuit #",i_state_test)
circ_ideal[i_state_test].draw(output='mpl')
print(device_name, "circuit #",i_state_test)
plot_histogram(ideal_dic[str(i_state_test)],
legend=['noise free simulation'],
color = "b", figsize=(10.,5.))
i_state_test = 10
print(device_name, "circuit #",i_state_test)
circ_ideal[i_state_test].draw(output='mpl')
print(device_name, "circuit #",i_state_test)
plot_histogram(ideal_dic[str(i_state_test)],
legend=['noise free simulation'],
color = "b", figsize=(10.,5.))
PD_ideal = np.ndarray((nb_states,nb_labels))
for i_state in range(nb_states):
PD_ideal[i_state, :] = list(ideal_dic[str(i_state)].values())
# now a little trick to get the ideal values from the simulator approximated values
with np.errstate(divide='ignore'): # ignore the divide by zero warning
PD_ideal = 1/np.round(s_sim/(PD_ideal))
# have a look at the matrix head and tail:
print("first and last state probability distributions:")
print(np.round(np.vstack((PD_ideal[0:1,:],PD_ideal[-1:,:])),4))
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
print(provider.backends())
project_device = 'ibmq_valencia'# you may choice here a different backend
device_name = dev_dic[project_device]
mitig_name = program_name + "_" + device_name
print(mitig_name)
# determine here the backend
device = provider.get_backend(project_device) # the backend names are listed here above
properties = device.properties()
coupling_map = device.configuration().coupling_map
id_gates = 0 # choice of 0 or 256 at this time
str_nb_id = str(id_gates)
zfilled = str_nb_id.zfill(4-len(str_nb_id))
project_name = mitig_name + "_" + unique_char + zfilled
print(project_name)
circuit_dic = json_dic_loader("circuit_"+ project_name)
real_circs = []
for i_state in list(range(nb_states)):
real_circs.append(QuantumCircuit().from_qasm_str(circuit_dic[str(i_state)]))
i_state_test = 10
print(project_device, "circuit #",i_state_test,
"circuit depth:",real_circs[i_state_test].depth())
print('gates = ',real_circs[i_state_test].count_ops())
# you may want to skip this if large nb of id gates before measurement
real_circs[i_state_test].draw(output='mpl')
job_simul = execute(real_circs[i_state_test], backend=simulator, shots=s_sim)
print(project_device, "circuit #",i_state_test, "on noise free simulator")
simul_results = job_simul.result().get_counts()
plot_histogram(simul_results,
legend=['noise free simulation'],
color = "b", figsize=(10.,5.))
# retrieve the corresponding measurement mitigation filter obtained at experimental time
# use a fake job because the calibration results were stored as dictionary
simulator = Aer.get_backend('qasm_simulator')
fake_job_cal = execute(meas_calibs, backend=simulator, shots=1)
fake_cal_results = fake_job_cal.result()
cal_results_dic = json_dic_loader("cal_results_dic_"+mitig_name)
if 'date' in cal_results_dic.keys():
str(cal_results_dic['date'])
cal_results = fake_cal_results.from_dict(cal_results_dic)
meas_fitter = CompleteMeasFitter(cal_results, label_list, qubit_list=qubit_list, circlabel='mcal')
meas_filter = meas_fitter.filter
# have a look at the average measurement fidefily of this device:
print("Average Measurement Fidelity was: %f" % meas_fitter.readout_fidelity(), "for",project_device)
empirical_dic = json_dic_loader('experimental_'+project_name)
test_dic = json_dic_loader('test_'+project_name)
def rectify_counts(tot_res, test_cqi,mitigation,m_filter) :
# IMPORTANT MODIFICATION
try:
counts_results_real_test = tot_res[str(test_cqi)]
except KeyError as error:
counts_results_real_test = tot_res[test_cqi]
raw_counts_test = copy.deepcopy(void_counts)
raw_counts_test.update(counts_results_real_test)
if mitigation:
mitigated_results_test = meas_filter.apply(raw_counts_test, method = 'least_squares')
returned_counts = copy.deepcopy(void_counts)
returned_counts.update(mitigated_results_test)
else:
returned_counts = copy.deepcopy(raw_counts_test)
return returned_counts
def get_clean_matrix(dic, mitigation,m_filter):
clean_matrix = np.ndarray((nb_states,nb_labels))
for i_state in range(nb_states):
rectified_counts = rectify_counts(dic,i_state, mitigation,m_filter) # get a rectified counts dictionary
clean_matrix[i_state, :] = list(rectified_counts.values())
clean_matrix = clean_matrix/clean_matrix.sum(axis=1, keepdims=True)
return clean_matrix
def obtain_pooled_PDM(mitigation):
PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation,
m_filter=meas_filter)
PD_test = get_clean_matrix(test_dic, mitigation=mitigation,
m_filter=meas_filter)
return PD_exper + PD_test
PD_tot = obtain_pooled_PDM(False)
PD_totm = obtain_pooled_PDM(True)
i_state_test = 19 # choose here the circuit
print(project_device, "circuit #",i_state_test,
"circuit depth:",real_circs[i_state_test].depth())
print('gates = ',real_circs[i_state_test].count_ops())
ideal_results = dict(zip(label_list,PD_ideal[i_state_test]))
real_results = dict(zip(label_list,PD_tot[i_state_test]))
mit_results = dict(zip(label_list,PD_totm[i_state_test]))
plot_histogram([ideal_results, real_results, mit_results],
legend=['ideal device','real results on\n '+ project_device, 'after measurement\n errror mitigation'],
color =["b","r","g"],
bar_labels=False,
figsize=(10.,5.))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
|
nahumsa
|
import numpy as np
from math import pi
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.circuit import Gate
from qiskit.visualization import plot_histogram
from qiskit.circuit.library.standard_gates import ZGate, XGate
# Define circuit parameters
a = '10x01xx'
n = len(a)
k = 7
circ = QuantumCircuit(k+n, k)
circ.reset(range(k+n))
circ.h(range(k+n))
circ.barrier()
for i in range(k):
name = '$G_' + str(i) + '$'
circ.append(QuantumCircuit(n, name=name).to_gate().control(1), [n+i]+list(range(n)))
circ.barrier()
circ.append(Gate(name="$QFT^{-1}$", num_qubits=k, params=[]), range(n, k+n))
circ.barrier()
circ.measure(range(n, k+n), range(k))
circ.draw('mpl', reverse_bits=True, scale=0.5)
def Gop(j):
p = 2 ** j
ctrl_bits = []
ctrl_state = ''
for i in range(n):
if a[n-i-1] != 'x':
ctrl_bits.append(i+1)
ctrl_state += a[n-i-1]
G = QuantumCircuit(n+1, name='G'+str(j))
for i in range(p):
G.append(XGate().control(len(ctrl_bits), ctrl_state=ctrl_state[::-1]), ctrl_bits + [0])
G.h(range(1, n+1))
G.x(range(1, n+1))
G.append(ZGate().control(n-1), reversed(range(1, n+1)))
G.x(range(1, n+1))
G.h(range(1, n+1))
return G
Gop(3).draw('mpl', reverse_bits=True, scale=0.5)
QFT_inv = QuantumCircuit(k, name='QFT^{-1}')
for i in reversed(range(k)):
if i != k-1:
QFT_inv.barrier()
for j in reversed(range(i+1,k)):
QFT_inv.cu1(-pi/(2 ** (j-i)), i, j)
QFT_inv.h(i)
QFT_inv.draw('mpl', reverse_bits=True)
circ = QuantumCircuit(k+n+1, k)
circ.reset(range(k+n+1))
circ.x(0)
circ.h(range(k+n+1))
circ.z(n+1)
circ.barrier()
for i in range(k):
circ.append(Gop(i).to_gate().control(1), [n+i+1]+list(range(n+1)))
circ.barrier()
circ.append(QFT_inv, range(n+1, k+n+1))
circ.barrier()
circ.measure(range(n+1, k+n+1), range(k))
circ.draw(reverse_bits=True, scale=0.5)
delta = 64
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, simulator, shots=delta).result()
counts = result.get_counts(circ)
plot_histogram(counts)
x = list(counts.keys())
x = [pi*int(i[::-1], 2)/(2 ** k) for i in x]
p = list(counts.values())
p = p.index(max(p))
theta = min(x[p], pi-x[p])
m_estimate = (2 ** n) * (theta ** 2)
m = 2 ** a.count('x')
print('Estimated Count:')
print(m_estimate)
print('Actual Count:')
print(m)
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
from qiskit.providers.basic_provider import BasicProvider # instead of BasicAer
import Our_Qiskit_Functions as oq
import numpy as np
import math as m
import scipy as sci
import random
import matplotlib
import matplotlib.pyplot as plt
from itertools import permutations
S_simulator = Aer.backends(name='statevector_simulator')[0]
def E(m1,m2,q):
return abs(m1-m2)*2*q**4 - abs(m1+m2)*10*q**2 + 25
#=====================================================
D = 10
M = [1,2,3]
GS = [999,0,0,0]
N = 100
for i in np.arange(N):
d12 = round(i/N,4)*D
for j in np.arange(N):
d13 = round((j/N)*(D-d12),4)
d23 = round((D-d12-d13),4)
Etotal = E(M[0],M[1],d12) + E(M[0],M[2],d13) + E(M[1],M[2],d23)
if( Etotal < GS[0] ):
GS = [Etotal,d12,d13,d23]
print('Total Particle Distance: ',D,' Particle Masses m1: ',M[0],' m2: ',M[1],' m3: ',M[2])
print('\nMinimal Total Energy: ',round(GS[0],4))
print('\nDistances Between Particles: 1-2: ',round(GS[1],3),' 1-3: ',round(GS[2],3),' 2-3: ',round(GS[3],3))
print('\nEnergy Contributions: 1-2: ',round(E(M[0],M[1],GS[1]),2),' 1-3: ',round(E(M[0],M[2],GS[2]),2), ' 2-3: ',round(E(M[1],M[2],GS[3]),2))
def Single_Qubit_Ansatz( qc, qubit, params ):
qc.ry( params[0], qubit )
qc.rz( params[1], qubit )
#================================================
q = QuantumRegister( 1, name='q' )
qc= QuantumCircuit( q, name='qc' )
theta = m.pi/3
phi = 3*m.pi/2
print('___ Initial State ___')
oq.Wavefunction( qc )
Single_Qubit_Ansatz( qc, q[0], [theta,phi] )
print('\n___ After U(\u03B8,\u03C6) ___')
oq.Wavefunction( qc )
print(' ')
print(qc)
Shots = 10000
#============================================
q = QuantumRegister(1,name='q')
c = ClassicalRegister(1,name='c')
qc= QuantumCircuit(q,c,name='qc')
qc.initialize( [m.sqrt(1/4),m.sqrt(3/4)], q[0] )
print(' ___ Ansatz State ___')
oq.Wavefunction( qc )
qc.measure(q,c)
M1 = oq.Measurement( qc, shots=Shots, print_M=False, return_M=True )
print( '\n{ |0> , |1> } Basis - Energy Expectation Value: ',round( (M1['0']/Shots)+(-1.0*M1['1']/Shots) ,3) )
#============================================
q2 = QuantumRegister(1,name='q2')
c2 = ClassicalRegister(1,name='c2')
qc2= QuantumCircuit(q2,c2,name='qc2')
qc.initialize( [m.sqrt(1/4),m.sqrt(3/4)], q[0] )
qc2.ry( -m.pi/2, q2[0] )
qc2.measure(q2,c2)
M2 = oq.Measurement( qc2, shots=Shots, print_M=False, return_M=True )
print( '\n{ |+> , |-> } Basis - Energy Expectation Value: ',round( (M2['0']/Shots)+(-1.0*M2['1']/Shots) ,3) )
t1 = 60
t2 = 60
Shots = 10000
Parameter_Space = np.zeros(shape=(t1,t2))
Ground_State = [100,0,0]
H = {'X':3,'Y':-2,'Z':1}
Hk = list( H.keys() )
#--------------------------------------------------
for i in np.arange( t1 ):
theta = m.pi*(i/t1)
for j in np.arange( t2 ):
phi = 2*m.pi*(j/t2)
Measures = []
for k in np.arange(len(Hk)):
q = QuantumRegister( 1, name='q' )
c = ClassicalRegister( 1, name='c' )
qc= QuantumCircuit( q, c, name='qc')
oq.Single_Qubit_Ansatz( qc, q[0], [theta, phi] )
if( Hk[k] == 'X' ):
qc.ry( -m.pi/2, q[0])
elif( Hk[k] == 'Y' ):
qc.rx(m.pi/2, q[0])
qc.measure( q,c )
M = {'0':0,'1':0}
M.update( oq.Measurement( qc, shots=Shots, print_M=False, return_M=True ) )
Measures.append( M )
Parameter_Space[i,j] = H['X']*(Measures[0]['0'] - Measures[0]['1'])/Shots + H['Y']*(Measures[1]['0'] - Measures[1]['1'])/Shots + H['Z']*(Measures[2]['0'] - Measures[2]['1'])/Shots
if( Parameter_Space[i,j] < Ground_State[0] ):
Ground_State[0] = Parameter_Space[i,j]
Ground_State[1] = theta
Ground_State[2] = phi
#==================================================
print('Ground State Energy: ',round(Ground_State[0],5),' \u03B8 = ',round(Ground_State[1],3),' \u03C6 = ',round(Ground_State[2],3))
fig, ax = plt.subplots()
show_text = False
show_ticks = False
oq.Heatmap(Parameter_Space, show_text, show_ticks, ax, "plasma", "Energy Expectation Value")
fig.tight_layout()
plt.show()
H = {'X':3,'Y':-2,'Z':1}
Hk = list( H.keys() )
Shots = 100000
Ground_State = [100,0,0]
epsilon = 0.001
step_size = 0.01
delta = 0.0001
M_bool = True
#-----------------------
EV = 100
EV_old = 1000
terminate = False
#========================================================
theta = m.pi*random.random()
phi = 2*m.pi*random.random()
iters = 0
while( (abs( EV - EV_old ) > delta) and (terminate==False) ):
EV_old = EV
EV = 0
for k in np.arange(len(Hk)):
q = QuantumRegister( 1, name='q' )
c = ClassicalRegister( 1, name='c' )
qc= QuantumCircuit( q, c, name='qc')
oq.Single_Qubit_Ansatz( qc, q[0], [theta, phi] )
if( Hk[k] == 'X' ):
qc.ry(-m.pi/2, q[0])
elif( Hk[k] == 'Y' ):
qc.rx(m.pi/2, q[0])
qc.measure( q,c )
M = {'0':0,'1':0}
M.update( oq.Measurement( qc, shots=Shots, print_M=False, return_M=True ) )
EV = EV + H[Hk[k]]*(M['0']-M['1'])/Shots
print('Iterations: ',iters,' EV: ',round(EV,5),' \u03B8 = ',round(theta,5),' \u03C6 = ',round(phi,5))
if( EV > EV_old ):
terminate = True
else:
if( EV < Ground_State[0] ):
Ground_State[0] = EV
Ground_State[1] = theta
Ground_State[2] = phi
theta_old = theta
phi_old = phi
theta,phi = oq.VQE_Gradient_Descent(qc,q,H,oq.Single_Qubit_Ansatz,theta,phi,epsilon,step_size,measure=M_bool,shots=Shots)
iters = iters + 1
if( (abs( EV - EV_old ) < delta) or (terminate==True) ):
print('\n_____ Gradient Descent Complete _____\n')
print('Iterations: ',iters,' EV: ',round(Ground_State[0],5),' \u03B8 = ',round(Ground_State[1],5),' \u03C6 = ',round(Ground_State[2],5))
t1 = 60
t2 = 60
Shots = 10000
Parameter_Space = np.zeros(shape=(t1,t2))
Ground_State = [100,0,0]
H = {'X':3,'Y':-2,'Z':1}
Hk = list( H.keys() )
#--------------------------------------------------
for i in np.arange( t1 ):
theta = m.pi/2+ (m.pi/10)*(i/t1)
#theta = m.pi*(i/t1)
for j in np.arange( t2 ):
phi = m.pi+ (m.pi/10)*(j/t2)
#phi = 2*m.pi*(j/t2)
EV = 0
for k in np.arange(len(Hk)):
q = QuantumRegister( 1, name='q' )
c = ClassicalRegister( 1, name='c' )
qc= QuantumCircuit( q, c, name='qc')
oq.Single_Qubit_Ansatz( qc, q[0], [theta, phi] )
if( Hk[k] == 'X' ):
qc.ry(-m.pi/2, q[0])
elif( Hk[k] == 'Y' ):
qc.rx(m.pi/2, q[0])
qc.measure( q,c )
M = {'0':0,'1':0}
M.update( oq.Measurement( qc, shots=Shots, print_M=False, return_M=True ) )
EV = EV + H[Hk[k]]*(M['0']-M['1'])/Shots
Parameter_Space[i,j] = EV
if( Parameter_Space[i,j] < Ground_State[0] ):
Ground_State[0] = Parameter_Space[i,j]
Ground_State[1] = theta
Ground_State[2] = phi
#==================================================
fig, ax = plt.subplots()
show_text = False
show_ticks = False
oq.Heatmap(Parameter_Space, show_text, show_ticks, ax, "plasma", "Energy Expectation Value")
fig.tight_layout()
plt.show()
t1 = 60
t2 = 60
Parameter_Space = np.zeros(shape=(t1,t2))
Ground_State = [100,0,0]
H = {'X':3,'Y':-2,'Z':1}
Hk = list( H.keys() )
#--------------------------------------------------
for i in np.arange( t1 ):
theta = m.pi/2+ (m.pi/10)*(i/t1)
for j in np.arange( t2 ):
phi = m.pi+ (m.pi/10)*(j/t2)
EV = 0
for k in np.arange(len(Hk)):
q = QuantumRegister( 1, name='q' )
qc= QuantumCircuit( q, name='qc')
oq.Single_Qubit_Ansatz( qc, q[0], [theta, phi] )
sv0 = oq.execute( qc, S_simulator, shots=1 ).result().get_statevector()
if( Hk[k] == 'X' ):
qc.x(q[0])
elif( Hk[k] == 'Y' ):
qc.y(q[0])
elif( Hk[k] == 'Z' ):
qc.z(q[0])
sv = oq.execute( qc, S_simulator, shots=1 ).result().get_statevector()
ev = 0
for k2 in range(len(np.asarray(sv))):
ev = ev + (np.conj(sv[k2])*sv0[k2]).real
EV = EV + H[Hk[k]] * ev
Parameter_Space[i,j] = EV
if( Parameter_Space[i,j] < Ground_State[0] ):
Ground_State[0] = Parameter_Space[i,j]
Ground_State[1] = theta
Ground_State[2] = phi
#==================================================
fig, ax = plt.subplots()
show_text = False
show_ticks = False
oq.Heatmap(Parameter_Space, show_text, show_ticks, ax, "plasma", "Energy Expectation Value")
fig.tight_layout()
plt.show()
H = {'X':3,'Y':-2,'Z':1}
Hk = list( H.keys() )
Ground_State = [100,0,0]
epsilon = 0.05
step_size = 0.01
delta = 0.00005
M_bool = False
#-----------------------
EV = 100
EV_old = 1000
terminate=False
EV_type = 'wavefunction'
#========================================================
theta = m.pi*random.random()
phi = 2*m.pi*random.random()
iters = 0
while( (abs( EV - EV_old ) > delta) and (terminate==False) ):
EV_old = EV
EV = oq.VQE_EV([theta,phi],oq.Single_Qubit_Ansatz,H,EV_type)
if( (iters/10.0)==m.ceil(iters/10.0) ):
print('Iterations: ',iters,' EV: ',round(EV,5),' \u03B8 = ',round(theta,5),' \u03C6 = ',round(phi,5))
if( EV > EV_old ):
terminate = True
else:
if( EV < Ground_State[0] ):
Ground_State[0] = EV
Ground_State[1] = theta
Ground_State[2] = phi
theta_old = theta
phi_old = phi
theta,phi = oq.VQE_Gradient_Descent(qc,q,H,oq.Single_Qubit_Ansatz,theta,phi,epsilon,step_size,measure=M_bool)
iters = iters + 1
if( (abs( EV - EV_old ) < delta) or (terminate==True) ):
print('\n_____ Gradient Descent Complete _____\n')
print('Iterations: ',iters,' EV: ',round(Ground_State[0],5),' \u03B8 = ',round(Ground_State[1],5),' \u03C6 = ',round(Ground_State[2],5))
H = {'X':3,'Y':-2,'Z':1}
EV_type = 'measure'
theta = random.random()*m.pi
phi = random.random()*2*m.pi
delta = 0.001
#------------------------------
Vertices = []
Values = []
radius = 0.35
R = random.random()*(2*m.pi/3)
for rr in np.arange(3):
angle = R+ rr*2*m.pi/3
Vertices.append( [theta+radius*m.cos(angle),phi+radius*m.sin(angle)] )
for v in np.arange(len(Vertices)):
Values.append( oq.VQE_EV(Vertices[v],oq.Single_Qubit_Ansatz,H,EV_type) )
#------------------------------
terminate = False
iters = 0
terminate_count = 0
terminate_limit = 6
while( (terminate==False) and (iters < 100) ):
iters = iters + 1
low = oq.Calculate_MinMax( Values,'min' )
oq.Nelder_Mead(H, oq.Single_Qubit_Ansatz, Vertices, Values, EV_type)
new_low = oq.Calculate_MinMax( Values,'min' )
if( abs( new_low[0] - low[0] ) < delta ):
terminate_count = terminate_count + 1
else:
terminate_count = 0
if( terminate_count >= terminate_limit ):
terminate = True
print('\n_____ Nelder-Mead Complete _____\n')
print('Iteration: ',iters,' Lowest EV: ',round(low[0],6),' \u03B8 = ',round(Vertices[low[1]][0],4),' \u03C6 = ',round(Vertices[low[1]][1],4))
if( ( (iters==1) or (m.ceil(iters/5))==m.floor(iters/5) ) and (terminate==False) ):
print('Iteration: ',iters,' Lowest EV: ',round(low[0],6),' \u03B8 = ',round(Vertices[low[1]][0],4),' \u03C6 = ',round(Vertices[low[1]][1],4))
H = {'XY':3,'ZZ':-2}
EV_type = 'measure'
P = []
for p in np.arange(4):
P.append( random.random()*m.pi )
P.append( random.random()*2*m.pi )
delta = 0.001
#------------------------------
Vertices = []
Values = []
for v1 in np.arange(len(P)):
V = []
for v2 in np.arange(len(P)):
R = (0.4+random.random()*0.8)*(-1)**round(random.random())
V.append( P[v2]+R )
Vertices.append( V )
Values.append( oq.VQE_EV(V,oq.Two_Qubit_Ansatz,H,EV_type) )
#------------------------------
terminate = False
iters = 0
terminate_count = 0
terminate_limit = 10
while( (terminate==False) and (iters < 100) ):
iters = iters + 1
low = oq.Calculate_MinMax( Values,'min' )
oq.Nelder_Mead(H, oq.Two_Qubit_Ansatz, Vertices, Values, EV_type)
new_low = oq.Calculate_MinMax( Values,'min' )
if( abs( new_low[0] - low[0] ) < delta ):
terminate_count = terminate_count + 1
else:
terminate_count = 0
if( terminate_count >= terminate_limit ):
terminate = True
print('\n_____ Nelder-Mead Complete _____\n')
print(' --------------------- \n Iteration: ',iters,' Lowest EV: ',round( low[0],6 ))
if( ( (iters==1) or (m.ceil(iters/10))==m.floor(iters/10) ) and (terminate==False) ):
print('Iteration: ',iters,' Lowest EV: ',round( low[0],6 ))
|
https://github.com/DaisukeIto-ynu/KosakaQ_client
|
DaisukeIto-ynu
|
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 24 12:38:00 2022
@author: daisu
"""
from kosakaq_experiments.KosakaQ_randomized_benchmarking import randomized_benchmarking
from kosakaq_backend import KosakaQBackend
from qiskit import *
from kosakaq_provider import *
provider = KosakaQProvider("8c8795d3fee73e69271bc8c9fc2e0c12e73e5879")
# print(provider.backends(),"\n")
backend = provider.backends()[0]
# rb = randomized_benchmarking("a",[1, 10, 20, 50, 75, 100, 125, 150, 175, 200],repetition = 1)
# rb = randomized_benchmarking("a",[100],repetition = 1)
rb = randomized_benchmarking(backend,length_vector = [1 ,20, 75, 125, 175], repetition = 5, seed = 5)
# emulator = Aer.get_backend('qasm_simulator')
# life = 10
# while life>0:
# rb.make_sequence()
# for i,j in zip(rb.circuits[0],rb.gate_sequence[0]):
# job = execute( i, emulator, shots=8192 )
# hist = job.result().get_counts()
# # print(hist)
# # print(hist.get("1"))
# if hist.get("1") is not None:
# print(j,hist)
# # print(i)
# # print(hist)
# life -= 1
# # for i in rb.gate_sequence[0]:
# # print(i)
# # 普段使っているのと異なるUser作る
rb.make_sequence()
rb.run()
# print(rb.gate_sequence[29][9])
|
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
|
JessicaJohnBritto
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
### Creating 3 qubit and 2 classical bits in each separate register
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
teleportation_circuit = QuantumCircuit(qr, crz, crx)
### A third party eve helps to create an entangled state
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a, b)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, a, b):
qc.cx(a, b)
qc.h(a)
teleportation_circuit.barrier()
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
teleportation_circuit.barrier()
measure_and_send(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1)
qc.z(qubit).c_if(crz, 1)
teleportation_circuit.barrier()
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
from qiskit.extensions import Initialize
import math
qc = QuantumCircuit(1)
initial_state = [0,1]
init_gate = Initialize(initial_state)
# qc.append(initialize_qubit, [0])
qr = QuantumRegister(3) # Protocol uses 3 qubits
crz = ClassicalRegister(1) # and 2 classical registers
crx = ClassicalRegister(1)
qc = QuantumCircuit(qr, crz, crx)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
out_vector = execute(qc, backend).result().get_statevector()
plot_bloch_multivector(out_vector)
inverse_init_gate = init_gate.gates_to_uncompute()
qc.append(inverse_init_gate, [2])
qc.draw()
cr_result = ClassicalRegister(1)
qc.add_register(cr_result)
qc.measure(2,2)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1024).result().get_counts()
plot_histogram(counts)
def bob_gates(qc, a, b, c):
qc.cz(a, c)
qc.cx(b, c)
qc = QuantumCircuit(3,1)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
qc.barrier()
# Alice sends classical bits to Bob
bob_gates(qc, 0, 1, 2)
# We undo the initialisation process
qc.append(inverse_init_gate, [2])
# See the results, we only care about the state of qubit 2
qc.measure(2,0)
# View the results:
qc.draw()
from qiskit import IBMQ
IBMQ.save_account('### IMB TOKEN ')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
job_exp = execute(qc, backend=backend, shots=8192)
exp_result = job_exp.result()
exp_measurement_result = exp_result.get_counts(qc)
print(exp_measurement_result)
plot_histogram(exp_measurement_result)
error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \
* 100./ sum(list(exp_measurement_result.values()))
print("The experimental error rate : ", error_rate_percent, "%")
|
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.
"""Tests for swap strategies."""
from typing import List
from ddt import data, ddt, unpack
import numpy as np
from qiskit import QiskitError
from qiskit.test import QiskitTestCase
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes.routing.commuting_2q_gate_routing import SwapStrategy
@ddt
class TestSwapStrategy(QiskitTestCase):
"""A class to test the swap strategies."""
def setUp(self):
super().setUp()
self.line_coupling_map = CouplingMap(
couplinglist=[
(0, 1),
(1, 2),
(2, 3),
(3, 4),
(1, 0),
(2, 1),
(3, 2),
(4, 3),
]
)
self.line_swap_layers = (
((0, 1), (2, 3)),
((1, 2), (3, 4)),
((0, 1), (2, 3)),
((1, 2), (3, 4)),
((0, 1), (2, 3)),
)
self.line_edge_coloring = {(0, 1): 0, (1, 2): 1, (2, 3): 0, (3, 4): 1}
self.line_strategy = SwapStrategy(self.line_coupling_map, self.line_swap_layers)
@data(
(0, [0, 1, 2, 3, 4]),
(1, [1, 0, 3, 2, 4]),
(2, [1, 3, 0, 4, 2]),
(3, [3, 1, 4, 0, 2]),
(4, [3, 4, 1, 2, 0]),
(5, [4, 3, 2, 1, 0]),
)
@unpack
def test_inverse_composed_permutation(self, layer_idx: int, expected: List[int]):
"""Test the inverse of the permutations."""
self.assertEqual(self.line_strategy.inverse_composed_permutation(layer_idx), expected)
def test_apply_swap_layer(self):
"""Test that swapping a list of elements is correct."""
list_to_swap = [0, 10, 20, 30, 40]
swapped_list = self.line_strategy.apply_swap_layer(list_to_swap, 0)
self.assertEqual(swapped_list, [10, 0, 30, 20, 40])
self.assertFalse(list_to_swap == swapped_list)
swapped_list = self.line_strategy.apply_swap_layer(list_to_swap, 1, inplace=True)
self.assertEqual(swapped_list, [0, 20, 10, 40, 30])
self.assertTrue(list_to_swap == swapped_list)
def test_length(self):
"""Test the __len__ operator."""
self.assertEqual(len(self.line_strategy), 5)
def test_swapped_coupling_map(self):
"""Test the edges generated by a swap strategy."""
edge_set = {(2, 0), (0, 4), (4, 1), (1, 3), (3, 1), (1, 4), (4, 0), (0, 2)}
swapped_map = self.line_strategy.swapped_coupling_map(3)
self.assertEqual(edge_set, set(swapped_map.get_edges()))
def test_check_configuration(self):
"""Test that tries to initialize an invalid swap strategy."""
with self.assertRaises(QiskitError):
SwapStrategy(
coupling_map=self.line_coupling_map,
swap_layers=(((0, 1), (2, 3)), ((1, 3), (2, 4))),
)
def test_only_one_swap_per_qubit_per_layer(self):
"""Test that tries to initialize an invalid swap strategy."""
message = "The 0th swap layer contains a qubit with multiple swaps."
with self.assertRaises(QiskitError, msg=message):
SwapStrategy(
coupling_map=self.line_coupling_map,
swap_layers=(((0, 1), (1, 2)),),
)
def test_distance_matrix(self):
"""Test the computation of the swap strategy distance matrix."""
line_distance_matrix = np.array(
[
[0, 0, 3, 1, 2],
[0, 0, 0, 2, 3],
[3, 0, 0, 0, 1],
[1, 2, 0, 0, 0],
[2, 3, 1, 0, 0],
]
)
self.assertTrue(np.all(line_distance_matrix == self.line_strategy.distance_matrix))
# Check that the distance matrix cannot be written to.
with self.assertRaises(ValueError):
self.line_strategy.distance_matrix[1, 2] = 5
def test_reaches_full_connectivity(self):
"""Test to reach full connectivity on the longest line of Mumbai."""
# The longest line on e.g. Mumbai has 21 qubits
ll27 = list(range(21))
ll27_map = [[ll27[idx], ll27[idx + 1]] for idx in range(len(ll27) - 1)]
ll27_map += [[ll27[idx + 1], ll27[idx]] for idx in range(len(ll27) - 1)]
# Create a line swap strategy on this line
layer1 = tuple((ll27[idx], ll27[idx + 1]) for idx in range(0, len(ll27) - 1, 2))
layer2 = tuple((ll27[idx], ll27[idx + 1]) for idx in range(1, len(ll27), 2))
n = len(ll27)
for n_layers, result in [
(n - 4, False),
(n - 3, False),
(n - 2, True),
(n - 1, True),
]:
swap_strat_ll = []
for idx in range(n_layers):
if idx % 2 == 0:
swap_strat_ll.append(layer1)
else:
swap_strat_ll.append(layer2)
strat = SwapStrategy(CouplingMap(ll27_map), tuple(swap_strat_ll))
self.assertEqual(len(strat.missing_couplings) == 0, result)
def test_new_connections(self):
"""Test the new connections method."""
new_cnx = self.line_strategy.new_connections(0)
expected = [{1, 0}, {2, 1}, {3, 2}, {4, 3}]
self.assertListEqual(new_cnx, expected)
# Test after first swap layer (0, 1) first
new_cnx = self.line_strategy.new_connections(1)
expected = [{3, 0}, {4, 2}]
self.assertListEqual(new_cnx, expected)
def test_possible_edges(self):
"""Test that possible edges works as expected."""
coupling_map = CouplingMap(couplinglist=[(0, 1), (1, 2), (2, 3)])
strat = SwapStrategy(coupling_map, (((0, 1), (2, 3)), ((1, 2),)))
expected = set()
for i in range(4):
for j in range(4):
if i != j:
expected.add((i, j))
self.assertSetEqual(strat.possible_edges, expected)
class TestSwapStrategyExceptions(QiskitTestCase):
"""A class to test the exceptions raised by swap strategies."""
def test_invalid_strategy(self):
"""Test that a raise properly occurs."""
coupling_map = CouplingMap(couplinglist=[(0, 1), (1, 2)])
swap_layers = (((0, 1), (2, 3)), ((1, 2), (3, 4)))
with self.assertRaises(QiskitError):
SwapStrategy(coupling_map, swap_layers)
def test_invalid_line_strategy(self):
"""Test the number of layers."""
message = "Negative number -1 passed for number of swap layers."
with self.assertRaises(ValueError, msg=message):
SwapStrategy.from_line([0, 1, 2], -1)
class TestLineSwapStrategy(QiskitTestCase):
"""A class to test the line swap strategy."""
def test_invalid_line(self):
"""Test that lines should be longer than 1."""
message = "The line cannot have less than two elements, but is [1]"
with self.assertRaises(ValueError, msg=message):
SwapStrategy.from_line([1], 0)
def test_full_line(self):
"""Test to reach full connectivity on a line."""
n_nodes = 5
strategy = SwapStrategy.from_line(list(range(n_nodes)))
self.assertEqual(len(strategy._swap_layers), n_nodes - 2)
# The LineSwapStrategy will apply the following permutations
layers = [
[0, 1, 2, 3, 4], # coupling map
[1, 0, 3, 2, 4], # layer 1
[1, 3, 0, 4, 2], # layer 2
[3, 1, 4, 0, 2], # layer 3 <-- full connectivity is reached.
]
for layer_idx, layer in enumerate(layers):
expected = set()
for idx in range(len(layer) - 1):
expected.add((layer[idx], layer[idx + 1]))
expected.add((layer[idx + 1], layer[idx]))
strat_edges = strategy.swapped_coupling_map(layer_idx).get_edges()
self.assertEqual(len(strat_edges), len(expected))
for edge in strat_edges:
self.assertTrue(edge in expected)
self.assertEqual(strategy.swap_layer(0), [(0, 1), (2, 3)])
self.assertEqual(strategy.swap_layer(1), [(1, 2), (3, 4)])
self.assertEqual(strategy.swap_layer(2), [(0, 1), (2, 3)])
self.assertEqual(len(strategy.missing_couplings), 0)
def test_line(self):
"""Test the creation of a line swap strategy."""
n_nodes = 5
strategy = SwapStrategy.from_line(list(range(n_nodes)))
self.assertEqual(strategy.swap_layer(0), [(0, 1), (2, 3)])
self.assertEqual(strategy.swap_layer(1), [(1, 2), (3, 4)])
self.assertEqual(strategy.swap_layer(2), [(0, 1), (2, 3)])
self.assertEqual(len(strategy.missing_couplings), 0)
def test_repr(self):
"""The the representation."""
expected = (
"SwapStrategy with swap layers:\n((0, 1),),\non "
"[[0, 1], [1, 0], [1, 2], [2, 1]] coupling map."
)
self.assertEqual(repr(SwapStrategy.from_line([0, 1, 2])), expected)
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
from qiskit import *
from qiskit.tools.visualization import plot_bloch_multivector
circuit = QuantumCircuit(1,1)
circuit.x(0)
simulator = Aer.get_backend('statevector_simulator')
result = execute(circuit, backend=simulator).result()
statevector = result.get_statevector()
print(statevector)
%matplotlib inline
circuit.draw(output='mpl')
# bloch sphere
plot_bloch_multivector(statevector)
# measurement
circuit.measure([0],[0])
backend = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=backend, shots=1024).result()
counts = result.get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
circuit = QuantumCircuit(1,1)
circuit.x(0)
simulator = Aer.get_backend('unitary_simulator')
result = execute(circuit, backend=simulator).result()
unitary = result.get_unitary()
print(unitary)
%matplotlib inline
circuit.draw(output='mpl')
# bloch sphere
plot_bloch_multivector(unitary)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Expression-tree nodes."""
# Given the nature of the tree representation and that there are helper functions associated with
# many of the classes whose arguments naturally share names with themselves, it's inconvenient to
# use synonyms everywhere. This goes for the builtin 'type' as well.
# pylint: disable=redefined-builtin,redefined-outer-name
from __future__ import annotations
__all__ = [
"Expr",
"Var",
"Value",
"Cast",
"Unary",
"Binary",
]
import abc
import enum
import typing
from .. import types
if typing.TYPE_CHECKING:
import qiskit
_T_co = typing.TypeVar("_T_co", covariant=True)
# If adding nodes, remember to update `visitors.ExprVisitor` as well.
class Expr(abc.ABC):
"""Root base class of all nodes in the expression tree. The base case should never be
instantiated directly.
This must not be subclassed by users; subclasses form the internal data of the representation of
expressions, and it does not make sense to add more outside of Qiskit library code.
All subclasses are responsible for setting their ``type`` attribute in their ``__init__``, and
should not call the parent initialiser."""
__slots__ = ("type",)
type: types.Type
# Sentinel to prevent instantiation of the base class.
@abc.abstractmethod
def __init__(self): # pragma: no cover
pass
def accept(
self, visitor: qiskit.circuit.classical.expr.ExprVisitor[_T_co], /
) -> _T_co: # pragma: no cover
"""Call the relevant ``visit_*`` method on the given :class:`ExprVisitor`. The usual entry
point for a simple visitor is to construct it, and then call :meth:`accept` on the root
object to be visited. For example::
expr = ...
visitor = MyVisitor()
visitor.accept(expr)
Subclasses of :class:`Expr` should override this to call the correct virtual method on the
visitor. This implements double dispatch with the visitor."""
return visitor.visit_generic(self)
@typing.final
class Cast(Expr):
"""A cast from one type to another, implied by the use of an expression in a different
context."""
__slots__ = ("operand", "implicit")
def __init__(self, operand: Expr, type: types.Type, implicit: bool = False):
self.type = type
self.operand = operand
self.implicit = implicit
def accept(self, visitor, /):
return visitor.visit_cast(self)
def __eq__(self, other):
return (
isinstance(other, Cast)
and self.type == other.type
and self.operand == other.operand
and self.implicit == other.implicit
)
def __repr__(self):
return f"Cast({self.operand}, {self.type}, implicit={self.implicit})"
@typing.final
class Var(Expr):
"""A classical variable."""
__slots__ = ("var",)
def __init__(
self, var: qiskit.circuit.Clbit | qiskit.circuit.ClassicalRegister, type: types.Type
):
self.type = type
self.var = var
def accept(self, visitor, /):
return visitor.visit_var(self)
def __eq__(self, other):
return isinstance(other, Var) and self.type == other.type and self.var == other.var
def __repr__(self):
return f"Var({self.var}, {self.type})"
@typing.final
class Value(Expr):
"""A single scalar value."""
__slots__ = ("value",)
def __init__(self, value: typing.Any, type: types.Type):
self.type = type
self.value = value
def accept(self, visitor, /):
return visitor.visit_value(self)
def __eq__(self, other):
return isinstance(other, Value) and self.type == other.type and self.value == other.value
def __repr__(self):
return f"Value({self.value}, {self.type})"
@typing.final
class Unary(Expr):
"""A unary expression.
Args:
op: The opcode describing which operation is being done.
operand: The operand of the operation.
type: The resolved type of the result.
"""
__slots__ = ("op", "operand")
class Op(enum.Enum):
"""Enumeration of the opcodes for unary operations.
The bitwise negation :data:`BIT_NOT` takes a single bit or an unsigned integer of known
width, and returns a value of the same type.
The logical negation :data:`LOGIC_NOT` takes an input that is implicitly coerced to a
Boolean, and returns a Boolean.
"""
# If adding opcodes, remember to add helper constructor functions in `constructors.py`.
# The opcode integers should be considered a public interface; they are used by
# serialisation formats that may transfer data between different versions of Qiskit.
BIT_NOT = 1
"""Bitwise negation. ``~operand``."""
LOGIC_NOT = 2
"""Logical negation. ``!operand``."""
def __str__(self):
return f"Unary.{super().__str__()}"
def __repr__(self):
return f"Unary.{super().__repr__()}"
def __init__(self, op: Unary.Op, operand: Expr, type: types.Type):
self.op = op
self.operand = operand
self.type = type
def accept(self, visitor, /):
return visitor.visit_unary(self)
def __eq__(self, other):
return (
isinstance(other, Unary)
and self.type == other.type
and self.op is other.op
and self.operand == other.operand
)
def __repr__(self):
return f"Unary({self.op}, {self.operand}, {self.type})"
@typing.final
class Binary(Expr):
"""A binary expression.
Args:
op: The opcode describing which operation is being done.
left: The left-hand operand.
right: The right-hand operand.
type: The resolved type of the result.
"""
__slots__ = ("op", "left", "right")
class Op(enum.Enum):
"""Enumeration of the opcodes for binary operations.
The bitwise operations :data:`BIT_AND`, :data:`BIT_OR` and :data:`BIT_XOR` apply to two
operands of the same type, which must be a single bit or an unsigned integer of fixed width.
The resultant type is the same as the two input types.
The logical operations :data:`LOGIC_AND` and :data:`LOGIC_OR` first implicitly coerce their
arguments to Booleans, and then apply the logical operation. The resultant type is always
Boolean.
The binary mathematical relations :data:`EQUAL`, :data:`NOT_EQUAL`, :data:`LESS`,
:data:`LESS_EQUAL`, :data:`GREATER` and :data:`GREATER_EQUAL` take unsigned integers
(with an implicit cast to make them the same width), and return a Boolean.
"""
# If adding opcodes, remember to add helper constructor functions in `constructors.py`
# The opcode integers should be considered a public interface; they are used by
# serialisation formats that may transfer data between different versions of Qiskit.
BIT_AND = 1
"""Bitwise "and". ``lhs & rhs``."""
BIT_OR = 2
"""Bitwise "or". ``lhs | rhs``."""
BIT_XOR = 3
"""Bitwise "exclusive or". ``lhs ^ rhs``."""
LOGIC_AND = 4
"""Logical "and". ``lhs && rhs``."""
LOGIC_OR = 5
"""Logical "or". ``lhs || rhs``."""
EQUAL = 6
"""Numeric equality. ``lhs == rhs``."""
NOT_EQUAL = 7
"""Numeric inequality. ``lhs != rhs``."""
LESS = 8
"""Numeric less than. ``lhs < rhs``."""
LESS_EQUAL = 9
"""Numeric less than or equal to. ``lhs <= rhs``"""
GREATER = 10
"""Numeric greater than. ``lhs > rhs``."""
GREATER_EQUAL = 11
"""Numeric greater than or equal to. ``lhs >= rhs``."""
def __str__(self):
return f"Binary.{super().__str__()}"
def __repr__(self):
return f"Binary.{super().__repr__()}"
def __init__(self, op: Binary.Op, left: Expr, right: Expr, type: types.Type):
self.op = op
self.left = left
self.right = right
self.type = type
def accept(self, visitor, /):
return visitor.visit_binary(self)
def __eq__(self, other):
return (
isinstance(other, Binary)
and self.type == other.type
and self.op is other.op
and self.left == other.left
and self.right == other.right
)
def __repr__(self):
return f"Binary({self.op}, {self.left}, {self.right}, {self.type})"
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Useful additional packages
import matplotlib.pyplot as plt
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.u(pi/2,pi/4,pi/8,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.p(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.id(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.x(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.y(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.z(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.h(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.s(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.sdg(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.t(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.tdg(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rx(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ry(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rz(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.cx(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cy(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cz(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ch(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.crz(pi/2,q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cp(pi/2,q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cu(pi/2, pi/2, pi/2, 0, q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.swap(q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.ccx(q[0], q[1], q[2])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cswap(q[0], q[1], q[2])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.measure(q, c)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.reset(q[0])
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.reset(q[0])
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.x(q[0]).c_if(c, 0)
qc.measure(q,c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q,c)
qc.x(q[0]).c_if(c, 0)
qc.measure(q,c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
# Initializing a three-qubit quantum state
import math
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0]
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.initialize(desired_vector, [q[0],q[1],q[2]])
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
job = backend.run(transpile(qc, backend))
qc_state = job.result().get_statevector(qc)
qc_state
state_fidelity(desired_vector,qc_state)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/declanmillar/qiskit-simulation
|
declanmillar
|
# General imports
import numpy as np
# SciPy minimizer routine
from scipy.optimize import minimize
# rustworkx graph library
import rustworkx as rx
from rustworkx.visualization import mpl_draw
# Pre-defined ansatz circuit, operator class and visualization tools
from qiskit import QuantumCircuit
from qiskit.circuit.library import QAOAAnsatz
from qiskit.quantum_info import SparsePauliOp
from qiskit.visualization import plot_distribution
# Qiskit Primitive imports
from qiskit.primitives import BaseEstimatorV2, BackendEstimatorV2 as Estimator
from qiskit.primitives import BackendSamplerV2 as Sampler
from qiskit.providers.fake_provider import GenericBackendV2
num_nodes = 5
# The edge syntax is (start, end, weight)
edges = [(0, 1, 1), (0, 2, 1), (0, 3, 1), (0, 4, 1)]
G = rx.PyGraph()
G.add_nodes_from(range(num_nodes))
G.add_edges_from(edges)
mpl_draw(
G, pos=rx.bipartite_layout(G, {0}), with_labels=True, node_color="#EE5396", font_color="#F4F4F4"
)
# Problem to Hamiltonian operator
hamiltonian = SparsePauliOp.from_list([("IIIZZ", 1), ("IIZIZ", 1), ("IZIIZ", 1), ("ZIIIZ", 1)])
# QAOA ansatz circuit
ansatz = QAOAAnsatz(hamiltonian, reps=2)
ansatz.decompose(reps=3).draw(output="mpl", style="iqp")
ansatz.decompose().draw(output="mpl", style="iqp")
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
backend = GenericBackendV2(hamiltonian.num_qubits)
target = backend.target
pm = generate_preset_pass_manager(target=target, optimization_level=3)
ansatz_isa = pm.run(ansatz)
ansatz_isa.draw(output="mpl", idle_wires=False, style="iqp")
hamiltonian_isa = hamiltonian.apply_layout(ansatz_isa.layout)
hamiltonian_isa
def cost_func(
params: np.ndarray,
ansatz: QuantumCircuit,
hamiltonian: SparsePauliOp,
estimator: BaseEstimatorV2,
) -> float:
"""Return estimate of energy from estimator
Parameters:
params: Array of ansatz parameters.
ansatz: Parameterized ansatz circuit.
hamiltonian: Operator representation of Hamiltonian.
estimator: Estimator primitive instance.
Returns:
Energy estimate
"""
pub = (ansatz, [hamiltonian], [params])
result = estimator.run(pubs=[pub]).result()
cost = result[0].data.evs[0]
return cost
# Configure estimator
estimator = Estimator(backend=backend)
estimator.options.default_shots = 10_000
# Configure sampler
sampler = Sampler(backend=backend)
sampler.options.default_shots = 10_000
x0 = 2 * np.pi * np.random.rand(ansatz_isa.num_parameters)
res = minimize(cost_func, x0, args=(ansatz_isa, hamiltonian_isa, estimator), method="COBYLA")
res
# Assign solution parameters to ansatz
qc = ansatz.assign_parameters(res.x)
# Add measurements to our circuit
qc.measure_all()
qc_isa = pm.run(qc)
qc_isa.draw(output="mpl", idle_wires=False, style="iqp")
result = sampler.run([qc_isa]).result()
samp_dist = result[0].data.meas.get_counts()
plot_distribution(samp_dist, figsize=(15, 5))
# Reverse 11110 to convert quantum result to classical solution
solution = [0, 1, 1, 1, 1]
mpl_draw(
G,
pos=rx.bipartite_layout(G, {0}),
with_labels=True,
node_color=["#EE5396" if kk else "#0F62FE" for kk in solution],
font_color="#F4F4F4",
)
import qiskit
qiskit.version.get_version_info()
import qiskit_aer
qiskit_aer.version.get_version_info()
|
https://github.com/cjsproject/qiskit_learning
|
cjsproject
|
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn
from sklearn import datasets
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumRegister
from qiskit import QuantumCircuit
from qiskit import Aer, execute
from math import pi,log
from qiskit import *
from qiskit.extensions import XGate, UnitaryGate
import tensorflow as tf
import cv2
#imported stuff from Weiwen's code
import torch
import torchvision
from torchvision import datasets
import torchvision.transforms as transforms
import torch.nn as nn
import shutil
import os
import time
import sys
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from skcuda.linalg import svd
from matplotlib import cm
import functools
%matplotlib inline
backend = Aer.get_backend('qasm_simulator')
print = functools.partial(print, flush=True)
interest_num = [3,6]
ori_img_size = 28 #original image is 28x28
img_size = 4 #size to downsize to (set to 28 if no downsizing)
# number of subprocesses to use for data loading
num_workers = 0
# how many samples per batch to load
batch_size = 1
inference_batch_size = 1
# Weiwen: modify the target classes starting from 0. Say, [3,6] -> [0,1]
def modify_target(target):
for j in range(len(target)):
for idx in range(len(interest_num)):
if target[j] == interest_num[idx]:
target[j] = idx
break
new_target = torch.zeros(target.shape[0],2)
for i in range(target.shape[0]):
if target[i].item() == 0:
new_target[i] = torch.tensor([1,0]).clone()
else:
new_target[i] = torch.tensor([0,1]).clone()
return target,new_target
def select_num(dataset,labels,interest_num):
valid_labels = np.array([])
for num in interest_num:
if valid_labels.size > 0:
valid_labels += labels== num
else:
valid_labels = labels == num
dataset = dataset[valid_labels]
labels = labels[valid_labels]
return (dataset,labels)
def nomalizatied(ori,fig):
row = fig['row']
col = fig['col']
transformed = []
for i in range(len(ori)):
transform = np.resize(ori[i],(row,col))
transformed.append(transform)
return transformed
################ Weiwen on 12-30-2020 ################
# Using torch to load MNIST data
######################################################
# convert data to torch.FloatTensor
transform = transforms.Compose([transforms.Resize((ori_img_size,ori_img_size)),
transforms.ToTensor()])
# Path to MNIST Dataset
(train_data,train_labels),(test_data,test_labels) = tf.keras.datasets.mnist.load_data()
(train_data,train_labels) = select_num(train_data,train_labels,interest_num)
(test_data,test_labels) = select_num(test_data,test_labels,interest_num)
#train_data = nomalizatied(train_data,{'row':4,'col':4})
#test_data = nomalizatied(test_data,{'row':4,'col':4})
train_data = train_data[:1000]
train_labels = train_labels[:1000]
train_data = torch.Tensor(train_data) # transform to torch tensor
train_labels = torch.Tensor(train_labels)
test_data = torch.Tensor(test_data)
test_labels = torch.Tensor(test_labels)
train = torch.utils.data.TensorDataset(train_data,train_labels) # create your datset
test =torch.utils.data.TensorDataset(test_data,test_labels)
u, s, v = svd(np.array(train_data[0:10]/255))
# prepare data loaders
train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size,
num_workers=num_workers, shuffle=False, drop_last=True)
test_loader = torch.utils.data.DataLoader(test, batch_size=inference_batch_size,
num_workers=num_workers, shuffle=False, drop_last=True)
class ToQuantumData(object):
def __call__(self, input_vec):
vec_len = len(input_vec)
input_matrix = np.zeros((vec_len, vec_len))
input_matrix[0] = input_vec
input_matrix = input_matrix.transpose()
u, s, v = np.linalg.svd(input_matrix)
output_matrix = np.dot(u, v)
output_data = output_matrix[:, 0].view()
return output_data
class ToQuantumMatrix(object):
def __call__(self, input_vec):
vec_len = len(input_vec)
input_matrix = np.zeros((vec_len, vec_len))
input_matrix[0] = input_vec
#print('new input vec')
input_matrix = input_matrix.transpose()
#print(input_vec)
u, s, v = np.linalg.svd(input_matrix)
output_matrix = np.dot(u, v)
return output_matrix
def data_pre_pro(vector):
# Converting classical data to quantum data
trans_to_vector = ToQuantumData()
trans_to_matrix = ToQuantumMatrix()
#print("Classical Data: {}".format(vector))
#print("Quantum Data: {}".format(trans_to_vector(vector)))
return trans_to_matrix(vector),trans_to_vector(vector)
def PaddingNeeded(n):
#check if n is a power of 2
num_decimal = np.log2(n)
num_int = int(-(-num_decimal//1)) #round any decimal number up
dims_needed = int(2**(num_int))
return dims_needed
def pad_zeros(data):
row = len(data)
col = len(data[0])
dims = max(row,col)
dims_needed = PaddingNeeded(dims)
return np.pad(data,((0,dims_needed-row),(0,dims_needed-col)),'constant', constant_values=(0,0))
from tqdm import tqdm
dataset = []
labels = []
# Use the first image from test loader as example
for batch_idx, (data, target) in tqdm(enumerate(train_loader)):
torch.set_printoptions(threshold=sys.maxsize)
np.set_printoptions(threshold=sys.maxsize)
data_grid = torchvision.utils.make_grid(data) #read the data from torch
np_data = data_grid.numpy() #convert tensor to numpy array
image = np.asarray(np_data[0] * 255, np.uint8)
im = Image.fromarray(image,mode="L")
im = im.resize((4,4),Image.BILINEAR)
np_image = np.asarray(im)*1/255 #normalize the resized image
data_pad = pad_zeros(np_image) #pad the data with zeros (if necessary) to make dimensionality a power of 2
np_1d = data_pad.ravel() #convert the padded data to 1-d array for encoding function
quantum_matrix,quantum_data = data_pre_pro(np_1d) #convert the data to unitary matrix
dataset.append(quantum_matrix)
labels.append(quantum_data)
for matrix in dataset:
print(is_unitary(np.matrix(matrix)))
train_labels_binary = train_labels == 3
train_labels_binary = np.array(train_labels_binary).astype('int') # 3 is Label 1, 6 is label 0
#------------------------------------------------------------------------------------------
#DATA ENCODING SECTION
#------------------------------------------------------------------------------------------
def is_unitary(m):
return np.allclose(np.eye(m.shape[0]), m.H * m)
def quantum_encode(quantum_matrix):
dims = len(quantum_matrix[0]) #dimensionality of data
q=int(np.log2(dims)) # Number of qubits = log2(Dimensionality of data) (could be a decimal number)
print(dims, 'classical bits encoded onto ', q, ' qubits')
c=1 #one classical bit
#Create quantum register and circuit
inp = QuantumRegister(q,"in_qbit")
circ = QuantumCircuit(inp)
# Add classical register
c_reg = ClassicalRegister(c,"reg")
circ.add_register(c_reg)
# From Listing 3: create auxiliary qubits
#aux = QuantumRegister(1,"aux_qbit")
#circ.add_register(aux)
circ.append(UnitaryGate(quantum_matrix, label="Input"), inp[0:q])
return circ, q
#encode the classicaL data into a quantum circuit (2^N parameters onto N qubits)
circ, q= quantum_encode(quantum_matrix)
print(circ)
# Using StatevectorSimulator from the Aer provider
simulator = Aer.get_backend('statevector_simulator')
result = execute(circ, simulator).result()
statevector = result.get_statevector(circ)
print("Data to be encoded: \n {}\n".format(quantum_data))
print("Data read from the circuit: \n {}".format(statevector))
#All functions needed for the functionality of the circuit simulation
def generate_and_save_images(model, epoch, test_input):
# Notice `training` is set to False.
# This is so all layers run in inference mode (batchnorm).
predictions = model(test_input, training=False)
fig = plt.figure(figsize=(4,4))
for i in range(predictions.shape[0]):
plt.subplot(4, 4, i+1)
dp = np.array((predictions[i] * 127.5) + 127.5).astype('uint8')
plt.imshow(dp)
plt.axis('off')
#plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))
plt.show()
def ran_ang():
#return np.pi/2
return np.random.rand()*np.pi
def single_qubit_unitary(circ_ident,qubit_index,values):
circ_ident.ry(values[0],qubit_index)
def dual_qubit_unitary(circ_ident,qubit_1,qubit_2,values):
circ_ident.ryy(values[0],qubit_1,qubit_2)
def controlled_dual_qubit_unitary(circ_ident,control_qubit,act_qubit,values):
circ_ident.cry(values[0],control_qubit,act_qubit)
#circ_ident.cry(values[0],act_qubit,control_qubit)
def traditional_learning_layer(circ_ident,num_qubits,values,style="Dual",qubit_start=1,qubit_end=5):
if style == "Dual":
for qub in np.arange(qubit_start,qubit_end):
single_qubit_unitary(circ_ident,qub,values[str(qub)])
for qub in np.arange(qubit_start,qubit_end-1):
dual_qubit_unitary(circ_ident,qub,qub+1,values[str(qub)+","+str(qub+1)])
elif style =="Single":
for qub in np.arange(qubit_start,qubit_end):
single_qubit_unitary(circ_ident,qub,values[str(qub)])
elif style=="Controlled-Dual":
for qub in np.arange(qubit_start,qubit_end):
single_qubit_unitary(circ_ident,qub,values[str(qub)])
for qub in np.arange(qubit_start,qubit_end-1):
dual_qubit_unitary(circ_ident,qub,qub+1,values[str(qub)+","+str(qub+1)])
for qub in np.arange(qubit_start,qubit_end-1):
controlled_dual_qubit_unitary(circ_ident,qub,qub+1,values[str(qub)+"--"+str(qub+1)])
'''
def data_loading_circuit(circ_ident,num_qubits,values,qubit_start=1,qubit_end=5):
k = 0
for qub in np.arange(qubit_start,qubit_end):
circ_ident.ry(values[k],qub)
k += 1
'''
def data_loading_circuit(circ_ident,quantum_matrix,qubit_start=1,qubit_end=5):
circ_ident.append(UnitaryGate(quantum_matrix, label="Input"), circ_ident.qubits[qubit_start:qubit_end])
def quantum_encode(quantum_matrix):
dims = len(quantum_matrix[0]) #dimensionality of data
q=int(np.log2(dims)) # Number of qubits = log2(Dimensionality of data) (could be a decimal number)
print(dims, 'classical bits encoded onto ', q, ' qubits')
c=1 #one classical bit
#Create quantum register and circuit
inp = QuantumRegister(q,"in_qbit")
circ = QuantumCircuit(inp)
# Add classical register
c_reg = ClassicalRegister(c,"reg")
circ.add_register(c_reg)
# From Listing 3: create auxiliary qubits
#aux = QuantumRegister(1,"aux_qbit")
#circ.add_register(aux)
circ.append(UnitaryGate(quantum_matrix, label="Input"), inp[0:q])
return circ, q
def swap_test(circ_ident,num_qubits):
num_swap = num_qubits//2
for i in range(num_swap):
circ_ident.cswap(0,i+1,i+num_swap+1)
circ_ident.h(0)
circ_ident.measure(0,0)
def init_random_variables(q,style):
trainable_variables = {}
if style=="Single":
for i in np.arange(1,q+1):
trainable_variables[str(i)] = [ran_ang()]
elif style=="Dual":
for i in np.arange(1,q+1):
trainable_variables[str(i)] = [ran_ang()]
if i != q:
trainable_variables[str(i)+","+str(i+1)] = [ran_ang()]
elif style=="Controlled-Dual":
for i in np.arange(1,q+1):
trainable_variables[str(i)] = [ran_ang()]
if i != q:
trainable_variables[str(i)+","+str(i+1)] = [ran_ang()]
trainable_variables[str(i)+"--"+str(i+1)] = [ran_ang()]
return trainable_variables
def get_probabilities(circ,counts=5000):
job = execute(circ, backend, shots=counts)
results = job.result().get_counts(circ)
try:
prob = results['0']/(results['1']+results['0'])
prob = (prob-0.5)
if prob <= 0.005:
prob = 0.005
else:
prob = prob*2
except:
prob = 1
return prob
# Define loss function. SWAP Test returns probability, so minmax probability is logical
def cost_function(p,yreal,trimming):
if yreal == 0:
return -np.log(p)
#return 1-p
elif yreal == 1:
return -np.log(1-p)
#return p
def generator_cost_function(p):
return -np.log(p)
def update_weights(init_value,lr,grad):
while lr*grad > 2*np.pi:
lr /= 10
print("Warning - Gradient taking steps that are very large. Drop learning rate")
weight_update = lr*grad
new_value = init_value
print("Updating with a new value of " + str(weight_update))
if new_value-weight_update > 2*np.pi:
new_value = (new_value-weight_update) - 2*np.pi
elif new_value-weight_update < 0:
new_value = (new_value-weight_update) + 2*np.pi
else:
new_value = new_value - weight_update
return new_value
# Define loss function. SWAP Test returns probability, so minmax probability is logical
def cost_function(p,yreal,trimming):
if yreal == 0:
return -np.log(p)
#return 1-p
elif yreal == 1:
return -np.log(1-p)
#return p
def generator_cost_function(p):
return -np.log(p)
def update_weights(init_value,lr,grad):
while lr*grad > 2*np.pi:
lr /= 10
print("Warning - Gradient taking steps that are very large. Drop learning rate")
weight_update = lr*grad
new_value = init_value
print("Updating with a new value of " + str(weight_update))
if new_value-weight_update > 2*np.pi:
new_value = (new_value-weight_update) - 2*np.pi
elif new_value-weight_update < 0:
new_value = (new_value-weight_update) + 2*np.pi
else:
new_value = new_value - weight_update
return new_value
QuantumCircuit(5,1).qubits
# ------------------------------------------------------------------------------------
# We treat the first n qubits are the discriminators state. n is always defined as the
# integer division floor of the qubit count.
# This is due to the fact that a state will always be k qubits, therefore the
# number of total qubits must be 2k+1. 2k as we need k for the disc, and k to represent
# either the other learned quantum state, or k to represent a data point
# then +1 to perform the SWAP test. Therefore, we know that we will always end up
# with an odd number of qubits. We take the floor to solve for k. 1st k represents
# disc, 2nd k represents the "loaded" state be it gen or real data
# ------------------------------------------------------------------------------------
# Use different function calls to represent training a GENERATOR or training a DISCRIMINATOR
# ------------------------------------------------------------------------------------
# THIS SECTION IS FOR THE ONLINE GENERATION OF QUANTUM CIRCUITS
def disc_fake_training_circuit(trainable_variables,key,key_value,diff=False,fwd_diff = False,Sample=False):
if Sample:
z = q//2
circ = QuantumCircuit(q,z)
else:
circ = QuantumCircuit(q,c)
circ.h(0)
if diff == True and fwd_diff == True:
trainable_variables[key][key_value] += par_shift
if diff == True and fwd_diff == False:
trainable_variables[key][key_value] -= par_shift
traditional_learning_layer(circ,q,trainable_variables,style=layer_style,qubit_start=1,qubit_end=q//2 +1)
traditional_learning_layer(circ,q,trainable_variables,style=layer_style,qubit_start=q//2 +1,qubit_end=q)
if Sample:
for qub in range(q//2):
circ.measure(q//2 + 1 + qub,qub)
else:
swap_test(circ,q)
if diff == True and fwd_diff == True:
trainable_variables[key][key_value] -= par_shift
if diff == True and fwd_diff == False:
trainable_variables[key][key_value] += par_shift
return circ
def disc_real_training_circuit(training_variables,data,key,key_value,diff,fwd_diff):
circ = QuantumCircuit(q,c)
circ.h(0)
if diff == True & fwd_diff == True:
training_variables[key][key_value] += par_shift
if diff == True & fwd_diff == False:
training_variables[key][key_value] -= par_shift
traditional_learning_layer(circ,q,training_variables,style=layer_style,qubit_start=1,qubit_end=q//2 +1)
data_loading_circuit(circ,data,qubit_start=q//2+1,qubit_end=q)
if diff == True & fwd_diff == True:
training_variables[key][key_value] -= par_shift
if diff == True & fwd_diff == False:
training_variables[key][key_value] += par_shift
swap_test(circ,q)
return circ
def generate_kl_divergence_hist(actual_data, epoch_results_data):
plt.clf() # clears current figure
sns.set()
kl_div_vec = []
for kl_dim in range(actual_data.shape[1]):
kl_div = kl_divergence(actual_data[:,kl_dim],epoch_results_data[:,kl_dim])
kl_div_vec.append(kl_div)
return kl_div_vec
def bin_data(dataset):
bins = np.zeros(10)
for point in dataset:
indx = int(str(point).split('.')[-1][0]) # The shittest way imaginable to extract the first val aft decimal
bins[indx] +=1
bins /= sum(bins)
return bins
def kl_divergence(p_dist, q_dist):
p = bin_data(p_dist)
q = bin_data(q_dist)
kldiv = 0
for p_point,q_point in zip(p,q):
kldiv += (np.sqrt(p_point) - np.sqrt(q_point))**2
kldiv = (1/np.sqrt(2))*kldiv**0.5
return kldiv
#return sum(p[i] * log2(p[i]/q[i]) for i in range(len(p))) # ?... are we confident in this...
# Checkpointing code
def save_variables(train_var,epoch,number):
with open(f"Epoch-{epoch}-Variables-numbers-{number}",'w') as file:
file.write(str(train_var))
def load_variables(epoch,number):
with open(f"Epoch-{epoch}-Variables-numbers-{number}",'r') as file:
texts = file.read()
return eval(texts)
train_var_1 = load_variables(11,6)
train_var_0 = load_variables(49,3)
train_var_1
z = disc_real_training_circuit(train_var,quantum_matrix,'1',0,diff=False,fwd_diff=False)
#z.append(UnitaryGate(quantum_matrix, label="Input"), z.qubits[10:20])
quantum_matrix
dataset = np.array(dataset)
labels = np.array(labels)
train_labels_binary = train_labels_binary[:dataset.shape[0]]
dataset = dataset[:5000]
train_labels_binary = train_labels_binary[:5000]
q=9# Number of qubits = Dimensionality of data = round up to even number = num qubits
c=1
circ = QuantumCircuit(q,c)
circ.h(0)
layer_style = "Controlled-Dual"
train_var_0 = init_random_variables(q//2,layer_style)
train_var_1 = init_random_variables(q//2,layer_style)
#train_var_2 = init_random_variables(q//2,layer_style)
tracked_d_loss = []
tracked_d_loss1 = []
gradients = []
learning_rate=0.015
train_iter = 50
corr = 0
wrong= 0
loss_d_to_real = 0
print('Starting Training')
print('-'*20)
print("train_var_0 training")
for epoch in range(train_iter):
start = time.time()
loss = [0,0]
par_shift = 0.5*np.pi/((1+epoch)**0.5)
for index,point in enumerate(dataset[train_labels_binary==0]):
for key,value in train_var_0.items():
if str(q//2 + 1 ) in key:
break
for key_value in range(len(value)):
forward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_0,point,key,key_value,diff=True,fwd_diff=True)))
backward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_0,point,key,key_value,diff=True,fwd_diff=False)))
df = 0.5*(forward_diff-backward_diff)
train_var_0[key][key_value] -= df*learning_rate
#print(f"Updated Variable {key}-({key_value}) by {-df*learning_rate}")
print('Time for Epoch {} is {} sec'.format(epoch+1,time.time()-start))
print("-"*20)
save_variables(train_var_0,epoch,3)
for epoch in range(train_iter):
start = time.time()
loss = [0,0]
par_shift = 0.5*np.pi/((1+epoch)**0.5)
for index,point in enumerate(dataset[train_labels_binary==1]):
for key,value in train_var_1.items():
if str(q//2 + 1 ) in key:
break
for key_value in range(len(value)):
forward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_1,point,key,key_value,diff=True,fwd_diff=True)))
backward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_1,point,key,key_value,diff=True,fwd_diff=False)))
df = 0.5*(forward_diff-backward_diff)
train_var_1[key][key_value] -= df*learning_rate
print('Time for Epoch {} is {} sec'.format(epoch+1,time.time()-start))
print("-"*20)
save_variables(train_var_1,epoch,6)
def is_unitary(m):
return np.allclose(np.eye(m.shape[0]), m.H * m)
is_unitary(np.matrix(quantum_matrix[0]))
corr = 0
wron = 0
for index,point in enumerate(dataset[train_labels_binary==1]):
p1 = get_probabilities(disc_real_training_circuit(train_var_0,point,key,key_value,diff=False,fwd_diff=False))
p2 = get_probabilities(disc_real_training_circuit(train_var_1,point,key,key_value,diff=False,fwd_diff=False))
if p1<p2:
corr +=1
else:
wron+=1
acc = corr/(corr+wron)
print(acc)
corr
wron
829
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit.circuit import Parameter
from qiskit import pulse
from qiskit.test.mock.backends.almaden import *
phase = Parameter('phase')
with pulse.build(FakeAlmaden()) as phase_test_sched:
pulse.shift_phase(phase, pulse.drive_channel(0))
phase_test_sched.instructions # ()
|
https://github.com/divyanshchoubisa/Quantum-Computing-Dynamic-Circuits
|
divyanshchoubisa
|
# Importing all the parts we will need.
from typing import List, Optional
from qiskit import transpile, QuantumCircuit, QuantumRegister, ClassicalRegister, Aer
from qiskit.providers.fake_provider import FakeManilaV2
from qiskit.visualization import plot_histogram
import warnings
warnings.filterwarnings("ignore")
import math
pi = math.pi
# Probability for a 000 message to contain one error:
p1 = 0.10
# Calculating the probability of a message containing 2 or 3 errors:
p3 = 3 * p1 * p1 * (1 - p1) + p1 * p1 * p1
print("Percent chance the 000 message has one error: {}".format(p1 * 100))
print("Percent chance the 000 message has 2 or 3 errors: {:.4f}".format(p3 * 100))
# Creating a simple decoder for the classical case
def create_decoder(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# Expect a bit being encoded in the first 3 qubits and decode it into the 4th qubit
# Make sure values of the first 3 qubit stays the same
qc = QuantumCircuit(qr, cr)
q0, q1, q2, q3 = qr
(c0,) = cr
####### your code goes here #######
qc.ccx(q0, q1, q3)
qc.ccx(q1, q2, q3)
qc.ccx(q0, q2, q3)
return qc
# We expect a bit being encoded in the first 3 qubits and decode it into the 4th qubit
qr = QuantumRegister(4)
cr = ClassicalRegister(1)
q0, q1, q2, q3 = qr
# To encode a 1. Change them to test the other encodings.
encoder = QuantumCircuit(qr, cr)
encoder.x(q0)
encoder.x(q1)
encoder.x(q2)
decoder = create_decoder(qr, cr)
qc1 = encoder.compose(decoder)
qc1.draw("mpl")
# Submit your circuit
from qc_grader.challenges.spring_2023 import grade_ex4a
grade_ex4a(create_decoder(qr, cr))
# Setup a base quantum circuit for our experiments
encoding = QuantumRegister(3)
stabilizer = QuantumRegister(2)
encoding_q0, encoding_q1, encoding_q2 = encoding
stabilizer_q0, stabilizer_q1 = stabilizer
# Results of the encoding
results = ClassicalRegister(3)
result_b0, result_b1, result_b2 = results
# For measuring the stabilizer
syndrome = ClassicalRegister(2)
syndrome_b0, syndrome_b1 = syndrome
# The actual qubit which is encoded
state = encoding[0]
# The ancillas used for encoding the state
ancillas = encoding[1:]
# Initializing
def initialize_circuit() -> QuantumCircuit:
return QuantumCircuit(encoding, stabilizer, results, syndrome)
initial_state = initialize_circuit()
initial_state.x(encoding[0])
initial_state.draw(output="mpl")
# Encoding using bit flip code
def encode_bit_flip(qc, state, ancillas):
qc.barrier(state, *ancillas)
for ancilla in ancillas:
qc.cx(state, ancilla)
return qc
# The circuit encoding our qubit
encoding_circuit = encode_bit_flip(initialize_circuit(), state, ancillas)
# The circuit including all parts so far
complete_circuit = initial_state.compose(encoding_circuit)
complete_circuit.draw(output="mpl")
# Decoding (doing the reverse)
def decode_bit_flip(qc, state, ancillas):
qc.barrier(state, *ancillas)
for ancilla in ancillas:
qc.cx(state, ancilla)
return qc
decoding_circuit = decode_bit_flip(initialize_circuit(), state, ancillas)
decoding_circuit.draw(output="mpl")
# Add functions such that the classical bits can be used to see which qubit is flipped in the case a single qubit is flipped.
# Use 2 classical bits for it.
# 0 = 00 = no qubit flipped
# 1 = 01 = first qubit (qubit 0) flipped
# 2 = 10 second qubit (qubit 1) flipped
# 3 = 11 = third qubit (qubit 2) flipped
def measure_syndrome_bit(qc, encoding, stabilizer):
qc.barrier()
encoding_q0, encoding_q1, encoding_q2 = encoding
stabilizer_q0, stabilizer_q1 = stabilizer
####### your code goes here #######
qc.cx(encoding_q0, stabilizer_q0)
qc.cx(encoding_q1, stabilizer_q1)
qc.cx(encoding_q2, stabilizer_q0)
qc.cx(encoding_q2, stabilizer_q1)
####### don't edit the code below #######
qc.barrier()
qc.measure(stabilizer, syndrome)
with qc.if_test((syndrome_b0, 1)):
qc.x(stabilizer_q0)
with qc.if_test((syndrome_b1, 1)):
qc.x(stabilizer_q1)
return qc
syndrome_circuit = measure_syndrome_bit(initialize_circuit(), encoding, stabilizer)
complete_circuit = initial_state.compose(encoding_circuit).compose(syndrome_circuit)
complete_circuit.draw("mpl")
# Submit your circuit
from qc_grader.challenges.spring_2023 import grade_ex4b
grade_ex4b(complete_circuit)
# Correct the errors, remember how we encoded the errors above!
def apply_correction_bit(qc, encoding, syndrome):
qc.barrier()
encoding_q0, encoding_q1, encoding_q2 = encoding
####### your code goes here #######
#qc.x(encoding_q0).c_if(syndrome, 1)
#qc.x(encoding_q1).c_if(syndrome, 1)
#qc.x(encoding_q2).c_if(syndrome, 2)
with qc.if_test((syndrome, 0b11)): #3
qc.x(encoding_q2)
with qc.if_test((syndrome, 0b10)): #2
qc.x(encoding_q1)
with qc.if_test((syndrome, 0b01)): #1
qc.x(encoding_q0)
qc.barrier(encoding)
return qc
correction_circuit = apply_correction_bit(initialize_circuit(), encoding, syndrome)
complete_circuit = (
initial_state.compose(encoding_circuit)
.compose(syndrome_circuit)
.compose(correction_circuit)
)
complete_circuit.draw(output="mpl")
def apply_final_readout(qc, encoding, results):
qc.barrier(encoding)
qc.measure(encoding, results)
return qc
measuring_circuit = apply_final_readout(initialize_circuit(), encoding, results)
complete_circuit = (
initial_state.compose(encoding_circuit)
.compose(syndrome_circuit)
.compose(correction_circuit)
.compose(decoding_circuit)
.compose(measuring_circuit)
)
complete_circuit.draw(output="mpl")
# Submit your circuit
from qc_grader.challenges.spring_2023 import grade_ex4c
grade_ex4c(complete_circuit)
# We first choose a simulator as our backend without any noise
backend = Aer.get_backend("qasm_simulator")
# We run the simulation and get the counts
counts = backend.run(complete_circuit, shots=1000).result().get_counts()
# And now we plot a histogram to see the possible outcomes and corresponding probabilities
plot_histogram(counts)
# We choose a simulator for Manila a 5 qubit device, includes errors
backend = FakeManilaV2()
# We run the simulation and get the counts
counts = backend.run(complete_circuit, shots=1000).result().get_counts()
# We plot a histogram to see the possible outcomes and corresponding probabilities
plot_histogram(counts)
qc3 = (
initial_state.compose(encoding_circuit)
.compose(syndrome_circuit)
.compose(decoding_circuit)
.compose(measuring_circuit)
)
# We choose a again FakeManila
backend = FakeManilaV2()
# let the simulation run
counts = backend.run(qc3, shots=1000).result().get_counts()
# and plot our results
plot_histogram(counts)
# Add some errors as defined above (only add errors to the encoding qubits)
def make_some_noise(qc, encoding, syndrome, error_percentage):
encoding_q0, encoding_q1, encoding_q2 = encoding
syndrome_b0, syndrome_b1 = syndrome
error_angle = 2*math.asin(math.sqrt(error_percentage/100))
####### your code goes here #######
qc.rx(error_angle, encoding_q0)
qc.rx(error_angle, encoding_q1)
qc.rx(error_angle, encoding_q2)
return qc
# Constructing a circuit with 10% error rate (for each of the encoding qubit)
noise_circuit = make_some_noise(initialize_circuit(), encoding, syndrome, 10)
noise_circuit.draw(output="mpl")
# Submit your circuit
from qc_grader.challenges.spring_2023 import grade_ex4d
grade_ex4d(noise_circuit)
qc4 = (
initial_state.compose(encoding_circuit)
.compose(noise_circuit)
.compose(syndrome_circuit)
.compose(correction_circuit)
.compose(decoding_circuit)
.compose(measuring_circuit)
)
# We choose again FakeManila
backend = FakeManilaV2()
# let the simulation run
counts = backend.run(qc4, shots=1000).result().get_counts()
# and plot our results
plot_histogram(counts)
from qiskit.circuit import IfElseOp
# Fill in a better layout to test!!
initial_layout = [0, 1, 2, 3, 4]
# We use Manila as our potential backend, since it has the wanted layout
backend = FakeManilaV2()
# Temporary workaround for fake backends. For real backends this is not required.
backend.target.add_instruction(IfElseOp, name="if_else")
# And now we transpile the circuit for the backend.
qc_transpiled = transpile(complete_circuit, backend, initial_layout=initial_layout)
qc_transpiled.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice
from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel
line = LineLattice(2)
fermi = FermiHubbardModel.uniform_parameters(line, 2.0, 4.0, 3.0)
print(fermi.second_q_ops()) # Note: the trailing `s`
from qiskit_nature.second_q.hamiltonians.lattices import LineLattice
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
line = LineLattice(2)
fermi = FermiHubbardModel(line.uniform_parameters(2.0, 4.0), 3.0)
print(fermi.second_q_op()) # Note: NO trailing `s`
import numpy as np
from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
fermi = FermiHubbardModel.from_parameters(interaction, 3.0)
print(fermi.second_q_ops()) # Note: the trailing `s`
import numpy as np
from qiskit_nature.second_q.hamiltonians.lattices import Lattice
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
lattice = Lattice.from_adjacency_matrix(interaction)
fermi = FermiHubbardModel(lattice, 3.0)
print(fermi.second_q_op()) # Note: NO trailing `s`
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice
from qiskit_nature.problems.second_quantization.lattice.models import IsingModel
line = LineLattice(2)
ising = IsingModel.uniform_parameters(line, 2.0, 4.0)
print(ising.second_q_ops()) # Note: the trailing `s`
from qiskit_nature.second_q.hamiltonians.lattices import LineLattice
from qiskit_nature.second_q.hamiltonians import IsingModel
line = LineLattice(2)
ising = IsingModel(line.uniform_parameters(2.0, 4.0))
print(ising.second_q_op()) # Note: NO trailing `s`
import numpy as np
from qiskit_nature.problems.second_quantization.lattice.models import IsingModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
ising = IsingModel.from_parameters(interaction)
print(ising.second_q_ops()) # Note: the trailing `s`
import numpy as np
from qiskit_nature.second_q.hamiltonians.lattices import Lattice
from qiskit_nature.second_q.hamiltonians import IsingModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
lattice = Lattice.from_adjacency_matrix(interaction)
ising = IsingModel(lattice)
print(ising.second_q_op()) # Note: NO trailing `s`
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 12345
from qiskit_machine_learning.datasets import ad_hoc_data
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=20,
test_size=5,
n=adhoc_dimension,
gap=0.3,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
import matplotlib.pyplot as plt
import numpy as np
def plot_features(ax, features, labels, class_label, marker, face, edge, label):
# A train plot
ax.scatter(
# x coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 0],
# y coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 1],
marker=marker,
facecolors=face,
edgecolors=edge,
label=label,
)
def plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total):
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
# A train plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "A train")
# B train plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B train")
# A test plot
plot_features(plt, test_features, test_labels, 0, "s", "b", "w", "A test")
# B test plot
plot_features(plt, test_features, test_labels, 1, "o", "r", "w", "B test")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset")
plt.show()
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
from qiskit.circuit.library import ZZFeatureMap
from qiskit.primitives import Sampler
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit_machine_learning.kernels import FidelityQuantumKernel
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
sampler = Sampler()
fidelity = ComputeUncompute(sampler=sampler)
adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map)
from sklearn.svm import SVC
adhoc_svc = SVC(kernel=adhoc_kernel.evaluate)
adhoc_svc.fit(train_features, train_labels)
adhoc_score_callable_function = adhoc_svc.score(test_features, test_labels)
print(f"Callable kernel classification test score: {adhoc_score_callable_function}")
adhoc_matrix_train = adhoc_kernel.evaluate(x_vec=train_features)
adhoc_matrix_test = adhoc_kernel.evaluate(x_vec=test_features, y_vec=train_features)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(
np.asmatrix(adhoc_matrix_train), interpolation="nearest", origin="upper", cmap="Blues"
)
axs[0].set_title("Ad hoc training kernel matrix")
axs[1].imshow(np.asmatrix(adhoc_matrix_test), interpolation="nearest", origin="upper", cmap="Reds")
axs[1].set_title("Ad hoc testing kernel matrix")
plt.show()
adhoc_svc = SVC(kernel="precomputed")
adhoc_svc.fit(adhoc_matrix_train, train_labels)
adhoc_score_precomputed_kernel = adhoc_svc.score(adhoc_matrix_test, test_labels)
print(f"Precomputed kernel classification test score: {adhoc_score_precomputed_kernel}")
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=adhoc_kernel)
qsvc.fit(train_features, train_labels)
qsvc_score = qsvc.score(test_features, test_labels)
print(f"QSVC classification test score: {qsvc_score}")
print(f"Classification Model | Accuracy Score")
print(f"---------------------------------------------------------")
print(f"SVC using kernel as a callable function | {adhoc_score_callable_function:10.2f}")
print(f"SVC using precomputed kernel matrix | {adhoc_score_precomputed_kernel:10.2f}")
print(f"QSVC | {qsvc_score:10.2f}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=0,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
# A label plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "B")
# B label plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for clustering")
plt.show()
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
adhoc_kernel = FidelityQuantumKernel(feature_map=adhoc_feature_map)
adhoc_matrix = adhoc_kernel.evaluate(x_vec=train_features)
plt.figure(figsize=(5, 5))
plt.imshow(np.asmatrix(adhoc_matrix), interpolation="nearest", origin="upper", cmap="Greens")
plt.title("Ad hoc clustering kernel matrix")
plt.show()
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score
adhoc_spectral = SpectralClustering(2, affinity="precomputed")
cluster_labels = adhoc_spectral.fit_predict(adhoc_matrix)
cluster_score = normalized_mutual_info_score(cluster_labels, train_labels)
print(f"Clustering score: {cluster_score}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=10,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement="linear")
qpca_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=feature_map)
matrix_train = qpca_kernel.evaluate(x_vec=train_features)
matrix_test = qpca_kernel.evaluate(x_vec=test_features, y_vec=test_features)
from sklearn.decomposition import KernelPCA
kernel_pca_rbf = KernelPCA(n_components=2, kernel="rbf")
kernel_pca_rbf.fit(train_features)
train_features_rbf = kernel_pca_rbf.transform(train_features)
test_features_rbf = kernel_pca_rbf.transform(test_features)
kernel_pca_q = KernelPCA(n_components=2, kernel="precomputed")
train_features_q = kernel_pca_q.fit_transform(matrix_train)
test_features_q = kernel_pca_q.fit_transform(matrix_test)
from sklearn.linear_model import LogisticRegression
logistic_regression = LogisticRegression()
logistic_regression.fit(train_features_q, train_labels)
logistic_score = logistic_regression.score(test_features_q, test_labels)
print(f"Logistic regression score: {logistic_score}")
fig, (q_ax, rbf_ax) = plt.subplots(1, 2, figsize=(10, 5))
plot_features(q_ax, train_features_q, train_labels, 0, "s", "w", "b", "A train")
plot_features(q_ax, train_features_q, train_labels, 1, "o", "w", "r", "B train")
plot_features(q_ax, test_features_q, test_labels, 0, "s", "b", "w", "A test")
plot_features(q_ax, test_features_q, test_labels, 1, "o", "r", "w", "A test")
q_ax.set_ylabel("Principal component #1")
q_ax.set_xlabel("Principal component #0")
q_ax.set_title("Projection of training and test data\n using KPCA with Quantum Kernel")
# Plotting the linear separation
h = 0.01 # step size in the mesh
# create a mesh to plot in
x_min, x_max = train_features_q[:, 0].min() - 1, train_features_q[:, 0].max() + 1
y_min, y_max = train_features_q[:, 1].min() - 1, train_features_q[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
predictions = logistic_regression.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
predictions = predictions.reshape(xx.shape)
q_ax.contourf(xx, yy, predictions, cmap=plt.cm.RdBu, alpha=0.2)
plot_features(rbf_ax, train_features_rbf, train_labels, 0, "s", "w", "b", "A train")
plot_features(rbf_ax, train_features_rbf, train_labels, 1, "o", "w", "r", "B train")
plot_features(rbf_ax, test_features_rbf, test_labels, 0, "s", "b", "w", "A test")
plot_features(rbf_ax, test_features_rbf, test_labels, 1, "o", "r", "w", "A test")
rbf_ax.set_ylabel("Principal component #1")
rbf_ax.set_xlabel("Principal component #0")
rbf_ax.set_title("Projection of training data\n using KernelPCA")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from qiskit import QuantumCircuit, compiler
from qiskit.transpiler.passes import Unroller
from qiskit.transpiler import PassManager
from qiskit import BasicAer
def apply_cu1(circuit, lam, c, t, use_basis_gates=True):
if use_basis_gates:
circuit.u1(lam / 2, c)
circuit.cx(c, t)
circuit.u1(-lam / 2, t)
circuit.cx(c, t)
circuit.u1(lam / 2, t)
else:
circuit.cu1(lam, c, t)
def apply_cu3(circuit, theta, phi, lam, c, t, use_basis_gates=True):
if use_basis_gates:
circuit.u1((lam - phi) / 2, t)
circuit.cx(c, t)
circuit.u3(-theta / 2, 0, -(phi + lam) / 2, t)
circuit.cx(c, t)
circuit.u3(theta / 2, phi, 0, t)
else:
circuit.cu3(theta, phi, lam, c, t)
# the u3 gate below is added to account for qiskit terra's cu3
# TODO: here or only in if=True clause?
if not np.isclose(float(phi + lam), 0.0):
circuit.u3(0, 0, (phi + lam) / 2, c)
def apply_ccx(circuit, a, b, c, use_basis_gates=True):
if use_basis_gates:
circuit.u2(0, np.pi, c)
circuit.cx(b, c)
circuit.u1(-np.pi / 4, c)
circuit.cx(a, c)
circuit.u1(np.pi / 4, c)
circuit.cx(b, c)
circuit.u1(-np.pi / 4, c)
circuit.cx(a, c)
circuit.u1(np.pi / 4, b)
circuit.u1(np.pi / 4, c)
circuit.u2(0, np.pi, c)
circuit.cx(a, b)
circuit.u1(np.pi / 4, a)
circuit.u1(-np.pi / 4, b)
circuit.cx(a, b)
else:
circuit.ccx(a, b, c)
def get_controlled_circuit(circuit, ctl_qubit, tgt_circuit=None, use_basis_gates=True):
"""
Construct the controlled version of a given circuit.
Args:
circuit (QuantumCircuit) : the base circuit
ctl_qubit (indexed QuantumRegister) : the control qubit to use
tgt_circuit (QuantumCircuit) : the target controlled circuit to be modified in-place
use_basis_gates (bool) : boolean flag to indicate whether or not only basis gates should be used
Return:
a QuantumCircuit object with the base circuit being controlled by ctl_qubit
"""
if tgt_circuit is not None:
qc = tgt_circuit
else:
qc = QuantumCircuit()
# get all the qubits and clbits
qregs = circuit.qregs
qubits = []
for qreg in qregs:
if not qc.has_register(qreg):
qc.add_register(qreg)
qubits.extend(qreg)
cregs = circuit.cregs
clbits = []
for creg in cregs:
if not qc.has_register(creg):
qc.add_register(creg)
clbits.extend(creg)
# get all operations from compiled circuit
unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id'])
pm = PassManager(passes=[unroller])
ops = compiler.transpile(
circuit,
BasicAer.get_backend('qasm_simulator'),
pass_manager=pm
).data
# process all basis gates to add control
if not qc.has_register(ctl_qubit[0]):
qc.add(ctl_qubit[0])
for op in ops:
if op[0].name == 'id':
apply_cu3(qc, 0, 0, 0, ctl_qubit, op[1][0], use_basis_gates=use_basis_gates)
elif op[0].name == 'u1':
apply_cu1(qc, *op[0].params, ctl_qubit, op[1][0], use_basis_gates=use_basis_gates)
elif op[0].name == 'u2':
apply_cu3(qc, np.pi / 2, *op[0].params, ctl_qubit, op[1][0], use_basis_gates=use_basis_gates)
elif op[0].name == 'u3':
apply_cu3(qc, *op[0].params, ctl_qubit, op[1][0], use_basis_gates=use_basis_gates)
elif op[0].name == 'cx':
apply_ccx(qc, ctl_qubit, *op[1], use_basis_gates=use_basis_gates)
elif op[0].name == 'measure':
qc.measure(op[1], op[2])
else:
raise RuntimeError('Unexpected operation {}.'.format(op['name']))
return qc
|
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)
return qc
def decode_message(qc):
qc.cx(1, 0)
### removed h gate ###
return qc
|
https://github.com/nahumsa/volta
|
nahumsa
|
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import unittest
from qiskit import QuantumCircuit, BasicAer
from qiskit.utils import QuantumInstance
from volta.swaptest import (
measure_swap_test,
measure_dswap_test,
measure_amplitude_transition_test,
)
class TestSWAPTest(unittest.TestCase):
def setUp(self):
self.qc1 = QuantumCircuit(1)
self.qc1.x(0)
self.qc2 = QuantumCircuit(1)
# self.backend = BasicAer.get_backend("qasm_simulator")
self.backend = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"), shots=10000
)
def test_10states(self):
want = 0.0
got = measure_swap_test(self.qc2, self.qc1, self.backend)
decimalPlace = 1
message = "Swap test not working for states 0 and 1."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_01states(self):
want = 0.0
got = measure_swap_test(self.qc1, self.qc2, self.backend)
decimalPlace = 1
message = "Swap test not working for states 0 and 1."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_00states(self):
want = 1.0
got = measure_swap_test(self.qc2, self.qc2, self.backend)
decimalPlace = 2
message = "Swap test not working for states 0 and 0."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_11states(self):
want = 1.0
got = measure_swap_test(self.qc1, self.qc1, self.backend)
decimalPlace = 2
message = "Swap test not working for states 1 and 1."
self.assertAlmostEqual(want, got, decimalPlace, message)
class TestDestructiveSWAPTest(unittest.TestCase):
def setUp(self):
self.qc1 = QuantumCircuit(1)
self.qc1.x(0)
self.qc2 = QuantumCircuit(1)
# self.backend = BasicAer.get_backend("qasm_simulator")
self.backend = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"), shots=10000
)
def test_10states(self):
want = 0.0
got = measure_dswap_test(self.qc2, self.qc1, self.backend)
decimalPlace = 1
message = "Swap test not working for states 0 and 1."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_01states(self):
want = 0.0
got = measure_dswap_test(self.qc1, self.qc2, self.backend)
decimalPlace = 1
message = "Swap test not working for states 0 and 1."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_00states(self):
want = 1.0
got = measure_dswap_test(self.qc2, self.qc2, self.backend)
decimalPlace = 2
message = "Swap test not working for states 0 and 0."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_11states(self):
want = 1.0
got = measure_dswap_test(self.qc1, self.qc1, self.backend)
decimalPlace = 2
message = "Swap test not working for states 1 and 1."
self.assertAlmostEqual(want, got, decimalPlace, message)
class TestAmplitudeTransitionTest(unittest.TestCase):
def setUp(self):
self.qc1 = QuantumCircuit(1)
self.qc1.x(0)
self.qc2 = QuantumCircuit(1)
self.backend = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"), shots=10000
)
def test_10states(self):
want = 0.0
got = measure_amplitude_transition_test(self.qc2, self.qc1, self.backend)
decimalPlace = 1
message = "Swap test not working for states 0 and 1."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_01states(self):
want = 0.0
got = measure_amplitude_transition_test(self.qc1, self.qc2, self.backend)
decimalPlace = 1
message = "Swap test not working for states 0 and 1."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_00states(self):
want = 1.0
got = measure_amplitude_transition_test(self.qc2, self.qc2, self.backend)
decimalPlace = 2
message = "Swap test not working for states 0 and 0."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_11states(self):
want = 1.0
got = measure_amplitude_transition_test(self.qc1, self.qc1, self.backend)
decimalPlace = 2
message = "Swap test not working for states 1 and 1."
self.assertAlmostEqual(want, got, decimalPlace, message)
if __name__ == "__main__":
unittest.main(argv=[""], verbosity=2, exit=False)
|
https://github.com/martynscn/Masters-Thesis-on-Quantum-Cryptography
|
martynscn
|
# This code has been adapted and modified from IBM Qiskit 2021 and also from https://github.com/ttlion/ShorAlgQiskit.
# It uses the implementation as contained in the work of Stephane Beauregard (https://arxiv.org/abs/quant-ph/0205095)
# Many thanks to IBM Qiskit team, Tiago Miguel (ttlion), Qubit by Qubit, Peter Shor and Stephane Beauregard.
from typing import Optional, Union, Tuple, List
import math
import array
import fractions
import logging
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, execute, IBMQ, transpile,BasicAer, Aer, assemble
from qiskit.circuit import Gate, Instruction, ParameterVector
from qiskit.circuit.library import QFT
from qiskit.providers import BaseBackend, Backend
from qiskit.quantum_info import partial_trace
from qiskit.utils import summarize_circuits
from qiskit.utils.arithmetic import is_power
from qiskit.utils.validation import validate_min
from qiskit.utils.quantum_instance import QuantumInstance
import qiskit.visualization
from qiskit.providers.aer import QasmSimulator
from datetime import datetime
import csv
# provider = IBMQ.enable_account("PUT TOKEN HERE")
backend = QasmSimulator()
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all" #"last_expr" or "all"
def get_angles(a: int, n) -> np.ndarray:
# """Calculates the array of angles to be used in the addition in Fourier Space."""
s = bin(int(a))[2:].zfill(n + 1)
angles = np.zeros([n + 1])
for i in range(0, n + 1):
for j in range(i, n + 1):
if s[j] == '1':
angles[n - i] += math.pow(2, -(j - i))
angles[n - i] *= np.pi
return angles[::-1]
# This returns the angles in the opposite order
def my_create_QFT(qft_num_qubits,approximation_degree: int = 0,do_swaps: bool = False,insert_barriers: bool = True, name: str = 'qft'):
# up_reg = QuantumRegister(size = qft_num_qubits, name="aux")
circuit_qft = QuantumCircuit(qft_num_qubits)
i=qft_num_qubits-1
while i>=0:
# circuit_qft.h(up_reg[i])
circuit_qft.h(i)
j=i-1
while j>=0:
if (np.pi)/(pow(2,(i-j))) > approximation_degree:
# circuit_qft.cu1( (np.pi)/(pow(2,(i-j))) , up_reg[i] , up_reg[j] )
circuit_qft.cu1( (np.pi)/(pow(2,(i-j))) , i , j )
j=j-1
if insert_barriers:
circuit_qft.barrier()
i=i-1
""" If specified, apply the Swaps at the end """
if do_swaps:
i=0
while i < ((qft_num_qubits-1)/2):
# circuit_qft.swap(up_reg[i], up_reg[qft_num_qubits-1-i])
circuit_qft.swap(i, qft_num_qubits-1-i)
i=i+1
circuit_qft.name = "QFT"
return circuit_qft
def my_create_inverse_QFT(qft_num_qubits,approximation_degree: int = 0,do_swaps: bool = False,insert_barriers: bool = True, name: str = 'iqft'):
my_create_QFT_circuit = my_create_QFT(qft_num_qubits,approximation_degree,do_swaps,insert_barriers, name)
my_create_inverse_QFT_circuit = my_create_QFT_circuit.inverse()
my_create_inverse_QFT_circuit.name = "QFT†"
return my_create_inverse_QFT_circuit
def phi_add_gate(size: int, angles: Union[np.ndarray, ParameterVector]) -> Gate:
# """Gate that performs addition by a in Fourier Space."""
circuit = QuantumCircuit(size, name="phi_add")
for i, angle in enumerate(angles):
circuit.p(angle, i)
return circuit.to_gate()
def double_controlled_phi_add_mod_N(num_qubits: int, angles: Union[np.ndarray, ParameterVector],reg_size, a, N, n) -> QuantumCircuit:
# """Creates a circuit which implements double-controlled modular addition by a."""
circuit = QuantumCircuit(num_qubits, name="ccphi_add_mod_N")
ctl_up = 0
ctl_down = 1
ctl_aux = 2
# get qubits from aux register, omitting the control qubit
qubits = range(3, num_qubits)
# store the gates representing addition/subtraction by a in Fourier Space
phi_add_a = phi_add_gate(len(qubits), angles)
iphi_add_a = phi_add_a.inverse()
phi_add_N = phi_add_gate(reg_size - 1, get_angles(N, n))
iphi_add_N = phi_add_N.inverse()
circuit.append(phi_add_a.control(2), [ctl_up, ctl_down, *qubits])
circuit.append(iphi_add_N, qubits)
qft = QFT(n + 1).to_instruction()
# qft = my_create_QFT(n + 1).to_instruction()
iqft = QFT(n + 1).inverse().to_instruction()
# iqft = my_create_inverse_QFT(n + 1).to_instruction()
circuit.append(iqft, qubits)
circuit.cx(qubits[0], ctl_aux)
circuit.append(qft, qubits)
circuit.append(phi_add_N, qubits)
circuit.append(iphi_add_a.control(2), [ctl_up, ctl_down, *qubits])
circuit.append(iqft, qubits)
circuit.x(qubits[0])
circuit.cx(qubits[0], ctl_aux)
circuit.x(qubits[0])
circuit.append(qft, qubits)
circuit.append(phi_add_a.control(2), [ctl_up, ctl_down, *qubits])
return circuit
# """Circuit that implements single controlled modular multiplication by a"""
def controlled_multiple_mod_N(num_qubits: int, N: int, a: int, n, aux_reg_size):
# """Implements modular multiplication by a as an instruction."""
circuit = QuantumCircuit(
num_qubits,
# name="multiply_by_{}_mod_{}".format(a % N, N),
name=r"${0}^{{{1}^{{{2}}}}} mod{3}$".format(2,2,int(math.log(math.log(a,2),2)), N)
)
# label = r"${0}^{{{1}^{{{2}}}}} mod{3}$".format("†","y")
down = circuit.qubits[1: n + 1]
aux = circuit.qubits[n + 1:]
qubits = [aux[i] for i in reversed(range(n + 1))]
ctl_up = 0
ctl_aux = aux[-1]
angle_params = ParameterVector("angles", length=len(aux) - 1)
double_controlled_phi_add = double_controlled_phi_add_mod_N(
len(aux) + 2, angle_params, aux_reg_size, a, N, n
)
idouble_controlled_phi_add = double_controlled_phi_add.inverse()
qft_circuit = QFT(n + 1).to_instruction()
# qft_circuit = my_create_QFT(n + 1).to_instruction()
iqft_circuit = QFT(n + 1).inverse().to_instruction()
# iqft_circuit = my_create_inverse_QFT(n + 1).to_instruction()
circuit.append(qft_circuit, qubits)
# perform controlled addition by a on the aux register in Fourier space
for i, ctl_down in enumerate(down):
a_exp = (2 ** i) * a % N
angles = get_angles(a_exp, n)
bound = double_controlled_phi_add.assign_parameters({angle_params: angles})
circuit.append(bound, [ctl_up, ctl_down, ctl_aux, *qubits])
circuit.append(iqft_circuit, qubits)
# perform controlled subtraction by a in Fourier space on both the aux and down register
for j in range(n):
circuit.cswap(ctl_up, down[j], aux[j])
circuit.append(qft_circuit, qubits)
a_inv = modinv(a, N)
for i in reversed(range(len(down))):
a_exp = (2 ** i) * a_inv % N
angles = get_angles(a_exp, n)
bound = idouble_controlled_phi_add.assign_parameters({angle_params: angles})
circuit.append(bound, [ctl_up, down[i], ctl_aux, *qubits])
circuit.append(iqft_circuit, qubits)
return circuit
def modinv(a: int, m: int) -> int:
# """Returns the modular multiplicative inverse of a with respect to the modulus m."""
def egcd(a: int, b: int) -> Tuple[int, int, int]:
if a == 0:
return b, 0, 1
else:
g, y, x = egcd(b % a, a)
return g, x - (b // a) * y, y
g, x, _ = egcd(a, m)
if g != 1:
raise ValueError("The greatest common divisor of {} and {} is {}, so the "
"modular inverse does not exist.".format(a, m, g))
return x % m
def get_factors(N: int, a: int, measurement: str) -> Optional[List[int]]:
# """Apply the continued fractions to find r and the gcd to find the desired factors."""
x_final = int(measurement, 2)
#print('In decimal, x_final value for this result is: {}.'.format(x_final))
if x_final <= 0:
fail_reason = 'x_final value is <= 0, there are no continued fractions.'
else:
fail_reason = None
#print('Running continued fractions for this case.')
# Calculate T and x/T
T_upper = len(measurement)
T = pow(2, T_upper)
x_over_T = x_final / T ## this is our theta
# Cycle in which each iteration corresponds to putting one more term in the
# calculation of the Continued Fraction (CF) of x/T
# Initialize the first values according to CF rule
i = 0
b = array.array('i')
t = array.array('f')
b.append(math.floor(x_over_T))
t.append(x_over_T - b[i])
exponential = 0.0
while i < N and fail_reason is None:
# From the 2nd iteration onwards, calculate the new terms of the CF based on the previous terms as the rule suggests
if i > 0:
try:
b_temp = math.floor(1 / t[i - 1])
except ZeroDivisionError as err:
b_temp = 0
b.append(b_temp)
try:
t_temp = (1 / t[i - 1]) - b[i]
except ZeroDivisionError as err:
t_temp = 0
t.append(t_temp) # type: ignore
# Calculate the denominator of the CF using the known terms
denominator = calculate_continued_fraction(b)
# Increment i for next iteration
i += 1
if denominator % 2 == 1:
#print('Odd denominator, will try next iteration of continued fractions.')
continue
# Denominator is even, try to get factors of N. Get the exponential a^(r/2)
if denominator < 1000:
try:
exponential = pow(a, denominator / 2)
except OverflowError as err:
exponential = 999999999
# Check if the value is too big or not
if exponential > 1000000:
if exponential == 999999999:
fail_reason = 'OverflowError'
else:
fail_reason = 'denominator of continued fraction is too big (> 10^9).'
else:
# The value is not too big, get the right values and do the proper gcd()
putting_plus = int(exponential + 1)
putting_minus = int(exponential - 1)
one_factor = math.gcd(putting_plus, N)
other_factor = math.gcd(putting_minus, N)
# Check if the factors found are trivial factors or are the desired factors
if any(factor in {1, N} for factor in (one_factor, other_factor)):
#print('Found just trivial factors, not good enough.')
# Check if the number has already been found, (use i - 1 because i was already incremented)
if t[i - 1] == 0:
fail_reason = 'the continued fractions found exactly x_final/(2^(2n)).'
else:
return sorted((one_factor, other_factor))
# Search for factors failed, write the reason for failure to the debug logs
#print('Cannot find factors from measurement {0} because {1}'.format(measurement, fail_reason or 'it took too many attempts.'))
return None
def calculate_continued_fraction(b: array.array) -> int:
# """Calculate the continued fraction of x/T from the current terms of expansion b."""
x_over_T = 0
for i in reversed(range(len(b) - 1)):
x_over_T = 1 / (b[i + 1] + x_over_T)
x_over_T += b[0]
frac = fractions.Fraction(x_over_T).limit_denominator()
#print('Approximation number %s of continued fractions:'.format(len(b)))
#print("Numerator:{0} \t\t Denominator: {1}.".format(frac.numerator, frac.denominator))
return frac.denominator
def process_results(sim_result, circuit, shots, N, a, n):
counts_result = sim_result.get_counts(circuit)
total_counts = len(counts_result)
counts_result_sorted = sorted(counts_result.items(), key=lambda x: x[1], reverse=True)
# """ Print info to user from the simulation results """
# print('Printing the various results followed by how many times they happened (out of the {} cases):\n'.format(shots))
counts_result_keys = list(counts_result.keys())
counts_result_values = list(counts_result.values())
#i=0
#while i < len(counts_result):
#print('Result \"{0}\" happened {1} times out of {2}\n'.format(list(sim_result.get_counts().keys())[i],list(sim_result.get_counts().values())[i],shots))
#print('Result \"{0}\" happened {1} times out of {2}\n'.format(counts_result_keys[i],counts_result_values[i],shots))
#i=i+1
prob_success=0
prob_failure=0
result_successful_counts = 0
result_failure_counts = 0
# len(counts_result_sorted)
# For each simulation result, print proper info to user and try to calculate the factors of N
#for measurement in counts_result_keys:
for measurement, frequency in counts_result_sorted:
# Get the x_final value from the final state qubits
x_value = int(measurement, 2)
#prob_this_result = 100 * ( int(counts_result[measurement] ) ) / (shots)
prob_this_result = 100 * frequency/shots
# print("------> Analyzing result {0}. This result happened in {1:.4f} % of all cases\nIn decimal, x_final value for this result is: {2}".format(measurement,prob_this_result,x_value))
factors = get_factors(N, a, measurement)
if factors:
prob_success = prob_success + prob_this_result
# print('Found factors {0} from measurement {1} which is {2} in decimal.\n'.format(factors, measurement, x_value))
result_successful_counts = result_successful_counts + 1
if factors not in result_factors:
result_factors.append(factors)
elif not factors:
prob_failure = prob_failure + prob_this_result
result_failure_counts = result_failure_counts + 1
return [result_factors, prob_success, prob_failure, total_counts, result_successful_counts,result_failure_counts]
def my_shor(a,N,shots):
start_time_number = datetime.now()
start_time = start_time_number.strftime("%H:%M:%S")
summary_result = dict()
validate_min('N', N, 3)
validate_min('a', a, 2)
if N < 1 or N % 2 == 0:
raise ValueError('The input needs to be an odd integer greater than 1.')
if a >= N or math.gcd(a, N) != 1:
raise ValueError('The integer a needs to satisfy a < N and gcd(a, N) = 1.')
n = math.ceil(math.log(N,2))
global result_factors
result_factors = []
tf, b, p = is_power(N, return_decomposition=True)
if tf:
print('The input integer is a power: {0}={1}^{2}.'.format(N, b, p))
result_factors.append(b)
# """auxilliary quantum register used in addition and multiplication"""
aux_reg = QuantumRegister(size = n+2, name="aux_reg")
up_reg = QuantumRegister(2*n, name = "up_reg")
# """quantum register where the multiplications are made"""
down_reg = QuantumRegister(n, name = "down_reg")
# """classical register where the measured values of the QFT are stored"""
up_classic = ClassicalRegister(2*n, name="up_classic")
# """ Create Quantum Circuit """
circuit = QuantumCircuit(up_reg ,down_reg ,aux_reg, up_classic, name="Shor circuit(N={}, a={})".format(N, a))
# phi_add_N_gate = phiADD(circuit,q,a,N,inv)
phi_add_N_gate = phi_add_gate(aux_reg.size - 1, get_angles(N,n))
iphi_add_N_gate = phi_add_N_gate.inverse()
# """ Initialize down register to 1 and create maximal superposition in top register """
circuit.h(up_reg)
circuit.x(down_reg[0])
# circuit.draw(filename = "shor_standard_QFT")
# """ Apply the multiplication gates as showed in the report in order to create the exponentiation """
for i, ctl_up in enumerate(up_reg): # type: ignore
a_aux = int(pow(a, pow(2, i)))
controlled_multiple_mod_N_circuit = controlled_multiple_mod_N(
len(down_reg) + len(aux_reg) + 1, N, a_aux,n,aux_reg.size
)
controlled_multiple_mod_N_result = controlled_multiple_mod_N_circuit.to_instruction()
circuit.append(
controlled_multiple_mod_N_result, [ctl_up, *down_reg, *aux_reg]
)
# circuit.draw()
iqft = QFT(len(up_reg)).inverse().to_instruction()
# iqft = my_create_inverse_QFT(len(up_reg)).to_instruction()
# iqft = my_create_inverse_QFT(len(up_reg), insert_barriers = False).to_gate(label = r"$QFT^{{{0}}}$".format("†"))
circuit.append(iqft, up_reg)
circuit.measure(up_reg, up_classic)
# circuit.draw(filename = "shor_standard_QFT_final_circuit",fold = -1 )
# print(summarize_circuits(circuit))
# circuit.draw()
print('Running with N={0} and a={1} with number of qubits n={2}'.format(N, a, 4*n + 2))
qc_compiled = transpile(circuit, backend, optimization_level = 3)
job_sim_1 = backend.run(qc_compiled, shots=shots)
sim_result=job_sim_1.result()
# counts_result = sim_result.get_counts(circuit)
# len(counts_result)
# measurement_plot = qiskit.visualization.plot_histogram(counts_result,figsize=(20, 12) ,number_to_keep = 30,bar_labels=True, title = "Measurement results from shor_standard_QFT circuit variant" )
# measurement_plot.savefig("shor_standard_QFT_measurement")
# measurement_plot
processed_result = process_results(sim_result, circuit, shots, N, a, n)
end_time_number = datetime.now()
end_time = end_time_number.strftime("%H:%M:%S")
duration = end_time_number - start_time_number
print("Current Start Time =", start_time)
print(processed_result)
print("Current End Time =", end_time)
circuit_count_ops = circuit.count_ops()
circuit_decomposed = circuit.decompose()
circuit_decomposed_count_ops = circuit_decomposed.count_ops()
qc_compiled_count_ops = qc_compiled.count_ops()
summary_result["num_qubits"] = n
summary_result["Number(N)"] = N
summary_result["a"] = a
summary_result["start_time"] = start_time
summary_result["end_time"] = end_time
summary_result["duration"] = duration
summary_result["result_factors"] = processed_result[0]
summary_result["prob_success"] = processed_result[1]
summary_result["prob_failure"] = processed_result[2]
summary_result["total_counts"] = processed_result[3]
summary_result["result_successful_counts"] = processed_result[4]
summary_result["result_failure_counts"] = processed_result[5]
summary_result["circuit_width"] = circuit.width()
summary_result["circuit_depth"] = circuit.depth()
summary_result["circuit_size"] = circuit.size()
summary_result["circuit_num_nonlocal_gates"] = circuit.num_nonlocal_gates()
summary_result["circuit_num_ancillas"] = circuit.num_ancillas
summary_result["circuit_num_clbits"] = circuit.num_clbits
summary_result["circuit_num_qubits"] = circuit.num_qubits
summary_result["circuit_num_ancillas"] = circuit.num_ancillas
summary_result["circuit_num_of_count_ops"] = len(circuit_count_ops)
summary_result["circuit_num_of_x"] = circuit_count_ops.get('x')
summary_result["circuit_num_of_measure"] = circuit_count_ops.get('measure')
summary_result["circuit_num_of_h"] = circuit_count_ops.get('h')
summary_result["circuit_num_of_cswap"] = circuit_count_ops.get('cswap')
summary_result["circuit_num_of_swap"] = circuit_count_ops.get('swap')
summary_result["circuit_num_of_cx"] = circuit_count_ops.get('cx')
summary_result["circuit_num_of_toffoli"] = circuit_count_ops.get('toffoli')
summary_result["circuit_num_of_p"] = circuit_count_ops.get('p')
summary_result["circuit_num_of_t"] = circuit_count_ops.get('t')
summary_result["circuit_decomposed_width"] = circuit_decomposed.width()
summary_result["circuit_decomposed_depth"] = circuit_decomposed.depth()
summary_result["circuit_decomposed_size"] = circuit_decomposed.size()
summary_result["circuit_decomposed_num_nonlocal_gates"] = circuit_decomposed.num_nonlocal_gates()
summary_result["circuit_decomposed_num_ancillas"] = circuit_decomposed.num_ancillas
summary_result["circuit_decomposed_num_clbits"] = circuit_decomposed.num_clbits
summary_result["circuit_decomposed_num_qubits"] = circuit_decomposed.num_qubits
summary_result["circuit_decomposed_num_ancillas"] = circuit_decomposed.num_ancillas
summary_result["circuit_decomposed_num_of_count_ops"] = len(circuit_decomposed_count_ops)
summary_result["circuit_decomposed_num_of_x"] = circuit_decomposed_count_ops.get('x')
summary_result["circuit_decomposed_num_of_measure"] = circuit_decomposed_count_ops.get('measure')
summary_result["circuit_decomposed_num_of_h"] = circuit_decomposed_count_ops.get('h')
summary_result["circuit_decomposed_num_of_cswap"] = circuit_decomposed_count_ops.get('cswap')
summary_result["circuit_decomposed_num_of_swap"] = circuit_decomposed_count_ops.get('swap')
summary_result["circuit_decomposed_num_of_cx"] = circuit_decomposed_count_ops.get('cx')
summary_result["circuit_decomposed_num_of_toffoli"] = circuit_decomposed_count_ops.get('toffoli')
summary_result["circuit_decomposed_num_of_p"] = circuit_decomposed_count_ops.get('p')
summary_result["circuit_decomposed_num_of_t"] = circuit_decomposed_count_ops.get('t')
summary_result["qc_compiled_width"] = qc_compiled.width()
summary_result["qc_compiled_depth"] = qc_compiled.depth()
summary_result["qc_compiled_size"] = qc_compiled.size()
summary_result["qc_compiled_num_nonlocal_gates"] = qc_compiled.num_nonlocal_gates()
summary_result["qc_compiled_num_ancillas"] = qc_compiled.num_ancillas
summary_result["qc_compiled_num_clbits"] = qc_compiled.num_clbits
summary_result["qc_compiled_num_qubits"] = qc_compiled.num_qubits
summary_result["qc_compiled_num_ancillas"] = qc_compiled.num_ancillas
summary_result["qc_compiled_num_of_count_ops"] = len(qc_compiled_count_ops)
summary_result["qc_compiled_num_of_x"] = qc_compiled_count_ops.get('x')
summary_result["qc_compiled_num_of_measure"] = qc_compiled_count_ops.get('measure')
summary_result["qc_compiled_num_of_h"] = qc_compiled_count_ops.get('h')
summary_result["qc_compiled_num_of_cswap"] = qc_compiled_count_ops.get('cswap')
summary_result["qc_compiled_num_of_swap"] = qc_compiled_count_ops.get('swap')
summary_result["qc_compiled_num_of_cx"] = qc_compiled_count_ops.get('cx')
summary_result["qc_compiled_num_of_toffoli"] = qc_compiled_count_ops.get('toffoli')
summary_result["qc_compiled_num_of_p"] = qc_compiled_count_ops.get('p')
summary_result["qc_compiled_num_of_t"] = qc_compiled_count_ops.get('t')
return summary_result
# Run for just a single number N
%%time
N = 33
shots = 1024
global result_factors
all_summary_result_temp = []
for random_a in range(16, 17):
if math.gcd(random_a,N) > 1:
continue
a = random_a
summary_result = my_shor(a,N,shots)
print("Finished running for a = {} and N = {}\n".format(a, N))
all_summary_result_temp.append(summary_result)
summary_result_list = []
for key, value in summary_result.items():
summary_result_list.append([key,value])
summary_result_list
with open("a({0})_N({1})_standard.csv".format(a, N), 'a') as myfile:
write = csv.writer(myfile)
#write.writerow(fields)
write.writerows(summary_result_list)
all_summary_result_temp
# Run for many numbers N.
%%time
shots = 1024
global result_factors
all_summary_result = []
for N in [15, 21, 33, 35, 39, 51, 55, 57]:
for a in range(2, N):
if math.gcd(a,N) > 1:
continue
print("Beginning running for a = {} and N = {}".format(a, N))
summary_result = my_shor(a,N,shots)
print("Finished running for a = {} and N = {}\n\n".format(a, N))
all_summary_result.append(summary_result)
all_summary_result
%qiskit_copyright
|
https://github.com/BoxiLi/qiskit-CR-calibration
|
BoxiLi
|
import logging
from copy import deepcopy
import numpy as np
from numpy import pi
from qiskit.circuit import Gate
from qiskit import transpile
from qiskit.transpiler import InstructionProperties
from qiskit_utilities import (
save_job_data,
setup_logger,
retrieve_expdata,
get_cr_schedule,
iy_drag_calibration,
get_default_cr_params,
read_calibration_data,
iterative_cr_pulse_calibration,
create_echoed_cnot_schedule,
initilize_qiskit_dynamics_backend
)
session = None # qiskit runtime session
# Setup a logging system.
setup_logger(filename=None, level=logging.INFO, stdout=True)
logger = logging.getLogger("qiskit_utilities")
# Create a qiskit-dynamics backend with two Transmon, see fake_backend.py for detail.
# fidelity
f0 = 5.188339840468758e9
f1 = 5.079647268847252e9
# anharmonicity
a0 = -0.341931669003125e9
a1 = -0.343248404293835e9
backend = initilize_qiskit_dynamics_backend(f0, f1, a0, a1, J=0.003e9)
# Operating qubits
QUBIT_C, QUBIT_T = (0, 1)
# Compute the sampling time steps for the CR tomography experiments
if backend.name == 'DynamicsBackend':
amp = 2 * pi * 0.04
cr_times = np.arange(16*16, 1440*3, 32*4, dtype=int)
duration = 720 # Used for plotting only, not tomography.
else:
amp = get_default_cr_params(backend, QUBIT_C, QUBIT_T)[0]
duration = backend.defaults().instruction_schedule_map.get("cx", (QUBIT_C, QUBIT_T)).duration/16 * 4
cr_times = 16 * np.arange(16, duration + 16, duration//30, dtype=int)
## Use the default Gaussian shape with 28ns ramping.
gate_name = "CR-default" # This name will be used to identify the calibration
# CR drive
cr_params = {
"duration": int(duration), # only for plotting
"sigma": 64, # The ramping time is hard coded to be 2 * sigma
"amp": amp,
"angle": 0.,
}
# Target qubit compensation drive
ix_params = {
"duration": int(duration), # only for plotting
"sigma": 64,
"amp": 0.,
"angle": 0.,
}
initial_calibration_data = {
"cr_params": cr_params,
"ix_params": ix_params,
"frequency_offset": 0.,
}
get_cr_schedule((QUBIT_C, QUBIT_T), backend, cr_params=cr_params, ix_params=ix_params).draw()
iterative_cr_pulse_calibration(
(QUBIT_C, QUBIT_T),
backend,
initial_calibration_data=initial_calibration_data,
cr_times=cr_times,
session=session,
gate_name=gate_name,
verbose=True,
restart=True, # fresh start
threshold_MHz=0.015,
max_repeat=3,
shots=512,
mode="CR",
)
iy_drag_calibration((QUBIT_C, QUBIT_T), backend, gate_name, cr_times, session, verbose=True)
from qiskit_experiments.library import ProcessTomography
calibration_data = read_calibration_data(backend, "CR-default", (QUBIT_C, QUBIT_T))
custom_cnot_sched = create_echoed_cnot_schedule(backend, (QUBIT_C, QUBIT_T), calibration_data, reverse_direction=False)
# Show the custom CNOT schedule.
custom_cnot_sched.draw()
custom_cnot = Gate("custom_cnot", 2, [])
backend_tmp = deepcopy(backend)
backend_tmp.target.add_instruction(
custom_cnot,
{(QUBIT_C, QUBIT_T): InstructionProperties(calibration=custom_cnot_sched)},
name="custom_cnot",
)
qptexp = ProcessTomography(custom_cnot, physical_qubits=[QUBIT_C, QUBIT_T])
try:
basis_gates = backend.configuration().basis_gates
except AttributeError:
basis_gates = ["measure", "sx", "x", "rz"]
transpiled_circ_list = transpile(
qptexp._transpiled_circuits(),
backend=backend_tmp,
basis_gates = basis_gates + ["custom_cnot"],
optimization_level= 1, # Turn off optimization to keep the custom pulse
)
shots = 4096
if session is not None:
qpt_job = session.run(
"circuit-runner",
inputs={
"circuits": transpiled_circ_list,
"skip_transpilation": True,
"shots": shots,
},
)
else:
qpt_job = backend.run(transpiled_circ_list, shots=shots)
parameters = {
"backend": backend.name,
"qubits": (QUBIT_C, QUBIT_T),
"shots": shots,
}
logger.info(
"Quantum process tomography job: "+
str(qpt_job.job_id()) + "\n"
+ "\n".join([f"{key}: {val}" for key, val in parameters.items()])
+ "\n"
)
save_job_data(qpt_job, backend=backend, parameters=parameters)
import qutip
from qutip.core.gates import cnot
qptdata = retrieve_expdata(qpt_job, backend=backend, exp=qptexp)
state_result = qptdata.analysis_results("state")
choi_matrix = state_result.value.data
choi_qobj = qutip.Qobj(
choi_matrix, dims=[[[2, 2], [2, 2]], [[2, 2], [2, 2]]], superrep="choi"
)
choi_qobj = choi_qobj.permute([[1, 0], [3, 2]]) # Permute the two qubit
qutip.to_super(choi_qobj)
op_basis = [[qutip.qeye(2), qutip.sigmax(), qutip.sigmay(), qutip.sigmaz()]] * 2
chi = qutip.qpt(qutip.to_super(choi_qobj), op_basis)
qutip.qpt_plot_combined(
chi, lbls_list=[["i", "x", "y", "z"]] * 2, title="Process Matrix"
)
choi_qobj = qutip.to_choi(cnot())
qutip.to_super(choi_qobj)
op_basis = [[qutip.qeye(2), qutip.sigmax(), qutip.sigmay(), qutip.sigmaz()]]
lbls_list = [["i", "x", "y", "z"]]
if len(choi_qobj.dims[0][0]) == 2:
op_basis = op_basis * 2
lbls_list = lbls_list * 2
chi_qobj = qutip.qpt(qutip.to_super(choi_qobj), op_basis)
qutip.qpt_plot_combined(chi_qobj, lbls_list=lbls_list, title="Process Matrix")
|
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/KMU-quantum-classroom/qiskit-classroom
|
KMU-quantum-classroom
|
"""test worker.py"""
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import unittest
from unittest import mock
from qiskit_classroom.expression_enum import QuantumExpression
from qiskit_classroom.worker import ConverterWorker
from qiskit_classroom.input_model import QuantumCircuitInput, MatrixInput
VALUE_NAME = "value_name"
QUANTUM_CIRCUIT_CODE = """from qiskit import QuantumCircuit
quantum_circuit = QuantumCircuit(2, 2)
quantum_circuit.x(0)
quantum_circuit.cx(0, 1)"""
MATRIX_CODE = """[[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0]]"""
RANDOM_FILE_NAME = "random_file_name"
QC_TO_MATRIX_EXPECTED = [
"converter = ConversionService(conversion_type='QC_TO_MATRIX',"
+ " option={'print': 'raw'})\n"
+ f"result = converter.convert(input_value={VALUE_NAME})",
"for gate, name in zip(reversed(result['gate']),reversed(result['name'])):\n"
+ "\totimes=' \\\\otimes '\n"
+ "\tprint('\\stackrel{' + otimes.join(name[1]) +'}' + f'{{{gate}}}')\n",
]
MATRIX_TO_QC_EXPECTED = [
"converter = ConversionService(conversion_type='MATRIX_TO_QC',"
+ " option={'label': 'unitary gate'})\n"
+ "from qiskit import QuantumCircuit\n"
+ f"""result = converter.convert(input_value={VALUE_NAME})
quantum_circuit = QuantumCircuit(2)
quantum_circuit.append(result, list(range(result.num_qubits)))
quantum_circuit.measure_all()""",
f"""quantum_circuit.draw(output="mpl").savefig("{RANDOM_FILE_NAME + ".png"}", """
+ """bbox_inches="tight")""",
]
class ConverterWorkerTest(unittest.IsolatedAsyncioTestCase):
"""test converter worker"""
def setUp(self):
ConverterWorker.generate_random_file_name = mock.Mock(
return_value=RANDOM_FILE_NAME
)
ConverterWorker.write_converting_code = mock.Mock(return_value=True)
self.quantum_circuit_input = QuantumCircuitInput(VALUE_NAME)
self.matrix_input = MatrixInput(2, True)
self.matrix_input.value_name = VALUE_NAME
def test_generate_conversion_code_quantum_circuit_to_matrix(self):
"""test generate_conversion_code
Conversion method: QC_TO_MATRIX
"""
worker = ConverterWorker(
QuantumExpression.CIRCUIT,
QuantumExpression.MATRIX,
self.quantum_circuit_input,
QUANTUM_CIRCUIT_CODE,
False,
)
self.assertEqual(worker.generate_conversion_code(), QC_TO_MATRIX_EXPECTED[0])
def test_generate_visualization_code_quantum_circuit_to_matrix(self):
"""test generate_visualization_code
Conversion method: QC_TO_MATRIX
"""
worker = ConverterWorker(
QuantumExpression.CIRCUIT,
QuantumExpression.MATRIX,
self.quantum_circuit_input,
QUANTUM_CIRCUIT_CODE,
False,
)
self.assertEqual(worker.generate_visualization_code(), QC_TO_MATRIX_EXPECTED[1])
def test_generate_conversion_code_matrix_to_quantum_circuit(self):
"""test generate_conversion_code
Conversion method: MATRIX_TO_QC
"""
worker = ConverterWorker(
QuantumExpression.MATRIX,
QuantumExpression.CIRCUIT,
self.matrix_input,
MATRIX_CODE,
False,
)
self.assertEqual(worker.generate_conversion_code(), MATRIX_TO_QC_EXPECTED[0])
def test_generate_visualiazation_code_matrix_to_quantum_circuit(self):
"""test generate_visualization_code
Conversion method: MATRIX_TO_QC
"""
worker = ConverterWorker(
QuantumExpression.MATRIX,
QuantumExpression.CIRCUIT,
self.matrix_input,
MATRIX_CODE,
False,
)
self.assertEqual(worker.generate_visualization_code(), MATRIX_TO_QC_EXPECTED[1])
def test_generate_conversion_code(self):
"""test generate_conversion_code
test it return ""
"""
worker = ConverterWorker(
QuantumExpression.MATRIX, QuantumExpression.MATRIX, None, "", False
)
self.assertEqual(worker.generate_conversion_code(), "")
def test_generate_visualization_code(self):
"""test generated_visualization_code
test case returns ""
"""
worker = ConverterWorker(
QuantumExpression.CIRCUIT, QuantumExpression.DIRAC, None, "", False
)
self.assertEqual(worker.generate_visualization_code(), "print(result)")
worker.to_expression = QuantumExpression.NONE
self.assertEqual(worker.generate_visualization_code(), "")
worker.to_expression = QuantumExpression.CIRCUIT
worker.input_data = QuantumCircuitInput(VALUE_NAME)
self.assertEqual(
worker.generate_visualization_code(),
f'{VALUE_NAME}.draw(output="mpl")'
+ f'.savefig("{RANDOM_FILE_NAME + ".png"}",'
+ 'bbox_inches="tight")',
)
worker.from_expression = QuantumExpression.MATRIX
worker.to_expression = QuantumExpression.MATRIX
worker.input_data: MatrixInput = MatrixInput(2, True)
self.assertEqual(
worker.generate_visualization_code(),
f"print(array_to_latex({worker.input_data.value_name}, source=True))",
)
async def test_run_quantum_circuit_to_matrix(self):
"""test run method"""
worker = ConverterWorker(
QuantumExpression.CIRCUIT,
QuantumExpression.MATRIX,
self.quantum_circuit_input,
QUANTUM_CIRCUIT_CODE,
False,
)
worker.run_subprocess = mock.AsyncMock(return_value=(" ", " "))
worker.cleanup = mock.Mock(return_value=True)
worker.draw_latex = mock.Mock(return_value="")
run_result = await worker.run()
self.assertEqual(run_result, "")
worker.cleanup.assert_called_once()
worker.run_subprocess.assert_awaited_once()
worker.draw_latex.assert_called_once()
async def test_run_matrix_to_quantum_circuit(self):
"""test run matrix to quantum circuit"""
worker = ConverterWorker(
QuantumExpression.MATRIX,
QuantumExpression.CIRCUIT,
self.matrix_input,
MATRIX_CODE,
False,
)
worker.run_subprocess = mock.AsyncMock(return_value=(" ", " "))
worker.cleanup = mock.Mock(return_value=True)
run_result = await worker.run()
self.assertEqual(run_result, f"{RANDOM_FILE_NAME}" + ".png")
worker.cleanup.assert_called_once()
worker.run_subprocess.assert_awaited_once()
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for the baa.py module.
"""
from test.test_baa_lowrank import TestBaaLowRank
import datetime
import os
from unittest import TestCase
import numpy as np
import qiskit
from qiskit import QiskitError
from qiskit.circuit.random import random_circuit
from qclib.entanglement import geometric_entanglement, \
meyer_wallach_entanglement
from qclib.state_preparation import BaaLowRankInitialize
from qclib.state_preparation.lowrank import cnot_count as schmidt_cnots
from qclib.state_preparation.util.baa import adaptive_approximation
from qclib.util import get_state
# pylint: disable=missing-function-docstring
# pylint: disable=missing-class-docstring
use_parallel = os.getenv('QLIB_TEST_PARALLEL', 'False') == 'True'
def get_vector(e_lower: float, e_upper: float, num_qubits: int,
start_depth_multiplier=1, measure='meyer_wallach'):
entanglement = -1.0
if isinstance(start_depth_multiplier, int):
multiplier = start_depth_multiplier
elif isinstance(start_depth_multiplier, (tuple, list, np.ndarray)):
assert len(start_depth_multiplier) > 1
multiplier = np.random.randint(start_depth_multiplier[0], start_depth_multiplier[1])
else:
raise ValueError("start_depth_multiplier must be either an int or an array-like of int.")
iteration = 0
entanglements = []
vector = np.ndarray(shape=(0,))
while e_lower > entanglement or entanglement > e_upper:
np.random.seed()
q_circuit: qiskit.QuantumCircuit = random_circuit(num_qubits, multiplier * num_qubits)
vector = get_state(q_circuit)
if measure == 'geometric':
entanglement = geometric_entanglement(vector)
elif measure == 'meyer_wallach':
entanglement = meyer_wallach_entanglement(vector)
else:
raise ValueError(f'Entanglement Measure {measure} unknown.')
iteration += 1
if iteration > 100:
multiplier += 1
iteration = 0
if not use_parallel:
print(
f'{multiplier} ({np.min(entanglements):.4f}-{np.max(entanglements):.4f})',
end='\n', flush=True
)
entanglements = []
else:
entanglements.append(entanglement)
if not use_parallel:
print('.', end='', flush=True)
if not use_parallel:
print(
f'Final {multiplier} ({np.min(entanglements):.4f}-{np.max(entanglements):.4f})',
end='\n', flush=True
)
return vector, entanglement, multiplier * num_qubits
def initialize_loss(fidelity_loss, state_vector=None, n_qubits=5, strategy='brute_force',
use_low_rank=False):
if state_vector is None:
state_vector = np.random.rand(2**n_qubits) + np.random.rand(2**n_qubits) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
opt_params = {'max_fidelity_loss': fidelity_loss,
'strategy': strategy, 'use_low_rank': use_low_rank}
circuit = BaaLowRankInitialize(state_vector, opt_params=opt_params).definition
state = get_state(circuit)
fidelity = TestBaaLowRank.fidelity(state_vector, state)
node = adaptive_approximation(state_vector, max_fidelity_loss=fidelity_loss,
strategy=strategy, use_low_rank=use_low_rank)
try:
basis_circuit = qiskit.transpile(
circuit, basis_gates=['rx', 'ry', 'rz', 'cx'], optimization_level=0
)
cnots = len([d[0] for d in basis_circuit.data if d[0].name == 'cx'])
depth = basis_circuit.depth()
except QiskitError as ex:
print(ex)
return -1, -1, -1, node
return cnots, depth, round(1 - fidelity, 4), node
def execute_experiment(exp_idx, num_qubits, entanglement_bounds,
max_fidelity_losses, return_state=False,
start_depth_multiplier=1):
print(f"Starting {exp_idx, num_qubits, entanglement_bounds, max_fidelity_losses}")
# State Generation
state_vector, entanglement, depth = get_vector(
*entanglement_bounds, num_qubits, start_depth_multiplier=start_depth_multiplier,
measure='geometric'
)
mw_entanglement = meyer_wallach_entanglement(state_vector)
geo_entanglement = geometric_entanglement(state_vector)
cnots = schmidt_cnots(state_vector)
if not use_parallel:
print(
f"Found state for entanglement bounds {entanglement} in {entanglement_bounds}. "
f"State preparation needs {cnots}."
)
# Benchmark against real Algorithm
real_cnots_benchmark, real_depth_benchmark, real_fidelity_loss_benchmark, _ = initialize_loss(
state_vector=state_vector, fidelity_loss=0.0, use_low_rank=False
)
data_result = []
for max_fidelity_loss in max_fidelity_losses:
for use_low_rank in [False, True]:
for strategy in ['brute_force', 'greedy']:
if not use_parallel:
print(
f"[{max_fidelity_loss}] {strategy.upper()} "
f"{'With' if use_low_rank else 'No'} Low Rank Processing....", end=''
)
start_time = datetime.datetime.now()
real_cnots, real_depth, real_fidelity_loss, node = initialize_loss(
state_vector=state_vector, fidelity_loss=max_fidelity_loss,
use_low_rank=use_low_rank, strategy=strategy
)
end_time = datetime.datetime.now()
duration = (end_time - start_time).total_seconds()
vector_data = list(
zip(node.ranks, [list(v.shape) for v in node.vectors])
)
data = [
exp_idx, use_low_rank, strategy, num_qubits, depth, cnots, geo_entanglement,
mw_entanglement, max_fidelity_loss, node.total_saved_cnots,
node.total_fidelity_loss, vector_data, real_cnots, real_cnots_benchmark,
real_depth, real_depth_benchmark, real_fidelity_loss,
real_fidelity_loss_benchmark, duration
]
if not use_parallel:
print(f"in {duration} secs")
data_result.append(data)
# Experiment transcription
data_result = np.asarray(data_result, dtype=object)
print(f"Done {exp_idx, num_qubits, entanglement_bounds, max_fidelity_losses}")
if return_state:
return data_result, state_vector
return data_result
class TestBaa(TestCase):
def test_node_state_vector(self):
"""
The method Node.state_vector() is an important function for analytics, but it was wrong. The ordering
of the qubits must be taken into account. One example, visible to the human eye, was a probability
distribution, the log-normal. For a max-fidelity-loss of 0.09, the ordering is computed with qubits
[(1,), (3,), (0, 2, 4, 5, 6)] and partitions [None, None, (1, 4)].
The resulting state has an actual fidelity loss of about 0.0859261062108.
The fix is to take the ordering into account. Here we test that for this example, the
fidelity is actually correct.
"""
from qclib.state_preparation.util import baa
# geometric measure = 0.11600417225836746
state = [0.07790067, 0.12411293, 0.10890448, 0.09848761, 0.05027826, 0.05027438,
0.03067742, 0.11846638, 0.09868947, 0.10711022, 0.01826258, 0.12535963,
0.11613662, 0.05865527, 0.05427737, 0.05451262, 0.07021045, 0.09220849,
0.08365776, 0.06869252, 0.09956702, 0.04754114, 0.0688004, 0.07704547,
0.08596225, 0.11279128, 0.05687908, 0.09127936, 0.09797266, 0.02743385,
0.09921588, 0.05256358, 0.03246542, 0.1239935, 0.12508287, 0.11444701,
0.07025331, 0.03978115, 0.10529168, 0.08444882, 0.04446722, 0.08957199,
0.02360472, 0.12138094, 0.06475262, 0.10360775, 0.07106703, 0.09179565,
0.09411756, 0.05472767, 0.12533861, 0.1120676, 0.12337869, 0.12040975,
0.0984252, 0.12221594, 0.03786564, 0.05635093, 0.02707025, 0.07260295,
0.07935725, 0.06630651, 0.11587787, 0.07602843, 0.06746749, 0.09377139,
0.04778426, 0.11400727, 0.03475503, 0.12645201, 0.11185863, 0.05674245,
0.00945899, 0.11494597, 0.10701826, 0.10868207, 0.11178804, 0.03463689,
0.07621068, 0.04332871, 0.11825607, 0.10049395, 0.07322158, 0.03209064,
0.0709839, 0.07258655, 0.10872672, 0.10163697, 0.11989633, 0.08747055,
0.04401971, 0.10750071, 0.11102557, 0.09536318, 0.11176607, 0.08944697,
0.09203053, 0.0832302, 0.02029422, 0.04181051, 0.02256621, 0.10154549,
0.07136789, 0.0907753, 0.12126382, 0.06355451, 0.08154299, 0.110643,
0.06088612, 0.03531675, 0.06851802, 0.05110969, 0.12273343, 0.11442741,
0.10130534, 0.11882721, 0.11411204, 0.05498105, 0.12025703, 0.09348119,
0.11437924, 0.12049476, 0.07178074, 0.04222706, 0.06077118, 0.08318802,
0.11512578, 0.1180934]
node = baa.adaptive_approximation(state, use_low_rank=True, max_fidelity_loss=0.09, strategy='brute_force')
fidelity = np.vdot(state, node.state_vector())**2
self.assertAlmostEqual(node.total_fidelity_loss, 1 - fidelity, places=4)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test boolean expression."""
import unittest
from os import path
from ddt import ddt, unpack, data
from qiskit.test.base import QiskitTestCase
from qiskit import execute, BasicAer
from qiskit.utils.optionals import HAS_TWEEDLEDUM
if HAS_TWEEDLEDUM:
from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
@ddt
class TestBooleanExpression(QiskitTestCase):
"""Test boolean expression."""
@data(
("x | x", "1", True),
("x & x", "0", False),
("(x0 & x1 | ~x2) ^ x4", "0110", False),
("xx & xxx | ( ~z ^ zz)", "0111", True),
)
@unpack
def test_evaluate(self, expression, input_bitstring, expected):
"""Test simulate"""
expression = BooleanExpression(expression)
result = expression.simulate(input_bitstring)
self.assertEqual(result, expected)
@data(
("x", False),
("not x", True),
("(x0 & x1 | ~x2) ^ x4", True),
("xx & xxx | ( ~z ^ zz)", True),
)
@unpack
def test_synth(self, expression, expected):
"""Test synth"""
expression = BooleanExpression(expression)
expr_circ = expression.synth()
new_creg = expr_circ._create_creg(1, "c")
expr_circ.add_register(new_creg)
expr_circ.measure(expression.num_qubits - 1, new_creg)
[result] = (
execute(
expr_circ,
backend=BasicAer.get_backend("qasm_simulator"),
shots=1,
seed_simulator=14,
)
.result()
.get_counts()
.keys()
)
self.assertEqual(bool(int(result)), expected)
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
class TestBooleanExpressionDIMACS(QiskitTestCase):
"""Loading from a cnf file"""
def normalize_filenames(self, filename):
"""Given a filename, returns the directory in terms of __file__."""
dirname = path.dirname(__file__)
return path.join(dirname, filename)
def test_simple(self):
"""Loads simple_v3_c2.cnf and simulate"""
filename = self.normalize_filenames("dimacs/simple_v3_c2.cnf")
simple = BooleanExpression.from_dimacs_file(filename)
self.assertEqual(simple.name, "simple_v3_c2.cnf")
self.assertEqual(simple.num_qubits, 4)
self.assertTrue(simple.simulate("101"))
def test_quinn(self):
"""Loads quinn.cnf and simulate"""
filename = self.normalize_filenames("dimacs/quinn.cnf")
simple = BooleanExpression.from_dimacs_file(filename)
self.assertEqual(simple.name, "quinn.cnf")
self.assertEqual(simple.num_qubits, 16)
self.assertFalse(simple.simulate("1010101010101010"))
if __name__ == "__main__":
unittest.main()
|
https://github.com/scaleway/qiskit-scaleway
|
scaleway
|
import os
import numpy as np
import random
from qiskit import QuantumCircuit
from qiskit_scaleway import ScalewayProvider
def _random_qiskit_circuit(size: int) -> QuantumCircuit:
num_qubits = size
num_gate = size
qc = QuantumCircuit(num_qubits)
for _ in range(num_gate):
random_gate = np.random.choice(["unitary", "cx", "cy", "cz"])
if random_gate == "cx" or random_gate == "cy" or random_gate == "cz":
control_qubit = np.random.randint(0, num_qubits)
target_qubit = np.random.randint(0, num_qubits)
while target_qubit == control_qubit:
target_qubit = np.random.randint(0, num_qubits)
getattr(qc, random_gate)(control_qubit, target_qubit)
else:
for q in range(num_qubits):
random_gate = np.random.choice(["h", "x", "y", "z"])
getattr(qc, random_gate)(q)
qc.measure_all()
return qc
def test_aer_multiple_circuits():
provider = ScalewayProvider(
project_id=os.environ["QISKIT_SCALEWAY_PROJECT_ID"],
secret_key=os.environ["QISKIT_SCALEWAY_API_TOKEN"],
url=os.environ["QISKIT_SCALEWAY_API_URL"],
)
backend = provider.get_backend("aer_simulation_pop_c16m128")
assert backend is not None
session_id = backend.start_session(
name="my-aer-session-autotest",
deduplication_id=f"my-aer-session-autotest-{random.randint(1, 1000)}",
max_duration="5m",
)
assert session_id is not None
try:
qc1 = _random_qiskit_circuit(20)
qc2 = _random_qiskit_circuit(15)
qc3 = _random_qiskit_circuit(21)
qc4 = _random_qiskit_circuit(17)
run_result = backend.run(
[qc1, qc2, qc3, qc4],
shots=1000,
max_parallel_experiments=0,
session_id=session_id,
).result()
results = run_result.results
assert len(results) == 4
for result in results:
assert result.success
finally:
backend.stop_session(session_id)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""General fermionic simulator backend tests."""
from time import sleep
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.providers import JobStatus
from qiskit.result import Result
from qiskit.test import QiskitTestCase
from qiskit_aer import AerJob
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_cold_atom.exceptions import QiskitColdAtomError
from qiskit_cold_atom.fermions.base_fermion_backend import BaseFermionBackend
from qiskit_cold_atom.fermions.fermion_gate_library import FermionicGate
from qiskit_cold_atom.fermions.fermion_simulator_backend import FermionSimulator
class TestFermionSimulatorBackend(QiskitTestCase):
"""class to test the FermionSimulatorBackend class."""
def setUp(self):
super().setUp()
self.backend = FermionSimulator()
def test_initialization(self):
"""test the initialization of the backend"""
target_config = {
"backend_name": "fermion_simulator",
"backend_version": "0.0.1",
"n_qubits": 20,
"basis_gates": None,
"gates": [],
"local": False,
"simulator": True,
"conditional": False,
"open_pulse": False,
"memory": True,
"max_shots": 1e5,
"coupling_map": None,
"description": r"a base simulator for fermionic circuits. Instead of qubits, "
r"each wire represents a single fermionic mode",
}
backend = FermionSimulator()
self.assertIsInstance(backend, BaseFermionBackend)
self.assertTrue(target_config.items() <= backend.configuration().to_dict().items())
def test_run_method(self):
"""Test the run method of the backend simulator"""
with self.subTest("test call"):
circ = self.backend.initialize_circuit([[0, 1], [1, 0]])
job = self.backend.run(circ)
self.assertIsInstance(job, AerJob)
self.assertIsInstance(job.job_id(), str)
self.assertIsInstance(job.result(), Result)
sleep(0.01)
self.assertEqual(job.status(), JobStatus.DONE)
circ1 = self.backend.initialize_circuit([[0, 1], [1, 0]])
circ2 = self.backend.initialize_circuit([[1, 1], [1, 0]])
with self.subTest("test call with multiple circuits"):
job = self.backend.run([circ1, circ2])
self.assertIsInstance(job, AerJob)
with self.subTest("test shot number"):
target_shots = 123
job = self.backend.run([circ1, circ2], shots=target_shots)
for exp in job.result().results:
self.assertEqual(exp.shots, target_shots)
with self.subTest("test seed of RNG"):
target_seed = 123
job = self.backend.run([circ1, circ2], seed=target_seed)
for exp in job.result().results:
self.assertEqual(exp.header.random_seed, target_seed)
with self.subTest("test number of fermionic species"):
# define a circuit that conserves the particle number per fermionic spin species
test_circ = QuantumCircuit(4)
test_circ.fload([0, 3])
test_circ.fhop([np.pi / 4], [0, 1, 2, 3])
statevector_1 = self.backend.run(test_circ).result().get_statevector()
self.assertEqual(len(statevector_1), 6)
# check whether specifying the number of species reduces the dimension of the simulation
statevector_2 = self.backend.run(test_circ, num_species=2).result().get_statevector()
self.assertEqual(len(statevector_2), 4)
def test_execute(self):
"""test the ._execute() method internally called by .run()"""
with self.subTest("test partial measurement"):
circ_meas = QuantumCircuit(2, 2)
circ_meas.fload(0)
circ_meas.measure(0, 0)
with self.assertWarns(UserWarning):
self.backend.run(circ_meas)
test_circ = QuantumCircuit(4)
test_circ.fload([0, 3])
test_circ.fhop([np.pi / 4], [0, 1, 2, 3])
test_circ.fint(np.pi, [0, 1, 2, 3])
test_circ.measure_all()
result = self.backend.run(test_circ, num_species=2, seed=40, shots=5).result()
with self.subTest("test simulation counts"):
self.assertEqual(result.get_counts(), {"1010": 1, "0110": 3, "0101": 1})
with self.subTest("test simulation memory"):
self.assertEqual(result.get_memory(), ["0110", "0101", "1010", "0110", "0110"])
with self.subTest("test simulation statevector"):
self.assertTrue(
np.allclose(result.get_statevector(), np.array([-0.5j, -0.5, 0.5, -0.5j]))
)
with self.subTest("test simulation unitary"):
self.assertTrue(
np.allclose(
result.get_unitary(),
np.array(
[
[-0.5, -0.5j, -0.5j, 0.5],
[0.5j, 0.5, -0.5, 0.5j],
[0.5j, -0.5, 0.5, 0.5j],
[0.5, -0.5j, -0.5j, -0.5],
]
),
)
)
with self.subTest("test time taken"):
self.assertTrue(result.to_dict()["time_taken"] < 0.1)
with self.subTest("test result success"):
self.assertTrue(result.to_dict()["success"])
def test_initialize_circuit(self):
"""test of initialize_circuit inherited from the abstract base class BaseFermionBackend"""
with self.subTest("Initialize circuit with single species of fermions"):
actual_circ = self.backend.initialize_circuit([0, 1, 0, 1])
target_circ = QuantumCircuit(QuantumRegister(4, "fer_mode"))
target_circ.fload(1)
target_circ.fload(3)
self.assertEqual(actual_circ, target_circ)
with self.subTest("Initialize circuit with multiple species of fermions"):
actual_circ = self.backend.initialize_circuit([[0, 1], [0, 1]])
target_circ = QuantumCircuit(QuantumRegister(2, "spin_0"), QuantumRegister(2, "spin_1"))
target_circ.fload(1)
target_circ.fload(3)
self.assertEqual(actual_circ, target_circ)
with self.subTest("check maximum size of circuit"):
with self.assertRaises(QiskitColdAtomError):
self.backend.initialize_circuit(np.ones(30, dtype=int).tolist())
def test_measure_observable_expectation(self):
"""test of the measure_observable_expectation method inherited from the abstract base class
BaseFermionBackend"""
with self.subTest("test error for non-diagonal observables"):
non_diag_observable = FermionicOp({"+_0 -_1 +_2 -_2": 1.0}, num_spin_orbitals=4)
test_circ = self.backend.initialize_circuit([0, 1, 0, 1])
with self.assertRaises(QiskitColdAtomError):
self.backend.measure_observable_expectation(
test_circ, non_diag_observable, shots=10
)
with self.subTest("test match of dimensionality"):
observable_too_small = FermionicOp({"+_0 -_1": 1.0}, num_spin_orbitals=2)
test_circ = self.backend.initialize_circuit([0, 1, 0, 1])
with self.assertRaises(QiskitColdAtomError):
self.backend.measure_observable_expectation(
test_circ, observable_too_small, shots=10
)
with self.subTest("test single measurement circuit"):
observable_1 = FermionicOp({"+_1 -_1 -_2 +_2": 1}, num_spin_orbitals=4)
observable_2 = FermionicOp({"+_1 -_1": 1}, num_spin_orbitals=4) + FermionicOp(
{"-_2 +_2": 1}, num_spin_orbitals=4
)
observable_3 = FermionicOp({"+_0 -_0 +_1 -_1": 1}, num_spin_orbitals=4)
eval_1 = self.backend.measure_observable_expectation(
circuits=self.backend.initialize_circuit([0, 1, 0, 1]),
observable=observable_1,
shots=1,
)
eval_2 = self.backend.measure_observable_expectation(
circuits=self.backend.initialize_circuit([0, 1, 0, 1]),
observable=observable_2,
shots=1,
)
eval_3 = self.backend.measure_observable_expectation(
circuits=self.backend.initialize_circuit([0, 1, 0, 1]),
observable=observable_3,
shots=1,
)
self.assertEqual(eval_1, [1.0])
self.assertEqual(eval_2, [2.0])
self.assertEqual(eval_3, [0.0])
with self.subTest("test multiple measurement circuits"):
test_circ_1 = self.backend.initialize_circuit([0, 1, 0, 1])
test_circ_2 = self.backend.initialize_circuit([1, 0, 0, 1])
observable = FermionicOp({"+_1 -_1 -_2 +_2": 1}, num_spin_orbitals=4)
expval = self.backend.measure_observable_expectation(
[test_circ_1, test_circ_2], observable, shots=1
)
self.assertEqual(expval, [1.0, 0.0])
def test_parameterized_circuits(self):
"""Test that parameterized circuits work."""
from qiskit.circuit import Parameter
theta = Parameter("theta")
test_circ = QuantumCircuit(4)
test_circ.fload([0, 3])
test_circ.fhop([theta], [0, 1, 2, 3])
with self.subTest("test running with unbound parameters:"):
with self.assertRaises(TypeError):
self.assertTrue(isinstance(self.backend.run(test_circ).result(), Result))
with self.subTest("test running with bound parameters"):
bound_circ = test_circ.assign_parameters([0.2])
self.assertTrue(isinstance(self.backend.run(bound_circ).result(), Result))
def test_permutation_invariance(self):
"""Test that a permutation-invariant gate doesn't care about qubit order."""
generator = FermionicOp(
{"+_0 -_1": 1, "+_1 -_0": 1},
num_spin_orbitals=2,
)
gate = FermionicGate(name="test", num_modes=2, generator=generator)
circuit01 = self.backend.initialize_circuit([1, 0])
circuit01.append(gate, [0, 1])
vec01 = self.backend.run(circuit01).result().get_statevector()
circuit10 = self.backend.initialize_circuit([1, 0])
circuit10.append(gate, [1, 0])
vec10 = self.backend.run(circuit10).result().get_statevector()
np.testing.assert_allclose(vec01, vec10)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test pulse builder context utilities."""
from math import pi
import numpy as np
from qiskit import circuit, compiler, pulse
from qiskit.pulse import builder, exceptions, macros
from qiskit.pulse.instructions import directives
from qiskit.pulse.transforms import target_qobj_transform
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeOpenPulse2Q
from qiskit.providers.fake_provider.utils.configurable_backend import (
ConfigurableFakeBackend as ConfigurableBackend,
)
from qiskit.pulse import library, instructions
class TestBuilder(QiskitTestCase):
"""Test the pulse builder context."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.configuration = self.backend.configuration()
self.defaults = self.backend.defaults()
self.inst_map = self.defaults.instruction_schedule_map
def assertScheduleEqual(self, program, target):
"""Assert an error when two pulse programs are not equal.
.. note:: Two programs are converted into standard execution format then compared.
"""
self.assertEqual(target_qobj_transform(program), target_qobj_transform(target))
class TestBuilderBase(TestBuilder):
"""Test builder base."""
def test_schedule_supplied(self):
"""Test that schedule is used if it is supplied to the builder."""
d0 = pulse.DriveChannel(0)
with pulse.build(name="reference") as reference:
with pulse.align_sequential():
pulse.delay(10, d0)
with pulse.build(schedule=reference) as schedule:
pass
self.assertScheduleEqual(schedule, reference)
self.assertEqual(schedule.name, "reference")
def test_default_alignment_left(self):
"""Test default left alignment setting."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(0)
with pulse.build(default_alignment="left") as schedule:
pulse.delay(10, d0)
pulse.delay(20, d1)
with pulse.build(self.backend) as reference:
with pulse.align_left():
pulse.delay(10, d0)
pulse.delay(20, d1)
self.assertScheduleEqual(schedule, reference)
def test_default_alignment_right(self):
"""Test default right alignment setting."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(0)
with pulse.build(default_alignment="right") as schedule:
pulse.delay(10, d0)
pulse.delay(20, d1)
with pulse.build() as reference:
with pulse.align_right():
pulse.delay(10, d0)
pulse.delay(20, d1)
self.assertScheduleEqual(schedule, reference)
def test_default_alignment_sequential(self):
"""Test default sequential alignment setting."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(0)
with pulse.build(default_alignment="sequential") as schedule:
pulse.delay(10, d0)
pulse.delay(20, d1)
with pulse.build() as reference:
with pulse.align_sequential():
pulse.delay(10, d0)
pulse.delay(20, d1)
self.assertScheduleEqual(schedule, reference)
class TestContexts(TestBuilder):
"""Test builder contexts."""
def test_align_sequential(self):
"""Test the sequential alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as schedule:
with pulse.align_sequential():
pulse.delay(3, d0)
pulse.delay(5, d1)
pulse.delay(7, d0)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(8, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(3, instructions.Delay(5, d1), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_align_left(self):
"""Test the left alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
with pulse.build() as schedule:
with pulse.align_left():
pulse.delay(11, d2)
pulse.delay(3, d0)
with pulse.align_left():
pulse.delay(5, d1)
pulse.delay(7, d0)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(3, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(3, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(0, instructions.Delay(11, d2), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_align_right(self):
"""Test the right alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
with pulse.build() as schedule:
with pulse.align_right():
with pulse.align_right():
pulse.delay(11, d2)
pulse.delay(3, d0)
pulse.delay(13, d0)
pulse.delay(5, d1)
reference = pulse.Schedule()
# d0
reference.insert(8, instructions.Delay(3, d0), inplace=True)
reference.insert(11, instructions.Delay(13, d0), inplace=True)
# d1
reference.insert(19, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(0, instructions.Delay(11, d2), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_transpiler_settings(self):
"""Test the transpiler settings context.
Tests that two cx gates are optimized away with higher optimization level.
"""
twice_cx_qc = circuit.QuantumCircuit(2)
twice_cx_qc.cx(0, 1)
twice_cx_qc.cx(0, 1)
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(optimization_level=0):
builder.call(twice_cx_qc)
self.assertNotEqual(len(schedule.instructions), 0)
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(optimization_level=3):
builder.call(twice_cx_qc)
self.assertEqual(len(schedule.instructions), 0)
def test_scheduler_settings(self):
"""Test the circuit scheduler settings context."""
inst_map = pulse.InstructionScheduleMap()
d0 = pulse.DriveChannel(0)
test_x_sched = pulse.Schedule()
test_x_sched += instructions.Delay(10, d0)
inst_map.add("x", (0,), test_x_sched)
ref_sched = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
ref_sched += pulse.instructions.Call(test_x_sched)
x_qc = circuit.QuantumCircuit(2)
x_qc.x(0)
with pulse.build(backend=self.backend) as schedule:
with pulse.transpiler_settings(basis_gates=["x"]):
with pulse.circuit_scheduler_settings(inst_map=inst_map):
builder.call(x_qc)
self.assertScheduleEqual(schedule, ref_sched)
def test_phase_offset(self):
"""Test the phase offset context."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
with pulse.phase_offset(3.14, d0):
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.ShiftPhase(3.14, d0)
reference += instructions.Delay(10, d0)
reference += instructions.ShiftPhase(-3.14, d0)
self.assertScheduleEqual(schedule, reference)
def test_frequency_offset(self):
"""Test the frequency offset context."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
with pulse.frequency_offset(1e9, d0):
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.ShiftFrequency(1e9, d0)
reference += instructions.Delay(10, d0)
reference += instructions.ShiftFrequency(-1e9, d0)
self.assertScheduleEqual(schedule, reference)
def test_phase_compensated_frequency_offset(self):
"""Test that the phase offset context properly compensates for phase
accumulation."""
d0 = pulse.DriveChannel(0)
with pulse.build(self.backend) as schedule:
with pulse.frequency_offset(1e9, d0, compensate_phase=True):
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.ShiftFrequency(1e9, d0)
reference += instructions.Delay(10, d0)
reference += instructions.ShiftPhase(
-2 * np.pi * ((1e9 * 10 * self.configuration.dt) % 1), d0
)
reference += instructions.ShiftFrequency(-1e9, d0)
self.assertScheduleEqual(schedule, reference)
class TestChannels(TestBuilder):
"""Test builder channels."""
def test_drive_channel(self):
"""Text context builder drive channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.drive_channel(0), pulse.DriveChannel(0))
def test_measure_channel(self):
"""Text context builder measure channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.measure_channel(0), pulse.MeasureChannel(0))
def test_acquire_channel(self):
"""Text context builder acquire channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.acquire_channel(0), pulse.AcquireChannel(0))
def test_control_channel(self):
"""Text context builder control channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.control_channels(0, 1)[0], pulse.ControlChannel(0))
class TestInstructions(TestBuilder):
"""Test builder instructions."""
def test_delay(self):
"""Test delay instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
self.assertScheduleEqual(schedule, reference)
def test_play_parametric_pulse(self):
"""Test play instruction with parametric pulse."""
d0 = pulse.DriveChannel(0)
test_pulse = library.Constant(10, 1.0)
with pulse.build() as schedule:
pulse.play(test_pulse, d0)
reference = pulse.Schedule()
reference += instructions.Play(test_pulse, d0)
self.assertScheduleEqual(schedule, reference)
def test_play_sample_pulse(self):
"""Test play instruction with sample pulse."""
d0 = pulse.DriveChannel(0)
test_pulse = library.Waveform([0.0, 0.0])
with pulse.build() as schedule:
pulse.play(test_pulse, d0)
reference = pulse.Schedule()
reference += instructions.Play(test_pulse, d0)
self.assertScheduleEqual(schedule, reference)
def test_play_array_pulse(self):
"""Test play instruction on an array directly."""
d0 = pulse.DriveChannel(0)
test_array = np.array([0.0, 0.0], dtype=np.complex_)
with pulse.build() as schedule:
pulse.play(test_array, d0)
reference = pulse.Schedule()
test_pulse = pulse.Waveform(test_array)
reference += instructions.Play(test_pulse, d0)
self.assertScheduleEqual(schedule, reference)
def test_play_name_argument(self):
"""Test name argument for play instruction."""
d0 = pulse.DriveChannel(0)
test_pulse = library.Constant(10, 1.0)
with pulse.build() as schedule:
pulse.play(test_pulse, channel=d0, name="new_name")
self.assertEqual(schedule.instructions[0][1].name, "new_name")
def test_acquire_memory_slot(self):
"""Test acquire instruction into memory slot."""
acquire0 = pulse.AcquireChannel(0)
mem0 = pulse.MemorySlot(0)
with pulse.build() as schedule:
pulse.acquire(10, acquire0, mem0)
reference = pulse.Schedule()
reference += pulse.Acquire(10, acquire0, mem_slot=mem0)
self.assertScheduleEqual(schedule, reference)
def test_acquire_register_slot(self):
"""Test acquire instruction into register slot."""
acquire0 = pulse.AcquireChannel(0)
reg0 = pulse.RegisterSlot(0)
with pulse.build() as schedule:
pulse.acquire(10, acquire0, reg0)
reference = pulse.Schedule()
reference += pulse.Acquire(10, acquire0, reg_slot=reg0)
self.assertScheduleEqual(schedule, reference)
def test_acquire_qubit(self):
"""Test acquire instruction on qubit."""
acquire0 = pulse.AcquireChannel(0)
mem0 = pulse.MemorySlot(0)
with pulse.build() as schedule:
pulse.acquire(10, 0, mem0)
reference = pulse.Schedule()
reference += pulse.Acquire(10, acquire0, mem_slot=mem0)
self.assertScheduleEqual(schedule, reference)
def test_instruction_name_argument(self):
"""Test setting the name of an instruction."""
d0 = pulse.DriveChannel(0)
for instruction_method in [
pulse.delay,
pulse.set_frequency,
pulse.set_phase,
pulse.shift_frequency,
pulse.shift_phase,
]:
with pulse.build() as schedule:
instruction_method(0, d0, name="instruction_name")
self.assertEqual(schedule.instructions[0][1].name, "instruction_name")
def test_set_frequency(self):
"""Test set frequency instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.set_frequency(1e9, d0)
reference = pulse.Schedule()
reference += instructions.SetFrequency(1e9, d0)
self.assertScheduleEqual(schedule, reference)
def test_shift_frequency(self):
"""Test shift frequency instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.shift_frequency(0.1e9, d0)
reference = pulse.Schedule()
reference += instructions.ShiftFrequency(0.1e9, d0)
self.assertScheduleEqual(schedule, reference)
def test_set_phase(self):
"""Test set phase instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.set_phase(3.14, d0)
reference = pulse.Schedule()
reference += instructions.SetPhase(3.14, d0)
self.assertScheduleEqual(schedule, reference)
def test_shift_phase(self):
"""Test shift phase instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.shift_phase(3.14, d0)
reference = pulse.Schedule()
reference += instructions.ShiftPhase(3.14, d0)
self.assertScheduleEqual(schedule, reference)
def test_snapshot(self):
"""Test snapshot instruction."""
with pulse.build() as schedule:
pulse.snapshot("test", "state")
reference = pulse.Schedule()
reference += instructions.Snapshot("test", "state")
self.assertScheduleEqual(schedule, reference)
class TestDirectives(TestBuilder):
"""Test builder directives."""
def test_barrier_with_align_right(self):
"""Test barrier directive with right alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
with pulse.build() as schedule:
with pulse.align_right():
pulse.delay(3, d0)
pulse.barrier(d0, d1, d2)
pulse.delay(11, d2)
with pulse.align_right():
pulse.delay(5, d1)
pulse.delay(7, d0)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(7, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(9, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(3, instructions.Delay(11, d2), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_barrier_with_align_left(self):
"""Test barrier directive with left alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
with pulse.build() as schedule:
with pulse.align_left():
pulse.delay(3, d0)
pulse.barrier(d0, d1, d2)
pulse.delay(11, d2)
with pulse.align_left():
pulse.delay(5, d1)
pulse.delay(7, d0)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(3, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(3, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(3, instructions.Delay(11, d2), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_barrier_on_qubits(self):
"""Test barrier directive on qubits."""
with pulse.build(self.backend) as schedule:
pulse.barrier(0, 1)
reference = pulse.ScheduleBlock()
reference += directives.RelativeBarrier(
pulse.DriveChannel(0),
pulse.DriveChannel(1),
pulse.MeasureChannel(0),
pulse.MeasureChannel(1),
pulse.ControlChannel(0),
pulse.ControlChannel(1),
pulse.AcquireChannel(0),
pulse.AcquireChannel(1),
)
self.assertEqual(schedule, reference)
def test_trivial_barrier(self):
"""Test that trivial barrier is not added."""
with pulse.build() as schedule:
pulse.barrier(pulse.DriveChannel(0))
self.assertEqual(schedule, pulse.ScheduleBlock())
class TestUtilities(TestBuilder):
"""Test builder utilities."""
def test_active_backend(self):
"""Test getting active builder backend."""
with pulse.build(self.backend):
self.assertEqual(pulse.active_backend(), self.backend)
def test_append_schedule(self):
"""Test appending a schedule to the active builder."""
d0 = pulse.DriveChannel(0)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
with pulse.build() as schedule:
builder.call(reference)
self.assertScheduleEqual(schedule, reference)
def test_append_instruction(self):
"""Test appending an instruction to the active builder."""
d0 = pulse.DriveChannel(0)
instruction = instructions.Delay(10, d0)
with pulse.build() as schedule:
builder.append_instruction(instruction)
self.assertScheduleEqual(schedule, (0, instruction))
def test_qubit_channels(self):
"""Test getting the qubit channels of the active builder's backend."""
with pulse.build(self.backend):
qubit_channels = pulse.qubit_channels(0)
self.assertEqual(
qubit_channels,
{
pulse.DriveChannel(0),
pulse.MeasureChannel(0),
pulse.AcquireChannel(0),
pulse.ControlChannel(0),
pulse.ControlChannel(1),
},
)
def test_active_transpiler_settings(self):
"""Test setting settings of active builder's transpiler."""
with pulse.build(self.backend):
self.assertFalse(pulse.active_transpiler_settings())
with pulse.transpiler_settings(test_setting=1):
self.assertEqual(pulse.active_transpiler_settings()["test_setting"], 1)
def test_active_circuit_scheduler_settings(self):
"""Test setting settings of active builder's circuit scheduler."""
with pulse.build(self.backend):
self.assertFalse(pulse.active_circuit_scheduler_settings())
with pulse.circuit_scheduler_settings(test_setting=1):
self.assertEqual(pulse.active_circuit_scheduler_settings()["test_setting"], 1)
def test_num_qubits(self):
"""Test builder utility to get number of qubits."""
with pulse.build(self.backend):
self.assertEqual(pulse.num_qubits(), 2)
def test_samples_to_seconds(self):
"""Test samples to time"""
config = self.backend.configuration()
config.dt = 0.1
with pulse.build(self.backend):
time = pulse.samples_to_seconds(100)
self.assertTrue(isinstance(time, float))
self.assertEqual(pulse.samples_to_seconds(100), 10)
def test_samples_to_seconds_array(self):
"""Test samples to time (array format)."""
config = self.backend.configuration()
config.dt = 0.1
with pulse.build(self.backend):
samples = np.array([100, 200, 300])
times = pulse.samples_to_seconds(samples)
self.assertTrue(np.issubdtype(times.dtype, np.floating))
np.testing.assert_allclose(times, np.array([10, 20, 30]))
def test_seconds_to_samples(self):
"""Test time to samples"""
config = self.backend.configuration()
config.dt = 0.1
with pulse.build(self.backend):
samples = pulse.seconds_to_samples(10)
self.assertTrue(isinstance(samples, int))
self.assertEqual(pulse.seconds_to_samples(10), 100)
def test_seconds_to_samples_array(self):
"""Test time to samples (array format)."""
config = self.backend.configuration()
config.dt = 0.1
with pulse.build(self.backend):
times = np.array([10, 20, 30])
samples = pulse.seconds_to_samples(times)
self.assertTrue(np.issubdtype(samples.dtype, np.integer))
np.testing.assert_allclose(pulse.seconds_to_samples(times), np.array([100, 200, 300]))
class TestMacros(TestBuilder):
"""Test builder macros."""
def test_macro(self):
"""Test builder macro decorator."""
@pulse.macro
def nested(a):
pulse.play(pulse.Gaussian(100, a, 20), pulse.drive_channel(0))
return a * 2
@pulse.macro
def test():
pulse.play(pulse.Constant(100, 1.0), pulse.drive_channel(0))
output = nested(0.5)
return output
with pulse.build(self.backend) as schedule:
output = test()
self.assertEqual(output, 0.5 * 2)
reference = pulse.Schedule()
reference += pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0))
reference += pulse.Play(pulse.Gaussian(100, 0.5, 20), pulse.DriveChannel(0))
self.assertScheduleEqual(schedule, reference)
def test_measure(self):
"""Test utility function - measure."""
with pulse.build(self.backend) as schedule:
reg = pulse.measure(0)
self.assertEqual(reg, pulse.MemorySlot(0))
reference = macros.measure(
qubits=[0], inst_map=self.inst_map, meas_map=self.configuration.meas_map
)
self.assertScheduleEqual(schedule, reference)
def test_measure_multi_qubits(self):
"""Test utility function - measure with multi qubits."""
with pulse.build(self.backend) as schedule:
regs = pulse.measure([0, 1])
self.assertListEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)])
reference = macros.measure(
qubits=[0, 1], inst_map=self.inst_map, meas_map=self.configuration.meas_map
)
self.assertScheduleEqual(schedule, reference)
def test_measure_all(self):
"""Test utility function - measure."""
with pulse.build(self.backend) as schedule:
regs = pulse.measure_all()
self.assertEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)])
reference = macros.measure_all(self.backend)
self.assertScheduleEqual(schedule, reference)
backend_100q = ConfigurableBackend("100q", 100)
with pulse.build(backend_100q) as schedule:
regs = pulse.measure_all()
reference = backend_100q.defaults().instruction_schedule_map.get(
"measure", list(range(100))
)
self.assertScheduleEqual(schedule, reference)
def test_delay_qubit(self):
"""Test delaying on a qubit macro."""
with pulse.build(self.backend) as schedule:
pulse.delay_qubits(10, 0)
d0 = pulse.DriveChannel(0)
m0 = pulse.MeasureChannel(0)
a0 = pulse.AcquireChannel(0)
u0 = pulse.ControlChannel(0)
u1 = pulse.ControlChannel(1)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
reference += instructions.Delay(10, m0)
reference += instructions.Delay(10, a0)
reference += instructions.Delay(10, u0)
reference += instructions.Delay(10, u1)
self.assertScheduleEqual(schedule, reference)
def test_delay_qubits(self):
"""Test delaying on multiple qubits to make sure we don't insert delays twice."""
with pulse.build(self.backend) as schedule:
pulse.delay_qubits(10, 0, 1)
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
m0 = pulse.MeasureChannel(0)
m1 = pulse.MeasureChannel(1)
a0 = pulse.AcquireChannel(0)
a1 = pulse.AcquireChannel(1)
u0 = pulse.ControlChannel(0)
u1 = pulse.ControlChannel(1)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
reference += instructions.Delay(10, d1)
reference += instructions.Delay(10, m0)
reference += instructions.Delay(10, m1)
reference += instructions.Delay(10, a0)
reference += instructions.Delay(10, a1)
reference += instructions.Delay(10, u0)
reference += instructions.Delay(10, u1)
self.assertScheduleEqual(schedule, reference)
class TestGates(TestBuilder):
"""Test builder gates."""
def test_cx(self):
"""Test cx gate."""
with pulse.build(self.backend) as schedule:
pulse.cx(0, 1)
reference_qc = circuit.QuantumCircuit(2)
reference_qc.cx(0, 1)
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_u1(self):
"""Test u1 gate."""
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(layout_method="trivial"):
pulse.u1(np.pi / 2, 0)
reference_qc = circuit.QuantumCircuit(1)
reference_qc.append(circuit.library.U1Gate(np.pi / 2), [0])
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_u2(self):
"""Test u2 gate."""
with pulse.build(self.backend) as schedule:
pulse.u2(np.pi / 2, 0, 0)
reference_qc = circuit.QuantumCircuit(1)
reference_qc.append(circuit.library.U2Gate(np.pi / 2, 0), [0])
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_u3(self):
"""Test u3 gate."""
with pulse.build(self.backend) as schedule:
pulse.u3(np.pi / 8, np.pi / 16, np.pi / 4, 0)
reference_qc = circuit.QuantumCircuit(1)
reference_qc.append(circuit.library.U3Gate(np.pi / 8, np.pi / 16, np.pi / 4), [0])
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_x(self):
"""Test x gate."""
with pulse.build(self.backend) as schedule:
pulse.x(0)
reference_qc = circuit.QuantumCircuit(1)
reference_qc.x(0)
reference_qc = compiler.transpile(reference_qc, self.backend)
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_lazy_evaluation_with_transpiler(self):
"""Test that the two cx gates are optimizied away by the transpiler."""
with pulse.build(self.backend) as schedule:
pulse.cx(0, 1)
pulse.cx(0, 1)
reference_qc = circuit.QuantumCircuit(2)
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_measure(self):
"""Test pulse measurement macro against circuit measurement and
ensure agreement."""
with pulse.build(self.backend) as schedule:
with pulse.align_sequential():
pulse.x(0)
pulse.measure(0)
reference_qc = circuit.QuantumCircuit(1, 1)
reference_qc.x(0)
reference_qc.measure(0, 0)
reference_qc = compiler.transpile(reference_qc, self.backend)
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_backend_require(self):
"""Test that a backend is required to use a gate."""
with self.assertRaises(exceptions.BackendNotSet):
with pulse.build():
pulse.x(0)
class TestBuilderComposition(TestBuilder):
"""Test more sophisticated composite builder examples."""
def test_complex_build(self):
"""Test a general program build with nested contexts,
circuits and macros."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
delay_dur = 30
short_dur = 20
long_dur = 49
with pulse.build(self.backend) as schedule:
with pulse.align_sequential():
pulse.delay(delay_dur, d0)
pulse.u2(0, pi / 2, 1)
with pulse.align_right():
pulse.play(library.Constant(short_dur, 0.1), d1)
pulse.play(library.Constant(long_dur, 0.1), d2)
pulse.u2(0, pi / 2, 1)
with pulse.align_left():
pulse.u2(0, pi / 2, 0)
pulse.u2(0, pi / 2, 1)
pulse.u2(0, pi / 2, 0)
pulse.measure(0)
# prepare and schedule circuits that will be used.
single_u2_qc = circuit.QuantumCircuit(2)
single_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [1])
single_u2_qc = compiler.transpile(single_u2_qc, self.backend)
single_u2_sched = compiler.schedule(single_u2_qc, self.backend)
# sequential context
sequential_reference = pulse.Schedule()
sequential_reference += instructions.Delay(delay_dur, d0)
sequential_reference.insert(delay_dur, single_u2_sched, inplace=True)
# align right
align_right_reference = pulse.Schedule()
align_right_reference += pulse.Play(library.Constant(long_dur, 0.1), d2)
align_right_reference.insert(
long_dur - single_u2_sched.duration, single_u2_sched, inplace=True
)
align_right_reference.insert(
long_dur - single_u2_sched.duration - short_dur,
pulse.Play(library.Constant(short_dur, 0.1), d1),
inplace=True,
)
# align left
triple_u2_qc = circuit.QuantumCircuit(2)
triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [0])
triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [1])
triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [0])
triple_u2_qc = compiler.transpile(triple_u2_qc, self.backend)
align_left_reference = compiler.schedule(triple_u2_qc, self.backend, method="alap")
# measurement
measure_reference = macros.measure(
qubits=[0], inst_map=self.inst_map, meas_map=self.configuration.meas_map
)
reference = pulse.Schedule()
reference += sequential_reference
# Insert so that the long pulse on d2 occurs as early as possible
# without an overval on d1.
insert_time = reference.ch_stop_time(d1) - align_right_reference.ch_start_time(d1)
reference.insert(insert_time, align_right_reference, inplace=True)
reference.insert(reference.ch_stop_time(d0, d1), align_left_reference, inplace=True)
reference += measure_reference
self.assertScheduleEqual(schedule, reference)
class TestSubroutineCall(TestBuilder):
"""Test for calling subroutine."""
def test_call(self):
"""Test calling schedule instruction."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
reference = pulse.Schedule()
reference = reference.insert(10, instructions.Delay(10, d0))
reference += instructions.Delay(20, d1)
ref_sched = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
ref_sched += pulse.instructions.Call(reference)
with pulse.build() as schedule:
with pulse.align_right():
builder.call(reference)
self.assertScheduleEqual(schedule, ref_sched)
with pulse.build() as schedule:
with pulse.align_right():
pulse.call(reference)
self.assertScheduleEqual(schedule, ref_sched)
def test_call_circuit(self):
"""Test calling circuit instruction."""
inst_map = self.inst_map
reference = inst_map.get("u1", (0,), 0.0)
ref_sched = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
ref_sched += pulse.instructions.Call(reference)
u1_qc = circuit.QuantumCircuit(2)
u1_qc.append(circuit.library.U1Gate(0.0), [0])
transpiler_settings = {"optimization_level": 0}
with pulse.build(self.backend, default_transpiler_settings=transpiler_settings) as schedule:
with pulse.align_right():
builder.call(u1_qc)
self.assertScheduleEqual(schedule, ref_sched)
def test_call_circuit_with_cregs(self):
"""Test calling of circuit wiht classical registers."""
qc = circuit.QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
with pulse.build(self.backend) as schedule:
pulse.call(qc)
reference_qc = compiler.transpile(qc, self.backend)
reference = compiler.schedule(reference_qc, self.backend)
ref_sched = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
ref_sched += pulse.instructions.Call(reference)
self.assertScheduleEqual(schedule, ref_sched)
def test_call_gate_and_circuit(self):
"""Test calling circuit with gates."""
h_control = circuit.QuantumCircuit(2)
h_control.h(0)
with pulse.build(self.backend) as schedule:
with pulse.align_sequential():
# this is circuit, a subroutine stored as Call instruction
pulse.call(h_control)
# this is instruction, not subroutine
pulse.cx(0, 1)
# this is macro, not subroutine
pulse.measure([0, 1])
# subroutine
h_reference = compiler.schedule(compiler.transpile(h_control, self.backend), self.backend)
# gate
cx_circ = circuit.QuantumCircuit(2)
cx_circ.cx(0, 1)
cx_reference = compiler.schedule(compiler.transpile(cx_circ, self.backend), self.backend)
# measurement
measure_reference = macros.measure(
qubits=[0, 1], inst_map=self.inst_map, meas_map=self.configuration.meas_map
)
reference = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
reference += pulse.instructions.Call(h_reference)
reference += cx_reference
reference += measure_reference << reference.duration
self.assertScheduleEqual(schedule, reference)
def test_subroutine_not_transpiled(self):
"""Test called circuit is frozen as a subroutine."""
subprogram = circuit.QuantumCircuit(1)
subprogram.x(0)
transpiler_settings = {"optimization_level": 2}
with pulse.build(self.backend, default_transpiler_settings=transpiler_settings) as schedule:
pulse.call(subprogram)
pulse.call(subprogram)
self.assertNotEqual(len(target_qobj_transform(schedule).instructions), 0)
def test_subroutine_not_transformed(self):
"""Test called schedule is not transformed."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
subprogram = pulse.Schedule()
subprogram.insert(0, pulse.Delay(30, d0), inplace=True)
subprogram.insert(10, pulse.Delay(10, d1), inplace=True)
with pulse.build() as target:
with pulse.align_right():
pulse.delay(10, d1)
pulse.call(subprogram)
reference = pulse.Schedule()
reference.insert(0, pulse.Delay(10, d1), inplace=True)
reference.insert(10, pulse.Delay(30, d0), inplace=True)
reference.insert(20, pulse.Delay(10, d1), inplace=True)
self.assertScheduleEqual(target, reference)
def test_deepcopying_subroutine(self):
"""Test if deepcopying the schedule can copy inline subroutine."""
from copy import deepcopy
with pulse.build() as subroutine:
pulse.delay(10, pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine)
copied_prog = deepcopy(main_prog)
main_call = main_prog.instructions[0]
copy_call = copied_prog.instructions[0]
self.assertNotEqual(id(main_call), id(copy_call))
def test_call_with_parameters(self):
"""Test call subroutine with parameters."""
amp = circuit.Parameter("amp")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine, amp=0.1)
pulse.call(subroutine, amp=0.3)
self.assertEqual(main_prog.is_parameterized(), False)
assigned_sched = target_qobj_transform(main_prog)
play_0 = assigned_sched.instructions[0][1]
play_1 = assigned_sched.instructions[1][1]
self.assertEqual(play_0.pulse.amp, 0.1)
self.assertEqual(play_1.pulse.amp, 0.3)
def test_call_partly_with_parameters(self):
"""Test multiple calls partly with parameters then assign."""
amp = circuit.Parameter("amp")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine, amp=0.1)
pulse.call(subroutine)
self.assertEqual(main_prog.is_parameterized(), True)
main_prog.assign_parameters({amp: 0.5})
self.assertEqual(main_prog.is_parameterized(), False)
assigned_sched = target_qobj_transform(main_prog)
play_0 = assigned_sched.instructions[0][1]
play_1 = assigned_sched.instructions[1][1]
self.assertEqual(play_0.pulse.amp, 0.1)
self.assertEqual(play_1.pulse.amp, 0.5)
def test_call_with_not_existing_parameter(self):
"""Test call subroutine with parameter not defined."""
amp = circuit.Parameter("amp1")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
with self.assertRaises(exceptions.PulseError):
with pulse.build():
pulse.call(subroutine, amp=0.1)
def test_call_with_common_parameter(self):
"""Test call subroutine with parameter that is defined multiple times."""
amp = circuit.Parameter("amp")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(320, amp, 80), pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine, amp=0.1)
assigned_sched = target_qobj_transform(main_prog)
play_0 = assigned_sched.instructions[0][1]
play_1 = assigned_sched.instructions[1][1]
self.assertEqual(play_0.pulse.amp, 0.1)
self.assertEqual(play_1.pulse.amp, 0.1)
def test_call_with_parameter_name_collision(self):
"""Test call subroutine with duplicated parameter names."""
amp1 = circuit.Parameter("amp")
amp2 = circuit.Parameter("amp")
sigma = circuit.Parameter("sigma")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp1, sigma), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, amp2, sigma), pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.2}, sigma=40)
assigned_sched = target_qobj_transform(main_prog)
play_0 = assigned_sched.instructions[0][1]
play_1 = assigned_sched.instructions[1][1]
self.assertEqual(play_0.pulse.amp, 0.1)
self.assertEqual(play_0.pulse.sigma, 40)
self.assertEqual(play_1.pulse.amp, 0.2)
self.assertEqual(play_1.pulse.sigma, 40)
def test_call_subroutine_with_parametrized_duration(self):
"""Test call subroutine containing a parametrized duration."""
dur = circuit.Parameter("dur")
with pulse.build() as subroutine:
pulse.play(pulse.Constant(dur, 0.1), pulse.DriveChannel(0))
pulse.play(pulse.Constant(dur, 0.2), pulse.DriveChannel(0))
with pulse.build() as main:
pulse.call(subroutine)
self.assertEqual(len(main.blocks), 1)
|
https://github.com/primaryobjects/oracle
|
primaryobjects
|
from qiskit import QuantumCircuit
def oracle(b1, b2, entanglements):
'''
Takes two bit strings (b1 and b2) and entangles the qubits at indices entanglements[] using CNOT.
Returns a quantum circuit that represents the state of both bit strings simultaneously.
Measuring the result will force an outcome of b1 or b2.
Parameters:
b1, b2: bit strings (for example, 16 bit ASCII character)
entanglements: list of pairs of indices to entangle qubits. For example: [ [9, 8], [control, target], ... ]
'''
b1 = b1[::-1]
b2 = b2[::-1]
# Number of qubits will be 1 qubit for each bit.
n = len(b1)
# We use a circuit of size n.
qc = QuantumCircuit(n)
# Flip all qubits that have a 1 in the bit string.
for i in range(n):
if b1[i] == '1' and b2[i] == '1':
qc.x(i)
# Entangle qubits.
for entanglement in entanglements:
control = entanglement[0]
target = entanglement[1]
# Place control qubit in superposition.
qc.h(control)
# Entangle target qubit to control, spreading superposition and state.
qc.cx(control, target)
print(qc.draw())
# Convert the oracle to a gate.
gate = qc.to_gate()
gate.name = "oracle"
return gate
|
https://github.com/menegolli/Quantum_synth
|
menegolli
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/Tojarieh97/VQE
|
Tojarieh97
|
%load_ext autoreload
%autoreload 2
import nbimporter
from typing import Dict, Tuple, List
import numpy as np
from tqdm import tqdm
QUBITS_NUM = 4
N = 2**QUBITS_NUM
NUM_SHOTS = 1024
NUM_ITERATIONS = 100
CIRCUIT_DEPTH = 3
PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1)
from qiskit import Aer
from qiskit.utils import QuantumInstance, algorithm_globals
seed = 50
algorithm_globals.random_seed = seed
simulator_backend = Aer.get_backend('qasm_simulator')
from scipy.optimize import minimize
from linear_entangelment_and_full_entangelment_ansatz_circuits import *
def get_ansatz_state(thetas, ansatz_entangelment, input_state):
if ansatz_entangelment=="full":
return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state)
if ansatz_entangelment=="linear":
return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state)
def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List:
pauli_operators = hamiltonian.to_pauli_op().settings['oplist']
pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators))
pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators))
return pauli_coeffs, pauli_strings
from qiskit.circuit.library.standard_gates import HGate, SGate
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
reducing_to_pauli_z_mapping = {
'I': 'I',
'Z': 'Z',
'X': 'Z',
'Y': 'Z'
}
def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str:
reduced_pauli_string = ""
for matrix_index in range(QUBITS_NUM):
pauli_matrix = str(pauli_string[matrix_index])
reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix]
reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string
return reduced_pauli_string
def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit):
quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit")
additional_circuit_layer = QuantumCircuit(quantum_registers)
for quantum_register_index, pauli_matrix in enumerate(pauli_string):
if pauli_matrix == "X":
additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]])
if pauli_string == "Y":
additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]])
additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]])
extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer)
return extended_quantum_circuit
def get_probability_distribution(counts: Dict) -> Dict:
proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()}
return proba_distribution
def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict:
quantum_state_circuit.measure_all()
transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend)
Qobj = assemble(transpiled_quantum_state_circuit)
result = simulator_backend.run(Qobj).result()
counts = result.get_counts(quantum_state_circuit)
return get_probability_distribution(counts)
def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict:
return dict(sorted(proba_distribution.items()))
def reset_power_of_minus_1(power_of_minus_1):
power_of_minus_1 = 0
return power_of_minus_1
def convert_pauli_string_into_str(pauli_string) -> str:
return str(pauli_string)
def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit):
pauli_string_expectation_value = 0
power_of_minus_1 = 0
pauli_string_str = convert_pauli_string_into_str(pauli_string)
extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit)
probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit)
reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string)
sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution)
for qubits_string, proba in sorted_probas_distribuition.items():
for string_index in range(QUBITS_NUM):
if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"):
power_of_minus_1 += 1
pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba
power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1)
return pauli_string_expectation_value
def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings):
total_expection_value = 0
for pauli_coeff, pauli_string in tqdm(zip(pauli_coeffs, pauli_strings)):
total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas(
pauli_string, ansatz_circuit)
return total_expection_value
from qiskit import assemble, transpile
def cost_function(thetas, hamiltonian, ansatz_entangelment):
initial_eigenvector = np.identity(N)[0]
pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian)
ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector)
L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings)
insert_approximated_energy_to_list_of_all_approximated_energies(L)
return L
def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment):
initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=PARAMS_NUM)
optimizer_result = minimize(cost_function,
x0=initial_thetas,
args=(hamiltonian, ansatz_entangelment),
method="L-BFGS-B",
options={"maxiter":NUM_ITERATIONS,
"disp": True})
optimal_thetas = optimizer_result.x
return optimal_thetas
def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment):
optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment)
print(optimal_thetas)
initial_eigenvector = np.identity(N)[0]
optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector)
pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian)
approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings)
return approximated_eigenvalue
from numpy import linalg as LA
def get_approximation_error(exact_eigenvalue, approximated_eigenvalue):
return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue)
def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian):
eigen_values = LA.eigvals(hamiltonian.to_matrix())
print(sorted(eigen_values))
return min(sorted(eigen_values))
def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue):
exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian)
print("Exact Eigenvalue:")
print(exact_eigenvalue)
print("\nApproximated Eigenvalue:")
print(approximated_eigenvalue)
print("\nApproximation Error")
print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue))
plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin=3)
approximated_energies = []
def insert_approximated_energy_to_list_of_all_approximated_energies(energy):
approximated_energies.append(energy)
import matplotlib.pyplot as plt
def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin):
plt.title("convergence of optimization process to the exact eigenvalue")
plt.margins(0, margin)
plt.plot(approximated_energies[-NUM_ITERATIONS:])
plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-')
plt.grid()
plt.xlabel("# of iterations")
plt.ylabel("Energy")
def plot_fidelity():
plt.plot(LiH_approximated_energies)
plt.xlabel("# of iterations")
plt.ylabel("Energy")
from qiskit.opflow import X, Z, I, H, Y
LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \
-0.0029329964409502266*(X^X^Y^Y) + \
0.0029329964409502266*(X^Y^Y^X) + \
0.01291078027311749*(X^Z^X^I) + \
-0.0013743761078958677*(X^Z^X^Z) + \
0.011536413200774975*(X^I^X^I) + \
0.0029329964409502266*(Y^X^X^Y) + \
-0.0029329964409502266*(Y^Y^X^X) + \
0.01291078027311749*(Y^Z^Y^I) + \
-0.0013743761078958677*(Y^Z^Y^Z) + \
0.011536413200774975*(Y^I^Y^I) + \
0.16199475388004184*(Z^I^I^I) + \
0.011536413200774975*(Z^X^Z^X) + \
0.011536413200774975*(Z^Y^Z^Y) + \
0.12444770133137588*(Z^Z^I^I) + \
0.054130445793298836*(Z^I^Z^I) + \
0.05706344223424907*(Z^I^I^Z) + \
0.012910780273117487*(I^X^Z^X) + \
-0.0013743761078958677*(I^X^I^X) + \
0.012910780273117487*(I^Y^Z^Y) + \
-0.0013743761078958677*(I^Y^I^Y) + \
0.16199475388004186*(I^Z^I^I) + \
0.05706344223424907*(I^Z^Z^I) + \
0.054130445793298836*(I^Z^I^Z) + \
-0.013243698330265966*(I^I^Z^I) + \
0.08479609543670981*(I^I^Z^Z) + \
-0.013243698330265952*(I^I^I^Z)
%%time
LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear")
compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue)
%%time
LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full")
compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue)
H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \
+ 0.1721839326191554 * (I^I^I^Z) \
- 0.22575349222402372 * (I^I^Z^I) \
+ 0.17218393261915543 * (I^Z^I^I) \
- 0.2257534922240237 * (Z^I^I^I) \
+ 0.12091263261776627 * (I^I^Z^Z) \
+ 0.16892753870087907 * (I^Z^I^Z) \
+ 0.045232799946057826 * (Y^Y^Y^Y) \
+ 0.045232799946057826 * (X^X^Y^Y) \
+ 0.045232799946057826 * (Y^Y^X^X) \
+ 0.045232799946057826 * (X^X^X^X) \
+ 0.1661454325638241 * (Z^I^I^Z) \
+ 0.1661454325638241 * (I^Z^Z^I) \
+ 0.17464343068300453 * (Z^I^Z^I) \
+ 0.12091263261776627 * (Z^Z^I^I)
%%time
H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear")
compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue)
%%time
H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full")
compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue)
transverse_ising_4_qubits = 0.0 * (I^I^I^I) \
+ 0.8398088405253477 * (X^I^I^I) \
+ 0.7989496312070936 * (I^X^I^I) \
+ 0.38189710487113193 * (Z^Z^I^I) \
+ 0.057753122422666725 * (I^I^X^I) \
+ 0.5633292636970458 * (Z^I^Z^I) \
+ 0.3152740621483513 * (I^Z^Z^I) \
+ 0.07209487981989715 * (I^I^I^X) \
+ 0.17892334004292654 * (Z^I^I^Z) \
+ 0.2273896497668042 * (I^Z^I^Z) \
+ 0.09762902934216211 * (I^I^Z^Z)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear")
compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full")
compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue)
QUBITS_NUM = 3
N = 2**QUBITS_NUM
NUM_SHOTS = 1024
NUM_ITERATIONS = 1000
CIRCUIT_DEPTH = 3
PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1)
from qiskit.opflow import X, Z, I
transverse_ising_3_qubits = 0.0 * (I^I^I) \
+ 0.012764169333459807 * (X^I^I) \
+ 0.7691573729160869 * (I^X^I) \
+ 0.398094746026449 * (Z^Z^I) \
+ 0.15250261906586637 * (I^I^X) \
+ 0.2094051920882264 * (Z^I^Z) \
+ 0.5131291860752999 * (I^Z^Z)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear")
compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full")
compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue)
QUBITS_NUM = 2
N = 2**QUBITS_NUM
NUM_SHOTS = 1024
NUM_ITERATIONS = 1000
CIRCUIT_DEPTH = 3
PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1)
transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \
+ 0.43305656297810435 * (X^I) \
+ 0.8538597608997253 * (Z^Z)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear")
compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full")
compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue)
from qiskit.opflow import X, Z, I
H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \
-0.3277380754984016*(Z^I) + \
0.15567463610622564*(Z^Z) + \
-0.3277380754984016*(I^Z)
%%time
H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear")
compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
%%time
H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full")
compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
|
https://github.com/cjsproject/qiskit_learning
|
cjsproject
|
%matplotlib inline
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ, assemble, extensions
from qiskit.visualization import *
from os import environ
#local environment variable to store the access token :)
token = environ.get('ibmq_token')
# Loading your IBM Q account(s)
account = IBMQ.save_account(token, overwrite=True)
provider = IBMQ.load_account()
# quasm_sim not necessary
simulator = Aer.get_backend('qasm_simulator')
import numpy as np
from matplotlib.image import imread
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
digits = load_digits()
# load the list of lists into a list :)
img_data = digits['images']
print(img_data[0])
# setting the figure parameters to the size of the input
plt.rcParams['figure.figsize'] = [4, 4]
# testing one input
A = img_data[5]
B = img_data[5]
# displays image in grayscale
display = plt.imshow(A)
display.set_cmap('gray')
# compress image to a 4x4
r=4
# approx image:
Xapp = np.zeros((r,r))
for i in range(0, len(A), 2):
for j in range(0, len(A), 2):
sub_mat = np.zeros(r)
sub_sum = 0
sub_sum += A[i][j] + A[i][j+1] + A[i+1][j] + A[i+1][j+1]
Xapp[int(i/2)][int(j/2)] = sub_sum/4
print(np.array(Xapp))
plt.figure(1)
img = plt.imshow(Xapp)
img.set_cmap('gray')
plt.show()
# Not sure if the inaccurate representation is an accurate one :) ie new unitary imgmap vs original imgmap
# perform full Singular Vector Decomposition (SVD) on compressed image
U, S, VT = np.linalg.svd(Xapp, full_matrices=True)
# take unitary parts for encoding
new_unitary = np.matmul(U, VT)
print(Xapp, new_unitary,sep='\n\n')
display = plt.imshow(new_unitary)
display.set_cmap('gray')
# circuit 2^n = 64, so n=6
qc = QuantumCircuit(2, 2)
# testing basic unitary
identity = np.identity(4)
print(len(new_unitary))
qc.unitary(new_unitary, [0, 1])
# measure qubit's output
qc.measure([0, 1], [0, 1])
qc.draw()
# run simulation 100000 times, stores results in counts
job = execute(qc, simulator, shots=100000)
results = job.result()
counts = results.get_counts(qc)
plot_histogram(counts)
""" NOT SURE HOW TO DECODE YET :("""
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
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),
]
)
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms.optimizers import SLSQP
ansatz = TwoLocal(3, rotation_blocks=["ry", "rz"], entanglement_blocks="cz", reps=1)
optimizer = SLSQP()
ansatz.decompose().draw('mpl')
from qiskit.primitives import Sampler, Estimator
from qiskit.algorithms.state_fidelities import ComputeUncompute
estimator = Estimator()
sampler = Sampler()
fidelity = ComputeUncompute(sampler)
k = 3
betas = [33, 33, 33]
counts = []
values = []
steps = []
def callback(eval_count, params, value, meta, step):
counts.append(eval_count)
values.append(value)
steps.append(step)
from qiskit.algorithms.eigensolvers import VQD
vqd = VQD(estimator, fidelity, ansatz, optimizer, k=k, betas=betas, callback=callback)
result = vqd.compute_eigenvalues(operator = H2_op)
vqd_values = result.optimal_values
print(vqd_values)
import numpy as np
import pylab
pylab.rcParams["figure.figsize"] = (12, 8)
steps = np.asarray(steps)
counts = np.asarray(counts)
values = np.asarray(values)
for i in range(1,4):
_counts = counts[np.where(steps == i)]
_values = values[np.where(steps == i)]
pylab.plot(_counts, _values, label=f"State {i-1}")
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Energy convergence for each computed state")
pylab.legend(loc="upper right");
from qiskit.algorithms.eigensolvers import NumPyEigensolver
from qiskit.opflow import PauliSumOp
exact_solver = NumPyEigensolver(k=3)
exact_result = exact_solver.compute_eigenvalues(PauliSumOp(H2_op))
ref_values = exact_result.eigenvalues
print(f"Reference values: {ref_values}")
print(f"VQD values: {vqd_values}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
# this notebook is for testing when we smush 1Q gates into a 2Q gate (and changing its weyl coordinates)
# whether the new coordinates it gets access to gives the overall 2Q+smush additional volume had it not had otherwise
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
import numpy as np
%matplotlib widget
from slam.utils.visualize import unitary_2dlist_weyl, coordinate_2dlist_weyl
from qiskit.quantum_info import Operator
from weylchamber import c1c2c3
import h5py
# from tqdm.notebook import tqdm as tqdm
from tqdm import tqdm
from config import srcpath
filename = f"{srcpath}/data/smush_unitary.h5"
from slam.utils.visualize import fpath_images
from slam.hamiltonian import ConversionGainPhaseHamiltonian
from slam.basisv2 import CircuitTemplateV2
from slam.utils.gates.custom_gates import ConversionGainGate
pp = lambda p1, p2: ConversionGainGate(p1, p2, np.pi / 4, np.pi / 4)
basis = CircuitTemplateV2(n_qubits=2, base_gates=[pp], no_exterior_1q=0, vz_only=1)
basis.build(1)
# what is volume of 1.5 iswaps with smushed gates, vs 3 sqrts with out
# can we make 1.8 pulse to 1.5 for swap
t = 1.5
duration_1q = 0.25
gc = 1 * np.pi / 2
gg = 0 * np.pi / 4
bounds_1q = 2 * np.pi
# from slam.utils.gates.custom_gates import ConversionGainSmushGate
# # NOTE first variable is tracking an offset (basically set it to 2 if counting the phase variables)
# p_expand = [0, round(t/duration_1q), round(t/duration_1q)]
# # XXX turn p_expand into indices is tricky
# #pp2 =lambda *vargs: ConversionGainSmushGate(vargs[0], vargs[1], np.pi/2, 0, vargs[2:2+round(t/duration_1q)], vargs[2+round(t/duration_1q):], t_el=t)
# pp2 =lambda *vargs: ConversionGainSmushGate(0, 0, gc, gg, vargs[:round(t/duration_1q)], vargs[round(t/duration_1q):], t_el=t)
# # circuittemplate builds # of parameters by checking the number of parameters in the lambda function to build the gate
# # because the parametes for gx and gy are vectors they only get counted once and it messes up
# # we can add an extra parameter called param_vec_expand
# # we need to use this to tell it to expand the number of parameters we should include
# # however, this will get really messy because we don't know which parameters are the vectors or not
# # be careful, this is going to be a mess :(
# basis = CircuitTemplateV2(n_qubits=2, base_gates=[pp2], no_exterior_1q=1, vz_only=0, param_vec_expand = p_expand)
# basis.build(1)
# # #adding constraint of 1Q params need to be positive valued
# # #this could be optional let's compare what happens if include it or not
# # for el in basis.circuit.parameters:
# # s_el = str(el)
# # if 'Q' in s_el:
# # basis.add_bound(s_el, bounds_1q, 0)
# # #basis.add_bound("Q0", 4*np.pi, 0)
# basis.circuit.draw(output='mpl')
# from slam.utils.visualize import unitary_2dlist_weyl
# from qiskit.quantum_info import Operator
# from tqdm import tqdm
# unitary_list = []
# param_list = []
# for i in tqdm(range(3000)):
# params = basis.parameter_guess()
# qc_init = basis.assign_Xk(params)
# unitary_list.append(Operator(qc_init).data)
# param_list.append(params)
# unitary_2dlist_weyl(unitary_list)
# coordinate_list = list(map(lambda x: c1c2c3(x), unitary_list))
# # combine the two lists
# combined_list = list(zip(coordinate_list, unitary_list, param_list))
# # arg min coordinate closest to (.75, 0, 0)
# sorted(combined_list, key=lambda x: np.linalg.norm(np.array(x[0]) - np.array([.75, 0,0])))[0][1]
from slam.utils.gates.custom_gates import ConversionGainSmushGate
# NOTE first variable is tracking an offset (basically set it to 2 if counting the phase variables)
poffset = 0
p_expand = [poffset, round(t / duration_1q), round(t / duration_1q)]
# XXX turn p_expand into indices is tricky
if poffset == 0:
pp2 = lambda *vargs: ConversionGainSmushGate(
0,
0,
gc,
gg,
vargs[: round(t / duration_1q)],
vargs[round(t / duration_1q) :],
t_el=t,
)
else:
pp2 = lambda *vargs: ConversionGainSmushGate(
vargs[0],
vargs[1],
gc,
gg,
vargs[poffset : poffset + round(t / duration_1q)],
vargs[poffset + round(t / duration_1q) :],
t_el=t,
)
# pp2 =lambda *vargs: ConversionGainSmushGate(0, 0, np.pi/2, 0, vargs[:round(t/du}ration_1q)], vargs[round(t/duration_1q):], t_el=t)
# circuittemplate builds # of parameters by checking the number of parameters in the lambda function to build the gate
# because the parametes for gx and gy are vectors they only get counted once and it messes up
# we can add an extra parameter called param_vec_expand
# we need to use this to tell it to expand the number of parameters we should include
# however, this will get really messy because we don't know which parameters are the vectors or not
# be careful, this is going to be a mess :(
basis = CircuitTemplateV2(
n_qubits=2, base_gates=[pp2], no_exterior_1q=1, vz_only=0, param_vec_expand=p_expand
)
k = 1
basis.build(k)
# adding constraint of 1Q params need to be positive valued
# this could be optional let's compare what happens if include it or not
# for el in basis.circuit.parameters:
# s_el = str(el)
# if 'Q' in s_el:
# basis.add_bound(s_el, bounds_1q, -bounds_1q)
# basis.add_bound("Q0", 4*np.pi, 0)
basis.circuit.draw()
from slam.utils.visualize import unitary_2dlist_weyl
from qiskit.quantum_info import Operator
from tqdm import tqdm
# NOTE don't reset unitary list if want to stack between each K
unitary_list = []
# print(len(unitary_list))
# param_list = []
for i in tqdm(range(1000)):
params = basis.parameter_guess()
qc_init = basis.assign_Xk(params)
unitary_list.append(Operator(qc_init).data)
# param_list.append(params)
# get this case which should be the vanilla basis gate
params = np.array(basis.parameter_guess()) * 0
qc_init = basis.assign_Xk(params)
unitary_list.append(Operator(qc_init).data)
# param_list.append(params)
unitary_2dlist_weyl(unitary_list, c="red", no_bar=1)
coordinate_list = list(map(lambda x: c1c2c3(x), unitary_list))
# coordinate_2dlist_weyl(reduced_coordinate_list, no_bar=1);
# # combine the two lists
# combined_list = list(zip(coordinate_list, unitary_list, param_list))
# # arg min coordinate closest to (.5, .25, .25)
# sorted(combined_list, key=lambda x: np.linalg.norm(np.array(x[0]) - np.array([.5, .25, .25])))[0]
# # does same thing :)
# # idx = np.argmin(np.linalg.norm(np.array(coordinate_list) - np.array([.5, .25, .25])))
# # print (coordinate_list[idx], unitary_list[idx])
from slam.utils.gates.custom_gates import ConversionGainSmushGate
# NOTE first variable is tracking an offset (basically set it to 2 if counting the phase variables)
p_expand = [4, round(t / duration_1q), round(t / duration_1q)]
# XXX turn p_expand into indices is tricky
# pp2 =lambda *vargs: ConversionGainSmushGate(vargs[0], vargs[1], vargs[2], vargs[3], vargs[4:4+round(t/duration_1q)], vargs[4+round(t/duration_1q):], t_el=t)
# #pp2 =lambda *vargs: ConversionGainSmushGate(0, 0, np.pi/2, 0, vargs[:round(t/duration_1q)], vargs[round(t/duration_1q):], t_el=t)
varg_offset = 2
pp2 = lambda *vargs: ConversionGainSmushGate(
0,
0,
vargs[0],
vargs[1],
vargs[varg_offset : varg_offset + round(t / duration_1q)],
vargs[varg_offset + round(t / duration_1q) :],
t_el=t,
)
basis = CircuitTemplateV2(
n_qubits=2,
base_gates=[pp2],
edge_params=[[(0, 1)]],
vz_only=True,
no_exterior_1q=1,
param_vec_expand=[varg_offset, round(t / duration_1q), round(t / duration_1q)],
)
basis_str = "CG2Q"
# varg_offset = 4
# pp3 =lambda *vargs: ConversionGainSmushGate(vargs[0], vargs[1], vargs[2], vargs[3], vargs[varg_offset:varg_offset+round(t/duration_1q)], vargs[varg_offset+round(t/duration_1q):], t_el=t)
# basis = CircuitTemplateV2(n_qubits=2, base_gates = [pp3], edge_params=[[(0,1)]], vz_only=True, param_vec_expand=[varg_offset,round(t/duration_1q),round(t/duration_1q)])
# basis_str = "CG2Q+P"
# circuittemplate builds # of parameters by checking the number of parameters in the lambda function to build the gate
# because the parametes for gx and gy are vectors they only get counted once and it messes up
# we can add an extra parameter called param_vec_expand
# we need to use this to tell it to expand the number of parameters we should include
# however, this will get really messy because we don't know which parameters are the vectors or not
# be careful, this is going to be a mess :(
# basis = CircuitTemplateV2(n_qubits=2, base_gates=[pp2], no_exterior_1q=1, vz_only=0, param_vec_expand = p_expand)
basis.build(1)
# adding constraint of 1Q params need to be positive valued
# this could be optional let's compare what happens if include it or not
for el in basis.circuit.parameters:
s_el = str(el)
if "Q" in s_el:
basis.add_bound(s_el, bounds_1q, -bounds_1q)
basis.circuit.draw()
# #load from hdf5 file
# with h5py.File(filename, 'a') as f:
# data = f.require_group(f'{basis_str}_unitary_cost_data_t{t}')
# if 'unitary_list' in data and 'cost_list' in data:
# unitary_list = list(data['unitary_list'][:])
# cost_list = list(data['cost_list'][:])
# else:
# unitary_list = []
# cost_list = []
unitary_list = []
cost_list = []
# outer loop is sweeping over gc and gc
for m in tqdm(np.linspace(0, 0.5, 11)): # 17
if m == 0:
continue # identity is not interesting case
for n in np.linspace(0, 1, 9): # 21
for i in range(800):
gc = n * m * np.pi
gg = (1 - n) * m * np.pi
cost = ConversionGainGate(0, 0, gc, gg, t_el=t).cost()
# need to convert strings to Parameter objects
# the reason need to do this is because need to get reference to the exact parameter object via iteration
if basis_str == "CG2Q+P":
pstrs = ["Q2", "Q3"]
else:
pstrs = ["Q0", "Q1"]
pdict = {
str(pstr): [p for p in basis.circuit.parameters if p.name == pstr][0]
for pstr in pstrs
}
qc_init = basis.circuit.assign_parameters({pdict[pstrs[0]]: gc})
qc_init = qc_init.assign_parameters({pdict[pstrs[1]]: gg})
# randomize the remaining parameters
# NOTE there isn't a 1-1 mapping from p to remaining parameters bc have replaced q2 and q3 already but doesnt matter since is random
p = basis.parameter_guess()
# qc_init = qc_init.assign_Xk(p)
qc_init = qc_init.assign_parameters(
{k: v for k, v in zip(qc_init.parameters, p)}
)
# eliminating x-axis symmetry
c = list(c1c2c3(Operator(qc_init).data))
if c[0] > 0.5:
c[0] = -1 * c[0] + 1
# #when checking for duplicates, keep the lower cost one
# #instead of checking for duplicates, check if already a coordinate close by
# if any([np.linalg.norm(np.array(c)-np.array(c2)) < 0.025 for c2 in unitary_list]):
# c2 = unitary_list[np.argmin([np.linalg.norm(np.array(c)-np.array(c2)) for c2 in unitary_list])]
# ind = unitary_list.index(c2)
# if cost < cost_list[ind]:
# unitary_list[ind] = c
# cost_list[ind] = cost
# continue
else:
unitary_list.append(c)
cost_list.append(cost)
# do some preprocessing that takes the smaller cost value if their is a match of coordinates
# no not a good idea
# # save unitary list into a hdf5 file
# with h5py.File(filename, 'w') as f:
# f.create_dataset(f'{basis_str}_unitary_cost_data_t{t}/unitary_list', data=unitary_list)
# f.create_dataset(f'{basis_str}_unitary_cost_data_t{t}/cost_list', data=cost_list)
dub_unitary_list = []
dub_cost_list = []
for unitary, cost in zip(unitary_list, cost_list):
# want to add the conjugate
x, y, z = unitary
dub_cost_list.append(cost)
dub_unitary_list.append([x, y, z])
dub_cost_list.append(cost)
dub_unitary_list.append([1 - x, y, z])
fig = coordinate_2dlist_weyl(dub_unitary_list, c=dub_cost_list)
# save fig as pdf and svg
fig.savefig(f"{fpath_images}/smush_primative_sweep.svg", format="svg")
fig.savefig(f"{fpath_images}/smush_primative_sweep.pdf", format="pdf")
# fill points on the triangle, interpolate
# and reflect over the axis
# load from hdf5 file
import h5py
with h5py.File(filename, "r") as f:
data = f.require_group(f"{basis_str}_unitary_cost_data_t{t}")
if "unitary_list" in data and "cost_list" in data:
unitary_list = list(data["unitary_list"][:])
cost_list = list(data["cost_list"][:])
fig = coordinate_2dlist_weyl(unitary_list, c=cost_list);
# #save fig to file as svg and as pdf
# fig.savefig(f'{fpath_images}/{basis_str}_unitary_cost_data_t{t}.svg', format='svg')
# fig.savefig(f'{fpath_images}/{basis_str}_unitary_cost_data_t{t}.pdf', format='pdf')
# #load from hdf5 file
# with h5py.File(filename, 'r') as f:
# data = f.require_group('unitary_cost_data')
# if 'unitary_list' in data and 'cost_list' in data:
# unitary_list = list(data['unitary_list'][:])
# cost_list = list(data['cost_list'][:])
# #if a coordinate is within some threshold of another coordinate, remove the one with the higher cost
# for i, (cost, c) in enumerate(zip(cost_list, unitary_list)):
# #check if there is a coordinate within some threshold, not including itself
# if any([np.linalg.norm(np.array(c)-np.array(c2)) < 0.025 for c2 in unitary_list if (c2 != c).all()]):
# #if there is, find the index of the coordinate that is closest
# c2 = unitary_list[np.argmin([np.linalg.norm(np.array(c)-np.array(c2)) for c2 in unitary_list if (c2 != c).all()])]
# ind = np.where(np.all(unitary_list == c2, axis=1))[0][0]
# #if the cost of the coordinate we are checking is higher, remove it
# if cost > cost_list[ind]:
# unitary_list.pop(i)
# cost_list.pop(i)
# print(len(unitary_list))
# coordinate_2dlist_weyl(unitary_list, c=cost_list)
from slam.utils.gates.custom_gates import ConversionGainSmushGate
# NOTE first variable is tracking an offset (basically set it to 2 if counting the phase variables)
p_expand = [2, round(t / duration_1q), round(t / duration_1q)]
# XXX turn p_expand into indices is tricky
# pp2 =lambda *vargs: ConversionGainSmushGate(0, 0, vargs[0], vargs[1], vargs[4:4+round(t/duration_1q)], vargs[4+round(t/duration_1q):], t_el=t)
# #pp2 =lambda *vargs: ConversionGainSmushGate(0, 0, np.pi/2, 0, vargs[:round(t/duration_1q)], vargs[round(t/duration_1q):], t_el=t)
varg_offset = 2
pp2 = lambda *vargs: ConversionGainSmushGate(
0,
0,
vargs[0],
vargs[1],
vargs[varg_offset : varg_offset + round(t / duration_1q)],
vargs[varg_offset + round(t / duration_1q) :],
t_el=t,
)
basis = CircuitTemplateV2(
n_qubits=2,
base_gates=[pp2],
edge_params=[[(0, 1)]],
vz_only=True,
param_vec_expand=[varg_offset, round(t / duration_1q), round(t / duration_1q)],
)
basis_str = "CG2Q"
# varg_offset = 4
# pp3 =lambda *vargs: ConversionGainSmushGate(vargs[0], vargs[1], vargs[2], vargs[3], vargs[varg_offset:varg_offset+round(t/duration_1q)], vargs[varg_offset+round(t/duration_1q):], t_el=t)
# basis = CircuitTemplateV2(n_qubits=2, base_gates = [pp3], edge_params=[[(0,1)]], vz_only=True, param_vec_expand=[varg_offset,round(t/duration_1q),round(t/duration_1q)])
# basis_str = "CG2Q+P"
# circuittemplate builds # of parameters by checking the number of parameters in the lambda function to build the gate
# because the parametes for gx and gy are vectors they only get counted once and it messes up
# we can add an extra parameter called param_vec_expand
# we need to use this to tell it to expand the number of parameters we should include
# however, this will get really messy because we don't know which parameters are the vectors or not
# be careful, this is going to be a mess :(
basis = CircuitTemplateV2(
n_qubits=2, base_gates=[pp2], no_exterior_1q=1, vz_only=0, param_vec_expand=p_expand
)
basis.build(1)
# adding constraint of 1Q params need to be positive valued
# this could be optional let's compare what happens if include it or not
for el in basis.circuit.parameters:
s_el = str(el)
if "Q" in s_el:
basis.add_bound(s_el, bounds_1q, -bounds_1q)
# basis.add_bound("Q0", 4*np.pi, 0)
basis.circuit.draw()
from slam.utils.visualize import unitary_2dlist_weyl, coordinate_2dlist_weyl
from qiskit.quantum_info import Operator
from weylchamber import c1c2c3
from tqdm import tqdm
from random import random
unitary_list = []
cost_list = []
from slam.utils.visualize import unitary_2dlist_weyl
from qiskit.quantum_info import Operator
from tqdm import tqdm
unitary_list = []
cost_list = []
for i in tqdm(range(2500)):
gc = random() * np.pi
gg = random() * np.pi
cost = ConversionGainGate(0, 0, gc, gg, t_el=t).cost()
# need to convert strings to Parameter objects
# the reason need to do this is because need to get reference to the exact parameter object via iteration
pstrs = ["Q2", "Q3"]
pdict = {
str(pstr): [p for p in basis.circuit.parameters if p.name == pstr][0]
for pstr in pstrs
}
qc_init = basis.circuit.assign_parameters({pdict["Q2"]: gc})
qc_init = qc_init.assign_parameters({pdict["Q3"]: gg})
# randomize the remaining parameters
# NOTE there isn't a 1-1 mapping from p to remaining parameters bc have replaced q2 and q3 already but doesnt matter since is random
p = basis.parameter_guess()
# qc_init = qc_init.assign_Xk(p)
qc_init = qc_init.assign_parameters({k: v for k, v in zip(qc_init.parameters, p)})
c = list(c1c2c3(Operator(qc_init).data))
# eliminating x-axis symmetry
if c[0] > 0.5:
c[0] = -1 * c[0] + 1
if c in unitary_list:
continue
unitary_list.append(c)
cost_list.append(cost)
coordinate_2dlist_weyl(unitary_list, c=cost_list);
from slam.utils.gates.custom_gates import ConversionGainSmushGate, ConversionGainGate
# NOTE first variable is tracking an offset (basically set it to 2 if counting the phase variables)
p_expand = [2, 1, 1]
# XXX turn p_expand into indices is tricky
pp2 = lambda *vargs: ConversionGainGate(0, 0, vargs[0], vargs[1], t_el=1.0)
# pp2 =lambda *vargs: ConversionGainSmushGate(0, 0, np.pi/2, 0, vargs[:round(t/duration_1q)], vargs[round(t/duration_1q):], t_el=t)
# circuittemplate builds # of parameters by checking the number of parameters in the lambda function to build the gate
# because the parametes for gx and gy are vectors they only get counted once and it messes up
# we can add an extra parameter called param_vec_expand
# we need to use this to tell it to expand the number of parameters we should include
# however, this will get really messy because we don't know which parameters are the vectors or not
# be careful, this is going to be a mess :(
basis = CircuitTemplateV2(
n_qubits=2, base_gates=[pp2], no_exterior_1q=1, vz_only=0, param_vec_expand=p_expand
)
# adding constraint of 1Q params need to be positive valued
# this could be optional let's compare what happens if include it or not
basis.build(1)
for el in basis.circuit.parameters:
s_el = str(el)
if "Q" in s_el:
basis.add_bound(s_el, bounds_1q, -bounds_1q)
# basis.add_bound("Q0", 4*np.pi, 0)
basis.circuit.draw()
from slam.utils.visualize import unitary_2dlist_weyl, coordinate_2dlist_weyl
from qiskit.quantum_info import Operator
from weylchamber import c1c2c3
from tqdm import tqdm
unitary_list = []
cost_list = []
# outer loop is sweeping over gc and gc
for m in tqdm(np.linspace(0, 0.5, 47)): # 47
for n in np.linspace(0, 1, 41): # 41
for i in range(1):
gc = n * m * np.pi
gg = (1 - n) * m * np.pi
cost = ConversionGainGate(0, 0, gc, gg, t_el=t).cost()
# need to convert strings to Parameter objects
# the reason need to do this is because need to get reference to the exact parameter object via iteration
pstrs = ["Q0", "Q1"]
pdict = {
str(pstr): [p for p in basis.circuit.parameters if p.name == pstr][0]
for pstr in pstrs
}
qc_init = basis.circuit.assign_parameters({pdict["Q0"]: gc})
qc_init = qc_init.assign_parameters({pdict["Q1"]: gg})
# randomize the remaining parameters
# p = basis.parameter_guess()
# qc_init = qc_init.assign_Xk(p)
# eliminating x-axis symmetry
c = list(c1c2c3(Operator(qc_init).data))
unitary_list.append(c)
cost_list.append(cost)
# add the conjugate
c_copy = c.copy()
if c_copy[0] > 0.5:
c_copy[0] = -1 * c_copy[0] + 1
elif c_copy[0] < 0.5:
c_copy[0] = 1 - c_copy[0]
unitary_list.append(c_copy)
cost_list.append(cost)
# do some preprocessing that takes the smaller cost value if their is a match of coordinates
# no not a good idea
coordinate_2dlist_weyl(unitary_list, c=cost_list)
print(len(unitary_list))
fig = coordinate_2dlist_weyl(unitary_list, c=cost_list)
# save fig as pdfpath_images svg
from slam.utils.visualize import fpath_images
fig.savefig(f"{fpath_images}/candidate_costs.pdf", format="pdf", bbox_inches="tight")
fig.savefig(f"{fpath_images}/candidate_costs.svg", format="svg", bbox_inches="tight")
# if a coordinate is within some threshold of another coordinate, remove the one with the higher cost
for i, (cost, c) in enumerate(zip(cost_list, unitary_list)):
# check if there is a coordinate within some threshold, not including itself
if any(
[
np.linalg.norm(np.array(c) - np.array(c2)) < 0.1
for c2 in unitary_list
if (np.array(c2) != np.array(c)).all()
]
):
# if there is, find the index of the coordinate that is closest
c2 = unitary_list[
np.argmin(
[
np.linalg.norm(np.array(c) - np.array(c2))
for c2 in unitary_list
if (c2 != c).all()
]
)
]
ind = np.where(np.all(unitary_list == c2, axis=1))[0][0]
# if the cost of the coordinate we are checking is higher, remove it
if cost > cost_list[ind]:
unitary_list.pop(i)
cost_list.pop(i)
print(len(unitary_list))
coordinate_2dlist_weyl(unitary_list, c=cost_list);
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
from qiskit import *
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
%matplotlib inline
circuit.draw()
circuit.h(qr[0])
circuit.draw(output = 'mpl')
circuit.cx(qr[0], qr[1])
circuit.draw(output='mpl')
circuit.measure(qr, cr)
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
execute(circuit, backend=simulator)
result = execute(circuit, backend=simulator).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
# plot_histogram
provider = IBMQ.get_provider('ibm-q')
backend = provider.get_backend('ibmq_16_melbourne')
job =execute(circuit, backend= backend)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(circuit))
|
https://github.com/martynscn/Masters-Thesis-on-Quantum-Cryptography
|
martynscn
|
# This code has been adapted and modified from IBM Qiskit 2021 and
# uses the constant optimized modular exponentiation circuit for mod 15 as contained
# in https://arxiv.org/abs/1202.6614.
import numpy as np
import math
from decimal import *
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.visualization import plot_histogram
from qiskit import Aer, transpile, assemble
import pandas as pd
from fractions import Fraction
#
# import math
# from math import gcd
# from numpy.random import randint
#
#
# from decimal import *
print("Imports Successful")
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
def my_mod(a,n):
getcontext().prec = 27
return round((Decimal(a)/Decimal(n) - Decimal(a)//Decimal(n) ) * n)
def constant_optimized_modular_exponentation_modulus15(a, power):
if a not in [2,7,8,11,13]:
raise ValueError("'a' must be 2,7,8,11 or 13")
U = QuantumCircuit(4)
for iteration in range(power):
if a in [2,13]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
if a in [7,8]:
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
if a == 11:
U.swap(1,3)
U.swap(0,2)
if a in [7,11,13]:
for q in range(4):
U.x(q)
U = U.to_gate()
U.name = "%i^%i mod 15" % (a, power)
control_U = U.control()
return control_U
def inverse_qft(n):
circuit = QuantumCircuit(n)
for i in range(n//2):
circuit.swap(i, n-1-i)
for j in range(n):
for m in range(j):
circuit.cp(-np.pi/float(2**(j-m)), m, j)
circuit.h(j)
circuit.name = "QFT†"
return circuit
N = 15
a = 7
n_count = 8
counting_register = QuantumRegister(size = n_count, name = "counting_register")
acting_register = QuantumRegister(size = 4, name="acting_register")
classic_register = ClassicalRegister(size = n_count, name="classic_register")
qc = QuantumCircuit(counting_register, acting_register ,classic_register)
initial_state = [1,0]
for q in range(8):
qc.initialize(initial_state, q)
qc.draw(output = 'mpl', filename = "Step0")
for q in range(n_count):
qc.h(q)
qc.draw(output = 'mpl', filename = "Step1")
qc.x(3+n_count)
qc.draw(output = 'mpl', filename = "Step1b")
for q in range(n_count):
qc.append(constant_optimized_modular_exponentation_modulus15(a, 2**q),
[q] + [i+n_count for i in range(4)])
qc.measure(range(n_count,n_count + 4), range(4))
qc.barrier()
qc.draw(output = 'mpl', filename = "Step2")
qc.append(inverse_qft(n_count), range(n_count))
qc.draw(output = 'mpl', filename = "Step3")
# Measure circuit
qc.measure(range(n_count), range(n_count))
qc.draw(output = 'mpl', filename = "Step4")
qasm_sim = Aer.get_backend('qasm_simulator')
t_qc = transpile(qc, qasm_sim)
qobj = assemble(t_qc)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
rows, measured_phases = [], []
for output in counts:
decimal = int(output, 2)
phase = decimal/(2**n_count)
measured_phases.append(phase)
rows.append([f"{output}(bin) = {decimal:>3}(dec)",
f"{decimal}/{2**n_count} = {phase:.2f}"])
headers=["Register Output", "Phase"]
df = pd.DataFrame(rows, columns=headers)
df
rows = []
for phase in measured_phases:
frac = Fraction(phase).limit_denominator(15)
rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator])
headers=["Phase", "Fraction", "Guess for r"]
df = pd.DataFrame(rows, columns=headers)
my_period_r = max(df["Guess for r"])
print("My period (r) is %i" % my_period_r)
# Confirm that the period is 4
xvals = np.arange(N)
xvals = [x.item() for x in xvals]
yvals = [my_mod(a**x, N) for x in xvals]
fig, ax = plt.subplots();
ax.plot(xvals, yvals, linewidth=1, linestyle='dotted', marker='x');
ax.set(xlabel='$x$', ylabel='$%i^x$ mod $%i$' % (a, N),
title="Example of Periodic Function in Shor's Algorithm");
try:
r = yvals[1:].index(1) +1
plt.annotate(s = '', xy=(0,1), xytext=(r,1), arrowprops=dict(arrowstyle='<->'));
plt.annotate(s = '$r=%i$' % r, xy=(r/3,1.5));
except ValueError:
print('Could not find a period')
first_shared_factor = math.gcd((7**(int(my_period_r/2)) + 1), 15)
first_shared_factor
second_shared_factor = math.gcd((7**(int(my_period_r/2)) - 1), 15)
second_shared_factor
%qiskit_copyright
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import numpy as np
from linear_solver_float import LinearSolverFloat
# set floating point accuracy
R = 3
# first example
M = np.array([[3,2],
[2,1]])
Y_1 = np.array([1,1])
Y_2 = np.array([-1/2,-1/2])
M_inv = np.linalg.inv(M)
M_inv.dot(Y_1), M_inv.dot(Y_2)
num_reads = 1000
lsf = LinearSolverFloat(M,Y_1,R=R,num_reads=num_reads)
sampleset = lsf.sample()
sampleset.to_pandas_dataframe()
min_occurence = num_reads / 20
solutions = lsf.getSolutions(min_occurence)
list(solutions)
lsf.setY(Y_2)
lsf.sample() #3cc3c704-57e3-4238-bf4a-3368e3f1a326
list(lsf.getSolutions(min_occurence))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
# Create a circuit with a register of three qubits
circ = QuantumCircuit(3)
# H gate on qubit 0, putting this qubit in a superposition of |0> + |1>.
circ.h(0)
# A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state.
circ.cx(0, 1)
# CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state.
circ.cx(0, 2)
# Draw the circuit
circ.draw('mpl')
|
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/kerenavnery/qmail
|
kerenavnery
|
#!/usr/bin/env python3
from qiskit import *
from qiskit.quantum_info import Statevector
from textwrap import wrap
from random import randrange
from SocketChannel2 import SocketChannel
import pickle
from channel_class import Channel
import time
import numpy as np
# Quantum One-Time pad related methods
def str_to_lbin(message, bin_size=4):
"""
String to 8 bit binary per character
:message:str, the message
"""
clist = [ord(x) for x in message]
bins = ''.join([format(x,'08b') for x in clist])
return wrap(bins,bin_size)
def bins_to_str(lbin):
"""
Return a list of unicode characters into a message
:lbin:list(bin), a list of characters
"""
sbin = ''.join(lbin)
lbin8 = wrap(sbin, 8)
message = chr(int(lbin8[0],2))
for c in lbin8[1:]:
message+=chr(int(c,2))
return message
def encode_cinfo_to_qstate(cinfo_bin):
"""
Return the quantum state that encodes the binary
:cinfo_bin:str, string of binary contains the classical information
return :QuantumCircuit:
"""
nreg = len(cinfo_bin)
qcirc = QuantumCircuit(nreg, nreg)
for i,bit_i in enumerate(cinfo_bin[::-1]):
if int(bit_i):
qcirc.x(i)
return qcirc
def generate_otp_key(key_length):
"""
Generate key_length random key for one-time pad
"""
x_key=bin(randrange(2**key_length))[2:]
z_key=bin(randrange(2**key_length))[2:]
return {'x': x_key, 'z': z_key}
def otp_enc_dec(qcirc, otpkey):
"""
:qcirc:QuantumCircuit instance
:key:dict={x:, z:}
"""
r_x , r_z = otpkey['x'], otpkey['z']
for i,k in enumerate(zip(r_x,r_z)):
if k[0]:
qcirc.x(i)
if k[1]:
qcirc.z(i)
def qotp_send(qcirc, otpkey, qChannel=None):
"""
Quantum one-time pad
:qmessage:qiksit.QuantumCircuit
:otpkey: dict{x:int y:int}
:qChannel: quantum channel
"""
#Alice's part: encrypting
otp_enc_dec(qcirc, otpkey)
#Alice send the qubits
#TODO:Channel stuff
# send over Qchannel
qChannel.send(qcirc, [0,1,2,3])
time.sleep(1)
# #Bob receives qubits, and decrypt them
# otp_enc_dec(qcirc, otpkey)
#Bob measure the states, single shot
# simulator = Aer.get_backend('qasm_simulator')
# nqubit = len(otpkey['x'])
# for i in range(nqubit):
# qcirc.measure(range(nqubit), range(nqubit))
# counts = execute(qcirc, backend=simulator, shots = 1).result()
# output = list(counts.get_counts().keys())[0]
# return output
def send_a_qmail(message, port, destAddr, destPort, batch_size=4):
""" Alice sends to Bob a quantum email
:nqubit:int, the number of qubits
:message:str, the secret message that wants to be sent
"""
nqubit = batch_size
print('Alice wants to send %s'%message)
# Initialize with Bob
classicC = SocketChannel(port+10, False)
# connect to Bob
classicC.connect(destAddr, destPort+10)
#send message per batch bits
Lbins = str_to_lbin(message, batch_size)
#generate key
print('generating key...')
otpkey = generate_otp_key(len(Lbins)*batch_size)
print('X-encryption key %s'%otpkey['x'], 'Z-encryption key %s'%otpkey['z'])
# send key to Bob
classicC.send(pickle.dumps(otpkey))
print("I am Alice I sent:", otpkey)
# close the classic channel as we don't need it anymore
classicC.close()
time.sleep(2)
key_per_batch = [{'x':x,'z':z} for x,z in zip(wrap(otpkey['x'],batch_size),wrap(otpkey['z'],batch_size))]
# TODO: setup quantum channel
n_master = batch_size
n_slave = batch_size
slave_offset = 0
channel = Channel(slave_offset, port, remote_port=destPort)
# bob_meas_results = [] # Bob
for bin_batch,k in zip(Lbins, key_per_batch):
print('Performing QOTP for string', bin_batch)
qcirc = encode_cinfo_to_qstate(bin_batch) # Alice
qotp_send(qcirc, k, channel)
# print('Bob measures',bob_meas_results[-1]) # Bob
print("Transmission complete.")
# print('Bobs message %s'%bins_to_str(bob_meas_results)) #Bob
# return bins_to_str(bob_meas_results)
def receive_a_qmail(port, srcAddr, srcPort, batch_size=4, adversary=False):
# Initialize with Bob
classicC = SocketChannel(port+10, True)
# connect to Bob
classicC.connect(srcAddr, srcPort+10)
# receive otpkey from alice
otpkey = classicC.receive()
otpkey = pickle.loads(otpkey)
print("I am Bob I received: ", otpkey)
classicC.close()
time.sleep(1)
key_per_batch = [{'x':x,'z':z} for x,z in zip(wrap(otpkey['x'],batch_size),wrap(otpkey['z'],batch_size))]
# TODO: setup quantum channel
n_master = batch_size
n_slave = batch_size
slave_offset = 0
channel = Channel(slave_offset, port, remote_port=srcPort)
qcirc = None
# TODO: decrypt and measure
# Eve siVmulation
recv = "Eve" if adversary else "Bob"
bob_meas_results = []
for k in key_per_batch:
circ_bob = QuantumCircuit(batch_size, batch_size)
circ_bob, offset = channel.receive(circ_bob)
# circ_bob.draw(output='mpl',filename="teleport_alice%s.png".format(k))
#Bob receives qubits, and decrypt them
if not adversary:
otp_enc_dec(circ_bob, k)
#Bob measure the states, single shot
simulator = Aer.get_backend('qasm_simulator')
nqubit = len(otpkey['x'])
# for i in range(nqubit):
circ_bob.measure(np.arange(batch_size)+offset, range(batch_size))
counts = execute(circ_bob, backend=simulator, shots = 1).result()
output = list(counts.get_counts().keys())[0]
bob_meas_results.append(output)
print('%s measures'%recv, bob_meas_results[-1])
print('%ss message %s'%(recv, bins_to_str(bob_meas_results)))
return bins_to_str(bob_meas_results)
# Grover-related methods
def apply_grover_oracle2(qcirc, dquery):
"""
grover oracle for query database:
:qcirc:QuantumCircuit, the qubits to apply
:query:str, 00 01 10 11
"""
qcirc.cz(1,0)
if dquery == '11':
qcirc.z(0)
qcirc.z(1)
elif dquery == '01':
qcirc.z(1)
elif dquery == '10':
qcirc.z(0)
else : pass
def multiparty_2grover_local(port, destPort):
"""
multiparties 2-qubit grover algorithm with separated oracle
as the database owner (Oscar). Oscar has a confiedential database,
and will help Alice to reveal her data.
:dquery:str, 00 01 10 11
"""
print("Alice creates state |00>")
qcirc = QuantumCircuit(2,2)
qcirc.h(0)
qcirc.h(1) #at this point qcirc is in the equal superposition of all quantum states
# TODO: setup quantum channel
n_master = 2
n_slave = 2
slave_offset = 0
channel = Channel(slave_offset, port, remote_port=destPort)
print("Alice send qubits to Oscar, quering the database")
# send ... Channel stuff......
channel.send(qcirc, [0,1])
# print("Oscar receives qubits, and apply oracles")
# apply_grover_oracle2(qcirc, dquery)
# print("Oscar sends the qubits back to Alice")
# # send ... Channel stuff......
print("Alice receives qubits, apply diffusion operator, and measure")
qcirc, offset = channel.receive(qcirc)
qcirc.h(0)
qcirc.h(1)
qcirc.cz(0,1)
qcirc.h(0)
qcirc.h(1)
qcirc.measure([0,1],[0,1])
simulator = Aer.get_backend('qasm_simulator')
counts = execute(qcirc, backend=simulator, shots = 1).result()
print("Alice measurement outcome", list(counts.get_counts().keys())[0])
def oscar_sends(dquery, port, srcPort):
# Init circuit
qcirc = QuantumCircuit(2,2)
# TODO: setup quantum channel
n_master = 2
n_slave = 2
slave_offset = 0
channel = Channel(slave_offset, port, remote_port=srcPort)
print("Oscar receives qubits, and apply oracles")
qcirc, offset = channel.receive(qcirc)
apply_grover_oracle2(qcirc, dquery)
print("Oscar sends the qubits back to Alice")
# send ... Channel stuff......
channel.send(qcirc, [0,1])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.