repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
|
#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/abbarreto/qiskit4
|
abbarreto
|
import numpy as np
from sklearn.datasets.samples_generator import make_blobs
from qiskit.aqua.utils import split_dataset_to_data_and_labels
from sklearn import svm
from utility import breast_cancer_pca
from matplotlib import pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
n = 2 # number of principal components kept
training_dataset_size = 20
testing_dataset_size = 10
sample_Total, training_input, test_input, class_labels = breast_cancer_pca(training_dataset_size, testing_dataset_size, n)
data_train, _ = split_dataset_to_data_and_labels(training_input)
data_test, _ = split_dataset_to_data_and_labels(test_input)
print (f"data_train[0].shape: {data_train[0].shape}" )
print (f"data_train[1].shape: {data_train[1].shape}" )
# We use the function of scikit learn to generate linearly separable blobs
centers = [(2.5,0),(0,2.5)]
x, y = make_blobs(n_samples=100, centers=centers, n_features=2,random_state=0,cluster_std=0.5)
fig,ax=plt.subplots(1,2,figsize=(12,4))
ax[0].scatter(data_train[0][:,0],data_train[0][:,1],c=data_train[1])
ax[0].set_title('Breast Cancer dataset');
ax[1].scatter(x[:,0],x[:,1],c=y)
ax[1].set_title('Blobs linearly separable');
plt.scatter(data_train[0][:,0],data_train[0][:,1],c=data_train[1])
plt.title('Breast Cancer dataset');
model= svm.LinearSVC()
model.fit(data_train[0], data_train[1])
#small utility function
# some utility functions
def make_meshgrid(x, y, h=.02):
x_min, x_max = x.min() - 1, x.max() + 1
y_min, y_max = y.min() - 1, y.max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
return xx, yy
def plot_contours(ax, clf, xx, yy, **params):
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
out = ax.contourf(xx, yy, Z, **params)
return out
accuracy_train = model.score(data_train[0], data_train[1])
accuracy_test = model.score(data_test[0], data_test[1])
X0, X1 = data_train[0][:, 0], data_train[0][:, 1]
xx, yy = make_meshgrid(X0, X1)
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
fig,ax=plt.subplots(1,2,figsize=(15,5))
ax[0].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[0].scatter(data_train[0][:,0], data_train[0][:,1], c=data_train[1])
ax[0].set_title('Accuracy on the training set: '+str(accuracy_train));
ax[1].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[1].scatter(data_test[0][:,0], data_test[0][:,1], c=data_test[1])
ax[1].set_title('Accuracy on the test set: '+str(accuracy_test));
clf = svm.SVC(gamma = 'scale')
clf.fit(data_train[0], data_train[1]);
accuracy_train = clf.score(data_train[0], data_train[1])
accuracy_test = clf.score(data_test[0], data_test[1])
X0, X1 = data_train[0][:, 0], data_train[0][:, 1]
xx, yy = make_meshgrid(X0, X1)
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
fig,ax=plt.subplots(1,2,figsize=(15,5))
ax[0].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[0].scatter(data_train[0][:,0], data_train[0][:,1], c=data_train[1])
ax[0].set_title('Accuracy on the training set: '+str(accuracy_train));
ax[1].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[1].scatter(data_test[0][:,0], data_test[0][:,1], c=data_test[1])
ax[1].set_title('Accuracy on the test set: '+str(accuracy_test));
import qiskit as qk
# Creating Qubits
q = qk.QuantumRegister(2)
# Creating Classical Bits
c = qk.ClassicalRegister(2)
circuit = qk.QuantumCircuit(q, c)
circuit.draw('mpl')
# Initialize empty circuit
circuit = qk.QuantumCircuit(q, c)
# Hadamard Gate on the first Qubit
circuit.h(q[0])
# CNOT Gate on the first and second Qubits
circuit.cx(q[0], q[1])
# Measuring the Qubits
circuit.measure(q, c)
circuit.draw('mpl')
# Using Qiskit Aer's Qasm Simulator: Define where do you want to run the simulation.
simulator = qk.BasicAer.get_backend('qasm_simulator')
# Simulating the circuit using the simulator to get the result
job = qk.execute(circuit, simulator, shots=100)
result = job.result()
# Getting the aggregated binary outcomes of the circuit.
counts = result.get_counts(circuit)
print (counts)
from qiskit.aqua.components.feature_maps import SecondOrderExpansion
feature_map = SecondOrderExpansion(feature_dimension=2, depth=1)
x = np.array([0.6, 0.3])
#feature_map.construct_circuit(x)
print(feature_map.construct_circuit(x))
from qiskit.aqua.algorithms import QSVM
qsvm = QSVM(feature_map, training_input, test_input)
#from qiskit.aqua import run_algorithm, QuantumInstance
from qiskit.aqua import algorithm, QuantumInstance
from qiskit import BasicAer
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=10598, seed_transpiler=10598)
result = qsvm.run(quantum_instance)
plt.scatter(training_input['Benign'][:,0], training_input['Benign'][:,1])
plt.scatter(training_input['Malignant'][:,0], training_input['Malignant'][:,1])
length_data = len(training_input['Benign']) + len(training_input['Malignant'])
print("size training set: {}".format(length_data))
#print("Matrix dimension: {}".format(result['kernel_matrix_training'].shape))
print("testing success ratio: ", result['testing_accuracy'])
test_set = np.concatenate((test_input['Benign'], test_input['Malignant']))
y_test = qsvm.predict(test_set, quantum_instance)
plt.scatter(test_set[:, 0], test_set[:,1], c=y_test)
plt.show()
plt.scatter(test_input['Benign'][:,0], test_input['Benign'][:,1])
plt.scatter(test_input['Malignant'][:,0], test_input['Malignant'][:,1])
plt.show()
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from qiskit import QuantumCircuit, Aer, execute, IBMQ
from qiskit.utils import QuantumInstance
import numpy as np
from qiskit.algorithms import Shor
IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here
provider = IBMQ.get_provider(hub='ibm-q')
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1000)
my_shor = Shor(quantum_instance)
result_dict = my_shor.factor(15)
print(result_dict)
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
|
#Assign these values as per your requirements.
global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion
min_qubits=4
max_qubits=15 #reference files are upto 12 Qubits only
skip_qubits=2
max_circuits=3
num_shots=4092
gate_counts_plots = True
Noise_Inclusion = False
saveplots = False
Memory_utilization_plot = True
Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2"
backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends
#Change your Specification of Simulator in Declaring Backend Section
#By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2()
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute
from qiskit.opflow import PauliTrotterEvolution, Suzuki
from qiskit.opflow.primitive_ops import PauliSumOp
import time,os,json
import matplotlib.pyplot as plt
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error)
# Benchmark Name
benchmark_name = "VQE Simulation"
# Selection of basis gate set for transpilation
# Note: selector 1 is a hardware agnostic gate set
basis_selector = 1
basis_gates_array = [
[],
['rx', 'ry', 'rz', 'cx'], # a common basis set, default
['cx', 'rz', 'sx', 'x'], # IBM default basis set
['rx', 'ry', 'rxx'], # IonQ default basis set
['h', 'p', 'cx'], # another common basis set
['u', 'cx'] # general unitaries basis gates
]
np.random.seed(0)
def get_QV(backend):
import json
# Assuming backend.conf_filename is the filename and backend.dirname is the directory path
conf_filename = backend.dirname + "/" + backend.conf_filename
# Open the JSON file
with open(conf_filename, 'r') as file:
# Load the JSON data
data = json.load(file)
# Extract the quantum_volume parameter
QV = data.get('quantum_volume', None)
return QV
def checkbackend(backend_name,Type_of_Simulator):
if Type_of_Simulator == "built_in":
available_backends = []
for i in Aer.backends():
available_backends.append(i.name)
if backend_name in available_backends:
platform = backend_name
return platform
else:
print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!")
print(f"available backends are : {available_backends}")
platform = "qasm_simulator"
return platform
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2":
import qiskit.providers.fake_provider as fake_backends
if hasattr(fake_backends,backend_name) is True:
print(f"Backend {backend_name} is available for type {Type_of_Simulator}.")
backend_class = getattr(fake_backends,backend_name)
backend_instance = backend_class()
return backend_instance
else:
print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!")
if Type_of_Simulator == "FAKEV2":
backend_class = getattr(fake_backends,"FakeSantiagoV2")
else:
backend_class = getattr(fake_backends,"FakeSantiago")
backend_instance = backend_class()
return backend_instance
if Type_of_Simulator == "built_in":
platform = checkbackend(backend_name,Type_of_Simulator)
#By default using "Qasm Simulator"
backend = Aer.get_backend(platform)
QV_=None
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"backend version is {backend.backend_version}")
elif Type_of_Simulator == "FAKE":
basis_selector = 0
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting.
max_qubits=backend.configuration().n_qubits
print(f"{platform} device is capable of running {backend.configuration().n_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
elif Type_of_Simulator == "FAKEV2":
basis_selector = 0
if "V2" not in backend_name:
backend_name = backend_name+"V2"
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.name +"-" +backend.backend_version
max_qubits=backend.num_qubits
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
else:
print("Enter valid Simulator.....")
# saved circuits for display
QC_ = None
Hf_ = None
CO_ = None
################### Circuit Definition #######################################
# 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
def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1):
# number of alpha spin orbitals
norb_a = int(n_spin_orbs / 2)
# construct the Hamiltonian
qubit_op = ReadHamiltonian(n_spin_orbs)
# allocate qubits
num_qubits = n_spin_orbs
qr = QuantumRegister(num_qubits)
qc = QuantumCircuit(qr, name=f"vqe-ansatz({method})-{num_qubits}-{circuit_id}")
# initialize the HF state
Hf = HartreeFock(num_qubits, na, nb)
qc.append(Hf, qr)
# form the list of single and double excitations
excitationList = []
for occ_a in range(na):
for vir_a in range(na, norb_a):
excitationList.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):
excitationList.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):
excitationList.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, excitationList[index])
# add to ansatz
qc.append(cluster_qc, [i for i in range(cluster_qc.num_qubits)])
# method 1, only compute the last term in the Hamiltonian
if method == 1:
# 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 = []
global normalization
normalization = 0.0
# add the first non-identity term
identity_qc = qc.copy()
identity_qc.measure_all()
qc_list.append(identity_qc) # add to circuit list
diag.append(qubit_op[1])
normalization += abs(qubit_op[1].coeffs[0]) # add to normalization factor
diag_coeff = abs(qubit_op[1].coeffs[0]) # add to coefficients of diagonal terms
# loop over rest of terms
for index, p in enumerate(qubit_op[2:]):
# get the circuit with expectation measurements
qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits)
# accumulate normalization
normalization += abs(p.coeffs[0])
# add to circuit list if non-diagonal
if not is_diag:
qc_list.append(qc_with_mea)
else:
diag_coeff += abs(p.coeffs[0])
# diagonal term
if is_diag:
diag.append(p)
# off-diagonal term
else:
off_diag.append(p)
# modify the name of diagonal circuit
qc_list[0].name = qubit_op[1].primitive.to_list()[0][0] + " " + str(np.real(diag_coeff))
normalization /= len(qc_list)
return qc_list
# Function that constructs the circuit for a given cluster operator
def ClusterOperatorCircuit(pauli_op, excitationIndex):
# 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(); qc.name = f'Cluster Op {excitationIndex}'
global CO_
if CO_ == None or qc.num_qubits <= 4:
if qc.num_qubits < 7: CO_ = qc
# return this circuit
return qc
# Function that adds expectation measurements to the raw circuits
def ExpectationCircuit(qc, pauli, nqubit, method=2):
# 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"):
is_diag = False
raw_qc.h(target_qubit)
elif (p == "Y"):
raw_qc.sdg(target_qubit)
raw_qc.h(target_qubit)
is_diag = False
# perform measurements
raw_qc.measure_all()
# name of this circuit
raw_qc.name = PauliString + " " + str(np.real(coeff))
# save circuit
global QC_
if QC_ == None or nqubit <= 4:
if nqubit < 7: QC_ = raw_qc
return raw_qc, is_diag
# Function that implements the Hartree-Fock state
def HartreeFock(norb, na, nb):
# initialize the quantum circuit
qc = QuantumCircuit(norb, name="Hf")
# alpha electrons
for ia in range(na):
qc.x(ia)
# beta electrons
for ib in range(nb):
qc.x(ib+int(norb/2))
# Save smaller circuit
global Hf_
if Hf_ == None or norb <= 4:
if norb < 7: Hf_ = qc
# return the circuit
return qc
################ Helper Functions
# 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(f'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(f'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
# Create an empty noise model
noise_parameters = NoiseModel()
if Type_of_Simulator == "built_in":
# Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5%
depol_one_qb_error = 0.05
depol_two_qb_error = 0.005
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx'])
# Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0%
amp_damp_one_qb_error = 0.0
amp_damp_two_qb_error = 0.0
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx'])
# Add reset noise to all single qubit resets
reset_to_zero_error = 0.005
reset_to_one_error = 0.005
noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"])
# Add readout error
p0given1_error = 0.000
p1given0_error = 0.000
error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]])
noise_parameters.add_all_qubit_readout_error(error_meas)
#print(noise_parameters)
elif Type_of_Simulator == "FAKE"or"FAKEV2":
noise_parameters = NoiseModel.from_backend(backend)
#print(noise_parameters)
### Analysis methods to be expanded and eventually compiled into a separate analysis.py file
import math, functools
def hellinger_fidelity_with_expected(p, q):
""" p: result distribution, may be passed as a counts distribution
q: the expected distribution to be compared against
References:
`Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_
Qiskit Hellinger Fidelity Function
"""
p_sum = sum(p.values())
q_sum = sum(q.values())
if q_sum == 0:
print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0")
return 0
p_normed = {}
for key, val in p.items():
p_normed[key] = val/p_sum
# if p_sum != 0:
# p_normed[key] = val/p_sum
# else:
# p_normed[key] = 0
q_normed = {}
for key, val in q.items():
q_normed[key] = val/q_sum
total = 0
for key, val in p_normed.items():
if key in q_normed.keys():
total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2
del q_normed[key]
else:
total += val
total += sum(q_normed.values())
# in some situations (error mitigation) this can go negative, use abs value
if total < 0:
print(f"WARNING: using absolute value in fidelity calculation")
total = abs(total)
dist = np.sqrt(total)/np.sqrt(2)
fidelity = (1-dist**2)**2
return fidelity
def polarization_fidelity(counts, correct_dist, thermal_dist=None):
"""
Combines Hellinger fidelity and polarization rescaling into fidelity calculation
used in every benchmark
counts: the measurement outcomes after `num_shots` algorithm runs
correct_dist: the distribution we expect to get for the algorithm running perfectly
thermal_dist: optional distribution to pass in distribution from a uniform
superposition over all states. If `None`: generated as
`uniform_dist` with the same qubits as in `counts`
returns both polarization fidelity and the hellinger fidelity
Polarization from: `https://arxiv.org/abs/2008.11294v1`
"""
num_measured_qubits = len(list(correct_dist.keys())[0])
#print(num_measured_qubits)
counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()}
# calculate hellinger fidelity between measured expectation values and correct distribution
hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist)
# to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits
if num_measured_qubits > 16:
return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity }
# if not provided, generate thermal dist based on number of qubits
if thermal_dist == None:
thermal_dist = uniform_dist(num_measured_qubits)
# set our fidelity rescaling value as the hellinger fidelity for a depolarized state
floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist)
# rescale fidelity result so uniform superposition (random guessing) returns fidelity
# rescaled to 0 to provide a better measure of success of the algorithm (polarization)
new_floor_fidelity = 0
fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity)
return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity }
## Uniform distribution function commonly used
def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity):
"""
Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks
fidelity: raw fidelity to rescale
floor_fidelity: threshold fidelity which is equivalent to random guessing
new_floor_fidelity: what we rescale the floor_fidelity to
Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0:
1 -> 1;
0.25 -> 0;
0.5 -> 0.3333;
"""
rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1
# ensure fidelity is within bounds (0, 1)
if rescaled_fidelity < 0:
rescaled_fidelity = 0.0
if rescaled_fidelity > 1:
rescaled_fidelity = 1.0
return rescaled_fidelity
def uniform_dist(num_state_qubits):
dist = {}
for i in range(2**num_state_qubits):
key = bin(i)[2:].zfill(num_state_qubits)
dist[key] = 1/(2**num_state_qubits)
return dist
from matplotlib.patches import Rectangle
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize
from matplotlib.patches import Circle
############### Color Map functions
# Create a selection of colormaps from which to choose; default to custom_spectral
cmap_spectral = plt.get_cmap('Spectral')
cmap_greys = plt.get_cmap('Greys')
cmap_blues = plt.get_cmap('Blues')
cmap_custom_spectral = None
# the default colormap is the spectral map
cmap = cmap_spectral
cmap_orig = cmap_spectral
# current cmap normalization function (default None)
cmap_norm = None
default_fade_low_fidelity_level = 0.16
default_fade_rate = 0.7
# Specify a normalization function here (default None)
def set_custom_cmap_norm(vmin, vmax):
global cmap_norm
if vmin == vmax or (vmin == 0.0 and vmax == 1.0):
print("... setting cmap norm to None")
cmap_norm = None
else:
print(f"... setting cmap norm to [{vmin}, {vmax}]")
cmap_norm = Normalize(vmin=vmin, vmax=vmax)
# Remake the custom spectral colormap with user settings
def set_custom_cmap_style(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
#print("... set custom map style")
global cmap, cmap_custom_spectral, cmap_orig
cmap_custom_spectral = create_custom_spectral_cmap(
fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate)
cmap = cmap_custom_spectral
cmap_orig = cmap_custom_spectral
# Create the custom spectral colormap from the base spectral
def create_custom_spectral_cmap(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
# determine the breakpoint from the fade level
num_colors = 100
breakpoint = round(fade_low_fidelity_level * num_colors)
# get color list for spectral map
spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)]
#print(fade_rate)
# create a list of colors to replace those below the breakpoint
# and fill with "faded" color entries (in reverse)
low_colors = [0] * breakpoint
#for i in reversed(range(breakpoint)):
for i in range(breakpoint):
# x is index of low colors, normalized 0 -> 1
x = i / breakpoint
# get color at this index
bc = spectral_colors[i]
r0 = bc[0]
g0 = bc[1]
b0 = bc[2]
z0 = bc[3]
r_delta = 0.92 - r0
#print(f"{x} {bc} {r_delta}")
# compute saturation and greyness ratio
sat_ratio = 1 - x
#grey_ratio = 1 - x
''' attempt at a reflective gradient
if i >= breakpoint/2:
xf = 2*(x - 0.5)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (yf + 0.5)
else:
xf = 2*(0.5 - x)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (0.5 - yf)
'''
grey_ratio = 1 - math.pow(x, 1/fade_rate)
#print(f" {xf} {yf} ")
#print(f" {sat_ratio} {grey_ratio}")
r = r0 + r_delta * sat_ratio
g_delta = r - g0
b_delta = r - b0
g = g0 + g_delta * grey_ratio
b = b0 + b_delta * grey_ratio
#print(f"{r} {g} {b}\n")
low_colors[i] = (r,g,b,z0)
#print(low_colors)
# combine the faded low colors with the regular spectral cmap to make a custom version
cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:])
#spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)]
#for i in range(10): print(spectral_colors[i])
#print("")
return cmap_custom_spectral
# Make the custom spectral color map the default on module init
set_custom_cmap_style()
# Arrange the stored annotations optimally and add to plot
def anno_volumetric_data(ax, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True):
# sort all arrays by the x point of the text (anno_offs)
global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos
all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos))
x_anno_offs = [a for a,b,c,d,e in all_annos]
y_anno_offs = [b for a,b,c,d,e in all_annos]
anno_labels = [c for a,b,c,d,e in all_annos]
x_annos = [d for a,b,c,d,e in all_annos]
y_annos = [e for a,b,c,d,e in all_annos]
#print(f"{x_anno_offs}")
#print(f"{y_anno_offs}")
#print(f"{anno_labels}")
for i in range(len(anno_labels)):
x_anno = x_annos[i]
y_anno = y_annos[i]
x_anno_off = x_anno_offs[i]
y_anno_off = y_anno_offs[i]
label = anno_labels[i]
if i > 0:
x_delta = abs(x_anno_off - x_anno_offs[i - 1])
y_delta = abs(y_anno_off - y_anno_offs[i - 1])
if y_delta < 0.7 and x_delta < 2:
y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6
#x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1
ax.annotate(label,
xy=(x_anno+0.0, y_anno+0.1),
arrowprops=dict(facecolor='black', shrink=0.0,
width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)),
xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]),
rotation=labelrot,
horizontalalignment='left', verticalalignment='baseline',
color=(0.2,0.2,0.2),
clip_on=True)
if saveplots == True:
plt.savefig("VolumetricPlotSample.jpg")
# Plot one group of data for volumetric presentation
def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True,
x_size=1.0, y_size=1.0, zorder=1, offset_flag=False,
max_depth=0, suppress_low_fidelity=False):
# since data may come back out of order, save point at max y for annotation
i_anno = 0
x_anno = 0
y_anno = 0
# plot data rectangles
low_fidelity_count = True
last_y = -1
k = 0
# determine y-axis dimension for one pixel to use for offset of bars that start at 0
(_, dy) = get_pixel_dims(ax)
# do this loop in reverse to handle the case where earlier cells are overlapped by later cells
for i in reversed(range(len(d_data))):
x = depth_index(d_data[i], depth_base)
y = float(w_data[i])
f = f_data[i]
# each time we star a new row, reset the offset counter
# DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars
# that represent time starting from 0 secs. We offset by one pixel each and center the group
if y != last_y:
last_y = y;
k = 3 # hardcoded for 8 cells, offset by 3
#print(f"{i = } {x = } {y = }")
if max_depth > 0 and d_data[i] > max_depth:
#print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}")
break;
# reject cells with low fidelity
if suppress_low_fidelity and f < suppress_low_fidelity_level:
if low_fidelity_count: break
else: low_fidelity_count = True
# the only time this is False is when doing merged gradation plots
if do_border == True:
# this case is for an array of x_sizes, i.e. each box has different width
if isinstance(x_size, list):
# draw each of the cells, with no offset
if not offset_flag:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder))
# use an offset for y value, AND account for x and width to draw starting at 0
else:
ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder))
# this case is for only a single cell
else:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size))
# save the annotation point with the largest y value
if y >= y_anno:
x_anno = x
y_anno = y
i_anno = i
# move the next bar down (if using offset)
k -= 1
# if no data rectangles plotted, no need for a label
if x_anno == 0 or y_anno == 0:
return
x_annos.append(x_anno)
y_annos.append(y_anno)
anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 )
# adjust radius of annotation circle based on maximum width of apps
anno_max = 10
if w_max > 10:
anno_max = 14
if w_max > 14:
anno_max = 18
scale = anno_max / anno_dist
# offset of text from end of arrow
if scale > 1:
x_anno_off = scale * x_anno - x_anno - 0.5
y_anno_off = scale * y_anno - y_anno
else:
x_anno_off = 0.7
y_anno_off = 0.5
x_anno_off += x_anno
y_anno_off += y_anno
# print(f"... {xx} {yy} {anno_dist}")
x_anno_offs.append(x_anno_off)
y_anno_offs.append(y_anno_off)
anno_labels.append(label)
if do_label:
ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot,
horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2))
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# init arrays to hold annotation points for label spreading
def vplot_anno_init ():
global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# Number of ticks on volumetric depth axis
max_depth_log = 22
# average transpile factor between base QV depth and our depth based on results from QV notebook
QV_transpile_factor = 12.7
# format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1
# (sign handling may be incorrect)
def format_number(num, digits=0):
if isinstance(num, str): num = float(num)
num = float('{:.3g}'.format(abs(num)))
sign = ''
metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1}
for index in metric:
num_check = num / metric[index]
if num_check >= 1:
num = round(num_check, digits)
sign = index
break
numstr = f"{str(num)}"
if '.' in numstr:
numstr = numstr.rstrip('0').rstrip('.')
return f"{numstr}{sign}"
# Return the color associated with the spcific value, using color map norm
def get_color(value):
# if there is a normalize function installed, scale the data
if cmap_norm:
value = float(cmap_norm(value))
if cmap == cmap_spectral:
value = 0.05 + value*0.9
elif cmap == cmap_blues:
value = 0.00 + value*1.0
else:
value = 0.0 + value*0.95
return cmap(value)
# Return the x and y equivalent to a single pixel for the given plot axis
def get_pixel_dims(ax):
# transform 0 -> 1 to pixel dimensions
pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0))
xpix = pixdims[1][0]
ypix = pixdims[0][1]
#determine x- and y-axis dimension for one pixel
dx = (1 / xpix)
dy = (1 / ypix)
return (dx, dy)
############### Helper functions
# return the base index for a circuit depth value
# take the log in the depth base, and add 1
def depth_index(d, depth_base):
if depth_base <= 1:
return d
if d == 0:
return 0
return math.log(d, depth_base) + 1
# draw a box at x,y with various attributes
def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1):
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5*y_size,
zorder=zorder)
# draw a circle at x,y with various attributes
def circle_at(x, y, value, type=1, fill=True):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Circle((x, y), size/2,
alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5)
def box4_at(x, y, value, type=1, fill=True, alpha=1.0):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.3,0.3,0.3)
ec = fc
return Rectangle((x - size/8, y - size/2), size/4, size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.1)
# Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value
def qv_box_at(x, y, qv_width, qv_depth, value, depth_base):
#print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}")
return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width,
edgecolor = (value,value,value),
facecolor = (value,value,value),
fill=True,
lw=1)
def bkg_box_at(x, y, value=0.9):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (value,value,value),
fill=True,
lw=0.5)
def bkg_empty_box_at(x, y):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (1.0,1.0,1.0),
fill=True,
lw=0.5)
# Plot the background for the volumetric analysis
def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"):
if suptitle == None:
suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}"
QV0 = QV
qv_estimate = False
est_str = ""
if QV == 0: # QV = 0 indicates "do not draw QV background or label"
QV = 2048
elif QV < 0: # QV < 0 indicates "add est. to label"
QV = -QV
qv_estimate = True
est_str = " (est.)"
if avail_qubits > 0 and max_qubits > avail_qubits:
max_qubits = avail_qubits
max_width = 13
if max_qubits > 11: max_width = 18
if max_qubits > 14: max_width = 20
if max_qubits > 16: max_width = 24
if max_qubits > 24: max_width = 33
#print(f"... {avail_qubits} {max_qubits} {max_width}")
plot_width = 6.8
plot_height = 0.5 + plot_width * (max_width / max_depth_log)
#print(f"... {plot_width} {plot_height}")
# define matplotlib figure and axis; use constrained layout to fit colorbar to right
fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True)
plt.suptitle(suptitle)
plt.xlim(0, max_depth_log)
plt.ylim(0, max_width)
# circuit depth axis (x axis)
xbasis = [x for x in range(1,max_depth_log)]
xround = [depth_base**(x-1) for x in xbasis]
xlabels = [format_number(x) for x in xround]
ax.set_xlabel('Circuit Depth')
ax.set_xticks(xbasis)
plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor")
# other label options
#plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left')
#plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor")
# circuit width axis (y axis)
ybasis = [y for y in range(1,max_width)]
yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now
ylabels = [str(y) for y in yround] # not used now
#ax.set_ylabel('Circuit Width (Number of Qubits)')
ax.set_ylabel('Circuit Width')
ax.set_yticks(ybasis)
#create simple line plot (not used right now)
#ax.plot([0, 10],[0, 10])
log2QV = math.log2(QV)
QV_width = log2QV
QV_depth = log2QV * QV_transpile_factor
# show a quantum volume rectangle of QV = 64 e.g. (6 x 6)
if QV0 != 0:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base))
else:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base))
# the untranspiled version is commented out - we do not show this by default
# also show a quantum volume rectangle un-transpiled
# ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base))
# show 2D array of volumetric cells based on this QV_transpiled
# DEVNOTE: we use +1 only to make the visuals work; s/b without
# Also, the second arg of the min( below seems incorrect, needs correction
maxprod = (QV_width + 1) * (QV_depth + 1)
for w in range(1, min(max_width, round(QV) + 1)):
# don't show VB squares if width greater than known available qubits
if avail_qubits != 0 and w > avail_qubits:
continue
i_success = 0
for d in xround:
# polarization factor for low circuit widths
maxtest = maxprod / ( 1 - 1 / (2**w) )
# if circuit would fail here, don't draw box
if d > maxtest: continue
if w * d > maxtest: continue
# guess for how to capture how hardware decays with width, not entirely correct
# # reduce maxtext by a factor of number of qubits > QV_width
# # just an approximation to account for qubit distances
# if w > QV_width:
# over = w - QV_width
# maxtest = maxtest / (1 + (over/QV_width))
# draw a box at this width and depth
id = depth_index(d, depth_base)
# show vb rectangles; if not showing QV, make all hollow (or less dark)
if QV0 == 0:
#ax.add_patch(bkg_empty_box_at(id, w))
ax.add_patch(bkg_box_at(id, w, 0.95))
else:
ax.add_patch(bkg_box_at(id, w, 0.9))
# save index of last successful depth
i_success += 1
# plot empty rectangle after others
d = xround[i_success]
id = depth_index(d, depth_base)
ax.add_patch(bkg_empty_box_at(id, w))
# Add annotation showing quantum volume
if QV0 != 0:
t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12,
horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2),
bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1))
# add colorbar to right of plot
plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax,
shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7))
return ax
# Function to calculate circuit depth
def calculate_circuit_depth(qc):
# Calculate the depth of the circuit
depth = qc.depth()
return depth
def calculate_transpiled_depth(qc,basis_selector):
# use either the backend or one of the basis gate sets
if basis_selector == 0:
qc = transpile(qc, backend)
else:
basis_gates = basis_gates_array[basis_selector]
qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0)
transpiled_depth = qc.depth()
return transpiled_depth,qc
def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title):
avg_fidelity_means = []
avg_Hf_fidelity_means = []
avg_num_qubits_values = list(fidelity_data.keys())
# Calculate the average fidelity and Hamming fidelity for each unique number of qubits
for num_qubits in avg_num_qubits_values:
avg_fidelity = np.average(fidelity_data[num_qubits])
avg_fidelity_means.append(avg_fidelity)
avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits])
avg_Hf_fidelity_means.append(avg_Hf_fidelity)
return avg_fidelity_means,avg_Hf_fidelity_means
list_of_gates = []
def list_of_standardgates():
import qiskit.circuit.library as lib
from qiskit.circuit import Gate
import inspect
# List all the attributes of the library module
gate_list = dir(lib)
# Filter out non-gate classes (like functions, variables, etc.)
gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)]
# Get method names from QuantumCircuit
circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction)
method_names = [name for name, _ in circuit_methods]
# Map gate class names to method names
gate_to_method = {}
for gate in gates:
gate_class = getattr(lib, gate)
class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name
for method in method_names:
if method == class_name or method == class_name.replace('cr', 'c-r'):
gate_to_method[gate] = method
break
# Add common operations that are not strictly gates
additional_operations = {
'Measure': 'measure',
'Barrier': 'barrier',
}
gate_to_method.update(additional_operations)
for k,v in gate_to_method.items():
list_of_gates.append(v)
def update_counts(gates,custom_gates):
operations = {}
for key, value in gates.items():
operations[key] = value
for key, value in custom_gates.items():
if key in operations:
operations[key] += value
else:
operations[key] = value
return operations
def get_gate_counts(gates,custom_gate_defs):
result = gates.copy()
# Iterate over the gate counts in the quantum circuit
for gate, count in gates.items():
if gate in custom_gate_defs:
custom_gate_ops = custom_gate_defs[gate]
# Multiply custom gate operations by the count of the custom gate in the circuit
for _ in range(count):
result = update_counts(result, custom_gate_ops)
# Remove the custom gate entry as we have expanded it
del result[gate]
return result
dict_of_qc = dict()
custom_gates_defs = dict()
# Function to count operations recursively
def count_operations(qc):
dict_of_qc.clear()
circuit_traverser(qc)
operations = dict()
operations = dict_of_qc[qc.name]
del dict_of_qc[qc.name]
# print("operations :",operations)
# print("dict_of_qc :",dict_of_qc)
for keys in operations.keys():
if keys not in list_of_gates:
for k,v in dict_of_qc.items():
if k in operations.keys():
custom_gates_defs[k] = v
operations=get_gate_counts(operations,custom_gates_defs)
custom_gates_defs.clear()
return operations
def circuit_traverser(qc):
dict_of_qc[qc.name]=dict(qc.count_ops())
for i in qc.data:
if str(i.operation.name) not in list_of_gates:
qc_1 = i.operation.definition
circuit_traverser(qc_1)
def get_memory():
import resource
usage = resource.getrusage(resource.RUSAGE_SELF)
max_mem = usage.ru_maxrss/1024 #in MB
return max_mem
def analyzer(qc,references,num_qubits):
# total circuit name (pauli string + coefficient)
total_name = qc.name
# pauli string
pauli_string = total_name.split()[0]
# get the correct measurement
if (len(total_name.split()) == 2):
correct_dist = references[pauli_string]
else:
circuit_id = int(total_name.split()[2])
correct_dist = references[f"Qubits - {num_qubits} - {circuit_id}"]
return correct_dist,total_name
# Max qubits must be 12 since the referenced files only go to 12 qubits
MAX_QUBITS = 12
method = 1
def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=2,
max_circuits=max_circuits, num_shots=num_shots):
creation_times = []
elapsed_times = []
quantum_times = []
circuit_depths = []
transpiled_depths = []
fidelity_data = {}
Hf_fidelity_data = {}
numckts = []
mem_usage = []
algorithmic_1Q_gate_counts = []
algorithmic_2Q_gate_counts = []
transpiled_1Q_gate_counts = []
transpiled_2Q_gate_counts = []
print(f"{benchmark_name} Benchmark Program - {platform}")
#defining all the standard gates supported by qiskit in a list
if gate_counts_plots == True:
list_of_standardgates()
max_qubits = max(max_qubits, min_qubits) # max must be >= min
# validate parameters (smallest circuit is 4 qubits and largest is 10 qubits)
max_qubits = min(max_qubits, MAX_QUBITS)
min_qubits = min(max(4, min_qubits), max_qubits)
if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even
skip_qubits = max(1, skip_qubits)
if method == 2: max_circuits = 1
if max_qubits < 4:
print(f"Max number of qubits {max_qubits} is too low to run method {method} of VQE algorithm")
return
global max_ckts
max_ckts = max_circuits
global min_qbits,max_qbits,skp_qubits
min_qbits = min_qubits
max_qbits = max_qubits
skp_qubits = skip_qubits
print(f"min, max qubits = {min_qubits} {max_qubits}")
# Execute Benchmark Program N times for multiple circuit sizes
for input_size in range(min_qubits, max_qubits + 1, skip_qubits):
# reset random seed
np.random.seed(0)
# determine the number of circuits to execute for this group
num_circuits = min(3, max_circuits)
num_qubits = input_size
fidelity_data[num_qubits] = []
Hf_fidelity_data[num_qubits] = []
# decides number of electrons
na = int(num_qubits/4)
nb = int(num_qubits/4)
# random seed
np.random.seed(0)
numckts.append(num_circuits)
# 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:
# loop over circuits
for circuit_id in range(num_circuits):
# 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)
# method 2
elif method == 2:
# construct all circuits
qc_list = VQEEnergy(num_qubits, na, nb, 0, method)
print(qc_list)
print(f"************\nExecuting [{len(qc_list)}] circuits with num_qubits = {num_qubits}")
for qc in qc_list:
print("*********************************************")
#print(f"qc of {qc} qubits for qc_list value: {qc_list}")
# get circuit id
if method == 1:
circuit_id = qc.name.split()[2]
else:
circuit_id = qc.name.split()[0]
#creation time
creation_time = time.time() - ts
creation_times.append(creation_time)
#print(qc)
print(f"creation time = {creation_time*1000} ms")
# Calculate gate count for the algorithmic circuit (excluding barriers and measurements)
if gate_counts_plots == True:
operations = count_operations(qc)
n1q = 0; n2q = 0
if operations != None:
for key, value in operations.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c") or key.startswith("mc"):
n2q += value
else:
n1q += value
print("operations: ",operations)
algorithmic_1Q_gate_counts.append(n1q)
algorithmic_2Q_gate_counts.append(n2q)
# collapse the sub-circuit levels used in this benchmark (for qiskit)
qc=qc.decompose()
#print(qc)
# Calculate circuit depth
depth = calculate_circuit_depth(qc)
circuit_depths.append(depth)
# Calculate transpiled circuit depth
transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector)
transpiled_depths.append(transpiled_depth)
#print(qc)
print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}")
if gate_counts_plots == True:
# Calculate gate count for the transpiled circuit (excluding barriers and measurements)
tr_ops = qc.count_ops()
#print("tr_ops = ",tr_ops)
tr_n1q = 0; tr_n2q = 0
if tr_ops != None:
for key, value in tr_ops.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c"): tr_n2q += value
else: tr_n1q += value
transpiled_1Q_gate_counts.append(tr_n1q)
transpiled_2Q_gate_counts.append(tr_n2q)
print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}")
print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}")
#execution
if Type_of_Simulator == "built_in":
#To check if Noise is required
if Noise_Inclusion == True:
noise_model = noise_parameters
else:
noise_model = None
ts = time.time()
job = execute(qc, backend, shots=num_shots, noise_model=noise_model)
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" :
ts = time.time()
job = backend.run(qc,shots=num_shots, noise_model=noise_parameters)
#retrieving the result
result = job.result()
#print(result)
#calculating elapsed time
elapsed_time = time.time() - ts
elapsed_times.append(elapsed_time)
# Calculate quantum processing time
quantum_time = result.time_taken
quantum_times.append(quantum_time)
print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms")
#counts in result object
counts = result.get_counts()
# load pre-computed data
if len(qc.name.split()) == 2:
filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit.json')
with open(filename) as f:
references = json.load(f)
else:
filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit_method2.json')
with open(filename) as f:
references = json.load(f)
#Correct distribution to compare with counts
correct_dist,total_name = analyzer(qc,references,num_qubits)
#fidelity calculation comparision of counts and correct_dist
fidelity_dict = polarization_fidelity(counts, correct_dist)
print(fidelity_dict)
# modify fidelity based on the coefficient
if (len(total_name.split()) == 2):
fidelity_dict *= ( abs(float(total_name.split()[1])) / normalization )
fidelity_data[num_qubits].append(fidelity_dict['fidelity'])
Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity'])
#maximum memory utilization (if required)
if Memory_utilization_plot == True:
max_mem = get_memory()
print(f"Maximum Memory Utilized: {max_mem} MB")
mem_usage.append(max_mem)
print("*********************************************")
##########
# print a sample circuit
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
print("\nHartree Fock Generator 'Hf' ="); print(Hf_ if Hf_ != None else " ... too large!")
print("\nCluster Operator Example 'Cluster Op' ="); print(CO_ if CO_ != None else " ... too large!")
return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths,
fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts,
transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage)
# Execute the benchmark program, accumulate metrics, and calculate circuit depths
(creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts,
algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run()
# Define the range of qubits for the x-axis
num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits)
print("num_qubits_range =",num_qubits_range)
# Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits
avg_creation_times = []
avg_elapsed_times = []
avg_quantum_times = []
avg_circuit_depths = []
avg_transpiled_depths = []
avg_1Q_algorithmic_gate_counts = []
avg_2Q_algorithmic_gate_counts = []
avg_1Q_Transpiled_gate_counts = []
avg_2Q_Transpiled_gate_counts = []
max_memory = []
start = 0
for num in numckts:
avg_creation_times.append(np.mean(creation_times[start:start+num]))
avg_elapsed_times.append(np.mean(elapsed_times[start:start+num]))
avg_quantum_times.append(np.mean(quantum_times[start:start+num]))
avg_circuit_depths.append(np.mean(circuit_depths[start:start+num]))
avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num]))
if gate_counts_plots == True:
avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num])))
avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num])))
avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num])))
avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num])))
if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num]))
start += num
# Calculate the fidelity data
avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison")
# Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits
# Add labels to the bars
def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"):
for rect in rects:
height = rect.get_height()
ax.annotate(str.format(height), # Formatting to two decimal places
xy=(rect.get_x() + rect.get_width() / 2, height / 2),
xytext=(0, 0),
textcoords="offset points",
ha='center', va=va,color=text_color,rotation=90)
bar_width = 0.3
# Determine the number of subplots and their arrangement
if Memory_utilization_plot and gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30))
# Plotting for both memory utilization and gate counts
# ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available
elif Memory_utilization_plot:
fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30))
# Plotting for memory utilization only
# ax1, ax2, ax3, ax6, ax7 are available
elif gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30))
# Plotting for gate counts only
# ax1, ax2, ax3, ax4, ax5, ax6 are available
else:
fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30))
# Default plotting
# ax1, ax2, ax3, ax6 are available
fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16)
for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000
avg_creation_times[i] *= 1000
ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue')
autolabel(ax1.patches, ax1)
ax1.set_xlabel('Number of Qubits')
ax1.set_ylabel('Average Creation Time (ms)')
ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14)
ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000
avg_elapsed_times[i] *= 1000
for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000
avg_quantum_times[i] *= 1000
Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time')
Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time')
autolabel(Elapsed,ax2,str='{:.1f}')
autolabel(Quantum,ax2,str='{:.1f}')
ax2.set_xlabel('Number of Qubits')
ax2.set_ylabel('Average Time (ms)')
ax2.set_title('Average Time vs Number of Qubits')
ax2.legend()
ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here
Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here
autolabel(Normalized,ax3,str='{:.2f}')
autolabel(Algorithmic,ax3,str='{:.2f}')
ax3.set_xlabel('Number of Qubits')
ax3.set_ylabel('Average Circuit Depth')
ax3.set_title('Average Circuit Depth vs Number of Qubits')
ax3.legend()
if gate_counts_plots == True:
ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_1Q_counts,ax4,str='{}')
autolabel(Algorithmic_1Q_counts,ax4,str='{}')
ax4.set_xlabel('Number of Qubits')
ax4.set_ylabel('Average 1-Qubit Gate Counts')
ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits')
ax4.legend()
ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_2Q_counts,ax5,str='{}')
autolabel(Algorithmic_2Q_counts,ax5,str='{}')
ax5.set_xlabel('Number of Qubits')
ax5.set_ylabel('Average 2-Qubit Gate Counts')
ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits')
ax5.legend()
ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here
Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here
autolabel(Hellinger,ax6,str='{:.2f}')
autolabel(Normalized,ax6,str='{:.2f}')
ax6.set_xlabel('Number of Qubits')
ax6.set_ylabel('Average Value')
ax6.set_title("Fidelity Comparison")
ax6.legend()
if Memory_utilization_plot == True:
ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations")
autolabel(ax7.patches, ax7)
ax7.set_xlabel('Number of Qubits')
ax7.set_ylabel('Maximum Memory Utilized (MB)')
ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14)
plt.tight_layout(rect=[0, 0, 1, 0.96])
if saveplots == True:
plt.savefig("ParameterPlotsSample.jpg")
plt.show()
# Quantum Volume Plot
Suptitle = f"Volumetric Positioning - {platform}"
appname=benchmark_name
if QV_ == None:
QV=2048
else:
QV=QV_
depth_base =2
ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity")
w_data = num_qubits_range
# determine width for circuit
w_max = 0
for i in range(len(w_data)):
y = float(w_data[i])
w_max = max(w_max, y)
d_tr_data = avg_transpiled_depths
f_data = avg_f
plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max)
anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from sympy import *
init_printing(use_unicode=True)
%matplotlib inline
p00,p01,p10,p11 = symbols('p_{00} p_{01} p_{10} p_{11}')
th,ph = symbols('theta phi')
Psi00 = Matrix([[cos(th)],[0],[0],[sin(th)]])
Psi01 = Matrix([[0],[sin(ph)],[cos(ph)],[0]])
Psi11 = Matrix([[0],[cos(ph)],[-sin(ph)],[0]])
Psi10 = Matrix([[-sin(th)],[0],[0],[cos(th)]])
#Psi00, Psi00.T, Psi00*Psi00.T
rhoX = p00*Psi00*Psi00.T + p01*Psi01*Psi01.T + p10*Psi10*Psi10.T + p11*Psi11*Psi11.T
simplify(rhoX)
def kp(x,y):
return KroneckerProduct(x,y)
I = Matrix([[1,0],[0,1]])
Y = Matrix([[0,-1j],[1j,0]])
Y = Matrix([[0,1],[1,0]])
Z = Matrix([[1,0],[0,-1]])
cxx,cyy,czz,az,bz = symbols('c_{xx} c_{yy} c_{zz} a_{z} b_{z}')
rhoX = (1/4)*(kp(I,I) + cxx*kp(X,X) + cyy*kp(Y,Y) + czz*kp(Z,Z) + az*kp(Z,I) + bz*kp(I,Z))
simplify(rhoX)
th,be,ga = symbols('theta beta gamma')
c00 = cos(th/2)*cos(be/2)*cos(ga/2) + sin(th/2)*sin(be/2)*sin(ga/2)
c01 = cos(th/2)*cos(be/2)*sin(ga/2) - sin(th/2)*sin(be/2)*cos(ga/2)
c10 = cos(th/2)*sin(be/2)*cos(ga/2) - sin(th/2)*cos(be/2)*sin(ga/2)
c11 = cos(th/2)*sin(be/2)*sin(ga/2) + sin(th/2)*cos(be/2)*cos(ga/2)
simplify(c00**2 + c01**2 + c10**2 + c11**2) # ok!
P0 = Matrix([[1,0],[0,0]])
P1 = Matrix([[0,0],[0,1]])
def Ry(th):
return cos(th/2)*I - 1j*sin(th/2)*Y
def Cx_ab():
return KroneckerProduct(P0,I) + KroneckerProduct(P1,X)
def Cx_ba():
return KroneckerProduct(I,P0) + KroneckerProduct(X,P1)
MB = Cx_ab()*KroneckerProduct(Ry(th-ph),I)*Cx_ba()*KroneckerProduct(Ry(th+ph),I) # mudanca de base
simplify(MB)
from qiskit import *
import numpy as np
import math
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# retorna o circuito quantico que prepara um certo estado real de 1 qubit
# coef = array com os 2 coeficientes reais do estado na base computacional
def qc_psi_1qb_real(coef):
qr = QuantumRegister(1)
qc = QuantumCircuit(qr, name='psir_1qb')
th = 2*math.acos(np.abs(coef[0]))
qc.ry(th, qr[0])
return qc
eigvals = [0.1,0.9]
coef = np.sqrt(eigvals)
print(coef)
qc_psi_1qb_real_ = qc_psi_1qb_real(coef)
qc_psi_1qb_real_.draw('mpl')
from qiskit.quantum_info import Statevector
sv = Statevector.from_label('0')
sv
sv = sv.evolve(qc_psi_1qb_real_)
sv
# retorna o circuito quantico que prepara um certo estado real de 2 qubits
# coef = array com os 4 coeficientes reais do estado na base computacional
def qc_psi_2qb_real(coef):
qr = QuantumRegister(2)
qc = QuantumCircuit(qr, name = 'psir_2qb')
xi = 2*math.acos(math.sqrt(coef[0]**2+coef[1]**2))
coef1 = [math.sqrt(coef[0]**2+coef[1]**2),math.sqrt(1-coef[0]**2-coef[1]**2)]
c_psi_1qb_real_ = qc_psi_1qb_real(coef1)
qc.append(c_psi_1qb_real_, [qr[0]])
th0 = 2*math.atan(np.abs(coef[1])/np.abs(coef[0]))
th1 = 2*math.atan(np.abs(coef[3])/np.abs(coef[2]))
qc.x(0)
qc.cry(th0, 0, 1)
qc.x(0)
qc.cry(th1, 0, 1)
return qc
eigvals = [0.1, 0.2, 0.3, 0.4]
coef = np.sqrt(eigvals)
print(coef)
qc_psi_2qb_real_ = qc_psi_2qb_real(coef)
qc_psi_2qb_real_.draw('mpl')
sv = Statevector.from_label('00')
sv
sv = sv.evolve(qc_psi_2qb_real_)
sv # note o ordenamento, o 2º qb é o 1º e o 1º é o 2º (00,10,01,11)
def qc_ry(th):
qr = QuantumRegister(1)
qc = QuantumCircuit(qr, name = 'RY')
qc.ry(th, 0)
return qc
# retorna o circuito quantico que prepara um certo estado real de 3 qubits
# coef = array com os 8 coeficientes reais do estado na base computacional
def qc_psi_3qb_real(coef):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr, name = 'psir_3qb')
d = len(coef)
coef2 = np.zeros(d//2)
th = np.zeros(d//2)
for j in range(0,2):
for k in range(0,2):
coef2[int(str(j)+str(k),2)] = math.sqrt(coef[int(str(j)+str(k)+str(0),2)]**2+coef[int(str(j)+str(k)+str(1),2)]**2)
c_psi_2qb_real_ = qc_psi_2qb_real(coef2)
qc.append(c_psi_2qb_real_, [qr[0],qr[1]])
for j in range(0,2):
for k in range(0,2):
th[int(str(j)+str(k),2)] = 2*math.atan(np.abs(coef[int(str(j)+str(k)+str(1),2)])/np.abs(coef[int(str(j)+str(k)+str(0),2)]))
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
qc_ry_ = qc_ry(th[int(str(j)+str(k),2)])
ccry = qc_ry_.to_gate().control(2)
qc.append(ccry, [0,1,2])
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
return qc
list_bin = []
for j in range(0,2**3):
b = "{:03b}".format(j)
list_bin.append(b)
print(list_bin)
eigvals = [0.01,0.1,0.04,0.2,0.05,0.3,0.18,0.12]
coef = np.sqrt(eigvals)
print(coef)
qc_psi_3qb_real_ = qc_psi_3qb_real(coef)
qc_psi_3qb_real_.draw('mpl') # odernamento: '000', '001', '010', '011', '100', '101', '110', '111'
sv = Statevector.from_label('000')
sv
sv = sv.evolve(qc_psi_3qb_real_)
sv # ordenamento aqui: 000 100 010 110 001 101 011 111
# retorna o circuito quantico que prepara um certo estado real de 4 qubits
# coef = array com os 16 coeficientes reais do estado na base computacional
def qc_psi_4qb_real(coef):
qr = QuantumRegister(4)
qc = QuantumCircuit(qr, name = 'psir_4qb')
d = len(coef)
coef3 = np.zeros(d//2)
th = np.zeros(d//2)
for j in range(0,2):
for k in range(0,2):
for l in range(0,2):
coef3[int(str(j)+str(k)+str(l),2)] = math.sqrt(coef[int(str(j)+str(k)+str(l)+str(0),2)]**2+coef[int(str(j)+str(k)+str(l)+str(1),2)]**2)
c_psi_3qb_real_ = qc_psi_3qb_real(coef3)
qc.append(c_psi_3qb_real_, [qr[0],qr[1],qr[2]])
for j in range(0,2):
for k in range(0,2):
for l in range(0,2):
th[int(str(j)+str(k)+str(l),2)] = 2*math.atan(np.abs(coef[int(str(j)+str(k)+str(l)+str(1),2)])/np.abs(coef[int(str(j)+str(k)+str(l)+str(0),2)]))
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
if l == 0:
qc.x(2)
qc_ry_ = qc_ry(th[int(str(j)+str(k)+str(l),2)])
ccry = qc_ry_.to_gate().control(3)
qc.append(ccry, [0,1,2,3])
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
if l == 0:
qc.x(2)
return qc
list_bin = []
for j in range(0,2**4):
b = "{:04b}".format(j)
list_bin.append(b)
print(list_bin)
eigvals = np.zeros(2**4)
eigvals[0] = 0.008
for j in range(1,len(eigvals)-1):
eigvals[j] = eigvals[j-1]+0.005
#print(np.sum(eigvals))
eigvals[j+1] = 1 - np.sum(eigvals)
#print(eigvals)
#print(np.sum(eigvals))
coef = np.sqrt(eigvals)
print(coef)
qc_psi_4qb_real_ = qc_psi_4qb_real(coef)
qc_psi_4qb_real_.draw('mpl')
# '0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111'
sv = Statevector.from_label('0000')
sv
sv = sv.evolve(qc_psi_4qb_real_)
sv # ordenamento aqui: 0000 1000 0100 1100 0010 1010 0110 1110 0001 1001 0101 1101 0011 1011 0111 1111
sv[1]
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from sympy import *
init_printing(use_unicode=True)
mu_u = Matrix([[-1],[+1],[+1]]); mu_u
A_R = Matrix([[1,1,-1,-1],[1,-1,1,-1],[1,-1,-1,1]]); A_R
p1,p2,p3,p4 = symbols('p_1 p_2 p_3 p_4')
p4 = 1-p1-p2-p3
cl = A_R[:,0]*p1 + A_R[:,1]*p2 + A_R[:,2]*p3 + A_R[:,3]*p4
mu_u - cl
s1 = Matrix([[0,1],[1,0]])
s2 = Matrix([[0,-1j],[1j,0]])
s1*s2
import numpy as np
a = [] # gera uma lista com com todos os 512 estados ônticos
for j in range(-1,2,2):
for k in range(-1,2,2):
for l in range(-1,2,2):
for m in range(-1,2,2):
for n in range(-1,2,2):
for o in range(-1,2,2):
for p in range(-1,2,2):
for q in range(-1,2,2):
for r in range(-1,2,2):
a.append(np.array([j,k,l,m,n,o,p,q,r]))
a[10], a[10][5], len(a)
mu = [] # gera, a partir dos estados ônticos, uma lista com os 512 vetores de medida, muitos dos quais são iguais
for j in range(0,2**9):
r1 = a[j][0]*a[j][1]*a[j][2]
r2 = a[j][3]*a[j][4]*a[j][5]
r3 = a[j][6]*a[j][7]*a[j][8]
c1 = a[j][0]*a[j][3]*a[j][6]
c2 = a[j][1]*a[j][4]*a[j][7]
c3 = a[j][2]*a[j][5]*a[j][8]
mu.append([r1,r2,r3,c1,c2,c3])
mu[0], len(mu)
mu_ = [] # remove as repeticoes do vetor de medida
for j in range(0,2**6):
if mu[j] not in mu_:
mu_.append(mu[j])
mu_, len(mu_), mu_[1]
A_R = np.zeros((6,16))#; A_R
for j in range(0,16):
A_R[:,j] = mu_[j]
print(A_R)
print(A_R.shape)
def rpv_zhsl(d): # vetor de probabilidades aleatório
rn = np.zeros(d-1)
for j in range(0,d-1):
rn[j] = np.random.random()
rpv = np.zeros(d)
rpv[0] = 1.0 - rn[0]**(1.0/(d-1.0))
norm = rpv[0]
if d > 2:
for j in range(1,d-1):
rpv[j] = (1.0 - rn[j]**(1.0/(d-j-1)))*(1.0-norm)
norm = norm + rpv[j]
rpv[d-1] = 1.0 - norm
return rpv
rpv = rpv_zhsl(16)
print(rpv)
print(np.linalg.norm(rpv))
mu_Q = np.zeros((6,1)); mu_Q = np.array([1,1,1,1,1,-1]); print(mu_Q.shape)
p = np.zeros((16,1)); p = rpv_zhsl(16); print(p.shape)
vec = mu_Q - A_R@p
print(vec)
def objective(x):
mu_Q = np.array([1,1,1,1,1,-1])
vec = mu_Q - A_R@x
return np.linalg.norm(vec)
from scipy.optimize import minimize
# define o vinculo como sendo uma distribuicao de probabilidades
constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x)-1},
{'type':'ineq', 'fun': lambda x: x},
{'type':'ineq', 'fun': lambda x: 1-x}]
# 'eq' quer dizer = 0 e 'ineq' quer dizer >=0
np.random.seed(130000)
x0 = rpv_zhsl(16)
print(x0)
result = minimize(objective, x0, constraints=constraints, method='trust-constr')
print('melhor distribuicao de probabilidades', result.x)
print(objective(result.x))
from qiskit import *
import numpy as np
import math
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_manila')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
#from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
#from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.visualization import plot_histogram
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier() # mede XI
qc.h(0)
qc.cx(0,2)
qc.barrier() # mede IX
qc.h(1)
qc.cx(1,2)
qc.barrier() # mede XX
qc.cx(0,2)
qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier() # mede YI
qc.sdg(0)
qc.h(0)
qc.cx(0,2)
qc.barrier() # mede IY
qc.sdg(1)
qc.h(1)
qc.cx(1,2)
qc.barrier() # mede YY
qc.cx(0,2)
qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier()
qc.h(0)
qc.cx(0,2) # mede XI
qc.barrier()
qc.sdg(1)
qc.h(1)
qc.cx(1,2) # mede IX
qc.barrier()
qc.cx(0,2); qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier()
qc.sdg(0)
qc.h(0)
qc.cx(0,2) # mede XI
qc.barrier()
qc.h(1)
qc.cx(1,2) # mede IX
qc.barrier()
qc.cx(0,2); qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
I = Matrix([[1,0],[0,1]]); X = Matrix([[0,1],[1,0]]);
Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]])
I,X,Y,Z
XX = kronecker_product(X,X); XX.eigenvects()
YY = kronecker_product(Y,Y); YY.eigenvects()
ZZ = kronecker_product(Z,Z); ZZ.eigenvects()
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier() # mede ZZ
qc.cx(0,2)
qc.cx(1,2)
qc.barrier() # mede XX
qc.h([0,1])
qc.cx(0,2)
qc.cx(1,2)
qc.barrier() # mede YY
qc.h([0,1])
qc.sdg([0,1])
qc.h([0,1])
qc.cx(0,2)
qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
XY = kronecker_product(X,Y); XY.eigenvects()
YX = kronecker_product(Y,X); YX.eigenvects()
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier() # mede ZZ
qc.cx(0,2)
qc.cx(1,2)
qc.barrier() # mede XX
qc.sdg(1)
qc.h([0,1])
qc.cx(0,2)
qc.cx(1,2)
qc.barrier() # mede YY
qc.h([0,1])
qc.sdg(0)
qc.s(1)
qc.h([0,1])
qc.cx(0,2)
qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
cr1 = {'0': 7921, '1': 271}
cr2 = {'0': 7944, '1': 248}
cr3 = {'0': 7754, '1': 438}
cc1 = {'0': 7913, '1': 279}
cc2 = {'0': 7940, '1': 252}
cc3 = {'0': 610, '1': 7582}
r1a = (cr1['0']-cr1['1'])/(cr1['0']+cr1['1'])
r2a = (cr2['0']-cr2['1'])/(cr2['0']+cr2['1'])
r3a = (cr3['0']-cr3['1'])/(cr3['0']+cr3['1'])
c1a = (cc1['0']-cc1['1'])/(cc1['0']+cc1['1'])
c2a = (cc2['0']-cc2['1'])/(cc2['0']+cc2['1'])
c3a = (cc3['0']-cc3['1'])/(cc3['0']+cc3['1'])
print(r1a,r2a,r3a,c1a,c2a,c3a)
def objective(x):
mu_Q = np.array([0.93,0.94,0.89,0.93,0.94,-0.85])
vec = mu_Q - A_R@x
return np.linalg.norm(vec)
constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x)-1},
{'type':'ineq', 'fun': lambda x: x},
{'type':'ineq', 'fun': lambda x: 1-x}]
np.random.seed(130000)
x0 = rpv_zhsl(16)
result = minimize(objective, x0, constraints=constraints, method='trust-constr')
print('melhor distribuicao de probabilidades', result.x)
print(objective(result.x))
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from sympy import *
init_printing(use_unicode=True)
r1,r2,r3,s1,s2,s3 = symbols('r_1 r_2 r_3 s_1 s_2 s_3')
I = Matrix([[1,0],[0,1]]); X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]])
rho = (1/2)*(I+r1*X+r2*Y+r3*Z); sigma = (1/2)*(I+s1*X+s2*Y+s3*Z)
#rho, sigma
def frho(r1,r2,r3):
return (1/2)*(I+r1*X+r2*Y+r3*Z)
def fsigma(s1,s2,s3):
return (1/2)*(I+s1*X+s2*Y+s3*Z)
A = frho(r1,0,r2)*fsigma(0,s2,0)
simplify(A.eigenvals())
A = frho(0,0,r3); B = fsigma(s1,s2,0)
simplify(A*(B**2)*A - B*(A**2)*B)
M = A*B; simplify(M)
simplify(M.eigenvals()) # parecem ser positivos o que esta na raiz e o autovalores
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from qiskit import *
import numpy as np
import math
import qiskit
nshots = 8192
IBMQ.load_account()
#provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
dth = math.pi/10
th = np.arange(0,math.pi+dth,dth)
ph = 0; lb = 0
N = len(th)
F_the = np.zeros(N); F_sim = np.zeros(N); F_exp = np.zeros(N)
for j in range(0,N):
F_the[j] = math.cos(th[j]/2)**2
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.u(th[j],ph,lb,qr[2])
qc.h(qr[0])
qc.cswap(qr[0],qr[1],qr[2])
qc.h(qr[0])
qc.measure(qr[0],cr[0])
job_sim = execute(qc, backend=simulator, shots=nshots)
counts = job_sim.result().get_counts(qc)
if '0' in counts:
F_sim[j] = 2*counts['0']/nshots - 1
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts = job_exp.result().get_counts(qc)
if '0' in counts:
F_exp[j] = 2*counts['0']/nshots - 1
qc.draw('mpl')
qc.decompose().decompose().draw('mpl') # o circuito é "profundo" por causa da swap controlada
F_the, F_sim, F_exp
from matplotlib import pyplot as plt
plt.plot(th, F_the, label=r'$F_{the}$')
plt.plot(th, F_sim, '*', label=r'$F_{sim}$')
plt.plot(th, F_exp, 'o', label=r'$F_{exp}$')
plt.xlabel(r'$\theta$')
plt.legend()
plt.show()
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from qiskit import *
import numpy as np
import math
from matplotlib import pyplot as plt
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
#from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.visualization import plot_histogram
def qc_dqc1(ph):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr, name='DQC1')
qc.h(0)
qc.h(1) # cria o estado de Bell dos qubits 1 e 2, que equivale ao estado de 1 sendo maximamente misto
qc.cx(1,2)
#qc.barrier()
qc.cp(ph, 0, 1)
return qc
ph = math.pi/2
qc_dqc1_ = qc_dqc1(ph)
qc_dqc1_.draw('mpl')
qc_dqc1_.decompose().draw('mpl')
def pTraceL_num(dl, dr, rhoLR): # Retorna traco parcial sobre L de rhoLR
rhoR = np.zeros((dr, dr), dtype=complex)
for j in range(0, dr):
for k in range(j, dr):
for l in range(0, dl):
rhoR[j,k] += rhoLR[l*dr+j,l*dr+k]
if j != k:
rhoR[k,j] = np.conj(rhoR[j,k])
return rhoR
def pTraceR_num(dl, dr, rhoLR): # Retorna traco parcial sobre R de rhoLR
rhoL = np.zeros((dl, dl), dtype=complex)
for j in range(0, dl):
for k in range(j, dl):
for l in range(0, dr):
rhoL[j,k] += rhoLR[j*dr+l,k*dr+l]
if j != k:
rhoL[k,j] = np.conj(rhoL[j,k])
return rhoL
# simulation
phmax = 2*math.pi
dph = phmax/20
ph = np.arange(0,phmax+dph,dph)
d = len(ph);
xm = np.zeros(d)
ym = np.zeros(d)
for j in range(0,d):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
qc_dqc1_ = qc_dqc1(ph[j])
qc.append(qc_dqc1_, [0,1,2])
qstc = state_tomography_circuits(qc, [1,0])
job = execute(qstc, backend=simulator, shots=nshots)
qstf = StateTomographyFitter(job.result(), qstc)
rho_01 = qstf.fit(method='lstsq')
rho_0 = pTraceR_num(2, 2, rho_01)
xm[j] = 2*rho_0[1,0].real
ym[j] = 2*rho_0[1,0].imag
qc.draw('mpl')
# experiment
phmax = 2*math.pi
dph = phmax/10
ph_exp = np.arange(0,phmax+dph,dph)
d = len(ph_exp);
xm_exp = np.zeros(d)
ym_exp = np.zeros(d)
for j in range(0,d):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
qc_dqc1_ = qc_dqc1(ph_exp[j])
qc.append(qc_dqc1_, [0,1,2])
qstc = state_tomography_circuits(qc, [1,0])
job = execute(qstc, backend=device, shots=nshots)
print(job.job_id())
job_monitor(job)
qstf = StateTomographyFitter(job.result(), qstc)
rho_01 = qstf.fit(method='lstsq')
rho_0 = pTraceR_num(2, 2, rho_01)
xm_exp[j] = 2*rho_0[1,0].real
ym_exp[j] = 2*rho_0[1,0].imag
plt.plot(ph, xm, label = r'$\langle X\rangle_{sim}$')#, marker='*')
plt.plot(ph, ym, label = r'$\langle Y\rangle_{sim}$')#, marker='o')
plt.scatter(ph_exp, xm_exp, label = r'$\langle X\rangle_{exp}$', marker='*', color='r')
plt.scatter(ph_exp, ym_exp, label = r'$\langle Y\rangle_{exp}$', marker='o', color='g')
plt.legend(bbox_to_anchor=(1, 1))#,loc='center right')
#plt.xlim(0,2*math.pi)
#plt.ylim(-1,1)
plt.xlabel(r'$\phi$')
plt.show()
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from qiskit import *
import numpy as np
import math
from matplotlib import pyplot as plt
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
#from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.visualization import plot_histogram
qr = QuantumRegister(4)
cr = ClassicalRegister(3)
qc = QuantumCircuit(qr, cr)
qc.x(3)
qc.h([0,1,2])
qc.draw('mpl')
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi/2, np.pi/2, 1000) # generate 1000 evenly spaced points between -pi and pi
y_sin = np.abs(np.sin(x/2)) # compute sin(x) for each x
y_x = np.abs(x/2) # set y=x for each x
plt.plot(x, y_sin, label='sin(x)') # plot sin(x) as a blue line
plt.plot(x, y_x, label='x', color='orange') # plot x as an orange line
plt.legend() # display the legend
plt.show() # show the plot
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from qiskit import *
import numpy as np
import math
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_manila')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
#from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
#from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.visualization import plot_histogram
def qc_bb84():
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr,cr)
qc.h([1,2])
qc.measure([1,2],[1,2])
qc.x(0).c_if(cr[1],1)
qc.h(0).c_if(cr[2],1)
qc.barrier()
qc.barrier()
qc.h(3)
qc.measure(qr[3],cr[3])
qc.h(0).c_if(cr[3],1)
qc.measure(0,0)
return qc
qc_bb84_ = qc_bb84(); qc_bb84_.draw('mpl')
nshots = 1
N = 100
counts = []
for j in range(0,N):
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
counts.append(counts_sim)
counts[0:5]
counts_keys = [j for j in counts]
counts_keys
k=0;l=1;m=0;n=0
s= str(k)+str(l)+str(m)+str(n)
s
eo = [] # observavel escolhido por Alice e Bob (mesmo = 0, diferente=1)
for j in range(0,N):
for k in range(0,2):
for l in range(0,2):
for m in range(0,2):
for n in range(0,2):
s = str(n) + str(m) + str(l) + str(k)
if counts[j][s] in counts and counts[j][s] == 1:
if l==0 and m==0:
eo.append(0)
else:
eo.append(1)
eo
qr = QuantumRegister(4)
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/Hayatto9217/Qiskit13
|
Hayatto9217
|
#error でインストール必要あり
pip install cvxpy
#approximate_error and approximate_noise_model
from qiskit_aer.utils import approximate_quantum_error, approximate_noise_model
import numpy as np
from qiskit_aer.noise import amplitude_damping_error, reset_error, pauli_error
from qiskit.quantum_info import Kraus
#Kraus 演算子
gamma = 0.23
error = amplitude_damping_error(gamma)
results = approximate_quantum_error(error, operator_string="reset")
print(results)
p = ( 1 + gamma -np.sqrt(1 - gamma)) / 2
q = 0
print("")
print("Expected results:")
print("P(0) = {}".format(1 -(p+q)))
print("P(1) = {}".format(p))
print("P(2) = {}".format(q))
#error operatorsはリスト、辞書またはハードコードされたチャネルを示す文字列として与える
gamma = 0.23
k0 = np.array([[1,0],[0,np.sqrt(1-gamma)]])
k1 = np.array([[0, np.sqrt(gamma)], [0,0]])
results =approximate_quantum_error(Kraus([k0, k1]), operator_string="reset")
print(results)
reset_to_0 = Kraus([np.array([[1,0],[0,0]]), np.array([[0,1],[0,0]])])
reset_to_1 = Kraus([np.array([[0,0],[1,0]]), np.array([[0,0],[0,1]])])
reset_kraus = [reset_to_0, reset_to_1]
gamma = 0.23
error = amplitude_damping_error(gamma)
results = approximate_quantum_error(error, operator_list=reset_kraus)
print(results)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/rochelleli165/qiskitfallfest2023
|
rochelleli165
|
########################################
# ENTER YOUR NAME AND WISC EMAIL HERE: #
########################################
# Name: Rochelle Li
# Email: rli484@wisc.edu
event = "Qiskit Fall Fest"
## Write your code below here. Delete the current information and replace it with your own ##
## Make sure to write your information between the quotation marks!
name = "Rochelle Li"
age = "19"
school = "University of Wisconsin Madison"
## Now press the "Run" button in the toolbar above, or press Shift + Enter while you're active in this cell
## You do not need to write any code in this cell. Simply run this cell to see your information in a sentence. ##
print(f'My name is {name}, I am {age} years old, and I attend {school}.')
## Run this cell to make sure your grader is setup correctly
%set_env QC_GRADE_ONLY=true
%set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com
from qiskit import QuantumCircuit
# Create quantum circuit with 3 qubits and 3 classical bits
# (we'll explain why we need the classical bits later)
qc = QuantumCircuit(3,3)
# return a drawing of the circuit
qc.draw()
## You don't need to write any new code in this cell, just run it
from qiskit import QuantumCircuit
qc = QuantumCircuit(3,3)
# measure all the qubits
qc.measure([0,1,2], [0,1,2])
qc.draw(output="mpl")
from qiskit.providers.aer import AerSimulator
# make a new simulator object
sim = AerSimulator()
job = sim.run(qc) # run the experiment
result = job.result() # get the results
result.get_counts() # interpret the results as a "counts" dictionary
from qiskit import QuantumCircuit
from qiskit.providers.aer import AerSimulator
## Write your code below here ##
qc = QuantumCircuit(4,4)
qc.measure([0,1,2,3], [0,1,2,3])
## Do not modify the code under this line ##
qc.draw()
sim = AerSimulator() # make a new simulator object
job = sim.run(qc) # run the experiment
result = job.result() # get the results
answer1 = result.get_counts()
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex1a
grade_ex1a(answer1)
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
# We start by flipping the first qubit, which is qubit 0, using an X gate
qc.x(0)
# Next we add an H gate on qubit 0, putting this qubit in superposition.
qc.h(0)
# Finally we add a CX (CNOT) gate on qubit 0 and qubit 1
# This entangles the two qubits together
qc.cx(0, 1)
qc.draw(output="mpl")
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 2)
## Write your code below here ##
qc.h(0)
qc.cx(0,1)
## Do not modify the code under this line ##
answer2 = qc
qc.draw(output="mpl")
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex1b
grade_ex1b(answer2)
|
https://github.com/rochelleli165/qiskitfallfest2023
|
rochelleli165
|
########################################
# ENTER YOUR NAME AND WISC EMAIL HERE: #
########################################
# Name: Rochelle Li
# Email: rli484@wisc.edu
## Run this cell to make sure your grader is setup correctly
%set_env QC_GRADE_ONLY=true
%set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, 3)
## Write your code below this line ##
qc.h(0)
qc.h(2)
qc.cx(0,1)
## Do not change the code below here ##
answer1 = qc
qc.draw()
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2a
grade_ex2a(answer1)
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, 3)
qc.barrier(0, 1, 2)
## Write your code below this line ##
qc.cx(1,2)
qc.x(2)
qc.cx(2,0)
qc.x(2)
## Do not change the code below this line ##
answer2 = qc
qc.draw()
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2b
grade_ex2b(answer2)
answer3: bool
## Quiz: evaluate the results and decide if the following statement is True or False
q0 = 1
q1 = 0
q2 = 1
## Based on this, is it TRUE or FALSE that the Guard on the left is a liar?
## Assign your answer, either True or False, to answer3 below
answer3 = True
from qc_grader.challenges.fall_fest23 import grade_ex2c
grade_ex2c(answer3)
## Quiz: Fill in the correct numbers to make the following statement true:
## The treasure is on the right, and the Guard on the left is the liar
q0 = 0
q1 = 1
q2 = 1
## HINT - Remember that Qiskit uses little-endian ordering
answer4 = [q0, q1, q2]
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2d
grade_ex2d(answer4)
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
## in the code below, fill in the missing gates. Run the cell to see a drawing of the current circuit ##
qc.h(0)
qc.h(2)
qc.cx(0,1)
qc.barrier(0, 1, 2)
qc.cx(2, 1)
qc.x(2)
qc.cx(2, 0)
qc.x(2)
qc.barrier(0, 1, 2)
qc.swap(0,1)
qc.x(0)
qc.x(1)
qc.cx(2,1)
qc.x(2)
qc.cx(2,0)
qc.x(2)
## Do not change any of the code below this line ##
answer5 = qc
qc.draw(output="mpl")
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2e
grade_ex2e(answer5)
from qiskit import QuantumCircuit, Aer, transpile
from qiskit.visualization import plot_histogram
## This is the full version of the circuit. Run it to see the results ##
quantCirc = QuantumCircuit(3)
quantCirc.h(0), quantCirc.h(2), quantCirc.cx(0, 1), quantCirc.barrier(0, 1, 2), quantCirc.cx(2, 1), quantCirc.x(2), quantCirc.cx(2, 0), quantCirc.x(2)
quantCirc.barrier(0, 1, 2), quantCirc.swap(0, 1), quantCirc.x(1), quantCirc.cx(2, 1), quantCirc.x(0), quantCirc.x(2), quantCirc.cx(2, 0), quantCirc.x(2)
# Execute the circuit and draw the histogram
measured_qc = quantCirc.measure_all(inplace=False)
backend = Aer.get_backend('qasm_simulator') # the device to run on
result = backend.run(transpile(measured_qc, backend), shots=1000).result()
counts = result.get_counts(measured_qc)
plot_histogram(counts)
from qiskit.primitives import Sampler
from qiskit.visualization import plot_distribution
sampler = Sampler()
result = sampler.run(measured_qc, shots=1000).result()
probs = result.quasi_dists[0].binary_probabilities()
plot_distribution(probs)
|
https://github.com/rochelleli165/qiskitfallfest2023
|
rochelleli165
|
########################################
# ENTER YOUR NAME AND WISC EMAIL HERE: #
########################################
# Name: Rochelle Li
# Email: rli484@wisc.edu
## Run this cell to make sure your grader is setup correctly
%set_env QC_GRADE_ONLY=true
%set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com
from qiskit import QuantumCircuit
from qiskit.circuit import QuantumRegister, ClassicalRegister
qr = QuantumRegister(1)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
# unpack the qubit and classical bits from the registers
(q0,) = qr
b0, b1 = cr
# apply Hadamard
qc.h(q0)
# measure
qc.measure(q0, b0)
# begin if test block. the contents of the block are executed if b0 == 1
with qc.if_test((b0, 1)):
# if the condition is satisfied (b0 == 1), then flip the bit back to 0
qc.x(q0)
# finally, measure q0 again
qc.measure(q0, b1)
qc.draw(output="mpl", idle_wires=False)
from qiskit_aer import AerSimulator
# initialize the simulator
backend_sim = AerSimulator()
# run the circuit
reset_sim_job = backend_sim.run(qc)
# get the results
reset_sim_result = reset_sim_job.result()
# retrieve the bitstring counts
reset_sim_counts = reset_sim_result.get_counts()
print(f"Counts: {reset_sim_counts}")
from qiskit.visualization import *
# plot histogram
plot_histogram(reset_sim_counts)
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
q0, q1 = qr
b0, b1 = cr
qc.h(q0)
qc.measure(q0, b0)
## Write your code below this line ##
with qc.if_test((b0, 0)) as else_:
qc.x(1)
with else_:
qc.h(1)
## Do not change the code below this line ##
qc.measure(q1, b1)
qc.draw(output="mpl", idle_wires=False)
backend_sim = AerSimulator()
job_1 = backend_sim.run(qc)
result_1 = job_1.result()
counts_1 = result_1.get_counts()
print(f"Counts: {counts_1}")
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3b
grade_ex3b(qc)
controls = QuantumRegister(2, name="control")
target = QuantumRegister(1, name="target")
mid_measure = ClassicalRegister(2, name="mid")
final_measure = ClassicalRegister(1, name="final")
base = QuantumCircuit(controls, target, mid_measure, final_measure)
def trial(
circuit: QuantumCircuit,
target: QuantumRegister,
controls: QuantumRegister,
measures: ClassicalRegister,
):
"""Probabilistically perform Rx(theta) on the target, where cos(theta) = 3/5."""
## Write your code below this line, making sure it's indented to where this comment begins from ##
c0,c1 = controls
(t0,) = target
b0, b1 = mid_measure
circuit.h(c0)
circuit.h(c1)
circuit.h(t0)
circuit.ccx(c0, c1, t0)
circuit.s(t0)
circuit.ccx(c0, c1, t0)
circuit.h(c0)
circuit.h(c1)
circuit.h(t0)
circuit.measure(c0, b0)
circuit.measure(c1, b1)
## Do not change the code below this line ##
qc = base.copy_empty_like()
trial(qc, target, controls, mid_measure)
qc.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3c
grade_ex3c(qc)
def reset_controls(
circuit: QuantumCircuit, controls: QuantumRegister, measures: ClassicalRegister
):
"""Reset the control qubits if they are in |1>."""
## Write your code below this line, making sure it's indented to where this comment begins from ##
c0, c1 = controls
r0, r1 = measures
# circuit.h(c0)
# circuit.h(c1)
# circuit.measure(c0, r0)
# circuit.measure(c1, r1)
with circuit.if_test((r0, 1)):
circuit.x(c0)
with circuit.if_test((r1, 1)):
circuit.x(c1)
## Do not change the code below this line ##
qc = base.copy_empty_like()
trial(qc, target, controls, mid_measure)
reset_controls(qc, controls, mid_measure)
qc.measure(controls, mid_measure)
qc.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3d
grade_ex3d(qc)
# Set the maximum number of trials
max_trials = 2
# Create a clean circuit with the same structure (bits, registers, etc) as the initial base we set up.
circuit = base.copy_empty_like()
# The first trial does not need to reset its inputs, since the controls are guaranteed to start in the |0> state.
trial(circuit, target, controls, mid_measure)
# Manually add the rest of the trials. In the future, we will be able to use a dynamic `while` loop to do this, but for now,
# we statically add each loop iteration with a manual condition check on each one.
# This involves more classical synchronizations than the while loop, but will suffice for now.
for _ in range(max_trials - 1):
reset_controls(circuit, controls, mid_measure)
with circuit.if_test((mid_measure, 0b00)) as else_:
# This is the success path, but Qiskit can't directly
# represent a negative condition yet, so we have an
# empty `true` block in order to use the `else` branch.
pass
with else_:
## Write your code below this line, making sure it's indented to where this comment begins from ##
# (t0,) = target
circuit.x(2)
trial(circuit, target, controls, mid_measure)
## Do not change the code below this line ##
# We need to measure the control qubits again to ensure we get their final results; this is a hardware limitation.
circuit.measure(controls, mid_measure)
# Finally, let's measure our target, to check that we're getting the rotation we desired.
circuit.measure(target, final_measure)
circuit.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3e
grade_ex3e(circuit)
sim = AerSimulator()
job = sim.run(circuit, shots=1000)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
|
https://github.com/hidemita/QiskitExamples
|
hidemita
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
import random
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit import BasicAer
qc = QuantumCircuit(9,4)
# Z-type Stabilizers
qc.h(5)
qc.cz(5, 0)
qc.cz(5, 1)
qc.cz(5, 2)
qc.h(5)
qc.h(8)
qc.cz(8, 2)
qc.cz(8, 3)
qc.cz(8, 4)
qc.h(8)
# X-type Stabilizers
qc.h(6)
qc.cx(6, 0)
qc.cx(6, 2)
qc.cx(6, 3)
qc.h(6)
qc.h(7)
qc.cx(7, 1)
qc.cx(7, 2)
qc.cx(7, 4)
qc.h(7)
# Measurement
qc.measure(5, 0)
qc.measure(6, 1)
qc.measure(7, 2)
qc.measure(8, 3)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
job.result().get_counts(qc)
qc = QuantumCircuit(9,4)
# Make stabilizer state
qc.h(0)
qc.cx(0, 2)
qc.cx(0, 3)
qc.h(1)
qc.cx(1, 2)
qc.cx(1, 4)
# Z-type Stabilizers
qc.h(5)
qc.cz(5, 0)
qc.cz(5, 1)
qc.cz(5, 2)
qc.h(5)
qc.h(8)
qc.cz(8, 2)
qc.cz(8, 3)
qc.cz(8, 4)
qc.h(8)
# X-type Stabilizers
qc.h(6)
qc.cx(6, 0)
qc.cx(6, 2)
qc.cx(6, 3)
qc.h(6)
qc.h(7)
qc.cx(7, 1)
qc.cx(7, 2)
qc.cx(7, 4)
qc.h(7)
# Measurement
qc.measure(5, 0)
qc.measure(6, 1)
qc.measure(7, 2)
qc.measure(8, 3)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
job.result().get_counts(qc)
qc = QuantumCircuit(9,4)
# Make stabilizer state
qc.h(0)
qc.cx(0, 2)
qc.cx(0, 3)
qc.h(1)
qc.cx(1, 2)
qc.cx(1, 4)
# Simulate Z error
qc.z(2)
# Z-type Stabilizers
qc.h(5)
qc.cz(5, 0)
qc.cz(5, 1)
qc.cz(5, 2)
qc.h(5)
qc.h(8)
qc.cz(8, 2)
qc.cz(8, 3)
qc.cz(8, 4)
qc.h(8)
# X-type Stabilizers
qc.h(6)
qc.cx(6, 0)
qc.cx(6, 2)
qc.cx(6, 3)
qc.h(6)
qc.h(7)
qc.cx(7, 1)
qc.cx(7, 2)
qc.cx(7, 4)
qc.h(7)
# Measurement
qc.measure(5, 0)
qc.measure(6, 1)
qc.measure(7, 2)
qc.measure(8, 3)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
job.result().get_counts(qc)
qc = QuantumCircuit(10,5) # q_9 and c_5 bits for logical bit measurement
# Make Stabilizer State
qc.h(0)
qc.cx(0, 2)
qc.cx(0, 3)
qc.h(1)
qc.cx(1, 2)
qc.cx(1, 4)
# Z-type Stabilizers
qc.h(5)
qc.cz(5, 0)
qc.cz(5, 1)
qc.cz(5, 2)
qc.h(5)
qc.h(8)
qc.cz(8, 2)
qc.cz(8, 3)
qc.cz(8, 4)
qc.h(8)
# X-type Stabilizers
qc.h(6)
qc.cx(6, 0)
qc.cx(6, 2)
qc.cx(6, 3)
qc.h(6)
qc.h(7)
qc.cx(7, 1)
qc.cx(7, 2)
qc.cx(7, 4)
qc.h(7)
# logical pauli-X operator
qc.x(0)
qc.x(1)
# logical Z-basis hadamard test for the logical bit
qc.h(9)
qc.cz(9,1)
qc.cz(9,4)
qc.h(9)
# Measurement
qc.measure(5, 0)
qc.measure(6, 1)
qc.measure(7, 2)
qc.measure(8, 3)
qc.measure(9, 4)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
job.result().get_counts(qc)
qc = QuantumCircuit(16,8)
# Z-type stabilizers
qc.h(12)
qc.cz(12, 0)
qc.cz(12, 2)
qc.cz(12, 3)
qc.cz(12, 4)
qc.h(12)
qc.h(13)
qc.cz(13, 0)
qc.cz(13, 2)
qc.cz(13, 3)
qc.cz(13, 4)
qc.h(13)
qc.h(14)
qc.cz(14, 0)
qc.cz(14, 2)
qc.cz(14, 3)
qc.cz(14, 4)
qc.h(14)
qc.h(15)
qc.cz(15, 0)
qc.cz(15, 2)
qc.cz(15, 3)
qc.cz(15, 4)
qc.h(15)
# X-type stabilizers
qc.h(8)
qc.cx(8, 0)
qc.cx(8, 1)
qc.cx(8, 2)
qc.cx(8, 6)
qc.h(8)
qc.h(9)
qc.cx(9, 0)
qc.cx(9, 1)
qc.cx(9, 3)
qc.cx(9, 7)
qc.h(9)
qc.h(10)
qc.cx(10, 2)
qc.cx(10, 4)
qc.cx(10, 5)
qc.cx(10, 6)
qc.h(10)
qc.h(11)
qc.cx(11, 3)
qc.cx(11, 4)
qc.cx(11, 5)
qc.cx(11, 7)
qc.h(11)
qc.measure(8, 0)
qc.measure(9, 1)
qc.measure(10, 2)
qc.measure(11, 3)
qc.measure(12, 4)
qc.measure(13, 5)
qc.measure(14, 6)
qc.measure(15, 7)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
job.result().get_counts(qc)
qc = QuantumCircuit(16,8)
# Initialize to a stabilizers state
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 6)
qc.h(3)
qc.cx(3, 0)
qc.cx(3, 1)
qc.cx(3, 7)
qc.h(4)
qc.cx(4, 2)
qc.cx(4, 5)
qc.cx(4, 6)
# Z-type stabilizers
qc.h(12)
qc.cz(12, 0)
qc.cz(12, 2)
qc.cz(12, 3)
qc.cz(12, 4)
qc.h(12)
qc.h(13)
qc.cz(13, 0)
qc.cz(13, 2)
qc.cz(13, 3)
qc.cz(13, 4)
qc.h(13)
qc.h(14)
qc.cz(14, 0)
qc.cz(14, 2)
qc.cz(14, 3)
qc.cz(14, 4)
qc.h(14)
qc.h(15)
qc.cz(15, 0)
qc.cz(15, 2)
qc.cz(15, 3)
qc.cz(15, 4)
qc.h(15)
# X-type stabilizers
qc.h(8)
qc.cx(8, 0)
qc.cx(8, 1)
qc.cx(8, 2)
qc.cx(8, 6)
qc.h(8)
qc.h(9)
qc.cx(9, 0)
qc.cx(9, 1)
qc.cx(9, 3)
qc.cx(9, 7)
qc.h(9)
qc.h(10)
qc.cx(10, 2)
qc.cx(10, 4)
qc.cx(10, 5)
qc.cx(10, 6)
qc.h(10)
qc.h(11)
qc.cx(11, 3)
qc.cx(11, 4)
qc.cx(11, 5)
qc.cx(11, 7)
qc.h(11)
qc.measure(8, 0)
qc.measure(9, 1)
qc.measure(10, 2)
qc.measure(11, 3)
qc.measure(12, 4)
qc.measure(13, 5)
qc.measure(14, 6)
qc.measure(15, 7)
#qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
job.result().get_counts(qc)
qc = QuantumCircuit(16,8)
# Initialize to a stabilizers state
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 6)
qc.h(3)
qc.cx(3, 0)
qc.cx(3, 1)
qc.cx(3, 7)
qc.h(4)
qc.cx(4, 2)
qc.cx(4, 5)
qc.cx(4, 6)
# A simulated error
qc.z(0)
# Z-type stabilizers
qc.h(12)
qc.cz(12, 0)
qc.cz(12, 2)
qc.cz(12, 3)
qc.cz(12, 4)
qc.h(12)
qc.h(13)
qc.cz(13, 0)
qc.cz(13, 2)
qc.cz(13, 3)
qc.cz(13, 4)
qc.h(13)
qc.h(14)
qc.cz(14, 0)
qc.cz(14, 2)
qc.cz(14, 3)
qc.cz(14, 4)
qc.h(14)
qc.h(15)
qc.cz(15, 0)
qc.cz(15, 2)
qc.cz(15, 3)
qc.cz(15, 4)
qc.h(15)
# X-type stabilizers
qc.h(8)
qc.cx(8, 0)
qc.cx(8, 1)
qc.cx(8, 2)
qc.cx(8, 6)
qc.h(8)
qc.h(9)
qc.cx(9, 0)
qc.cx(9, 1)
qc.cx(9, 3)
qc.cx(9, 7)
qc.h(9)
qc.h(10)
qc.cx(10, 2)
qc.cx(10, 4)
qc.cx(10, 5)
qc.cx(10, 6)
qc.h(10)
qc.h(11)
qc.cx(11, 3)
qc.cx(11, 4)
qc.cx(11, 5)
qc.cx(11, 7)
qc.h(11)
qc.measure(8, 0)
qc.measure(9, 1)
qc.measure(10, 2)
qc.measure(11, 3)
qc.measure(12, 4)
qc.measure(13, 5)
qc.measure(14, 6)
qc.measure(15, 7)
#qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
job.result().get_counts(qc)
|
https://github.com/hidemita/QiskitExamples
|
hidemita
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
import random
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit import BasicAer, Aer
qc = QuantumCircuit(65, 32)
# Z-type Stabilizers
Zstab = [
[47, [0,3,5]],
[48, [1,3,4,6]],
[49, [2,4,7]],
[50, [5,8,10]],
[51, [6,8,9,11]],
[52, [7,9,12]],
[53, [10,13,15]],
[54, [11,13,14,16]],
[55, [12,14,17]],
[56, [15,18,20]],
[57, [16,18,19,21]],
[58, [17,19,22]],
[59, [20,23,25]],
[60, [21,23,24,26]],
[61, [22,24,27]],
[62, [25,28,30]],
[63, [26,28,29,31]],
[64, [27,29,32]]
]
# X-type Stabilizers
Xstab = [
[33, [0,1,3]],
[34, [1,2,4]],
[35, [3,5,6,8]],
[36, [4,6,7,9]],
[37, [8,10,11,13]],
[38, [9,11,12,14]],
[39, [13,15,16,18]],
[40, [14,16,17,19]],
[41, [18,20,21,23]],
[42, [19,21,22,24]],
[43, [23,25,26,28]],
[44, [24,26,27,29]],
[45, [28,30,31]],
[46, [29,31,32]]
]
# Make stabilizer state
Xinitialize = [
[0, 1, 3],
[2, 1, 4],
[5, 3, 6, 8],
[7, 4, 6, 9],
[10, 8, 11, 13],
[12, 9, 11, 14],
[15, 13, 16, 18],
[17, 14, 16, 19],
[20, 18, 21, 23],
[22, 19, 21, 24],
[25, 23, 26, 28],
[27, 24, 26, 29],
[30, 28, 31],
[32, 29, 31],
]
for x in Xinitialize:
q0 = x[0]
qc.h(q0)
for q1 in x[1:]:
qc.cx(q0, q1)
# Place stabilizers
for z in Zstab:
qc.h(z[0])
for q in z[1]:
qc.cz(z[0], q)
qc.h(z[0])
for x in Xstab:
qc.h(x[0])
for q in x[1]:
qc.cx(x[0], q)
qc.h(x[0])
# Measurement stabilizer errors
for m, q in enumerate(Zstab + Xstab):
qc.measure(q[0], m)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
job.result().get_counts(qc)
qc = QuantumCircuit(65, 32+1) # classical bit-32 for logical bit test
# Z-type Stabilizers
Zstab = [
[47, [0,3,5]],
[48, [1,3,4,6]],
[49, [2,4,7]],
[50, [5,8,10]],
# [51, [6,8,9,11]], # defect Z-cut hole 1
[52, [7,9,12]],
[53, [10,13,15]],
[54, [11,13,14,16]],
[55, [12,14,17]],
[56, [15,18,20]],
[57, [16,18,19,21]],
[58, [17,19,22]],
[59, [20,23,25]],
# [60, [21,23,24,26]], # defect Z-cut hole 2
[61, [22,24,27]],
[62, [25,28,30]],
[63, [26,28,29,31]],
[64, [27,29,32]]
]
# X-type Stabilizers
Xstab = [
[33, [0,1,3]],
[34, [1,2,4]],
[35, [3,5,6,8]],
[36, [4,6,7,9]],
[37, [8,10,11,13]],
[38, [9,11,12,14]],
[39, [13,15,16,18]],
[40, [14,16,17,19]],
[41, [18,20,21,23]],
[42, [19,21,22,24]],
[43, [23,25,26,28]],
[44, [24,26,27,29]],
[45, [28,30,31]],
[46, [29,31,32]]
]
# Make stabilizer state
Xinitialize = [
[0, 1, 3],
[2, 1, 4],
[5, 3, 6, 8],
[7, 4, 6, 9],
[10, 8, 11, 13],
[12, 9, 11, 14],
[15, 13, 16, 18],
[17, 14, 16, 19],
[20, 18, 21, 23],
[22, 19, 21, 24],
[25, 23, 26, 28],
[27, 24, 26, 29],
[30, 28, 31],
[32, 29, 31],
]
for x in Xinitialize:
q0 = x[0]
qc.h(q0)
for q1 in x[1:]:
qc.cx(q0, q1)
# Place stabilizers
for z in Zstab:
qc.h(z[0])
for q in z[1]:
qc.cz(z[0], q)
qc.h(z[0])
for x in Xstab:
qc.h(x[0])
for q in x[1]:
qc.cx(x[0], q)
qc.h(x[0])
# logical X-operator
logical_x = True
if logical_x:
qc.x(11)
qc.x(16)
qc.x(21)
# Measurement for logical bit of # [51, [6,8,9,11]], # defect Z-cut hole 1
qc.h(51)
qc.cz(51, 6)
qc.cz(51, 8)
qc.cz(51, 9)
qc.cz(51, 11)
qc.h(51)
# Measurement stabilizer errors
for m, q in enumerate(Zstab + Xstab):
qc.measure(q[0], m)
# Z-Measurement of logical bit (Observe bit-32 change, with no stabilizer errors)
qc.measure(51, 32)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
job.result().get_counts(qc)
|
https://github.com/jmamczynska/QiskitLabs
|
jmamczynska
|
from qiskit import *
from qiskit.visualization import plot_histogram
from qiskit.visualization import plot_state_qsphere, plot_bloch_vector
from qiskit.quantum_info import Statevector
import numpy as np
sim = Aer.get_backend('aer_simulator')
qr = QuantumRegister(3)
qc_3qx = QuantumCircuit(qr)
### your code goes here. ###
qc_3qx.h(0)
qc_3qx.s(0)
qc_3qx.cx(0,1)
qc_3qx.cx(0,2)
#######
qc_3qx.draw('mpl')
from qiskit.visualization import array_to_latex
state_ve = Statevector.from_instruction(qc_3qx)
array_to_latex(state_ve)
### your code goes here ###
state_ve = Statevector.from_instruction(qc_3qx)
plot_state_qsphere(state_ve)
def apply_err(n, err):
qc = QuantumCircuit(int(n), name='Error')
which_qubit = np.random.randint(n)
if err=='bit':
qc.x(which_qubit)
elif err=='phase':
qc.z(which_qubit)
else:
pass
err = qc.to_gate()
return err, which_qubit
err, which_qubit = apply_err(3, 'bit')
print('Error applied to qubit: ', which_qubit)
qc_3qx.append(err,range(3))
qc_3qx.draw('mpl')
# Execute this cell to add the extra registers
k = int(input('number of auxiliary qubits ( / syndrome bits): '))
ar = QuantumRegister(k, 'auxiliary')
cr = ClassicalRegister(k, 'syndrome')
qc_3qx.add_register(ar)
qc_3qx.add_register(cr)
# Apply the parity check gates and measure the parities on the syndrome bits to localize a single bit-flip ( X ) error on the code.
### your code goes here. ###
qc_3qx.draw('mpl')
qc_3qx.cx(qr[0], ar[0])
qc_3qx.cx(qr[1], ar[0])
qc_3qx.cx(qr[1], ar[1])
qc_3qx.cx(qr[2], ar[1])
qc_3qx.barrier()
qc_3qx.measure(ar, cr)
######
qc_3qx.draw('mpl')
#### complete the dictionary ###
table_syndrome = {'00': 'I[0]I[1]I[2]', '01':'I[0]I[1]X[2]',
'10': 'X[0]I[1]I[2]', '11':'I[0]X[1]I[2]'}
######
print(table_syndrome)
qc_3qx_trans = transpile(qc_3qx, sim)
syndrome = sim.run(qc_3qx_trans, shots=1, memory=True).result().get_memory()
print(syndrome)
your_answer = input('Enter the index of the code qubit that underwent bit-flip error: ')
print('\n')
print(which_qubit == int(your_answer))
### your code goes here ###
def get_logical_x():
qr_xl = QuantumRegister(3, 'qubit')
ar_xl = QuantumRegister(2, 'auxiliary')
sr_xl = ClassicalRegister(2, 'syndrome')
qc_xl = QuantumCircuit(qr_xl, ar_xl, sr_xl)
qc_xl.x(range(3))
qc_xl.cx([qr_xl[0], qr_xl[1]], [ar_xl[0], ar_xl[0]])
qc_xl.cx([qr_xl[1], qr_xl[2]], [ar_xl[1], ar_xl[1]])
qc_xl.barrier()
qc_xl.measure(ar_xl, sr_xl)
# correct errors
qc_xl.x(qr_xl[2]).c_if(sr_xl, 2)
qc_xl.x(qr_xl[0]).c_if(sr_xl, 1)
qc_xl.x(qr_xl[1]).c_if(sr_xl, 3)
return qc_xl
logical_x = get_logical_x()
bits_out = sim.run(logical_x, shots=1, memory=True).result().get_memory()
print(bits_out)
logical_x.draw('mpl')
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
aer_sim = Aer.get_backend('aer_simulator')
def get_noise(p_gate):
error_gate1 = depolarizing_error(p_gate, 1)
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error_gate1, ["x"]) # single qubit gate error is applied to x gates
return noise_model
noise_model = get_noise(0.01)
qr = QuantumRegister(3, 'qubit')
ar = QuantumRegister(2, 'auxiliary')
sr = ClassicalRegister(2, 'syndrome')
cr = ClassicalRegister(3, 'measure')
qc_000 = QuantumCircuit(qr, ar, sr, cr)
qc_000 = qc_000.compose(logical_x)
qc_000.barrier()
qc_000.measure(qr, cr)
qc_000.draw('mpl')
# run the circuit with the noise model and extract the counts
qobj = assemble(qc_000)
counts = aer_sim.run(qobj, noise_model=noise_model).result().get_counts()
plot_histogram(counts)
qc_3qz = QuantumCircuit(3)
### your code goes here. ###
########
qc_3qz.draw('mpl')
err, which_qubit = apply_err(3, 'phase')
qc_3qz.append(err, range(3))
### your code goes here ###
##########
qc_3qz.draw('mpl')
qc_3qz_trans = transpile(qc_3qz, sim)
syndrome = sim.run(qc_3qz_trans, shots=1, memory=True).result().get_memory()
print(syndrome)
your_answer = input('Enter the index of the code qubit that underwent phase-flip error: ')
print('\n')
print(which_qubit == int(your_answer))
## Your answer goes here
t = int(input('The number of counting qubit: '))
qc0 = QuantumCircuit(t+3, 1)
qc0.h(-1)
qc0.barrier()
## your code goes here ##
######
qc0.measure(0, 0)
qc0.draw('mpl')
counts_qc0 = sim.run(qc0, shots=8192).result().get_counts()
plot_histogram(counts_qc0)
qc1 = QuantumCircuit(t+3, 1)
qc1.h(-1)
qc1.barrier()
## your code goes here ##
######
qc1.measure(0, 0)
qc1.draw('mpl')
counts_qc1 = sim.run(qc1, shots=8192).result().get_counts()
plot_histogram(counts_qc1)
|
https://github.com/Alan-Robertson/QiskitPool
|
Alan-Robertson
|
import time
import qiskitpool
from qiskit import IBMQ, QuantumCircuit
import qiskit.tools.jupyter
IBMQ.load_account()
provider = IBMQ.get_provider(group='open', project='main')
%qiskit_job_watcher
pool = qiskitpool.QPool(provider)
backend = provider.get_backend('simulator_statevector')
n_shots = 10
circ = QuantumCircuit(1, 1)
circ.x(0)
circ.measure(0, 0)
job = pool(circ, backend, shots=n_shots)
pool
while not job.poll():
time.sleep(2)
assert(job.result().get_counts()['1'] == n_shots)
pool = qiskitpool.QPool(provider)
backend = provider.get_backend('simulator_statevector')
n_shots = 10
n_rounds = 20
circ = QuantumCircuit(1, 1)
circ.x(0)
circ.measure(0, 0)
# Create jobs
jobs = [pool(circ, backend, shots=n_shots) for i in range(n_rounds)]
print(pool)
# Wait for jobs to finish
n_complete = 0
while n_complete < n_rounds - 1:
n_complete = 0
for job in jobs:
if job.poll():
n_complete += 1
for job in jobs:
assert(job.poll())
assert(job.result().get_counts()['1'] == n_shots)
pool['simulator_statevector'].finished_jobs
pool['simulator_statevector'][0]
pool.join()
|
https://github.com/Alan-Robertson/QiskitPool
|
Alan-Robertson
|
'''
qiskitpool/job.py
Contains the QJob class
'''
from functools import partial
from qiskit import execute
class QJob():
'''
QJob
Job manager for asynch qiskit backends
'''
def __init__(self, *args, qjob_id=None, **kwargs):
'''
QJob.__init__
Initialiser for a qiksit job
:: *args :: Args for qiskit execute
:: **kwargs :: Kwargs for qiskit execute
'''
self.job_fn = partial(execute, *args, **kwargs)
self.job = None
self.done = False
self.test_count = 10
self.qjob_id = qjob_id
def __call__(self):
'''
QJob.__call__
Wrapper for QJob.run
'''
return self.run()
def run(self):
'''
QJob.run
Send async job to qiskit backend
'''
self.job = self.job_fn()
return self
def poll(self):
'''
QJob.poll
Poll qiskit backend for job completion status
'''
if self.job is not None:
return self.job.done()
return False
def cancel(self):
'''
QJob.cancel
Cancel job on backend
'''
if self.job is None:
return None
return self.job.cancel()
def position(self):
pos = self.job.queue_position()
if pos is None:
return 0
return pos
def status(self):
if self.job is None:
return 'LOCAL QUEUE'
else:
status = self.job.status().value
if 'running' in status:
return 'RUNNING'
if 'run' in status:
return 'COMPLETE'
if 'validated' in status:
return 'VALIDATING'
if 'queued' in status:
pos = self.position()
return f'QISKIT QUEUE: {self.position()}'
def status_short(self):
if self.job is None:
return ' '
else:
status = self.job.status().value
if 'running' in status:
return 'R'
if 'run' in status:
return 'C'
if 'validated' in status:
return 'V'
if 'queued' in status:
return str(self.position())
def result(self):
'''
QJob.result
Get result from backend
Non blocking - returns False if a job is not yet ready
'''
if self.poll():
return self.job.result()
return False
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
import qiskit
from qiskit import *
import math
import numpy as np
def qc_ezz(t):
qc = QuantumCircuit(2, name = 'e^(-itZZ)')
qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1)
return qc
def qc_exx(t):
qc = QuantumCircuit(2, name = 'e^(-itXX)')
qc.h([0,1]); qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1); qc.h([0,1])
return qc
def qc_eyy(t):
qc = QuantumCircuit(2, name = 'e^(-itYY)')
qc.sdg([0,1]); qc.h([0,1]); qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1); qc.h([0,1]); qc.s([0,1])
return qc
def qc_Bj(t):
qc = QuantumCircuit(3, name = 'B_j')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
return qc
qc_Bj_ = qc_Bj(math.pi/2); qc_Bj_.draw(output='mpl')
qc_Bj_.decompose().draw(output='mpl')
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
#provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_jakarta')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.tools.monitor import backend_overview, backend_monitor
from qiskit.providers.aer import noise
from qiskit.providers.aer.noise import NoiseModel
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
noise_model = NoiseModel.from_backend(device)
basis_gates = noise_model.basis_gates
coupling_map = device.configuration().coupling_map
ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]);
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
for j in range(0, 10): # Trotter stepsm_info.
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_ = qc_Bj(t/(j+1))
for k in range(0, j+1):
qc.append(qc_Bj_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
qstf_exp = StateTomographyFitter(job_exp.result(), qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('No. passos=', j+1, ',F_sim=', F_sim, ',F_exp=', F_exp)
inha visto essa reprovação mas não me dei por conta que n# for error mitigation
qr = QuantumRegister(7)
qubit_list = [5,3,1] # the qubits on which we shall apply error mitigation
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr)
job_cal = execute(meas_calibs, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
meas_fitter = CompleteMeasFitter(job_cal.result(), state_labels)
ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
for j in range(0, 10): # Trotter steps
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_ = qc_Bj(t/(j+1))
for k in range(0, j+1):
qc.append(qc_Bj_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('No. passos=', j+1, ',F_sim=', F_sim, ',F_exp=', F_exp)
def qc_Bj_zz(t, th, ph):
qc = QuantumCircuit(3, name = 'B_j_zz')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.rz(2*th, [1,2])
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.rz(-2*th, [1,2])
qc.rz(2*ph, [0,1])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
qc.rz(-2*ph, [0,1])
return qc
qc_Bj_zz_ = qc_Bj_zz(math.pi, math.pi/3, math.pi/4); qc_Bj_zz_.draw(output='mpl')
ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
j = 6; print('N. of Trotter steps = ', j+1)
th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0]
ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0]
for m in range(0, dim_th):
for n in range(0, dim_ph):
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_zz_ = qc_Bj_zz(t/(j+1), th[m], ph[n])
for k in range(0, j+1):
qc.append(qc_Bj_zz_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp)
def qc_Bj_zx(t, th, ph):
qc = QuantumCircuit(3, name = 'B_j_zz')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.rx(2*th, [1,2])
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.rx(-2*th, [1,2])
qc.rz(2*ph, [0,1])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
qc.rz(-2*ph, [0,1])
return qc
qc_Bj_zx_ = qc_Bj_zx(math.pi, math.pi/3, math.pi/4); qc_Bj_zx_.draw(output='mpl')
inha visto essa reprovação mas não me dei por conta que nket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
j = 6; print('N. of Trotter steps = ', j+1)
th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0]
ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0]
for m in range(0, dim_th):
for n in range(0, dim_ph):
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_zx_ = qc_Bj_zx(t/(j+1), th[m], ph[n])
for k in range(0, j+1):
qc.append(qc_Bj_zx_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp)
def qc_Bj_yx(t, th, ph):
qc = QuantumCircuit(3, name = 'B_j_zz')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.rx(2*th, [1,2])
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.rx(-2*th, [1,2])
qc.barrier()
qc.ry(2*ph, [0,1])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
qc.ry(-2*ph, [0,1])
return qc
qc_Bj_yx_ = qc_Bj_yx(math.pi, math.pi/3, math.pi/4); qc_Bj_yx_.draw(output='mpl')
https://arxiv.org/abs/2204.07816ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
j = 6; print('N. of Trotter steps = ', j+1)
th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0]
ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0]
for m in range(0, dim_th):
for n in range(0, dim_ph):
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_yx_ = qc_Bj_yx(t/(j+1), th[m], ph[n])
for k in range(0, j+1):
qc.append(qc_Bj_yx_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation0.34
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp)
noise_model = NoiseModel.from_backend(device)
basis_gates = noise_model.basis_gates
coupling_map = device.configuration().coupling_map
basis_gates
print(coupling_map)
553/3
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import math
th = np.arange(0, 2*math.pi, 0.1)
prE3 = 2*(1-(math.sqrt(2)*(np.sin(th/2)**2))/(1+math.sqrt(2)))
matplotlib.rcParams.update({'font.size':10})
plt.figure(figsize = (5,3), dpi = 100)
plt.plot(th, prE3)
plt.xlabel(r'$\theta$')
plt.ylabel(r'$Pr(E_{3})$')
plt.show()
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
cos(pi/8), sin(pi/8)
U = (1/sqrt(2))*Matrix([[1,1],[1,-1]]); V1 = Matrix([[1,0],[0,1]]); V2 = V1
D1 = Matrix([[cos(pi/8),0],[0,cos(pi/8)]]); D2 = Matrix([[sin(pi/8),0],[0,sin(pi/8)]])
U, U*U.T, D1, D2
M1 = V1*D1*U; M2 = V2*D2*U; M1, M2
M1*M1, M2*M2, M1*M1 + M2*M2 # não são projetores, mas são operadores de medida
2*float((1/4)*(1+1/sqrt(2))), 2*float((1/4)*(1-1/sqrt(2)))
qr = QuantumRegister(2); cr = ClassicalRegister(1); qc = QuantumCircuit(qr, cr)
qc.h(qr[0]); qc.x(qr[0]); qc.cry(math.pi/4, 0, 1); qc.x(qr[0]); qc.cry(math.pi/4, 0, 1)
# V1=V2=I
qc.measure(1,0)
qc.draw(output = 'mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
def U(xi, et, ga):
return Matrix([[(cos(xi)+1j*sin(xi))*cos(ga), (cos(et)+1j*sin(et))*sin(ga)],
[-(cos(et)-1j*sin(et))*sin(ga), (cos(xi)-1j*sin(xi))*cos(ga)]])
xi, et, ga = symbols('xi eta gamma'); U(xi, et, ga)
def D1(th, ph):
return Matrix([[cos(th/2),0],[0,cos(ph/2)]])
def D2(th, ph):
return Matrix([[sin(th/2),0],[0,sin(ph/2)]])
th,ph = symbols('theta phi'); D1(th, ph), D2(th, ph)
xi1,et1,ga1,xi2,et2,ga2,xi3,et3,ga3 = symbols('xi_1 eta_1 gamma_1 xi_2 eta_2 gamma_2 xi_3 eta_3 gamma_3')
simplify(U(xi1,et1,ga1)*D1(th,ph)*U(xi2,et2,ga2) - (1/2)*sqrt(1+1/sqrt(2))*Matrix([[1,1],[1,-1]]))
simplify(U(xi3,et3,ga3)*D2(th,ph)*U(xi2,et2,ga2) - (1/2)*sqrt(1+1/sqrt(2))*Matrix([[1,1],[1,-1]]))
cos(pi/3), sin(pi/3), cos(2*pi/3), sin(2*pi/3)
M1 = sqrt(2/3)*Matrix([[1,0],[0,0]])
M2 = (1/(4*sqrt(6)))*Matrix([[1,sqrt(3)],[sqrt(3),3]])
M3 = (1/(4*sqrt(6)))*Matrix([[1,-sqrt(3)],[-sqrt(3),3]])
M1,M2,M3
M1.T*M1 + M2.T*M2 + M3.T*M3
M1 = sqrt(2/3.)*Matrix([[1,0],[0,0]]); M2 = sqrt(2/3.)*(1/4)*Matrix([[1,sqrt(3.)],[sqrt(3.),3]])
M3 = sqrt(2/3.)*(1/4)*Matrix([[1,-sqrt(3.)],[-sqrt(3.),3]])
M1, M2, M3
M1.T*M1 + M2.T*M2 + M3.T*M3
2/3, 1/6, 2/3+2*(1/6)
#th1 = acos(sqrt(2/3)); ph1 = pi; th2 = pi/2; ph2 = pi/2
D11 = Matrix([[sqrt(2/3),0],[0,0]])
D21 = Matrix([[sqrt(1/3),0],[0,1]])
D12 = Matrix([[1/sqrt(2),0],[0,1/sqrt(2)]])
D22 = Matrix([[1/sqrt(2),0],[0,1/sqrt(2)]])
U = Matrix([[1,0],[0,1]])
V11 = Matrix([[1,0],[0,1]])
V21 = (1/sqrt(2))*Matrix([[1,1],[-1,1]])
V12 = (1/2)*Matrix([[1,-sqrt(3)],[sqrt(3),1]])
V22 = -(1/2)*Matrix([[sqrt(3),-1],[1,sqrt(3)]])
M1 = V11*D11*U
np.array(M1).astype(np.float64), np.array(Matrix([[sqrt(2/3),0],[0,0]])).astype(np.float64)
M2 = V12*D12*V21*D21*U
np.array(M2).astype(np.float64), np.array((1/4)*sqrt(2/3)*Matrix([[1,sqrt(3)],[sqrt(3),3]])).astype(np.float64)
# não é o resultado que precisamos
M3 = V22*D22*V21*D21*U
np.array(M3).astype(np.float64), np.array((1/4)*sqrt(2/3)*Matrix([[1,-sqrt(3)],[-sqrt(3),3]])).astype(np.float64)
# não é o resultado que precisamos
np.array(M1.T*M1 + M2.T*M2 + M3.T*M3).astype(np.float64) # esta ok a relacao de completeza
cos(pi/3), sin(pi/3), cos(pi/6)
def qc_ry(th):
qr = QuantumRegister(1); qc = QuantumCircuit(qr, name = 'RY')
qc.ry(th, 0)
return qc
def qc_u(th,ph,lb):
qr = QuantumRegister(1); qc = QuantumCircuit(qr, name = 'U')
qc.u(th,ph,lb, 0)
return qc
qr = QuantumRegister(3); cr = ClassicalRegister(2); qc = QuantumCircuit(qr, cr)
# U = I
qc.x(qr[0]); qc.cry(math.acos(math.sqrt(2/3)), 0, 1); qc.x(qr[0]); qc.cry(math.pi/2, 0, 1)
# V11 = I
qc.cu(math.pi/2,math.pi,math.pi,0, 1,0)
qc.barrier()
qc_ry_ = qc_ry(0); ccry = qc_ry_.to_gate().control(2) # cria a ctrl-ctrl-RY
qc.x(0); qc.append(ccry, [0,1,2]); qc.x(0)
qc_ry_ = qc_ry(math.pi/2); ccry = qc_ry_.to_gate().control(2)
qc.append(ccry, [0,1,2]) # os primeiros sao o controle, os ultimos sao o target
qc.x(2)
qc_u_ = qc_u(2*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2)
qc.append(ccu, [1,2,0])
qc.x(2)
qc_u_ = qc_u(4*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2)
qc.append(ccu, [1,2,0])
qc.barrier()
qc.measure(1,0); qc.measure(2,1)
qc.draw(output = 'mpl')
qc.decompose().draw(output = 'mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
# sequencia: 000 001 010 011 100 101 110 111 = 0 1 2 3 4 5 6 7
Phi_ACD = [math.sqrt(2/3), (1/4)*math.sqrt(2/3), (1/4)*math.sqrt(2/3), 0,
0, (1/4)*math.sqrt(2), -(1/4)*math.sqrt(2), 0]
qr = QuantumRegister(3); cr = ClassicalRegister(2); qc = QuantumCircuit(qr,cr)
qc.initialize(Phi_ACD, [qr[2],qr[1],qr[0]])
qc.draw(output='mpl')
backend = BasicAer.get_backend('statevector_simulator')
job = backend.run(transpile(qc, backend))
qc_state = job.result().get_statevector(qc)
qc_state
sqrt(2/3), 0.25*sqrt(2/3), 0.25*sqrt(2.)
state_fidelity(Phi_ACD,qc_state)
qc.measure([1,2],[0,1])
qc.draw(output='mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
# tava dando errado o resultado. Me parece que na inicializacao a ordem dos qubits foi trocada
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
# sequencia: 000 001 010 011 100 101 110 111 = 0 1 2 3 4 5 6 7
Phi_ACD = [1/math.sqrt(2), 1/(2*math.sqrt(2)), 0, 1/(2*math.sqrt(2)),
0, 1/(2*math.sqrt(2)), 0, -1/(2*math.sqrt(2))]
qr = QuantumRegister(3); cr = ClassicalRegister(2); qc = QuantumCircuit(qr,cr)
qc.initialize(Phi_ACD, [qr[2],qr[1],qr[0]])
qc.measure([1,2],[0,1])
qc.draw(output='mpl')
qc.decompose().decompose().decompose().decompose().decompose().draw(output='mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
qr = QuantumRegister(4); cr = ClassicalRegister(3); qc = QuantumCircuit(qr, cr)
# U = I
qc.x(qr[0]); qc.cry(math.acos(math.sqrt(2/3)), 0, 1); qc.x(qr[0]); qc.cry(math.pi/2, 0, 1)
# V11 = I
qc.cu(math.pi/2,math.pi,math.pi,0, 1,0)
qc.barrier()
qc_ry_ = qc_ry(0); ccry = qc_ry_.to_gate().control(2) # cria a ctrl-ctrl-RY
qc.x(0); qc.append(ccry, [0,1,2]); qc.x(0)
qc_ry_ = qc_ry(math.pi/2); ccry = qc_ry_.to_gate().control(2)
qc.append(ccry, [0,1,2]) # os primeiros sao o controle, os ultimos sao o target
qc.x(2)
qc_u_ = qc_u(2*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2)
qc.append(ccu, [1,2,0])
qc.x(2)
qc_u_ = qc_u(4*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2)
qc.append(ccu, [1,2,0])
qc.barrier()
qc_ry_ = qc_ry(math.pi); cccry = qc_ry_.to_gate().control(3) # cria a ctrl-ctrl-ctrl-RY
qc.x(0); qc.append(cccry, [0,1,2,3]); qc.x(0)
qc_ry_ = qc_ry(math.pi/2); cccry = qc_ry_.to_gate().control(3)
qc.append(cccry, [0,1,2,3])
qc_u_ = qc_u(math.pi,0,0); cccu = qc_u_.to_gate().control(3)
qc.x(3); qc.append(cccu, [3,2,1,0]); qc.x(3)
qc.append(cccu, [3,2,1,0])
qc_u_ = qc_u(math.pi/3,0,0); cccu = qc_u_.to_gate().control(3)
qc.barrier()
qc.measure(1,0); qc.measure(2,1); qc.measure(3,2)
qc.draw(output = 'mpl')
qc.decompose().draw(output = 'mpl')
%run init.ipynb
# 2 element 1-qubit povm (Yordanov)
M1 = (1/2)*Matrix([[1,0],[0,sqrt(3)]]); M2 = M1
M1, M2
M1.T*M1 + M2.T*M2
# 3 element 1-qubit povm (Yordanov)
M1 = sqrt(2/3)*Matrix([[1,0],[0,0]])
M2 = (1/(4*sqrt(6)))*Matrix([[1,sqrt(3)],[sqrt(3),1]])
M3 = (1/(4*sqrt(6)))*Matrix([[1,-sqrt(3)],[-sqrt(3),1]])
M1,M2,M3
M1.T*M1 + M2.T*M2 + M3.T*M3
# 2-element 1-qubit POVM (Douglas)
M1 = (1/(2*sqrt(2)))*Matrix([[1,0],[sqrt(3),2]])
M2 = (1/(2*sqrt(2)))*Matrix([[1,0],[-sqrt(3),2]])
M1,M2
M1.T*M1 + M2.T*M2
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
%run init.ipynb
p = symbols('p')
Ubf = Matrix([[sqrt(1-p),-sqrt(p),0,0],[0,0,sqrt(p),sqrt(1-p)],[0,0,sqrt(1-p),-sqrt(p)],[sqrt(p),sqrt(1-p),0,0]])
Ubf
Ubf*Ubf.T, Ubf.T*Ubf
g = symbols('gamma')
Uad = Matrix([[sqrt(1-g),0,0,sqrt(g)],[0,1,0,0],[0,0,1,0],[-sqrt(g),0,0,sqrt(1-g)]])
Uad, Uad*Uad.T, Uad.T*Uad
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
from qiskit import *
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_bogota')
from qiskit.tools.monitor import job_monitor
from qiskit.tools.visualization import plot_histogram
def qc_ent_dist():
qc = QuantumCircuit(2, name = 'E dist')
qc.h([1]); qc.cx(1, 0)
return qc
qc_ent_dist_ = qc_ent_dist()
qc_ent_dist_.draw(output = 'mpl')
def qc_encoding(cbits):
qc = QuantumCircuit(1, name = 'codificação')
if cbits == '00':
qc.id([0])
elif cbits == '01':
qc.z([0])
elif cbits == '10':
qc.x([0])
elif cbits == '11':
qc.x([0]); qc.z([0])
return qc
qc_encoding_ = qc_encoding('11')
qc_encoding_.draw(output = 'mpl')
def qc_decoding():
qc = QuantumCircuit(2, name = 'decodificação')
qc.cx(1, 0); qc.h([1])
return qc
qc_decoding_ = qc_decoding(); qc_decoding_.draw(output = 'mpl')
cbits = '00'
qc = QuantumCircuit(2, 2)
qc_ent_dist_ = qc_ent_dist(); qc.append(qc_ent_dist_, [0,1])
qc.barrier()
qc_encoding_ = qc_encoding(cbits); qc.append(qc_encoding_, [0])
qc.barrier()
qc_decoding_ = qc_decoding(); qc.append(qc_decoding_, [0,1])
qc.measure([0,1],[0,1])
#qc.draw(output = 'mpl')
qc.decompose().draw(output = 'mpl')
result = execute(qc, backend = simulator, shots = nshots).result()
plot_histogram(result.get_counts(qc))
job = execute(qc, backend = device, shots = nshots)
job_monitor(job)
plot_histogram(job.result().get_counts(qc))
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
1 + cos(2*pi/3) + 1j*sin(2*pi/3) + cos(4*pi/3) + 1j*sin(4*pi/3)
1 + cos(4*pi/3) + 1j*sin(4*pi/3) + cos(8*pi/3) + 1j*sin(8*pi/3)
cos(2*pi/3), cos(4*pi/3)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_lima')
from qiskit.tools.visualization import plot_histogram
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
def qc_ent_dist():
qc = QuantumCircuit(2, name = 'E dist')
qc.h([0]); qc.cx(0, 1)
return qc
qc_ent_dist_ = qc_ent_dist(); qc_ent_dist_.draw(output = 'mpl')
def qc_bb_cb():
qc = QuantumCircuit(2, name = 'BB->CB')
qc.cx(0,1); qc.h(0)
return qc
qc_bb_cb_ = qc_bb_cb(); qc_bb_cb_.draw(output = 'mpl')
def qc_teleport(th, ph, lb):
qc = QuantumCircuit(3)
qc_ent_dist_ = qc_ent_dist(); qc.append(qc_ent_dist_, [1, 2]) # distribuição de emaranhamento
qc.barrier()
qc.u(th, ph, lb, [0]) # Preparação do estado a ser teletransportado
qc.barrier()
qc_bb_cb_ = qc_bb_cb(); qc.append(qc_bb_cb_, [0, 1]) # Base de Bell para base computacional
qc.barrier()
qc.cx(1, 2); qc.cz(0, 2) # infor clássica + unitária de Bob
return qc
qc_teleport_ = qc_teleport(0.1, 0.5, 0); qc_teleport_.decompose().draw(output = 'mpl')
import numpy as np
import math
th, ph, lb = 0, 0, 0;
rho_teo = np.array([[math.cos(th/2)**2, (math.cos(ph)+1j*math.sin(ph))*math.sin(th/2)*math.cos(th/2)],
[(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2)*math.cos(th/2), math.sin(th/2)**2]])
qc_teleport_ = qc_teleport(0.1, 0.5, 0)
qstc = state_tomography_circuits(qc_teleport_, [2])
# simulação
job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots = nshots)
qstf = StateTomographyFitter(job.result(), qstc)
rho_sim = qstf.fit(method='lstsq')
print('rho_teo = ', rho_teo)
print('rho_sim = ', rho_sim)
# experimento
job = qiskit.execute(qstc, backend = device, shots = nshots)
job_monitor(job)
qstf = StateTomographyFitter(job.result(), qstc)
rho_exp = qstf.fit(method = 'lstsq')
print('rho_exp = ', rho_exp)
F = qiskit.quantum_info.state_fidelity(rho_teo, rho_exp); print('F = ', F)
# variar th em cos(th/2)|0>+exp(i*ph)sin(th/2)|1>
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibm_nairobi')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
from qiskit.tools.visualization import plot_histogram
q0 = QuantumRegister(1); q1 = QuantumRegister(1); q2 = QuantumRegister(1); q3 = QuantumRegister(1)
c0 = ClassicalRegister(1); c1 = ClassicalRegister(1); c2 = ClassicalRegister(1); c3 = ClassicalRegister(1)
qc = QuantumCircuit(q0,q1,q2,q3,c0,c1,c2,c3)
# q0 e q1 estao com Alice, q2 com Charlies e q3 com Bob
qc.h(q1); qc.cx(q1,q2); qc.cx(q2,q3) # prepara o estado GHZ
qc.barrier()
#qc.sdg(q0); qc.h(q0) # prepara o estado a ser teletransportado (y+)
# prepara o estado |0>
qc.barrier()
qc.cx(q0,q1); qc.h(q0); qc.measure(q0,c0); qc.measure(q1,c1) # Medida de Alice na base de Bell
qc.h(q2); qc.measure(q2,c2) # medida de Charlie na base +,-
qc.barrier()
qc.z(q3).c_if(c0, 1) # acao de Bob condicionada no 1º cbit enviado por Alice
qc.x(q3).c_if(c1, 1) # acao de Bob condicionada no 2º cbit enviado por Alice
qc.z(q3).c_if(c2, 1) # acao de Bob condicionada no cbit enviado por Charlie
qc.barrier()
#qc.sdg(q3); qc.h(q3); qc.measure(q3,c3) # passa da base circular pra computacional
qc.measure(q3,c3) # mede na base computacional
qc.draw(output='mpl')
jobS = execute(qc, backend = simulator, shots = nshots)
plot_histogram(jobS.result().get_counts(qc))
jobE = execute(qc, backend = device, shots = nshots)
job_monitor(jobE)
tqc = transpile(qc, device)
jobE = device.run(tqc)
job_monitor(jobE)
plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)],
bar_labels = False, legend = ['sim', 'exp'])
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
from qiskit.tools.visualization import plot_histogram
q0 = QuantumRegister(1); q1 = QuantumRegister(1)
c0 = ClassicalRegister(1); c1 = ClassicalRegister(1)
qc = QuantumCircuit(q0,q1,c0,c1)
qc.h(q0); qc.cx(q0,q1) # emaranhamento compartilhado entre Alice e Bob
qc.barrier()
qc.x(q0); qc.sdg(q0); qc.h(q0); qc.measure(q0,c0) # Medida de Alice
qc.barrier()
qc.z(q1).c_if(c0, 1) # acao de Bob condicionada no cbit enviado por Alice
qc.barrier()
qc.sdg(q1); qc.h(q1); qc.measure(q1,c1) # passa da base circular pra computacional
qc.draw(output='mpl')
jobS = execute(qc, backend = simulator, shots = nshots)
plot_histogram(jobS.result().get_counts(qc))
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_lima')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
def qc_qft(n):
qr = QuantumRegister(n); qc = QuantumCircuit(qr, name = 'QFT')
for l in range(0, n):
qc.h(qr[l])
if l < n-1:
for q in range(l+1, n):
lb = 2*math.pi*2**(-q+l-1)
qc.cp(lb, qr[q], qr[l])
#qc.barrier()
#qc.barrier()
if n%2 == 0:
ul = n//2
else:
ul = (n-1)//2
for p in range(0, ul):
qc.swap(p, n-1-p)
return qc
n = 4; qc_qft_ = qc_qft(n); qc_qft_.draw(output='mpl')
def qc_iqft(n):
qr = QuantumRegister(n); qc = QuantumCircuit(qr, name = 'IQFT')
if n%2 == 0:
ul = n//2
else:
ul = (n-1)//2
for p in range(ul-1, -1, -1):
qc.swap(p, n-1-p)
#qc.barrier()
for l in range(n-1, -1, -1):
if l < n-1:
for q in range(n-1, l+1-1, -1):
lb = -2*math.pi*2**(-q+l-1)#; print(lb)
qc.cp(lb, qr[q], qr[l])
qc.h(qr[l])
#qc.barrier()
return qc
n = 4; qc_iqft_ = qc_iqft(n); qc_iqft_.draw(output='mpl')
#x0 = 1 + 0*1j; x1 = 0 + 0*1j # estado |0>
#x0 = 0 + 0*1j; x1 = 1 + 0*1j # estado |1>
x0 = 1/math.sqrt(2) + 0*1j; x1 = 1/math.sqrt(2) + 0*1j # estado |+>
mx0 = math.sqrt(x0.real**2 + x0.imag**2)
if x0.real != 0:
ph0 = math.atan(x0.imag/x0.real)
elif x0.real == 0 and x0.imag != 0:
ph0 = math.pi/2
elif x0.real == 0 and x0.imag == 0:
ph0 = 0
mx1 = math.sqrt(x1.real**2 + x1.imag**2)
if x1.real != 0:
ph1 = math.atan(x1.imag/x1.real)
elif x1.real == 0 and x1.imag != 0:
ph1 = math.pi/2
elif x1.real == 0 and x1.imag == 0:
ph1 = 0
print('|x0|=',mx0,', ph0=', ph0,', |x1|=', mx1,', ph1=', ph1)
th = 2*math.acos(mx1); ph = ph1-ph0+math.pi; lb = ph0-math.pi
print('th=',th,', ph=', ph,', lb=', lb)
n = 1
qr = QuantumRegister(n); qc = QuantumCircuit(qr)
qc.x(qr[0]); qc.u(th, ph, lb, qr[0]); qc.barrier()
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0])
qc.draw(output='mpl')
svsimulator = Aer.get_backend('statevector_simulator')
job = execute(qc, backend = svsimulator, shots = 1, memory = True)
print(job.result().get_statevector(qc))
def tfc(x): # classical discrete Fourier transform
d = len(x)
y = np.zeros(d, dtype = complex)
for k in range(0, d):
for j in range(0, d):
y[k] += x[j]*(math.cos(2*math.pi*j*k/d) + 1j*math.sin(2*math.pi*j*k/d))
return y/math.sqrt(d)
d = 4; x = np.zeros(d, dtype = complex);
#x = [1/2, 1/2, 1/2, 1/2]
x = [-1/2, -1/2, 1/2, 1/2]
y = tfc(x); print(y)
n = 2
qr = QuantumRegister(n); qc = QuantumCircuit(qr)
#qc.h([0,1]); qc.barrier() # ok
qc.x([0]); qc.h([0,1]); qc.barrier() # ok a menos de uma fase global de pi
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0,1])
qc.draw(output='mpl')
svsimulator = Aer.get_backend('statevector_simulator')
job = execute(qc, backend = svsimulator, shots = 1, memory = True)
print(job.result().get_statevector(qc)) # para >1 qubit tem a questao da ordem da bc
d = 4; x = np.zeros(d, dtype = complex);
x = [math.sqrt(1/6), math.sqrt(1/6), math.sqrt(2/3), 0]
y = tfc(x); print(y)
n = 3
qr = QuantumRegister(n); cr = ClassicalRegister(n); qc = QuantumCircuit(qr, cr)
qc.x([0,2]); qc.barrier()
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0,1,2]); qc.barrier()
qc_iqft_ = qc_iqft(n); iqft = qc_iqft_.to_gate(); qc.append(iqft, [0,1,2]); qc.barrier()
qc.measure([0,1,2],[0,1,2])
qc.draw(output='mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_jakarta')
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
def bernstein_vazirani(s):
ls = len(s)
qc = QuantumCircuit(ls+1,ls)
qc.h(range(ls))
qc.x(ls)
qc.h(ls)
qc.barrier();
for ii, yesno in enumerate(reversed(s)): # the black box
if yesno == '1':
qc.cx(ii, ls);
qc.barrier();
qc.h(range(ls));
qc.barrier();
qc.measure(range(ls),range(ls))
return qc
s = '011' # secretnumber
qc = bernstein_vazirani(s)
qc.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 1).result()
counts = result.get_counts()
print(counts)
jobE = execute(qc, backend = device, shots = nshots)
job_monitor(jobE)
jobS = execute(qc, backend = simulator, shots = nshots)
plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)],
bar_labels = False, legend = ['sim', 'exp'])
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibm_nairobi')
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
qr = QuantumRegister(4); cr = ClassicalRegister(4); qc = QuantumCircuit(qr,cr)
qc.h([0,1])
qc.barrier()
qc.cx(0,2); qc.cx(0,3); qc.cx(1,2); qc.cx(1,3) # oraculo
qc.barrier()
qc.measure([2,3],[2,3])
qc.barrier()
qc.h([0,1]); qc.measure([0,1],[0,1])
qc.draw(output='mpl')
jobS = execute(qc, backend = simulator, shots = nshots)
jobE = execute(qc, backend = device, shots = nshots)
job_monitor(jobE)
plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)],
bar_labels = False, legend = ['sim', 'exp'])
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
2*acos(sqrt(2/3)), 2*asin(sqrt(1/3)).
cos(2*pi/3), sin(2*pi/3), cos(4*pi/3), sin(4*pi/3), cos(8*pi/3), sin(8*pi/3)
cos(2*pi/3), sin(2*pi/3), cos(4*pi/3), sin(4*pi/3), cos(8*pi/3), sin(8*pi/3)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
rx,ry,rz = symbols('r_x r_y r_z')
rho1qb = (1/2)*(id(2) + rx*pauli(1) + ry*pauli(2) + rz*pauli(3))
rho1qb
pI,pX,pZ,pY = symbols('p_I p_X p_Z p_Y')
K0 = sqrt(pI)*id(2); K1 = sqrt(pX)*pauli(1); K2 = sqrt(pZ)*pauli(3); K3 = sqrt(pY)*pauli(2)
rho_p = K0*rho1qb*K0 + K1*rho1qb*K1 + K2*rho1qb*K2 + K3*rho1qb*K3
simplify(rho_p)
p = symbols('p')
pI = (1+3*p)/4; pX = (1-p)/4; pY = pX; pZ = pX
rho_p = K0*rho1qb*K0 + K1*rho1qb*K1 + K2*rho1qb*K2 + K3*rho1qb*K3
simplify(rho_p)
import numpy as np
from matplotlib import pyplot as plt
p = np.arange(0,1.1,0.1) # PD channel
C = np.sqrt(1-p)
plt.plot(p,C)
plt.show()
from sympy import *
N,p = symbols('N p')
K0 = sqrt(1-N)*Matrix([[1,0],[0,sqrt(1-p)]])
K1 = sqrt(1-N)*Matrix([[0,sqrt(p)],[0,0]])
K2 = sqrt(N)*Matrix([[sqrt(1-p),0],[0,1]])
K3 = sqrt(N)*Matrix([[0,0],[sqrt(p),0]])
#K0
r00,r01,r10,r11 = symbols('r_{00} r_{01} r_{10} r_{11}')#; r00
rho = Matrix([[r00,r01],[r10,r11]])#; rho
rho_gad = K0*rho*K0 + K1*rho*K1.T + K2*rho*K2 + K3*rho*K3.T
simplify(rho_gad)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
cos(-2*pi/3), sin(-2*pi/3), cos(-4*pi/3), sin(-4*pi/3), cos(-8*pi/3), sin(-8*pi/3)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
import sympy
from sympy import *
import numpy as np
from numpy import random
import math
import scipy
init_printing(use_unicode=True)
from matplotlib import pyplot as plt
%matplotlib inline
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum import TensorProduct as tp
from mpmath import factorial as fact
import io
import base64
#from IPython.core.display import display, HTML, clear_output
from IPython import *
from ipywidgets import interactive, interact, fixed, interact_manual, widgets
import csv
import importlib
import scipy.interpolate
from mpl_toolkits.mplot3d import Axes3D, proj3d
from itertools import product, combinations
from matplotlib.patches import FancyArrowPatch
from matplotlib import cm, colors
from sympy.functions.special.tensor_functions import KroneckerDelta
from scipy.linalg import polar, lapack
import mpmath
# constantes físicas
e = 1.60217662*10**-19 # C (carga elementar)
k = 8.9875517923*10**9 # Nm^2/C^2 (constante de Coulomb)
eps0 = 8.8541878128*10**-12 #F/m (permissividade do vácuo)
mu0 = 1.25663706212*10**-6 # N/A^2 (permeabilidade do vácuo)
h = 6.626069*10**-34 # Js (constante de Planck)
heV = h/e # em eV
hb = h/(2*math.pi) # hbar
hbeV = hb/e # em eV
c = 2.99792458*10**8 # m/s (velocidade da luz no vácuo)
G = 6.6742*10**-11 # Nm^2/kg^2 (constante gravitacional)
kB = 1.38065*10**-23 # J/K (constante de Boltzmann)
me = 9.109382*10**-31 # kg (massa do elétron)
mp = 1.6726219*10**-27 # kg (massa do próton)
mn = 1.67492749804*10**-27 # kg (massa do nêutron)
mT = 5.9722*10**24 # kg (massa da Terra)
mS = 1.98847*10**30 # kg (massa do Sol)
u = 1.660538921*10**-27 # kg (unidade de massa atômica)
dTS = 1.496*10**11 # m (distância Terra-Sol)
rT = 6.3781*10**6 # m (raio da Terra)
sSB = 5.670374419*10**-8 # W⋅m−2⋅K−4 (constante de Stefan-Boltzmann)
Ri = 10973734.848575922 # m^-1 (constante de Rydberg)
al = (k*e**2)/(hb*c) # ~1/137.035999084 (constante de estrutura fina)
a0=(hb**2)/(me*k*e**2) # ~ 0.52917710^-10 m (raio de Bohr)
ge = 2 # (fator giromagnetico do eletron)
gp = 5.58 # (fator giromagnetico do proton)
def id(n):
'''retorna a matriz identidade nxn'''
id = zeros(n,n)
for j in range(0,n):
id[j,j] = 1
return id
#id(2)
def pauli(j):
'''retorna as matrizes de Pauli'''
if j == 1:
return Matrix([[0,1],[1,0]])
elif j == 2:
return Matrix([[0,-1j],[1j,0]])
elif j == 3:
return Matrix([[1,0],[0,-1]])
#pauli(1), pauli(2), pauli(3)
def tr(A):
'''retorna o traço de uma matriz'''
d = A.shape[0]
tr = 0
for j in range(0,d):
tr += A[j,j]
return tr
#tr(pauli(1))
def comm(A,B):
'''retorna a função comutador'''
return A*B-B*A
#comm(pauli(1),pauli(2))
def acomm(A,B):
'''retorna a função anti-comutador'''
return A*B+B*A
#acomm(pauli(1),pauli(2))
def cb(n,j):
'''retorna um vetor da base padrão de C^n'''
vec = zeros(n,1)
vec[j] = 1
return vec
#cb(2,0)
def proj(psi):
'''retorna o projeto no vetor psi'''
d = psi.shape[0]
P = zeros(d,d)
for j in range(0,d):
for k in range(0,d):
P[j,k] = psi[j]*conjugate(psi[k])
return P
#proj(cb(2,0))
def bell(j,k):
if j == 0 and k == 0:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))+tp(cb(2,1),cb(2,1)))
elif j == 0 and k == 1:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))+tp(cb(2,1),cb(2,0)))
elif j == 1 and k == 0:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))-tp(cb(2,1),cb(2,0)))
elif j == 1 and k == 1:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))-tp(cb(2,1),cb(2,1)))
#bell(0,0), bell(0,1), bell(1,0), bell(1,1)
def inner_product(v,w):
d = len(v); ip = 0
for j in range(0,d):
ip += conjugate(v[j])*w[j]
return ip
#a,b,c,d = symbols("a b c d"); v = [b,a]; w = [c,d]; inner_product(v,w)
def norm(v):
d = len(v)
return sqrt(inner_product(v,v))
#v = [2,2]; norm(v)
def tp(x,y):
return tensorproduct(x,y)
A = tp(pauli(3),pauli(1)); A
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
import qiskit
from qiskit import *
import math
import numpy as np
def qc_ezz(t):
qc = QuantumCircuit(2, name = 'e^(-itZZ)')
qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1)
return qc
def qc_exx(t):
qc = QuantumCircuit(2, name = 'e^(-itXX)')
qc.h([0,1]); qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1); qc.h([0,1])
return qc
def qc_eyy(t):
qc = QuantumCircuit(2, name = 'e^(-itYY)')
qc.sdg([0,1]); qc.h([0,1]); qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1); qc.h([0,1]); qc.s([0,1])
return qc
def qc_Bj(t):
qc = QuantumCircuit(3, name = 'B_j')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
return qc
qc_Bj_ = qc_Bj(math.pi/2); qc_Bj_.draw(output='mpl')
qc_Bj_.decompose().draw(output='mpl')
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
#provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_jakarta')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.tools.monitor import backend_overview, backend_monitor
from qiskit.providers.aer import noise
from qiskit.providers.aer.noise import NoiseModel
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
noise_model = NoiseModel.from_backend(device)
basis_gates = noise_model.basis_gates
coupling_map = device.configuration().coupling_map
ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]);
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
for j in range(0, 10): # Trotter stepsm_info.
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_ = qc_Bj(t/(j+1))
for k in range(0, j+1):
qc.append(qc_Bj_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
qstf_exp = StateTomographyFitter(job_exp.result(), qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('No. passos=', j+1, ',F_sim=', F_sim, ',F_exp=', F_exp)
inha visto essa reprovação mas não me dei por conta que n# for error mitigation
qr = QuantumRegister(7)
qubit_list = [5,3,1] # the qubits on which we shall apply error mitigation
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr)
job_cal = execute(meas_calibs, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
meas_fitter = CompleteMeasFitter(job_cal.result(), state_labels)
ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
for j in range(0, 10): # Trotter steps
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_ = qc_Bj(t/(j+1))
for k in range(0, j+1):
qc.append(qc_Bj_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('No. passos=', j+1, ',F_sim=', F_sim, ',F_exp=', F_exp)
def qc_Bj_zz(t, th, ph):
qc = QuantumCircuit(3, name = 'B_j_zz')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.rz(2*th, [1,2])
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.rz(-2*th, [1,2])
qc.rz(2*ph, [0,1])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
qc.rz(-2*ph, [0,1])
return qc
qc_Bj_zz_ = qc_Bj_zz(math.pi, math.pi/3, math.pi/4); qc_Bj_zz_.draw(output='mpl')
ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
j = 6; print('N. of Trotter steps = ', j+1)
th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0]
ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0]
for m in range(0, dim_th):
for n in range(0, dim_ph):
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_zz_ = qc_Bj_zz(t/(j+1), th[m], ph[n])
for k in range(0, j+1):
qc.append(qc_Bj_zz_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp)
def qc_Bj_zx(t, th, ph):
qc = QuantumCircuit(3, name = 'B_j_zz')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.rx(2*th, [1,2])
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.rx(-2*th, [1,2])
qc.rz(2*ph, [0,1])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
qc.rz(-2*ph, [0,1])
return qc
qc_Bj_zx_ = qc_Bj_zx(math.pi, math.pi/3, math.pi/4); qc_Bj_zx_.draw(output='mpl')
inha visto essa reprovação mas não me dei por conta que nket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
j = 6; print('N. of Trotter steps = ', j+1)
th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0]
ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0]
for m in range(0, dim_th):
for n in range(0, dim_ph):
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_zx_ = qc_Bj_zx(t/(j+1), th[m], ph[n])
for k in range(0, j+1):
qc.append(qc_Bj_zx_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp)
def qc_Bj_yx(t, th, ph):
qc = QuantumCircuit(3, name = 'B_j_zz')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.rx(2*th, [1,2])
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.rx(-2*th, [1,2])
qc.barrier()
qc.ry(2*ph, [0,1])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
qc.ry(-2*ph, [0,1])
return qc
qc_Bj_yx_ = qc_Bj_yx(math.pi, math.pi/3, math.pi/4); qc_Bj_yx_.draw(output='mpl')
https://arxiv.org/abs/2204.07816ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
j = 6; print('N. of Trotter steps = ', j+1)
th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0]
ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0]
for m in range(0, dim_th):
for n in range(0, dim_ph):
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_yx_ = qc_Bj_yx(t/(j+1), th[m], ph[n])
for k in range(0, j+1):
qc.append(qc_Bj_yx_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation0.34
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp)
noise_model = NoiseModel.from_backend(device)
basis_gates = noise_model.basis_gates
coupling_map = device.configuration().coupling_map
basis_gates
print(coupling_map)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import math
th = np.arange(0, 2*math.pi, 0.1)
prE3 = 2*(1-(math.sqrt(2)*(np.sin(th/2)**2))/(1+math.sqrt(2)))
matplotlib.rcParams.update({'font.size':10})
plt.figure(figsize = (5,3), dpi = 100)
plt.plot(th, prE3)
plt.xlabel(r'$\theta$')
plt.ylabel(r'$Pr(E_{3})$')
plt.show()
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
cos(pi/8), sin(pi/8)
U = (1/sqrt(2))*Matrix([[1,1],[1,-1]]); V1 = Matrix([[1,0],[0,1]]); V2 = V1
D1 = Matrix([[cos(pi/8),0],[0,cos(pi/8)]]); D2 = Matrix([[sin(pi/8),0],[0,sin(pi/8)]])
U, U*U.T, D1, D2
M1 = V1*D1*U; M2 = V2*D2*U; M1, M2
M1*M1, M2*M2, M1*M1 + M2*M2 # não são projetores, mas são operadores de medida
2*float((1/4)*(1+1/sqrt(2))), 2*float((1/4)*(1-1/sqrt(2)))
qr = QuantumRegister(2); cr = ClassicalRegister(1); qc = QuantumCircuit(qr, cr)
qc.h(qr[0]); qc.x(qr[0]); qc.cry(math.pi/4, 0, 1); qc.x(qr[0]); qc.cry(math.pi/4, 0, 1)
# V1=V2=I
qc.measure(1,0)
qc.draw(output = 'mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
def U(xi, et, ga):
return Matrix([[(cos(xi)+1j*sin(xi))*cos(ga), (cos(et)+1j*sin(et))*sin(ga)],
[-(cos(et)-1j*sin(et))*sin(ga), (cos(xi)-1j*sin(xi))*cos(ga)]])
xi, et, ga = symbols('xi eta gamma'); U(xi, et, ga)
def D1(th, ph):
return Matrix([[cos(th/2),0],[0,cos(ph/2)]])
def D2(th, ph):
return Matrix([[sin(th/2),0],[0,sin(ph/2)]])
th,ph = symbols('theta phi'); D1(th, ph), D2(th, ph)
xi1,et1,ga1,xi2,et2,ga2,xi3,et3,ga3 = symbols('xi_1 eta_1 gamma_1 xi_2 eta_2 gamma_2 xi_3 eta_3 gamma_3')
simplify(U(xi1,et1,ga1)*D1(th,ph)*U(xi2,et2,ga2) - (1/2)*sqrt(1+1/sqrt(2))*Matrix([[1,1],[1,-1]]))
simplify(U(xi3,et3,ga3)*D2(th,ph)*U(xi2,et2,ga2) - (1/2)*sqrt(1+1/sqrt(2))*Matrix([[1,1],[1,-1]]))
cos(pi/3), sin(pi/3), cos(2*pi/3), sin(2*pi/3)
M1 = sqrt(2/3)*Matrix([[1,0],[0,0]])
M2 = (1/(4*sqrt(6)))*Matrix([[1,sqrt(3)],[sqrt(3),3]])
M3 = (1/(4*sqrt(6)))*Matrix([[1,-sqrt(3)],[-sqrt(3),3]])
M1,M2,M3
M1.T*M1 + M2.T*M2 + M3.T*M3
M1 = sqrt(2/3.)*Matrix([[1,0],[0,0]]); M2 = sqrt(2/3.)*(1/4)*Matrix([[1,sqrt(3.)],[sqrt(3.),3]])
M3 = sqrt(2/3.)*(1/4)*Matrix([[1,-sqrt(3.)],[-sqrt(3.),3]])
M1, M2, M3
M1.T*M1 + M2.T*M2 + M3.T*M3
2/3, 1/6, 2/3+2*(1/6)
#th1 = acos(sqrt(2/3)); ph1 = pi; th2 = pi/2; ph2 = pi/2
D11 = Matrix([[sqrt(2/3),0],[0,0]])
D21 = Matrix([[sqrt(1/3),0],[0,1]])
D12 = Matrix([[1/sqrt(2),0],[0,1/sqrt(2)]])
D22 = Matrix([[1/sqrt(2),0],[0,1/sqrt(2)]])
U = Matrix([[1,0],[0,1]])
V11 = Matrix([[1,0],[0,1]])
V21 = (1/sqrt(2))*Matrix([[1,1],[-1,1]])
V12 = (1/2)*Matrix([[1,-sqrt(3)],[sqrt(3),1]])
V22 = -(1/2)*Matrix([[sqrt(3),-1],[1,sqrt(3)]])
M1 = V11*D11*U
np.array(M1).astype(np.float64), np.array(Matrix([[sqrt(2/3),0],[0,0]])).astype(np.float64)
M2 = V12*D12*V21*D21*U
np.array(M2).astype(np.float64), np.array((1/4)*sqrt(2/3)*Matrix([[1,sqrt(3)],[sqrt(3),3]])).astype(np.float64)
# não é o resultado que precisamos
M3 = V22*D22*V21*D21*U
np.array(M3).astype(np.float64), np.array((1/4)*sqrt(2/3)*Matrix([[1,-sqrt(3)],[-sqrt(3),3]])).astype(np.float64)
# não é o resultado que precisamos
np.array(M1.T*M1 + M2.T*M2 + M3.T*M3).astype(np.float64) # esta ok a relacao de completeza
cos(pi/3), sin(pi/3), cos(pi/6)
def qc_ry(th):
qr = QuantumRegister(1); qc = QuantumCircuit(qr, name = 'RY')
qc.ry(th, 0)
return qc
def qc_u(th,ph,lb):
qr = QuantumRegister(1); qc = QuantumCircuit(qr, name = 'U')
qc.u(th,ph,lb, 0)
return qc
qr = QuantumRegister(3); cr = ClassicalRegister(2); qc = QuantumCircuit(qr, cr)
# U = I
qc.x(qr[0]); qc.cry(math.acos(math.sqrt(2/3)), 0, 1); qc.x(qr[0]); qc.cry(math.pi/2, 0, 1)
# V11 = I
qc.cu(math.pi/2,math.pi,math.pi,0, 1,0)
qc.barrier()
qc_ry_ = qc_ry(0); ccry = qc_ry_.to_gate().control(2) # cria a ctrl-ctrl-RY
qc.x(0); qc.append(ccry, [0,1,2]); qc.x(0)
qc_ry_ = qc_ry(math.pi/2); ccry = qc_ry_.to_gate().control(2)
qc.append(ccry, [0,1,2]) # os primeiros sao o controle, os ultimos sao o target
qc.x(2)
qc_u_ = qc_u(2*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2)
qc.append(ccu, [1,2,0])
qc.x(2)
qc_u_ = qc_u(4*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2)
qc.append(ccu, [1,2,0])
qc.barrier()
qc.measure(1,0); qc.measure(2,1)
qc.draw(output = 'mpl')
qc.decompose().draw(output = 'mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
# sequencia: 000 001 010 011 100 101 110 111 = 0 1 2 3 4 5 6 7
Phi_ACD = [math.sqrt(2/3), (1/4)*math.sqrt(2/3), (1/4)*math.sqrt(2/3), 0,
0, (1/4)*math.sqrt(2), -(1/4)*math.sqrt(2), 0]
qr = QuantumRegister(3); cr = ClassicalRegister(2); qc = QuantumCircuit(qr,cr)
qc.initialize(Phi_ACD, [qr[2],qr[1],qr[0]])
qc.draw(output='mpl')
backend = BasicAer.get_backend('statevector_simulator')
job = backend.run(transpile(qc, backend))
qc_state = job.result().get_statevector(qc)
qc_state
sqrt(2/3), 0.25*sqrt(2/3), 0.25*sqrt(2.)
state_fidelity(Phi_ACD,qc_state)
qc.measure([1,2],[0,1])
qc.draw(output='mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
# tava dando errado o resultado. Me parece que na inicializacao a ordem dos qubits foi trocada
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
# sequencia: 000 001 010 011 100 101 110 111 = 0 1 2 3 4 5 6 7
Phi_ACD = [1/math.sqrt(2), 1/(2*math.sqrt(2)), 0, 1/(2*math.sqrt(2)),
0, 1/(2*math.sqrt(2)), 0, -1/(2*math.sqrt(2))]
qr = QuantumRegister(3); cr = ClassicalRegister(2); qc = QuantumCircuit(qr,cr)
qc.initialize(Phi_ACD, [qr[2],qr[1],qr[0]])
qc.measure([1,2],[0,1])
qc.draw(output='mpl')
qc.decompose().decompose().decompose().decompose().decompose().draw(output='mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
qr = QuantumRegister(4); cr = ClassicalRegister(3); qc = QuantumCircuit(qr, cr)
# U = I
qc.x(qr[0]); qc.cry(math.acos(math.sqrt(2/3)), 0, 1); qc.x(qr[0]); qc.cry(math.pi/2, 0, 1)
# V11 = I
qc.cu(math.pi/2,math.pi,math.pi,0, 1,0)
qc.barrier()
qc_ry_ = qc_ry(0); ccry = qc_ry_.to_gate().control(2) # cria a ctrl-ctrl-RY
qc.x(0); qc.append(ccry, [0,1,2]); qc.x(0)
qc_ry_ = qc_ry(math.pi/2); ccry = qc_ry_.to_gate().control(2)
qc.append(ccry, [0,1,2]) # os primeiros sao o controle, os ultimos sao o target
qc.x(2)
qc_u_ = qc_u(2*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2)
qc.append(ccu, [1,2,0])
qc.x(2)
qc_u_ = qc_u(4*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2)
qc.append(ccu, [1,2,0])
qc.barrier()
qc_ry_ = qc_ry(math.pi); cccry = qc_ry_.to_gate().control(3) # cria a ctrl-ctrl-ctrl-RY
qc.x(0); qc.append(cccry, [0,1,2,3]); qc.x(0)
qc_ry_ = qc_ry(math.pi/2); cccry = qc_ry_.to_gate().control(3)
qc.append(cccry, [0,1,2,3])
qc_u_ = qc_u(math.pi,0,0); cccu = qc_u_.to_gate().control(3)
qc.x(3); qc.append(cccu, [3,2,1,0]); qc.x(3)
qc.append(cccu, [3,2,1,0])
qc_u_ = qc_u(math.pi/3,0,0); cccu = qc_u_.to_gate().control(3)
qc.barrier()
qc.measure(1,0); qc.measure(2,1); qc.measure(3,2)
qc.draw(output = 'mpl')
qc.decompose().draw(output = 'mpl')
%run init.ipynb
# 2 element 1-qubit povm (Yordanov)
M1 = (1/2)*Matrix([[1,0],[0,sqrt(3)]]); M2 = M1
M1, M2
M1.T*M1 + M2.T*M2
# 3 element 1-qubit povm (Yordanov)
M1 = sqrt(2/3)*Matrix([[1,0],[0,0]])
M2 = (1/(4*sqrt(6)))*Matrix([[1,sqrt(3)],[sqrt(3),1]])
M3 = (1/(4*sqrt(6)))*Matrix([[1,-sqrt(3)],[-sqrt(3),1]])
M1,M2,M3
M1.T*M1 + M2.T*M2 + M3.T*M3
# 2-element 1-qubit POVM (Douglas)
M1 = (1/(2*sqrt(2)))*Matrix([[1,0],[sqrt(3),2]])
M2 = (1/(2*sqrt(2)))*Matrix([[1,0],[-sqrt(3),2]])
M1,M2
M1.T*M1 + M2.T*M2
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
%run init.ipynb
p = symbols('p')
Ubf = Matrix([[sqrt(1-p),-sqrt(p),0,0],[0,0,sqrt(p),sqrt(1-p)],[0,0,sqrt(1-p),-sqrt(p)],[sqrt(p),sqrt(1-p),0,0]])
Ubf
Ubf*Ubf.T, Ubf.T*Ubf
g = symbols('gamma')
Uad = Matrix([[sqrt(1-g),0,0,sqrt(g)],[0,1,0,0],[0,0,1,0],[-sqrt(g),0,0,sqrt(1-g)]])
Uad, Uad*Uad.T, Uad.T*Uad
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
from qiskit import *
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_bogota')
from qiskit.tools.monitor import job_monitor
from qiskit.tools.visualization import plot_histogram
def qc_ent_dist():
qc = QuantumCircuit(2, name = 'E dist')
qc.h([1]); qc.cx(1, 0)
return qc
qc_ent_dist_ = qc_ent_dist(); qc_ent_dist_.draw(output = 'mpl')
def qc_encoding(cbits):
qc = QuantumCircuit(1, name = 'codificação')
if cbits == '00':
qc.id([0])
elif cbits == '01':
qc.z([0])
elif cbits == '10':
qc.x([0])
elif cbits == '11':
qc.x([0]); qc.z([0])
return qc
qc_encoding_ = qc_encoding('11'); qc_encoding_.draw(output = 'mpl')
def qc_decoding():
qc = QuantumCircuit(2, name = 'decodificação')
qc.cx(1, 0); qc.h([1])
return qc
qc_decoding_ = qc_decoding(); qc_decoding_.draw(output = 'mpl')
cbits = '00'
qc = QuantumCircuit(2, 2)
qc_ent_dist_ = qc_ent_dist(); qc.append(qc_ent_dist_, [0,1])
qc.barrier()
qc_encoding_ = qc_encoding(cbits); qc.append(qc_encoding_, [0])
qc.barrier()
qc_decoding_ = qc_decoding(); qc.append(qc_decoding_, [0,1])
qc.measure([0,1],[0,1])
#qc.draw(output = 'mpl')
qc.decompose().draw(output = 'mpl')
result = execute(qc, backend = simulator, shots = nshots).result()
plot_histogram(result.get_counts(qc))
job = execute(qc, backend = device, shots = nshots)
job_monitor(job)
plot_histogram(job.result().get_counts(qc))
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
1 + cos(2*pi/3) + 1j*sin(2*pi/3) + cos(4*pi/3) + 1j*sin(4*pi/3)
1 + cos(4*pi/3) + 1j*sin(4*pi/3) + cos(8*pi/3) + 1j*sin(8*pi/3)
cos(2*pi/3), cos(4*pi/3)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_lima')
from qiskit.tools.visualization import plot_histogram
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
def qc_ent_dist():
qc = QuantumCircuit(2, name = 'E dist')
qc.h([0]); qc.cx(0, 1)
return qc
qc_ent_dist_ = qc_ent_dist(); qc_ent_dist_.draw(output = 'mpl')
def qc_bb_cb():
qc = QuantumCircuit(2, name = 'BB->CB')
qc.cx(0,1); qc.h(0)
return qc
qc_bb_cb_ = qc_bb_cb(); qc_bb_cb_.draw(output = 'mpl')
def qc_teleport(th, ph, lb):
qc = QuantumCircuit(3)
qc_ent_dist_ = qc_ent_dist(); qc.append(qc_ent_dist_, [1, 2]) # distribuição de emaranhamento
qc.barrier()
qc.u(th, ph, lb, [0]) # Preparação do estado a ser teletransportado
qc.barrier()
qc_bb_cb_ = qc_bb_cb(); qc.append(qc_bb_cb_, [0, 1]) # Base de Bell para base computacional
qc.barrier()
qc.cx(1, 2); qc.cz(0, 2) # infor clássica + unitária de Bob
return qc
qc_teleport_ = qc_teleport(0.1, 0.5, 0); qc_teleport_.decompose().draw(output = 'mpl')
import numpy as np
import math
th, ph, lb = 0, 0, 0;
rho_teo = np.array([[math.cos(th/2)**2, (math.cos(ph)+1j*math.sin(ph))*math.sin(th/2)*math.cos(th/2)],
[(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2)*math.cos(th/2), math.sin(th/2)**2]])
qc_teleport_ = qc_teleport(0.1, 0.5, 0)
qstc = state_tomography_circuits(qc_teleport_, [2])
# simulação
job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots = nshots)
qstf = StateTomographyFitter(job.result(), qstc)
rho_sim = qstf.fit(method='lstsq')
print('rho_teo = ', rho_teo)
print('rho_sim = ', rho_sim)
# experimento
job = qiskit.execute(qstc, backend = device, shots = nshots)
job_monitor(job)
qstf = StateTomographyFitter(job.result(), qstc)
rho_exp = qstf.fit(method = 'lstsq')
print('rho_exp = ', rho_exp)
F = qiskit.quantum_info.state_fidelity(rho_teo, rho_exp); print('F = ', F)
# variar th em cos(th/2)|0>+exp(i*ph)sin(th/2)|1>
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibm_nairobi')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
from qiskit.tools.visualization import plot_histogram
q0 = QuantumRegister(1); q1 = QuantumRegister(1); q2 = QuantumRegister(1); q3 = QuantumRegister(1)
c0 = ClassicalRegister(1); c1 = ClassicalRegister(1); c2 = ClassicalRegister(1); c3 = ClassicalRegister(1)
qc = QuantumCircuit(q0,q1,q2,q3,c0,c1,c2,c3)
# q0 e q1 estao com Alice, q2 com Charlies e q3 com Bob
qc.h(q1); qc.cx(q1,q2); qc.cx(q2,q3) # prepara o estado GHZ
qc.barrier()
#qc.sdg(q0); qc.h(q0) # prepara o estado a ser teletransportado (y+)
# prepara o estado |0>
qc.barrier()
qc.cx(q0,q1); qc.h(q0); qc.measure(q0,c0); qc.measure(q1,c1) # Medida de Alice na base de Bell
qc.h(q2); qc.measure(q2,c2) # medida de Charlie na base +,-
qc.barrier()
qc.z(q3).c_if(c0, 1) # acao de Bob condicionada no 1º cbit enviado por Alice
qc.x(q3).c_if(c1, 1) # acao de Bob condicionada no 2º cbit enviado por Alice
qc.z(q3).c_if(c2, 1) # acao de Bob condicionada no cbit enviado por Charlie
qc.barrier()
#qc.sdg(q3); qc.h(q3); qc.measure(q3,c3) # passa da base circular pra computacional
qc.measure(q3,c3) # mede na base computacional
qc.draw(output='mpl')
jobS = execute(qc, backend = simulator, shots = nshots)
plot_histogram(jobS.result().get_counts(qc))
jobE = execute(qc, backend = device, shots = nshots)
job_monitor(jobE)
tqc = transpile(qc, device)
jobE = device.run(tqc)
job_monitor(jobE)
plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)],
bar_labels = False, legend = ['sim', 'exp'])
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
from qiskit.tools.visualization import plot_histogram
q0 = QuantumRegister(1); q1 = QuantumRegister(1)
c0 = ClassicalRegister(1); c1 = ClassicalRegister(1)
qc = QuantumCircuit(q0,q1,c0,c1)
qc.h(q0); qc.cx(q0,q1) # emaranhamento compartilhado entre Alice e Bob
qc.barrier()
qc.x(q0); qc.sdg(q0); qc.h(q0); qc.measure(q0,c0) # Medida de Alice
qc.barrier()
qc.z(q1).c_if(c0, 1) # acao de Bob condicionada no cbit enviado por Alice
qc.barrier()
qc.sdg(q1); qc.h(q1); qc.measure(q1,c1) # passa da base circular pra computacional
qc.draw(output='mpl')
jobS = execute(qc, backend = simulator, shots = nshots)
plot_histogram(jobS.result().get_counts(qc))
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_lima')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
def qc_qft(n):
qr = QuantumRegister(n); qc = QuantumCircuit(qr, name = 'QFT')
for l in range(0, n):
qc.h(qr[l])
if l < n-1:
for q in range(l+1, n):
lb = 2*math.pi*2**(-q+l-1)
qc.cp(lb, qr[q], qr[l])
#qc.barrier()
#qc.barrier()
if n%2 == 0:
ul = n//2
else:
ul = (n-1)//2
for p in range(0, ul):
qc.swap(p, n-1-p)
return qc
n = 4; qc_qft_ = qc_qft(n); qc_qft_.draw(output='mpl')
def qc_iqft(n):
qr = QuantumRegister(n); qc = QuantumCircuit(qr, name = 'IQFT')
if n%2 == 0:
ul = n//2
else:
ul = (n-1)//2
for p in range(ul-1, -1, -1):
qc.swap(p, n-1-p)
#qc.barrier()
for l in range(n-1, -1, -1):
if l < n-1:
for q in range(n-1, l+1-1, -1):
lb = -2*math.pi*2**(-q+l-1)#; print(lb)
qc.cp(lb, qr[q], qr[l])
qc.h(qr[l])
#qc.barrier()
return qc
n = 4; qc_iqft_ = qc_iqft(n); qc_iqft_.draw(output='mpl')
#x0 = 1 + 0*1j; x1 = 0 + 0*1j # estado |0>
#x0 = 0 + 0*1j; x1 = 1 + 0*1j # estado |1>
x0 = 1/math.sqrt(2) + 0*1j; x1 = 1/math.sqrt(2) + 0*1j # estado |+>
mx0 = math.sqrt(x0.real**2 + x0.imag**2)
if x0.real != 0:
ph0 = math.atan(x0.imag/x0.real)
elif x0.real == 0 and x0.imag != 0:
ph0 = math.pi/2
elif x0.real == 0 and x0.imag == 0:
ph0 = 0
mx1 = math.sqrt(x1.real**2 + x1.imag**2)
if x1.real != 0:
ph1 = math.atan(x1.imag/x1.real)
elif x1.real == 0 and x1.imag != 0:
ph1 = math.pi/2
elif x1.real == 0 and x1.imag == 0:
ph1 = 0
print('|x0|=',mx0,', ph0=', ph0,', |x1|=', mx1,', ph1=', ph1)
th = 2*math.acos(mx1); ph = ph1-ph0+math.pi; lb = ph0-math.pi
print('th=',th,', ph=', ph,', lb=', lb)
n = 1
qr = QuantumRegister(n); qc = QuantumCircuit(qr)
qc.x(qr[0]); qc.u(th, ph, lb, qr[0]); qc.barrier()
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0])
qc.draw(output='mpl')
svsimulator = Aer.get_backend('statevector_simulator')
job = execute(qc, backend = svsimulator, shots = 1, memory = True)
print(job.result().get_statevector(qc))
def tfc(x): # classical discrete Fourier transform
d = len(x)
y = np.zeros(d, dtype = complex)
for k in range(0, d):
for j in range(0, d):
y[k] += x[j]*(math.cos(2*math.pi*j*k/d) + 1j*math.sin(2*math.pi*j*k/d))
return y/math.sqrt(d)
d = 4; x = np.zeros(d, dtype = complex);
#x = [1/2, 1/2, 1/2, 1/2]
x = [-1/2, -1/2, 1/2, 1/2]
y = tfc(x); print(y)
n = 2
qr = QuantumRegister(n); qc = QuantumCircuit(qr)
#qc.h([0,1]); qc.barrier() # ok
qc.x([0]); qc.h([0,1]); qc.barrier() # ok a menos de uma fase global de pi
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0,1])
qc.draw(output='mpl')
svsimulator = Aer.get_backend('statevector_simulator')
job = execute(qc, backend = svsimulator, shots = 1, memory = True)
print(job.result().get_statevector(qc)) # para >1 qubit tem a questao da ordem da bc
d = 4; x = np.zeros(d, dtype = complex);
x = [math.sqrt(1/6), math.sqrt(1/6), math.sqrt(2/3), 0]
y = tfc(x); print(y)
n = 3
qr = QuantumRegister(n); cr = ClassicalRegister(n); qc = QuantumCircuit(qr, cr)
qc.x([0,2]); qc.barrier()
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0,1,2]); qc.barrier()
qc_iqft_ = qc_iqft(n); iqft = qc_iqft_.to_gate(); qc.append(iqft, [0,1,2]); qc.barrier()
qc.measure([0,1,2],[0,1,2])
qc.draw(output='mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_jakarta')
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
def bernstein_vazirani(s):
ls = len(s)
qc = QuantumCircuit(ls+1,ls)
qc.h(range(ls))
qc.x(ls)
qc.h(ls)
qc.barrier();
for ii, yesno in enumerate(reversed(s)): # the black box
if yesno == '1':
qc.cx(ii, ls);
qc.barrier();
qc.h(range(ls));
qc.barrier();
qc.measure(range(ls),range(ls))
return qc
s = '011' # secretnumber
qc = bernstein_vazirani(s)
qc.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 1).result()
counts = result.get_counts()
print(counts)
jobE = execute(qc, backend = device, shots = nshots)
job_monitor(jobE)
jobS = execute(qc, backend = simulator, shots = nshots)
plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)],
bar_labels = False, legend = ['sim', 'exp'])
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibm_nairobi')
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
qr = QuantumRegister(4); cr = ClassicalRegister(4); qc = QuantumCircuit(qr,cr)
qc.h([0,1])
qc.barrier()
qc.cx(0,2); qc.cx(0,3); qc.cx(1,2); qc.cx(1,3) # oraculo
qc.barrier()
qc.measure([2,3],[2,3])
qc.barrier()
qc.h([0,1]); qc.measure([0,1],[0,1])
qc.draw(output='mpl')
jobS = execute(qc, backend = simulator, shots = nshots)
jobE = execute(qc, backend = device, shots = nshots)
job_monitor(jobE)
plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)],
bar_labels = False, legend = ['sim', 'exp'])
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
2*acos(sqrt(2/3)), 2*asin(sqrt(1/3)).
cos(2*pi/3), sin(2*pi/3), cos(4*pi/3), sin(4*pi/3), cos(8*pi/3), sin(8*pi/3)
cos(2*pi/3), sin(2*pi/3), cos(4*pi/3), sin(4*pi/3), cos(8*pi/3), sin(8*pi/3)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
rx,ry,rz = symbols('r_x r_y r_z')
rho1qb = (1/2)*(id(2) + rx*pauli(1) + ry*pauli(2) + rz*pauli(3))
rho1qb
pI,pX,pZ,pY = symbols('p_I p_X p_Z p_Y')
K0 = sqrt(pI)*id(2); K1 = sqrt(pX)*pauli(1); K2 = sqrt(pZ)*pauli(3); K3 = sqrt(pY)*pauli(2)
rho_p = K0*rho1qb*K0 + K1*rho1qb*K1 + K2*rho1qb*K2 + K3*rho1qb*K3
simplify(rho_p)
p = symbols('p')
pI = (1+3*p)/4; pX = (1-p)/4; pY = pX; pZ = pX
rho_p = K0*rho1qb*K0 + K1*rho1qb*K1 + K2*rho1qb*K2 + K3*rho1qb*K3
simplify(rho_p)
import numpy as np
from matplotlib import pyplot as plt
p = np.arange(0,1.1,0.1) # PD channel
C = np.sqrt(1-p)
plt.plot(p,C)
plt.show()
from sympy import *
N,p = symbols('N p')
K0 = sqrt(1-N)*Matrix([[1,0],[0,sqrt(1-p)]])
K1 = sqrt(1-N)*Matrix([[0,sqrt(p)],[0,0]])
K2 = sqrt(N)*Matrix([[sqrt(1-p),0],[0,1]])
K3 = sqrt(N)*Matrix([[0,0],[sqrt(p),0]])
#K0
r00,r01,r10,r11 = symbols('r_{00} r_{01} r_{10} r_{11}')#; r00
rho = Matrix([[r00,r01],[r10,r11]])#; rho
rho_gad = K0*rho*K0 + K1*rho*K1.T + K2*rho*K2 + K3*rho*K3.T
simplify(rho_gad)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
cos(-2*pi/3), sin(-2*pi/3), cos(-4*pi/3), sin(-4*pi/3), cos(-8*pi/3), sin(-8*pi/3)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
| |
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
def plot_Pr0(R1, R2):
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100)
ph_max = 2*math.pi; dph = ph_max/20; ph = np.arange(0, ph_max+dph, dph)
dimph = ph.shape[0]; P0 = np.zeros(dimph)
T1 = math.sqrt(1 - R1**2); T2 = math.sqrt(1 - R2**2)
P0 = T1**2*R2**2 + R1**2*T2**2 + 2*T1*R1*T2*R2*np.cos(ph)
plt.plot(ph, P0); plt.xlabel(r'$\phi$'); plt.ylabel(r'$Pr(0)$')
plt.xlim(0, 2*math.pi); plt.ylim(0, 1)
plt.annotate(r'$R_{1}=$'+str(R1), xy=(0.5,0.5), xytext=(0.5,0.5), fontsize=12)
plt.annotate(r'$R_{2}=$'+str(R1), xy=(0.5,0.4), xytext=(0.5,0.4), fontsize=12)
plt.show()
interactive(plot_Pr0, R1 = (0, 1, 0.05), R2 = (0, 1, 0.05))
def V1(T1, T2):
return (2*T1*T2*np.sqrt(1-T1**2)*np.sqrt(1-T2**2))/((T1**2)*(T2**2) + (1-T1**2)*(1-T2**2))
def V_3d(th, ph):
x = np.linspace(0.00001, 0.99999, 20); y = np.linspace(0.00001, 0.99999, 20); X, Y = np.meshgrid(x, y)
Z = V1(X, Y); fig = plt.figure();
ax = plt.axes(projection = "3d"); ax.plot_wireframe(X, Y, Z, color = 'blue')
ax.set_xlabel(r'$T_{1}$'); ax.set_ylabel(r'$T_{2}$'); ax.set_zlabel(r'$V_{0}$')
ax.view_init(th, ph); fig.tight_layout(); plt.show()
interactive(V_3d, th = (0,90,10), ph = (0,360,10))
from mpl_toolkits import mplot3d
def V0(T1, T2):
return (2*T1*T2*np.sqrt(1-T1**2)*np.sqrt(1-T2**2))/((T1**2)*(1-T2**2) + (1-T1**2)*T2**2)
def V_3d(th, ph):
x = np.linspace(0.00001, 0.99999, 20); y = np.linspace(0.00001, 0.99999, 20); X, Y = np.meshgrid(x, y)
Z = V0(X, Y); fig = plt.figure();
ax = plt.axes(projection = "3d"); ax.plot_wireframe(X, Y, Z, color = 'blue')
ax.set_xlabel(r'$T_{1}$'); ax.set_ylabel(r'$T_{2}$'); ax.set_zlabel(r'$V_{0}$')
ax.view_init(th, ph); fig.tight_layout(); plt.show()
interactive(V_3d, th = (0,90,10), ph = (0,360,10))
def V_3d(th, ph):
x = np.linspace(0.00001, 0.99999, 20); y = np.linspace(0.00001, 0.99999, 20); X, Y = np.meshgrid(x, y)
Z = V0(X, Y)-V1(X, Y); fig = plt.figure();
ax = plt.axes(projection = "3d"); ax.plot_wireframe(X, Y, Z, color = 'blue')
ax.set_xlabel(r'$T_{1}$'); ax.set_ylabel(r'$T_{2}$'); ax.set_zlabel(r'$V_{0}-V_{1}$')
ax.view_init(th, ph); fig.tight_layout(); plt.show()
interactive(V_3d, th = (0,90,10), ph = (0,360,10))
import math
import qiskit
def shannon_num(pv):
d = pv.shape[0]; SE = 0.0; j = -1
while (j < d-1):
j = j + 1
if pv[j] > 10**-15 and pv[j] < (1.0-10**-15):
SE -= pv[j]*math.log2(pv[j])
return SE
import scipy.linalg.lapack as lapak
def von_neumann_num(rho):
d = rho.shape[0]; b = lapak.zheevd(rho)
return shannon_num(b[0])
def coh_re_num(rho):
d = rho.shape[0]; pv = np.zeros(d)
for j in range(0,d):
pv[j] = rho[j,j].real
return shannon_num(pv) - von_neumann_num(rho)
def P_vn_num(rho):
d = rho.shape[0]; P = 0
for j in range(0, d):
if rho[j,j] > 10**-15 and rho[j,j] < (1.0-10**-15):
P += np.absolute(rho[j,j])*math.log2(np.absolute(rho[j,j]))
return math.log2(d) + P
def qc_gmzi(th, ph, ga):
qc = qiskit.QuantumCircuit(1)
qc.rx(-2*th, 0); qc.z(0); qc.y(0); qc.p(ph, 0); qc.rx(-2*ga, 0)
return qc
th, ph, ga = math.pi/3, math.pi/2, math.pi; qcgmzi = qc_gmzi(th, ph, ga); qcgmzi.draw(output = 'mpl')
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_armonk')
simulator = qiskit.Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
# for error mitigation
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
qr = qiskit.QuantumRegister(1)
qubit_list = [0] # os qubits para os quais aplicaremos calibracao de medidas
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr)
job = qiskit.execute(meas_calibs, backend = device, shots = nshots); job_monitor(job)
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels)
# for computing coherence and predictability
th_max = math.pi/2; dth = th_max/10; th = np.arange(0, th_max+dth, dth); dimth = th.shape[0]
Csim = np.zeros(dimth); Psim = np.zeros(dimth); Cexp = np.zeros(dimth); Pexp = np.zeros(dimth)
for j in range(0, dimth):
qr = qiskit.QuantumRegister(1); qc = qiskit.QuantumCircuit(qr); qc.rx(-2*th[j], qr[0])
qstc = state_tomography_circuits(qc, qr[0])
job = qiskit.execute(qstc, simulator, shots = nshots) # simulation
qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method = 'lstsq')
Csim[j] = coh_re_num(rho); Psim[j] = P_vn_num(rho)
jobE = qiskit.execute(qstc, backend = device, shots = nshots); job_monitor(jobE)
mitigated_results = meas_fitter.filter.apply(jobE.result())
qstfE = StateTomographyFitter(mitigated_results, qstc)
#qstfE = StateTomographyFitter(jobE.result(), qstc)
rhoE = qstfE.fit(method = 'lstsq')
Cexp[j] = coh_re_num(rhoE); Pexp[j] = P_vn_num(rhoE)
Cexp
Pexp
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100)
plt.plot(th, Csim, label = r'$C_{re}^{sim}$')
plt.plot(th, Psim, label = r'$P_{vn}^{sim}$')
plt.plot(th, Cexp, 'o', label = r'$C_{re}^{exp}$')
plt.plot(th, Pexp, '*', label = r'$P_{vn}^{exp}$')
plt.legend(); plt.xlabel(r'$\theta$')
plt.savefig('coh_vs_ivi_armonk_mit.pdf', format = 'pdf', dpi = 200)
plt.show()
# for computing the visibility
ph_max = 2*math.pi; dph = ph_max/10; ph = np.arange(0, ph_max+dph, dph); dimph = ph.shape[0]
P0sim = np.zeros(dimph); P0exp = np.zeros(dimph)
th[j] = math.pi/2
for k in range(0, dimph):
qr = qiskit.QuantumRegister(1); cr = qiskit.ClassicalRegister(1); qc = qiskit.QuantumCircuit(qr, cr)
qc.rx(-2*th[j], qr[0]); qc.z(qr[0]); qc.y(qr[0])
qc.p(ph[k], qr[0]); ga = th[j]; qc.rx(-2*ga, qr[0]); qc.measure(qr[0], cr[0])
job = qiskit.execute(qc, backend = simulator, shots = nshots) # simulation
counts = job.result().get_counts(qc)
if '0' in counts:
P0sim[k] = counts['0']
jobE = qiskit.execute(qc, backend = device, shots = nshots); job_monitor(jobE)
mitigated_results = meas_fitter.filter.apply(jobE.result())
countsE = mitigated_results.get_counts(qc)
#countsE = jobE.result().get_counts(qc)
if '0' in countsE:
P0exp[k] = countsE['0']
P0sim = P0sim/nshots; P0exp = P0exp/nshots
P0exp
P0sim
P0expthpi2 =
P0simthpi2 =
P0expthpi4 = np.array([1. , 0.90838173, 0.66274091, 0.37488527, 0.11976134,
0.01881309, 0.12251453, 0.36310798, 0.65050474, 0.90455797,
1. ])
P0simthpi4 = np.array([1. , 0.90612793, 0.65258789, 0.34069824, 0.09924316,
0. , 0.09228516, 0.34741211, 0.64331055, 0.90209961,
1. ])
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100)
plt.plot(ph, P0simthpi4, label = r'$P_{0}^{sim}(\theta=\pi/4)$')
plt.plot(ph, P0expthpi4, 'o', label = r'$P_{0}^{exp}(\theta=\pi/4)$')
plt.plot(ph, P0simthpi2, label = r'$P_{0}^{sim}(\theta=\pi/2)$')
plt.plot(ph, P0expthpi2, '*', label = r'$P_{0}^{exp}(\theta=\pi/2)$')
plt.ylim(0, 2*math.pi); plt.ylim(-0.01, 1.01)
plt.legend(); plt.xlabel(r'$\phi$')
plt.savefig('P0_thpi4_armonk_mit.pdf', format = 'pdf', dpi = 200)
plt.show()
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
hub=qc-spring-22-2, group=group-5 and project=recPrYILNAOsYMWIV
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
import sympy
from sympy import *
import numpy as np
from numpy import random
import math
import scipy
init_printing(use_unicode=True)
from matplotlib import pyplot as plt
%matplotlib inline
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum import TensorProduct as tp
from mpmath import factorial as fact
import io
import base64
#from IPython.core.display import display, HTML, clear_output
from IPython import *
from ipywidgets import interactive, interact, fixed, interact_manual, widgets
import csv
import importlib
import scipy.interpolate
from mpl_toolkits.mplot3d import Axes3D, proj3d
from itertools import product, combinations
from matplotlib.patches import FancyArrowPatch
from matplotlib import cm, colors
from sympy.functions.special.tensor_functions import KroneckerDelta
from scipy.linalg import polar, lapack
import mpmath
# constantes físicas
e = 1.60217662*10**-19 # C (carga elementar)
k = 8.9875517923*10**9 # Nm^2/C^2 (constante de Coulomb)
eps0 = 8.8541878128*10**-12 #F/m (permissividade do vácuo)
mu0 = 1.25663706212*10**-6 # N/A^2 (permeabilidade do vácuo)
h = 6.626069*10**-34 # Js (constante de Planck)
heV = h/e # em eV
hb = h/(2*math.pi) # hbar
hbeV = hb/e # em eV
c = 2.99792458*10**8 # m/s (velocidade da luz no vácuo)
G = 6.6742*10**-11 # Nm^2/kg^2 (constante gravitacional)
kB = 1.38065*10**-23 # J/K (constante de Boltzmann)
me = 9.109382*10**-31 # kg (massa do elétron)
mp = 1.6726219*10**-27 # kg (massa do próton)
mn = 1.67492749804*10**-27 # kg (massa do nêutron)
mT = 5.9722*10**24 # kg (massa da Terra)
mS = 1.98847*10**30 # kg (massa do Sol)
u = 1.660538921*10**-27 # kg (unidade de massa atômica)
dTS = 1.496*10**11 # m (distância Terra-Sol)
rT = 6.3781*10**6 # m (raio da Terra)
sSB = 5.670374419*10**-8 # W⋅m−2⋅K−4 (constante de Stefan-Boltzmann)
Ri = 10973734.848575922 # m^-1 (constante de Rydberg)
al = (k*e**2)/(hb*c) # ~1/137.035999084 (constante de estrutura fina)
a0=(hb**2)/(me*k*e**2) # ~ 0.52917710^-10 m (raio de Bohr)
ge = 2 # (fator giromagnetico do eletron)
gp = 5.58 # (fator giromagnetico do proton)
def id(n):
'''retorna a matriz identidade nxn'''
id = zeros(n,n)
for j in range(0,n):
id[j,j] = 1
return id
#id(2)
def pauli(j):
'''retorna as matrizes de Pauli'''
if j == 1:
return Matrix([[0,1],[1,0]])
elif j == 2:
return Matrix([[0,-1j],[1j,0]])
elif j == 3:
return Matrix([[1,0],[0,-1]])
#pauli(1), pauli(2), pauli(3)
def tr(A):
'''retorna o traço de uma matriz'''
d = A.shape[0]
tr = 0
for j in range(0,d):
tr += A[j,j]
return tr
#tr(pauli(1))
def comm(A,B):
'''retorna a função comutador'''
return A*B-B*A
#comm(pauli(1),pauli(2))
def acomm(A,B):
'''retorna a função anti-comutador'''
return A*B+B*A
#acomm(pauli(1),pauli(2))
def cb(n,j):
'''retorna um vetor da base padrão de C^n'''
vec = zeros(n,1)
vec[j] = 1
return vec
#cb(2,0)
def proj(psi):
'''retorna o projeto no vetor psi'''
d = psi.shape[0]
P = zeros(d,d)
for j in range(0,d):
for k in range(0,d):
P[j,k] = psi[j]*conjugate(psi[k])
return P
#proj(cb(2,0))
def bell(j,k):
if j == 0 and k == 0:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))+tp(cb(2,1),cb(2,1)))
elif j == 0 and k == 1:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))+tp(cb(2,1),cb(2,0)))
elif j == 1 and k == 0:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))-tp(cb(2,1),cb(2,0)))
elif j == 1 and k == 1:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))-tp(cb(2,1),cb(2,1)))
#bell(0,0), bell(0,1), bell(1,0), bell(1,1)
def inner_product(v,w):
d = len(v); ip = 0
for j in range(0,d):
ip += conjugate(v[j])*w[j]
return ip
#a,b,c,d = symbols("a b c d"); v = [b,a]; w = [c,d]; inner_product(v,w)
def norm(v):
d = len(v)
return sqrt(inner_product(v,v))
#v = [2,2]; norm(v)
def tp(x,y):
return tensorproduct(x,y)
A = tp(pauli(3),pauli(1)); A
|
https://github.com/abbarreto/qiskit2
|
abbarreto
| |
https://github.com/abbarreto/qiskit2
|
abbarreto
| |
https://github.com/liudingshan/QiskitGrovers
|
liudingshan
|
import qiskit as qis
from qiskit.tools.visualization import plot_bloch_multivector
import matplotlib.pyplot as plt
from qiskit.tools.visualization import plot_histogram
import math as math
# Define Registers
qr = qis.QuantumRegister(4)
cr = qis.ClassicalRegister(4)
# Make Circuit
circuit = qis.QuantumCircuit(qr, cr)
# Make Gates and Circuit Additions
circuit.h(qr[0])
circuit.crz(math.pi/2, qr[1], qr[0])
circuit.crz(math.pi/4, qr[2], qr[0])
circuit.crz(math.pi/8, qr[3], qr[0])
circuit.barrier
circuit.h(qr[1])
circuit.crz(math.pi/2, qr[2], qr[1])
circuit.crz(math.pi/4, qr[3], qr[1])
circuit.h(qr[2])
circuit.crz(math.pi/2, qr[3], qr[2])
circuit.h(qr[3])
# Choose Unitary Simulator
simulator = qis.Aer.get_backend('unitary_simulator')
# Get Unitary Results (Multiplication of all Gates/Additions)
result = qis.execute(circuit, backend=simulator).result()
unitary = result.get_unitary()
# Plot Unitary Results
print(unitary)
# Choose Statevector Simulator
simulator = qis.Aer.get_backend('statevector_simulator')
# Get Statevector Results
result = qis.execute(circuit, backend=simulator).result()
statevector = result.get_statevector()
# Plot Statevector Results
plot_bloch_multivector(statevector)
# Measure Qubits to Classical
circuit.measure(qr, cr)
# Print Circuit (Along w/ Measurements)
#print(circuit)
circuit.draw(output='mpl')
# Choose Qasm Simulator
simulator = qis.Aer.get_backend('qasm_simulator')
# Get Qasm Results
result = qis.execute(circuit, backend=simulator).result()
# Plot Qasm Measurements
plot_histogram(result.get_counts(circuit))
plt.show()
print()
|
https://github.com/liudingshan/QiskitGrovers
|
liudingshan
|
from qiskit import *
from qiskit.tools.visualization import plot_bloch_multivector
import matplotlib.pyplot as plt
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circuit = QuantumCircuit(qr, cr)
circuit.x(0)
#simulator = Aer.get_backend('statevector_simulator')
simulator = Aer.get_backend('unitary_simulator')
result = execute(circuit, backend=simulator).result()
#statevector = result.get_statevector()
unitary = result.get_unitary()
#plot_bloch_multivector(statevector)
#plt.show()
circuit.measure(qr, cr)
#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(result.get_counts(circuit))
plt.show()
#print(statevector)
#print(circuit)
print(unitary)
|
https://github.com/liudingshan/QiskitGrovers
|
liudingshan
|
import qiskit as qis
from qiskit.tools.visualization import plot_bloch_multivector
import matplotlib.pyplot as plt
from qiskit.tools.visualization import plot_histogram
import math as math
# Define Registers
qr = qis.QuantumRegister(3)
cr = qis.ClassicalRegister(3)
# Make Circuit
circuit = qis.QuantumCircuit(qr, cr)
# Make Gates and Circuit Additions
circuit.h(qr[0])
circuit.h(qr[1])
circuit.x(qr[2])
circuit.h(qr[2])
circuit.ccx(qr[0], qr[1], qr[2])
circuit.h(qr[0])
circuit.x(qr[0])
circuit.h(qr[1])
circuit.x(qr[1])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.h(qr[1])
circuit.x(qr[0])
circuit.x(qr[1])
circuit.h(qr[0])
circuit.h(qr[1])
circuit.h(qr[2])
# Choose Unitary Simulator
simulator = qis.Aer.get_backend('unitary_simulator')
# Get Unitary Results (Multiplication of all Gates/Additions)
result = qis.execute(circuit, backend=simulator).result()
unitary = result.get_unitary()
# Plot Unitary Results
print(unitary)
# Choose Statevector Simulator
simulator = qis.Aer.get_backend('statevector_simulator')
# Get Statevector Results
result = qis.execute(circuit, backend=simulator).result()
statevector = result.get_statevector()
# Plot Statevector Results
plot_bloch_multivector(statevector)
# Measure Qubits to Classical
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
# Print Circuit (Along w/ Measurements)
#print(circuit)
circuit.draw(output='mpl')
# Choose Qasm Simulator
simulator = qis.Aer.get_backend('qasm_simulator')
# Get Qasm Results
result = qis.execute(circuit, backend=simulator).result()
# Plot Qasm Measurements
plot_histogram(result.get_counts(circuit))
plt.show()
print()
|
https://github.com/liudingshan/QiskitGrovers
|
liudingshan
|
import qiskit as qis
from qiskit.tools.visualization import plot_bloch_multivector
import matplotlib.pyplot as plt
from qiskit.tools.visualization import plot_histogram
import math as math
# Define Registers
qr = qis.QuantumRegister(1)
cr = qis.ClassicalRegister(1)
# Make Circuit
circuit = qis.QuantumCircuit(qr, cr)
# Make Gates and Circuit Additions
#circuit.cz(qr[0], qr[1])
circuit.x(qr[0])
#circuit.x(qr[1])
#circuit.cswap(qr[0], qr[1], qr[2])
#circuit.ccx(qr[0], qr[1], qr[2])
#circuit.h(qr[0])
#circuit.cx(qr[0], qr[1])
#circuit.rx(math.pi/2, qr[0])
#circuit.swap(qr[0], qr[1])
# Choose Unitary Simulator
simulator = qis.Aer.get_backend('unitary_simulator')
# Get Unitary Results (Multiplication of all Gates/Additions)
result = qis.execute(circuit, backend=simulator).result()
unitary = result.get_unitary()
# Plot Unitary Results
print(unitary)
# Choose Statevector Simulator
simulator = qis.Aer.get_backend('statevector_simulator')
# Get Statevector Results
result = qis.execute(circuit, backend=simulator).result()
statevector = result.get_statevector()
# Plot Statevector Results
plot_bloch_multivector(statevector)
# Measure Qubits to Classical
circuit.measure(qr, cr)
# Print Circuit (Along w/ Measurements)
print(circuit)
#circuit.draw(output='mpl')
# Choose Qasm Simulator
simulator = qis.Aer.get_backend('qasm_simulator')
# Get Qasm Results
result = qis.execute(circuit, backend=simulator).result()
# Plot Qasm Measurements
plot_histogram(result.get_counts(circuit))
plt.show()
|
https://github.com/MartenSkogh/QiskitVQEWrapper
|
MartenSkogh
|
import sys
import numpy as np
import scipy as sp
import re
from copy import deepcopy
from pprint import pprint
from timeit import default_timer as timer
from enum import Enum
from qiskit import Aer
from qiskit.aqua import QuantumInstance
from qiskit.aqua.operators import Z2Symmetries
from qiskit.aqua.algorithms.minimum_eigen_solvers import VQE
from qiskit.aqua.algorithms import ExactEigensolver
from qiskit.aqua.components.optimizers import SLSQP, L_BFGS_B, COBYLA, SPSA
from qiskit.chemistry.core import Hamiltonian, TransformationType, QubitMappingType
from qiskit.chemistry.drivers import PySCFDriver, GaussianDriver, UnitsType, HFMethodType
from qiskit.chemistry.components.variational_forms import UCCSD
from qiskit.chemistry.components.initial_states import HartreeFock
class DriverType(Enum):
""" DriverType Enum """
PYSCF = 'PySCF'
GAUSSIAN = 'Gaussian'
class VQEWrapper():
def __init__(self):
### MOLECULE ###
# These things need to be set before running
self.molecule_string = None
# You can make a pretty educated guess for these two
self.spin = None
self.charge = None
self.qmolecule = None
### CHEMISTRY DRIVER ###
#Basis has to be in a format accepted by Gaussian (sto-3g, 6-31g)
self.basis = 'sto-3g'
self.chem_driver = DriverType.GAUSSIAN
self.hf_method = HFMethodType.UHF
self.length_unit = UnitsType.ANGSTROM
self.gaussian_checkfile = ''
self.driver = None
self.core = None
### HAMILTONIAN ###
self.transformation = TransformationType.FULL
self.qubit_mapping = QubitMappingType.JORDAN_WIGNER
self.two_qubit_reduction = False
self.freeze_core = True
self.orbital_reduction = []
self.qubit_op = None
self.aux_ops = None
self.initial_point = None
self.optimizer = SLSQP(maxiter=5000)
self.ansatz = 'UCCSD'
self.excitation_type = 'sd'
self.num_time_slices = 1
self.shallow_circuit_concat = False
self.vqe_algo = None
self.var_form = None
self.vqe_callback = None
self.vqe_time = None
### BACKEND CONFIG ###
#Choose the backend (use Aer instead of BasicAer)
self.simulator = 'statevector_simulator'
self.shots = 1024
self.seed_simulator = None
self.seed_transpiler = None
self.noise_model = None
self.measurement_error_mitigation_cls = None
self.backend_options = {}
def opt_str(self):
match = re.search(r'optimizers.[A-z]+.(.+) object', str(self.optimizer))
opt_str = match.group(1)
return opt_str
def gaussian_config(self):
#Format properties to a string fitting the gaussian input format
if self.gaussian_checkfile != '':
chk = f'%Chk={self.gaussian_checkfile}\n'
else:
chk = ''
gaussian_config = chk + f'# {self.hf_method.value}/{self.basis} scf(conventional)\n\nMolecule\n\n{self.charge} {self.spin+1}\n'
gaussian_config = gaussian_config + self.molecule_string.replace('; ','\n') + '\n\n'
return gaussian_config
def initiate(self):
self.init_backend()
self.init_driver()
self.init_core()
self.init_ops()
self.init_init_state()
self.init_var_form()
self.init_vqe()
def init_driver(self):
if self.chem_driver.value == 'PySCF':
if self.hf_method == HFMethodType.RHF and self.spin % 2 == 0:
print(f'WARNING: Restricted Hartree-Fock (RHF) cannot handle unpaired electrons!')
print(f'Switching to Unrestricted Hartree-Fock!')
self.chem_driver = HFMethodType.UHF
self.driver = PySCFDriver(atom=self.molecule_string,
unit=self.length_unit,
charge=self.charge,
spin=self.spin,
hf_method=self.hf_method,
basis=self.basis)
elif self.chem_driver.value == 'Gaussian':
self.driver = GaussianDriver(config=self.gaussian_config())
self.qmolecule = self.driver.run()
def init_backend(self):
self.backend = Aer.get_backend(self.simulator)
self.quantum_instance = QuantumInstance(backend=self.backend,
shots=self.shots,
seed_simulator = self.seed_simulator,
seed_transpiler = self.seed_transpiler,
noise_model = self.noise_model,
measurement_error_mitigation_cls = self.measurement_error_mitigation_cls,
backend_options = self.backend_options)
def init_core(self):
self.core = Hamiltonian(transformation=self.transformation,
qubit_mapping=self.qubit_mapping,
two_qubit_reduction=self.two_qubit_reduction,
freeze_core=self.freeze_core,
orbital_reduction=self.orbital_reduction)
def init_ops(self):
self.qubit_op, self.aux_ops = self.core.run(self.qmolecule)
#Initial state
def init_init_state(self):
self.init_state = HartreeFock(num_orbitals=self.core._molecule_info['num_orbitals'],
qubit_mapping=self.core._qubit_mapping,
two_qubit_reduction=self.core._two_qubit_reduction,
num_particles=self.core._molecule_info['num_particles'])
#Set up VQE
def init_vqe(self):
self.vqe_algo = VQE(self.qubit_op,
self.var_form,
self.optimizer,
initial_point=self.initial_point,
callback=self.vqe_callback)
def init_var_form(self):
if self.ansatz.upper() == 'UCCSD':
# UCCSD Ansatz
self.var_form = UCCSD(num_orbitals=self.core._molecule_info['num_orbitals'],
num_particles=self.core._molecule_info['num_particles'],
initial_state=self.init_state,
qubit_mapping=self.core._qubit_mapping,
two_qubit_reduction=self.core._two_qubit_reduction,
num_time_slices=self.num_time_slices,
excitation_type=self.excitation_type,
shallow_circuit_concat=self.shallow_circuit_concat)
else:
if self.var_form is None:
raise ValueError('No variational form specified!')
def print_config(self):
print(f'\n\n=== MOLECULAR INFORMATION ===')
print(f'* Molecule string: {self.molecule_string}')
print(f'* Charge: {self.charge}')
print(f'* Spin (2S): {self.spin}')
print(f'* Basis set: {self.basis}')
print(f'* Num orbitals: {self.qmolecule.num_orbitals}')
print(f'* Lenght Unit: {self.length_unit}')
print(f'* HF method: {self.hf_method}')
print(f'\n\n=== HAMILTONIAN INFORMATION ===')
print(f'* Transformation type: {self.transformation}')
print(f'* Qubit mapping: {self.qubit_mapping}')
print(f'* Two qubit reduction: {self.two_qubit_reduction}')
print(f'* Freeze core: {self.freeze_core}')
print(f'* Orbital reduction: {self.orbital_reduction}')
print(f'\n\n=== CHEMISTRY DRIVER INFORMATION ===')
print(f'* Not yet implemented!')
print(f'\n\n=== BACKEND INFORMATION ===')
print(f'* Not yet implemented!')
def run_vqe(self):
#Run the algorithm
vqe_start = timer()
self.vqe_result = self.vqe_algo.run(self.quantum_instance)
self.vqe_time = timer() - vqe_start
#Get the results
result = self.core.process_algorithm_result(self.vqe_result)
return result
|
https://github.com/DSamuel1/QiskitProjects
|
DSamuel1
|
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 *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
from qiskit import *
def dj(n, case, bstring):
qc = QuantumCircuit(n+1, n)
qc.x(n)
for i in range(n+1):
qc.h(i)
oracle(qc, n, case, bstring)
for i in range(n):
qc.h(i)
qc.measure(i,i)
return qc
def oracle(qc, n, case, bstring):
#let case 1 be f(x)=0, case 2 is f(x)=1, case 3 is f(x)=x, case 4 is f(x)=!x
if(case == 2):
qc.x(n)
elif(case == 3):
for i in range(n):
if bstring[i] == '1':
qc.x(i)
qc.cx(i,n)
if bstring[i] == '1':
qc.x(i)
elif(case == 4):
for i in range(n):
if bstring[i]=='1':
qc.x(i)
qc.cx(i, n)
if bstring[i]=='1':
qc.x(i)
qc.x(n)
circ = dj(3, 3, "101")
circ.draw('mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(circ, backend, shots = 1024)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/KoljaFrahm/QiskitPerformance
|
KoljaFrahm
|
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
from scipy.sparse.sputils import getdata
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.utils import gen_batches
from qiskit import Aer
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.opflow import AerPauliExpectation
from qiskit.circuit.library import TwoLocal, ZFeatureMap, RealAmplitudes
from qiskit_machine_learning.neural_networks import TwoLayerQNN
from qiskit_machine_learning.connectors import TorchConnector
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier, VQC
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA
#from IPython.display import clear_output
# callback function that draws a live plot when the .fit() method is called
def callback_graph(weights, obj_func_eval):
#print("callback_graph called")
#clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.figure()
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.savefig("callback_graph_all.png")
plt.close()
def onehot(data):
"""
returns the the data vector in one hot enconding.
@data :: Numpy array with data of type int.
"""
return np.eye(int(data.max()+1))[data]
def index(onehotdata):
"""
returns the the data vector in index enconding.
@onehotdata :: Numpy array with data of type int on onehot encoding.
"""
return np.argmax(onehotdata, axis=1)
def splitData(x_data, y_data, ratio_train, ratio_test, ratio_val):
# Produces test split.
x_remaining, x_test, y_remaining, y_test = train_test_split(
x_data, y_data, test_size=ratio_test)
# Adjusts val ratio, w.r.t. remaining dataset.
ratio_remaining = 1 - ratio_test
ratio_val_adjusted = ratio_val / ratio_remaining
# Produces train and val splits.
x_train, x_val, y_train, y_val = train_test_split(
x_remaining, y_remaining, test_size=ratio_val_adjusted)
return x_train, x_test, x_val, y_train, y_test, y_val
def getData():
data_bkg = np.load("QML-HEP-data/x_data_bkg_8features.npy")
data_sig = np.load("QML-HEP-data/x_data_sig_8features.npy")
y_bkg = np.zeros(data_bkg.shape[0],dtype=int)
y_sig = np.ones(data_sig.shape[0],dtype=int)
x_data = np.concatenate((data_bkg,data_sig))
y_data = np.concatenate((y_bkg,y_sig))
# Defines ratios, w.r.t. whole dataset.
ratio_train, ratio_test, ratio_val = 0.9, 0.05, 0.05
x_train, x_test, x_val, y_train, y_test, y_val = splitData(
x_data, y_data, ratio_train, ratio_test, ratio_val)
return x_train, x_test, x_val, y_train, y_test, y_val
def plot_roc_get_auc(model,sets,labels):
aucl = []
plt.figure()
for set,label in zip(sets,labels):
x,y = set
pred = index(model(x)) #index because the prediction is onehot encoded
fpr, tpr, thresholds = metrics.roc_curve(y, pred)
plt.plot(fpr, tpr, label=label)
auc = metrics.roc_auc_score(y, pred)
aucl.append(auc)
plt.savefig("rocplot.png")
plt.close()
return aucl
def VQCTraining(vqc, x_train, y_train, x_test, y_test, epoch, bs):
# create empty array for callback to store evaluations of the objective function
plt.figure()
plt.rcParams["figure.figsize"] = (12, 6)
#training
print("fitting starts")
for epoch in range(epochs):
batches = gen_batches(x_train.shape[0],bs)
print(f"Epoch: {epoch + 1}/{epochs}")
for batch in batches:
vqc.fit(x_train[batch], onehot(y_train[batch]))
loss = vqc.score(x_test, onehot(y_test))
print(loss)
print("fitting finished")
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
#declare quantum instance
#simulator_gpu = Aer.get_backend('aer_simulator_statevector')
#simulator_gpu.set_options(device='GPU')
#qi = QuantumInstance(simulator_gpu)
qi = QuantumInstance(Aer.get_backend("aer_simulator_statevector_gpu"))
epochs = 20
nqubits = 8
niter = 20 #how many maximal iterations of the optimizer function
bs = 128 # batch size
#bs = 50 # test batch size
####Define VQC####
feature_map = ZFeatureMap(nqubits, reps=1)
#ansatz = RealAmplitudes(nqubits, reps=1)
ansatz = TwoLocal(nqubits, 'ry', 'cx', 'linear', reps=1)
#optimizer = SPSA(maxiter=niter)
#optimizer = COBYLA(maxiter=niter, disp=True)
optimizer = None
vqc = VQC(
feature_map=feature_map,
ansatz=ansatz,
loss="cross_entropy",
optimizer=optimizer,
warm_start=False,
quantum_instance=qi,
callback=callback_graph,
)
print("starting program")
print(vqc.circuit)
x_train, x_test, x_val, y_train, y_test, y_val = getData()
####reduce events for testing the program####
#num_samples = 256
#x_train, x_test, x_val = x_train[:num_samples], x_test[:num_samples], x_val[:num_samples]
#y_train, y_test, y_val = y_train[:num_samples], y_test[:num_samples], y_val[:num_samples]
####VQC#####
objective_func_vals = []
VQCTraining(vqc, x_train, y_train, x_test, y_test, epochs, bs)
####score classifier####
aucs = plot_roc_get_auc(vqc.predict,((x_test, y_test),(x_val,y_val)),("test data","validation data"))
print(aucs)
print("test")
|
https://github.com/Manish-Sudhir/QiskitCheck
|
Manish-Sudhir
|
import warnings
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, Aer, transpile, IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_bloch_multivector, plot_histogram, array_to_latex
warnings.filterwarnings("ignore", category=DeprecationWarning)
import numpy as np
import pandas as pd
import math
from qiskit.quantum_info import Statevector
from scipy.stats import chi2_contingency, ttest_ind
import unittest
import hypothesis.strategies as st
from hypothesis import given, settings
pi = np.pi
# q = QuantumRegister(2)
# c = ClassicalRegister(1)
# qc2 = QuantumCircuit(q,c)
# qc2.x(1)
# qc2.h(0)
# qc2.cnot(0,1)
qc2 = QuantumCircuit(2)
# qc2.x(1)
# qc2.h(0)
# qc2.measure(q[0],c)
# qc2.measure(q[1],c)
# THIS DOESNT WORK
# qc2.h(0)
# qc2.cnot(0,1)
# qc2.h(1)
# qc2.h(0)
# qc2.x(0)
# qc2.h(0)
# qc2.cnot(0,1)
# qc2.h(1)
# qc2.h(0)
# 4 BELL STATES
# qc2.x(1)
# qc2.h(0)
# qc2.cnot(0,1)
# qc2.h(1)
qc2.h(1)
qc2.cp(pi/2,1,0)
qc2.h(0)
print(qc2)
sv = Statevector.from_label('01')
sv.evolve(qc2)
print(sv)
backend = Aer.get_backend('aer_simulator')
qc2.measure_all()
# sv = Statevector.from_label('01')
# sv.evolve(qc2)
# print(sv)
qc2.save_statevector()
# probs = psi.probabilities()
# print(probs)
final_state = backend.run(qc2).result().get_statevector()
print(final_state)
# display(array_to_latex(final_state, prefix="\\text{Statevector} = "))
job = execute(qc2, backend, shots=10000, memory=True)#run the circuit 1000000 times
counts = job.result().get_counts()#return the result counts
print(counts)
qc2 = QuantumCircuit(2)
# qc2.p(0.5*2*math.pi/100, 1)
qc2.h(0)
# qc2.cnot(0,1)
# qc2.x(0)
# qc2.x(1)
# qc2.h(0)
# qc2.cnot(0,1)
# qc2.h(1)
print(qc2)
backend = Aer.get_backend('aer_simulator')
sv1 = Statevector.from_label('00')
print(type(sv1))
wow = sv1.evolve(qc2)
probs = wow.probabilities()
probsD = wow.probabilities_dict()
print(sv1)
for values in probsD.values():
round(values,2)
d = {key: round(values,2) for key,values in probsD.items()}
print("probs dictionary rounded",d)
print("probs for qubit1 (not rounded): ",wow.probabilities_dict([0]))
print("probs for qubit2 (not rounded): ", wow.probabilities_dict([1]))
# print("probs: ", type(probs))
# print("probs Dictionary: ", probsD)
# probs_qubit_0 = wow.probabilities([0])
# probs_qubit_1 = wow.probabilities([1])
# print('Qubit-0 probs: {}'.format(probs_qubit_0))
# print('Qubit-1 probs: {}'.format(probs_qubit_1))
# print(wow.probabilities_dict([0]))
# print(wow.probabilities_dict([1]))
for values in d.values():
# print(values)
if (values==0.5):
print("true")
else:
print("false")
qc2.measure_all()
sv = qc2.save_statevector()
print("sv: " ,sv)
# probs = psi.probabilities()
# print(probs)
final_state = backend.run(qc2).result().get_statevector()
print("final : " ,final_state)
job = execute(qc2, backend, shots=10000, memory=True)#run the circuit 1000000 times
counts = job.result().get_counts()#return the result counts
print(counts)
def assertProbability(qc,qubitChoice: int, qubitState :str, expectedProbability):
sv = Statevector.from_label("00")
evl = sv.evolve(qc)
probs = evl.probabilities_dict([qubitChoice])
probsRound = {key: round(values,2) for key,values in probs.items()}
for key,value in probsRound.items():
if(key==qubitState):
if(value==expectedProbability):
print("Expected Probability present")
else:
raise(AssertionError("Probability not present"))
else:
raise(AssertionError("Probability not present"))
qc = QuantumCircuit(2)
qc.h(0)
assertProbability(qc,1,"0",1)
psi = Statevector.from_label('10')
print(psi)
print("statevector measurement: " ,psi.measure())
# rev = psi.reverse_qargs()
# Probabilities for measuring both qubits
probs = psi.probabilities()
print('probs: {}'.format(probs))
probsD = psi.probabilities_dict()
print("probs dictionary: ", probsD)
# Probabilities for measuring only qubit-0
probs_qubit_0 = psi.probabilities([0])
print('Qubit-0 probs: {}'.format(probs_qubit_0))
print('Qubit-0 probs: {}'.format(psi.probabilities_dict([0])))
# Probabilities for measuring only qubit-1
probs_qubit_1 = psi.probabilities([1])
print('Qubit-1 probs: {}'.format(probs_qubit_1))
print('Qubit-1 probs: {}'.format(psi.probabilities_dict([1])))
def measure_z(circuit, qubit_indexes):
cBitIndex = 0
for index in qubit_indexes:
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def assertEntangled(backend,qc,qubit1,qubit2,measurements_to_make,alpha = 0.05):
if (qc.num_clbits == 0):
qc.add_register(ClassicalRegister(2))
elif (qc.num_clbits != 2):
raise ValueError("QuantumCircuit classical register must be of length 2")
zQuantumCircuit = measure_z(qc, [qubit1, qubit2])
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
zMemory = zJob.result().get_memory()
zCounts = zJob.result().get_counts()
# zDf = pd.DataFrame(columns=['q0', 'q1'])
# for row in zCounts:
# zDf = zDf.append({'q0':row[0], 'q1':row[1]}, ignore_index=True)
# print(zDf.astype(str))
resDf = pd.DataFrame(columns=['0','1'])
classical_qubit_index = 1
for qubit in [qubit1,qubit2]:
zero_amount, one_amount = 0,0
for experiment in zCounts:
if (experiment[2-classical_qubit_index] == '0'):
zero_amount += zCounts[experiment]
else:
one_amount += zCounts[experiment]
df = {'0':zero_amount, '1':one_amount}
resDf = resDf.append(df, ignore_index = True)
classical_qubit_index+=1
resDf['0'] = resDf['0'].astype(int)
resDf['1'] = resDf['1'].astype(int)
print(resDf.astype(str))
chiVal, pVal, dOfFreedom, exp = chi2_contingency(resDf)
print("chi square value: ",chiVal,"p value: ",pVal,"expected values: ",exp)
if(pVal<alpha):
raise(AssertionError("states are not entangled"))
else:
print("states are entangled")
backend = Aer.get_backend('aer_simulator')
qc3 = QuantumCircuit(2)
qc3.h(0)
# qc3.cnot(0,1)
# qc3.x(0)
# qc3.h(0)
# qc3.cnot(0,1)
# qc3.h(1)
# qc3.h(0)
assertEntangled(backend,qc3,0,1,100000,0.05)
# Completed but more testing required
def assertEntangled(backend,qc,qubits_to_assert,measurements_to_make,alpha = 0.05):
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
## classical register must be of same length as amount of qubits to assert
## if there is no classical register add them according to length of qubit list
if (qc.num_clbits == 0):
qc.add_register(ClassicalRegister(len(qubits_to_assert)))
elif (len(qubits_to_assert) != 2):
raise ValueError("QuantumCircuit classical register must be of length 2")
zQuantumCircuit = measure_z(qc, qubits_to_assert)
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
zMemory = zJob.result().get_memory()
print(zMemory)
q1=[]
q2=[]
print("lol ",qubits_to_assert[0])
print(qubits_to_assert[1])
newDict = dict.fromkeys(['qubit1','qubit2'])
newDict = {'qubit1': qubits_to_assert[0],'qubit2':qubits_to_assert[1]}
print("new dict", newDict)
# if(qubits_to_assert[0]==0 and qubits_to_assert[1]==0):
# qubits_to_assert[1]
classicalQubitIndex = 1
for qubit in newDict.keys():
print("this qubit:",qubit)
for measurement in zMemory:
print("this measurement", measurement)
if (measurement[2-classicalQubitIndex] == '0'):
print("measure: ",measurement[2-classicalQubitIndex],"also: qubittoassert0",qubits_to_assert[0],"and qubittoassert1: ",qubits_to_assert[1])
if(qubit=='qubit1'):
q1.append(measurement[2-classicalQubitIndex])
print("Added to q1 for measure0:", measurement[2-classicalQubitIndex])
else:
q2.append(measurement[2-classicalQubitIndex])
print("Added to q2 for measure0:", measurement[2-classicalQubitIndex])
else:
print("measureOTHER: ",measurement[2-classicalQubitIndex], "also: qubittoassert0",qubits_to_assert[0],"and qubittoassert1: ",qubits_to_assert[1])
if(qubit=='qubit1'):
q1.append(measurement[2-classicalQubitIndex])
print("Added to q1 for measure1:", measurement[2-classicalQubitIndex])
else:
q2.append(measurement[2-classicalQubitIndex])
print("Added to q2 for measure1:", measurement[2-classicalQubitIndex])
classicalQubitIndex+=1
print("Q1: ",q1)
print("Q2: ",q2)
measDict = dict.fromkeys(['qubit1','qubit2'])
measDict = {'qubit1': q1,'qubit2':q2}
measDf1 = pd.DataFrame.from_dict(measDict,orient='index')
# measDf = pd.DataFrame.from_dict(measDict)
# print(measDf)
measDf12=measDf1.transpose()
print(measDf12)
# df = pd.DataFrame.from_dict(a, orient='index')
# df = df.transpose()
ct = pd.crosstab(measDf12.qubit1,measDf12.qubit2)
chiVal, pVal, dOfFreedom, exp = chi2_contingency(ct)
print("chi square value: ",chiVal,"p value: ",pVal,"expected values: ",exp)
if(pVal>alpha):
raise(AssertionError("states are not entangled"))
else:
print("states are entangled")
backend = Aer.get_backend('aer_simulator')
qr = QuantumRegister(2)
cr=ClassicalRegister(2)
qc3 = QuantumCircuit(qr,cr)
qc3.x(1)
# # qc3.x(1)
# # qc3.x(0)
qc3.h(0)
# qc3.cnot(0,1)
# qc3.h(0)
# qc3.cnot(0,1)
# qc3.x(1)
# qc3.rx(np.pi/2,qr[0])
# qc3.p(10*2*math.pi/100, 0)
# qc3.p(0.5*2*math.pi/100, 1)
print(qc3)
assertEntangled(backend,qc3,[0,1],20,0.05)
# circuit = QuantumCircuit(2)
# circuit.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits)
# assertEntangled(backend,circuit,[0,1],10,0.05)
def measure_x(circuit, qubitIndexes):
cBitIndex = 0
for index in qubitIndexes:
circuit.h(index)
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def measure_y(circuit, qubit_indexes):
cBitIndex = 0
for index in qubit_indexes:
circuit.sdg(index)
circuit.h(index)
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
## assert that qubits are equal
def assertEqual(backend, quantumCircuit, qubits_to_assert, measurements_to_make, alpha):
## needs to make at least 2 measurements, one for x axis, one for y axis
## realistically we need more for any statistical significance
if (measurements_to_make < 2):
raise ValueError("Must make at least 2 measurements")
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
## classical register must be of same length as amount of qubits to assert
## if there is no classical register add them according to length of qubit list
if (quantumCircuit.num_clbits == 0):
quantumCircuit.add_register(ClassicalRegister(len(qubits_to_assert)))
elif (len(qubits_to_assert) != 2):
raise ValueError("QuantumCircuit classical register must be of length 2")
## divide measurements to make by 3 as we need to run measurements twice, one for x and one for y
measurements_to_make = measurements_to_make // 3
## copy the circit and set measurement to y axis
yQuantumCircuit = measure_y(quantumCircuit.copy(), qubits_to_assert)
## measure the x axis
xQuantumCircuit = measure_x(quantumCircuit.copy(), qubits_to_assert)
## measure the z axis
zQuantumCircuit = measure_z(quantumCircuit, qubits_to_assert)
## get y axis results
yJob = execute(yQuantumCircuit, backend, shots=measurements_to_make, memory=True)
yMemory = yJob.result().get_memory()
yCounts = yJob.result().get_counts()
## get x axis results
xJob = execute(xQuantumCircuit, backend, shots=measurements_to_make, memory=True)
xMemory = xJob.result().get_memory()
xCounts = xJob.result().get_counts()
## get z axis results
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
zMemory = zJob.result().get_memory()
zCounts = zJob.result().get_counts()
resDf = pd.DataFrame(columns=['0','1','+','i','-','-i'])
classical_qubit_index = 1
for qubit in qubits_to_assert:
zero_amount, one_amount, plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0,0,0
for experiment in xCounts:
if (experiment[2-classical_qubit_index] == '0'):
plus_amount += xCounts[experiment]
else:
minus_amount += xCounts[experiment]
for experiment in yCounts:
if (experiment[2-classical_qubit_index] == '0'):
i_amount += yCounts[experiment]
else:
minus_i_amount += yCounts[experiment]
for experiment in zCounts:
if (experiment[2-classical_qubit_index] == '0'):
zero_amount += zCounts[experiment]
else:
one_amount += zCounts[experiment]
df = {'0':zero_amount, '1':one_amount,
'+':plus_amount, 'i':i_amount,
'-':minus_amount,'-i':minus_i_amount}
resDf = resDf.append(df, ignore_index = True)
classical_qubit_index+=1
## convert the columns to a strict numerical type
resDf['+'] = resDf['+'].astype(int)
resDf['i'] = resDf['i'].astype(int)
resDf['-'] = resDf['-'].astype(int)
resDf['-i'] = resDf['-i'].astype(int)
resDf['0'] = resDf['0'].astype(int)
resDf['1'] = resDf['1'].astype(int)
print(resDf.astype(str))
# print(z1)
arr = resDf.to_numpy()
q1Vals = arr[0, 0:] # Stores measurements across all axes for the 1st qubit
print("Measurements for qubit1: ", q1Vals)
q2Vals = arr[1, 0:] # Stores measurements across all axes for the 2nd qubit
print("Measurements for qubit2: ", q2Vals)
tTest, pValue = ttest_ind(q1Vals, q2Vals, alternative = 'two-sided') # Apply t test
print("stat: ",tTest, "pValue: ", pValue)
if pValue > alpha:
print("The two qubits are equal (fail to reject null hypothesis) ")
else:
print("There is a significant difference between the two qubits (reject null hypothesis)")
qc = QuantumCircuit(2)
# qc.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], qc.qubits)
# qc.h(0)
# qc.x(1)
# qc.p(0.5*2*math.pi/100, 1)
# qc.h(0)
# qc.h(1)
# qc.p(10*2*math.pi/100, 0)
# qc.p(20*2*math.pi/100, 1)
assertEqual(backend, qc, [0,0], 300000, 0.01)
qc = QuantumCircuit(2,2)
qc.h(0)
qc.h(1)
qc.p(0.5*2*math.pi/100, 1)
# qc.cnot(0,1)
zQuantumCircuit = measure_z(qc, [0,1])
zJob = execute(zQuantumCircuit, backend, shots=100000, memory=True)
zMemory = zJob.result().get_memory()
zCounts = zJob.result().get_counts()
xQuantumCircuit = measure_x(qc, [0,1])
xJob = execute(xQuantumCircuit, backend, shots=100000, memory=True)
xMemory = xJob.result().get_memory()
xCounts = xJob.result().get_counts()
yQuantumCircuit = measure_y(qc, [0,1])
yJob = execute(yQuantumCircuit, backend, shots=100000, memory=True)
yMemory = yJob.result().get_memory()
yCounts = yJob.result().get_counts()
print("z axis : ", zCounts)
print("x axis : ", xCounts)
print("y axis : ", yCounts)
resDf = pd.DataFrame(columns=['0','1','+','i','-','-i'])
classical_qubit_index = 1
for qubit in [0,1]:
zero_amount, one_amount, plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0,0,0
for experiment in xCounts:
if (experiment[2-classical_qubit_index] == '0'):
plus_amount += xCounts[experiment]
else:
minus_amount += xCounts[experiment]
for experiment in yCounts:
if (experiment[2-classical_qubit_index] == '0'):
i_amount += yCounts[experiment]
else:
minus_i_amount += yCounts[experiment]
for experiment in zCounts:
if (experiment[2-classical_qubit_index] == '0'):
zero_amount += zCounts[experiment]
else:
one_amount += zCounts[experiment]
df = {'0':zero_amount, '1':one_amount,
'+':plus_amount, 'i':i_amount,
'-':minus_amount,'-i':minus_i_amount}
resDf = resDf.append(df, ignore_index = True)
classical_qubit_index+=1
print(resDf.astype(str))
lst = [["Ajay", 70], ["Manish", 92], ["Arjun", 42]]
df = pd.DataFrame(lst, columns=["Name", "Marks"], index=["Student1","Student2","Student3"])
df
def getList(dict):
return list(dict.keys())
qubitVal = {0: [1,0], 1: [0,1]}
values = getList(counts)
if(len(values) == 1):
print("They are not entangled")
elif(len(values) == 4):
firstStr = values[0]
secondStr = values[1]
thirdStr = values[2]
fourthStr = values[3]
print(firstStr,secondStr,thirdStr,fourthStr)
first1 = int(firstStr[0])
first2 = int(firstStr[1])
second1 = int(secondStr[0])
second2 =int(secondStr[1])
third1 = int(thirdStr[0])
third2 = int(thirdStr[1])
fourth1 = int(fourthStr[0])
fourth2 = int(fourthStr[1])
firstArr = np.array([qubitVal[first1], qubitVal[first2]])
secondArr = np.array([qubitVal[second1], qubitVal[second2]])
thirdArr = np.array([qubitVal[third1], qubitVal[third2]])
fourthArr = np.array([qubitVal[fourth1], qubitVal[fourth2]])
firstTensor = np.tensordot(firstArr[0], firstArr[1], axes=0)
secondTensor = np.tensordot(secondArr[0], secondArr[1], axes=0)
thirdTensor = np.tensordot(thirdArr[0], thirdArr[1], axes=0)
fourthTensor = np.tensordot(fourthArr[0], fourthArr[1], axes=0)
print("Tensors: ",firstTensor, " HI ",secondTensor,thirdTensor,fourthTensor)
column1 = np.add(firstTensor,secondTensor)
column2 = np.add(thirdTensor, fourthTensor)
print("AB: ",column1," CD: ",column2)
column = np.add(column1,column2)
print(column)
else:
firstStr = values[0]
secondStr = values[1]
print(firstStr)
print(secondStr)
first1 = int(firstStr[0])
first2 = int(firstStr[1])
second1 = int(secondStr[0])
second2 = int(secondStr[1])
firstArr = np.array([qubitVal[first1], qubitVal[first2]])
secondArr = np.array([qubitVal[second1], qubitVal[second2]])
firstTensor= np.tensordot(firstArr[0], firstArr[1], axes=0)
secondTensor = np.tensordot(secondArr[0], secondArr[1], axes=0)
print("first: ",firstTensor)
print("second: ",secondTensor)
print("final: ")
column = np.add(firstTensor,secondTensor)
print(column)
abVal = column[0]
cdVal = column[1]
aVal = abVal[0]
bVal = abVal[1]
cVal = cdVal[0]
dVal = cdVal[1]
if(aVal*dVal!=bVal*cVal):
print("They are entangled")
else:
print("Not Entangled")
def getList(dict):
return list(dict.keys())
# NOTE: Checks if a qubit value is 0 then return a matrix with [1,0] similarly for 1 with [0,1]
qubitVal = {0: [1,0], 1: [0,1]}
# NOTE: Upon analysis the measurement returned by the QC are also present in the bell state of the qc
# NOTE: For example if the counts output 00 and 01
values = getList(counts) # NOTE: Returns the measurement counts of the circuit and takes the key values ie 00 and 01 and converts it to a list using a function I created
if(len(values) == 1):
print("They are not entangled")
else:
# NOTE: Stores the first and second values as strings returned by counts for example: 00 and 01
firstStr = values[0]
secondStr = values[1]
# NOTE: Seperates the digits and stores them as integers
first1 = int(firstStr[0])
first2 = int(firstStr[1])
second1 = int(secondStr[0])
second2 = int(secondStr[1])
# NOTE: Creates a 2x2 matrix to store ___
firstArr = np.array([qubitVal[first1], qubitVal[first2]])
secondArr = np.array([qubitVal[second1], qubitVal[second2]])
# if(second1==1):
# subtract = True
# NOTE: Performs the tensor product for the ___ for both the first and second values
firstTensor= np.tensordot(firstArr[0], firstArr[1], axes=0)
print("first: ", firstArr, "first array first position: ", firstArr[0],"first array second position: ", firstArr[1])
print("second: ",secondArr,"second array first position: ", secondArr[0], "second array second position: ",secondArr[1])
secondTensor = np.tensordot(secondArr[0], secondArr[1], axes=0)
# print("first: ",firstTensor)
# print("second: ",secondTensor)
# NOTE: Condition to check if counts returns 4 measurements in which case we repeat the process for the 3rd and 4th measurements
if(len(values) == 4):
thirdStr = values[2]
fourthStr = values[3]
third1 = int(thirdStr[0])
third2 = int(thirdStr[1])
fourth1 = int(fourthStr[0])
fourth2 = int(fourthStr[1])
thirdArr = np.array([qubitVal[third1], qubitVal[third2]])
fourthArr = np.array([qubitVal[fourth1], qubitVal[fourth2]])
thirdTensor = np.tensordot(thirdArr[0], thirdArr[1], axes=0)
fourthTensor = np.tensordot(fourthArr[0], fourthArr[1], axes=0)
print(f"Tensors: {firstTensor}\n ,{secondTensor}\n,{thirdTensor}\n,{fourthTensor}\n")
column1 = np.add(firstTensor,secondTensor)
column2 = np.add(thirdTensor, fourthTensor)
print("AB: ",column1," CD: ",column2)
column = np.add(column1,column2)
print(column)
else:
print("first: ",firstTensor)
print("second: ",secondTensor)
print("final: ")
# NOTE: adds the two tensorproducts to give our column vector
# if(subtract==True):
# column = np.subtract(firstTensor,secondTensor)
# else:
column = np.add(firstTensor,secondTensor)
print(column)
# NOTE: Sets the value for our A,B,C,D values
abVal = column[0]
cdVal = column[1]
aVal = abVal[0]
bVal = abVal[1]
cVal = cdVal[0]
dVal = cdVal[1]
# NOTE: Checks our condition
if(aVal*dVal!=bVal*cVal):
print("They are entangled")
else:
print("Not Entangled")
def getList(dict):
return list(dict.keys())
# NOTE: Checks if a qubit value is 0 then return a matrix with [1,0] similarly for 1 with [0,1]
qubitVal = {0: [1,0], 1: [0,1]}
# NOTE: Upon analysis the measurement returned by the QC are also present in the bell state of the qc
# NOTE: For example if the counts output 00 and 01
values = getList(counts) # NOTE: Returns the measurement counts of the circuit and takes the key values ie 00 and 01 and converts it to a list using a function I created
if(len(values) == 1):
print("They are not entangled")
else:
# NOTE: Stores the first and second values as strings returned by counts for example: 00 and 01
firstStr = values[0]
secondStr = values[1]
# NOTE: Seperates the digits and stores them as an integer based on our previous example first1 woul store 0 and first2 would store 0
first1 = int(firstStr[0])
first2 = int(firstStr[1])
second1 = int(secondStr[0])
second2 = int(secondStr[1])
# NOTE: Creates a 2x2 matrix to store qubit values ex: first Arr would be [[1,0],[1,0]]
firstArr = np.array([qubitVal[first1], qubitVal[first2]])
secondArr = np.array([qubitVal[second1], qubitVal[second2]])
# NOTE: Performs the tensor product for the ___ for both the first and second values ex: firstTensor is the tensor product of [1,0] and [1,0]
firstTensor= np.tensordot(firstArr[0], firstArr[1], axes=0)
secondTensor = np.tensordot(secondArr[0], secondArr[1], axes=0)
# NOTE: Condition to check if counts returns 4 measurements in which case we repeat the process for the 3rd and 4th measurements
if(len(values) == 4):
thirdStr = values[2]
fourthStr = values[3]
third1 = int(thirdStr[0])
third2 = int(thirdStr[1])
fourth1 = int(fourthStr[0])
fourth2 = int(fourthStr[1])
thirdArr = np.array([qubitVal[third1], qubitVal[third2]])
fourthArr = np.array([qubitVal[fourth1], qubitVal[fourth2]])
thirdTensor = np.tensordot(thirdArr[0], thirdArr[1], axes=0)
fourthTensor = np.tensordot(fourthArr[0], fourthArr[1], axes=0)
column1 = np.add(firstTensor,secondTensor)
column2 = np.add(thirdTensor, fourthTensor)
column = np.add(column1,column2)
print(column)
else:
# NOTE: adds the two tensorproducts to give our column vector
column = np.add(firstTensor,secondTensor)
print(column)
# NOTE: Sets the value for our A,B,C,D values
abVal = column[0]
cdVal = column[1]
aVal = abVal[0]
bVal = abVal[1]
cVal = cdVal[0]
dVal = cdVal[1]
# NOTE: Checks our condition
if(aVal*dVal!=bVal*cVal):
print("They are entangled")
else:
print("Not Entangled")
# no constructor
# usee gate
|
https://github.com/Manish-Sudhir/QiskitCheck
|
Manish-Sudhir
|
import warnings
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, Aer, transpile, IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_histogram, plot_bloch_multivector
warnings.filterwarnings("ignore", category=DeprecationWarning)
import numpy as np
import math
pi = np.pi
qc2 = QuantumCircuit(2)
# qc2.x(1)
# qc2.h(0)
# qc2.cnot(0,1)
# THIS DOESNT WORK
# qc2.h(0)
# qc2.cnot(0,1)
# qc2.h(1)
# qc2.h(0)
# qc2.x(0)
# qc2.h(0)
# qc2.cnot(0,1)
# qc2.h(1)
# qc2.h(0)
qc2.x(0)
print(qc2)
backend = Aer.get_backend('aer_simulator')
qc2.measure_all()
job = execute(qc2, backend, shots=10000)#run the circuit 1000000 times
counts = job.result().get_counts()#return the result counts
print(counts)
def getList(dict):
return list(dict.keys())
umar = {0: [1,0], 1: [0,1]}
values = getList(counts)
if(len(values) == 1):
print("They are not entangled")
else:
abStr = values[0]
cdStr = values[1]
print(abStr)
print(cdStr)
aStr = abStr[0]
bStr = abStr[1]
cStr = cdStr[0]
dStr = cdStr[1]
a = int(aStr)
b = int(bStr)
c = int(cStr)
d = int(dStr)
haha = [a,b,c,d]
abArr = np.array([umar[a], umar[b]])
cdArr = np.array([umar[c], umar[d]])
print("lol")
print(abArr)
print(cdArr)
print("jahja")
tensorprod_ab= np.tensordot(abArr[0], abArr[1], axes=0)
tensorprod_cd = np.tensordot(cdArr[0], cdArr[1], axes=0)
print(type(tensorprod_ab))
print(tensorprod_cd)
print("final")
column = np.add(tensorprod_ab,tensorprod_cd)
print(column)
abVal = column[0]
cdVal = column[1]
aVal = abVal[0]
bVal = abVal[1]
cVal = cdVal[0]
dVal = cdVal[1]
if(aVal*dVal!=bVal*cVal):
print("They are entangled")
else:
print("Not Entangled")
print("first " + values[0])
print("second " + values[1])
def set_measure_x(circuit, n):
for num in range(n):
circuit.h(num)
def measure_x(circuit, qubitIndexes):
cBitIndex = 0
for index in qubitIndexes:
circuit.h(index)
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def set_measure_y(circuit, n):
for num in range(n):
circuit.sdg(num)
circuit.h(num)
def qft_rotations(circuit, n):
#if qubit amount is 0, then do nothing and return
if n == 0:
#set it to measure the x axis
# set_measure_x(qc, 4)
# qc.measure_all()
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
return qft_rotations(circuit, n)
backend = Aer.get_backend('aer_simulator')
qc = QuantumCircuit(2)
qc.x(0)
qc.x(1)
print(qc)
after = qft_rotations(qc,2)#call the recursive qft method
print(after)
#set it to measure the x axis
after.measure_all()
job = execute(after, backend, shots=1000)#run the circuit 1000000 times
counts = job.result().get_counts()#return the result counts
print(counts)
print(max(counts, key=counts.get))
def qft_dagger(qc, n):
for j in range(n):
for m in range(j):
qc.cp(math.pi/float(2**(j-m)), m, j)
qc.h(j)
qc = QuantumCircuit(2)
# qc.x(0)
qc.x(0)
qc.x(1)
qc.measure_all()
print(qc)
qft_dagger(qc,2)#call the recursive qft method
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=1000000)#run the circuit 1000000 times
counts = job.result().get_counts()
print(counts)#return the result counts
highest = max(counts, key=counts.get)
reverse = highest[::-1]
print(reverse)
print(type(highest))
print(str(highest))
lol3 = [0,1]
yes1 = [0,0,0,0]
for i in lol3:
qc.x(i)
yes1[i] = 1
answer = ''.join(map(str,yes1))
print(answer)
if (reverse == answer):
print("True")
else:
print("False")
#OTHER QFT
def qft_rotations(circuit, n):
"""Performs qft on the first n qubits in circuit (without swaps)"""
if n == 0:
# set_measure_x(qc, 3)
# set_measure_y(qc,3)
# qc.measure_all()
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
# At the end of our function, we call the same function again on
# the next qubits (we reduced n by one earlier in the function)
qft_rotations(circuit, n)
# Let's see how it looks:
qc = QuantumCircuit(3)
qc.x(0)
qc.x(2)
lol= [0,0,0]
print(lol)
qft_rotations(qc,3)
qc.measure_all()
qc.draw()
# set_measure_x(qc, 3)
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=2048)
counts = job.result().get_counts()
print(counts)
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
"""QFT on the first n qubits in circuit"""
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
# Let's see how it looks:
qc = QuantumCircuit(2)
qc.x(0)
qc.x(1)
qft(qc,2)
qc.draw()
def inverse_qft(circuit, n):
"""Does the inverse QFT on the first n qubits in circuit"""
# First we create a QFT circuit of the correct size:
qft_circ = qft(QuantumCircuit(n), n)
# Then we take the inverse of this circuit
invqft_circ = qft_circ.inverse()
# And add it to the first n qubits in our existing circuit
circuit.append(invqft_circ, circuit.qubits[:n])
return circuit.decompose() # .decompose() allows us to see the individual gates
nqubits = 3
number = 5
qc = QuantumCircuit(nqubits)
for qubit in range(nqubits):
qc.h(qubit)
qc.p(number*pi/4,0)
qc.p(number*pi/2,1)
qc.p(number*pi,2)
qc.draw()
qc = inverse_qft(qc, nqubits)
qc.measure_all()
qc.draw()
backend = Aer.get_backend('aer_simulator')
shots = 2048
transpiled_qc = transpile(qc, backend, optimization_level=3)
# transpiled_qc = transpile(qc, backend)
job = backend.run(transpiled_qc, shots=shots)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
pip install hypothesis
import unittest
import hypothesis.strategies as st
from hypothesis import given, settings
# @st.composite
# def qubit_combos(draw):
# qubit_string = draw(st.sampled_from(['000','001','010','011','100','101','110','111']))
# return int(qubit_string)
# qubit_combos().example()
@st.composite
def circuit(draw):
nQubits = [0,1,2,3]
nQubitsLength = len(nQubits)
n= draw(st.sampled_from(nQubits))
x1 = []
x1.append(n)
nQubits.remove(n)
m = draw(st.sampled_from(nQubits))
x1.append(m)
nQubits.remove(m)
# l = draw(st.sampled_from(nQubits))
# x1.append(l)
# nQubits.remove(l)
noOfRegisters = nQubitsLength
return [x1,noOfRegisters]
print(circuit().example())
# ex = circuit().example()
# print(type(ex[0]))
# print(type(ex[1]))
# print(type(ex))
# lol = [1,2,0,4,6,0]
# for i in lol:
# if i == 0:
# lol.remove(0)
# print(lol)
lol2 = [0,1]
yes = [0,0,0,0]
qc = QuantumCircuit(4)
for i in lol2:
qc.x(i)
yes[i] = 1
answer = ''.join(map(str,yes))
# strings = [str(integer) for integer in yes]
# a_string = "".join(strings)
# an_integer = int(a_string)
print (qc)
# print(an_integer)
print(answer)
qc.measure_all()
qft_dagger(qc,4)
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=2048)
counts = job.result().get_counts()
inverseOutput = max(counts, key=counts.get)
print(inverseOutput)
reverse = inverseOutput[::-1]
print(reverse)
if(reverse == answer):
print("They are equal")
@given(circuit())
@settings(deadline=None)
def test_inverse_holds_true(xList):
x1 = xList[0]
noOfRegisters = xList[1]
baseQubit = [0,0,0,0]
qc= QuantumCircuit(noOfRegisters)
for i in x1:
qc.x(i)
baseQubit[i] = 1
iQFT = ''.join(map(str,baseQubit))
qc.measure_all()
qft_dagger(qc,noOfRegisters)
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=2048)
counts = job.result().get_counts()
inverseOutput = max(counts, key=counts.get)
reverse = inverseOutput[::-1]
assert(reverse == iQFT)
if __name__ == "__main__":
test_inverse_holds_true()
_bits_types = dict()
bits_template = """"""
def mk_bits( nbits ):
assert nbits > 0, "We don't allow Bits0"
# assert nbits < 512, "We don't allow bitwidth to exceed 512."
if nbits not in _bits_types:
custom_exec(compile( bits_template.format(nbits), filename=f"Bits{nbits}", mode="exec" ),
globals(), locals() )
return _bits_types[nbits]
def custom_exec( prog, _globals, _locals ):
assert _globals is not None
assert _locals is not None
norm_globals = _globals
norm_locals = _locals
if _globals is not None:
norm_globals = _normalize_dict( _globals )
if _locals is not None:
norm_locals = _normalize_dict( _locals )
exec( prog, norm_globals, norm_locals )
# Local may have more stuff generated by the code.
# We need to put this back to the original _locals
if _locals is not None:
_locals.update( norm_locals )
def bits( nbits, signed=False, min_value=None, max_value=None ):
BitsN = mk_bits( nbits )
if (min_value is not None or max_value is not None) and signed:
raise ValueError("bits strategy currently doesn't support setting "
"signedness and min/max value at the same time")
if min_value is None:
min_value = (-(2**(nbits-1))) if signed else 0
if max_value is None:
max_value = (2**(nbits-1)-1) if signed else (2**nbits - 1)
strat = st.booleans() if nbits == 1 else st.integers( min_value, max_value )
@st.composite
def strategy_bits( draw ):
return BitsN( draw( strat ) )
strategy_bits().example()
return strategy_bits().example()
bits(3).example()
@st.composite
def list_and_index(draw, elements=st.integers()):
xs = draw(st.lists(elements, min_size=1))
i = draw(st.integers(min_value=0, max_value=len(xs) - 1))
return (xs, i)
list_and_index().example()
|
https://github.com/Manish-Sudhir/QiskitCheck
|
Manish-Sudhir
|
import warnings
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, Aer, transpile, IBMQ, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_bloch_multivector, plot_histogram, array_to_latex
warnings.filterwarnings("ignore", category=DeprecationWarning)
import numpy as np
import pandas as pd
import math
from math import sqrt
from qiskit.quantum_info import Statevector, random_statevector
from qiskit.circuit.random import random_circuit
from scipy.stats import chi2_contingency, ttest_ind, chisquare
import unittest
import hypothesis.strategies as st
from hypothesis import given, settings
pi = np.pi
def measure_z(circuit, qubit_indexes):
cBitIndex = 0
for index in qubit_indexes:
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def measure_x(circuit, qubitIndexes):
cBitIndex = 0
for index in qubitIndexes:
circuit.h(index)
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def measure_y(circuit, qubit_indexes):
cBitIndex = 0
for index in qubit_indexes:
circuit.sdg(index)
circuit.h(index)
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def flip_endian(dict):
newdict = {}
for key in list(dict):
newdict[key[::-1]] = dict.pop(key)
return newdict
def set_measure_x(circuit, n):
for num in range(n):
circuit.h(num)
def set_measure_y(circuit, n):
for num in range(n):
circuit.sdg(num)
circuit.h(num)
def qft_rotations(circuit, n):
#if qubit amount is 0, then do nothing and return
if n == 0:
#set it to measure the x axis
set_measure_x(qc, 2)
qc.measure_all()
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
return qft_rotations(circuit, n)
backend = Aer.get_backend('aer_simulator')
qc = QuantumCircuit(2)
qc.x(0)
circ = qft_rotations(qc,2)#call the recursive qft method
print(circ)
#set it to measure the x axis
set_measure_x(qc, 2)
job = execute(qc, backend, shots=100000)#run the circuit 1000000 times
print(flip_endian(job.result().get_counts()))#return the result counts
def assertEntangled(backend,qc,qubits_to_assert,measurements_to_make,alpha = 0.05):
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
## classical register must be of same length as amount of qubits to assert
## if there is no classical register add them according to length of qubit list
if (qc.num_clbits == 0):
qc.add_register(ClassicalRegister(len(qubits_to_assert)))
elif (len(qubits_to_assert) != 2):
raise ValueError("QuantumCircuit classical register must be of length 2")
zQuantumCircuit = measure_z(qc, qubits_to_assert)
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
zMemory = zJob.result().get_memory()
q1=[]
q2=[]
qubitDict = dict.fromkeys(['qubit1','qubit2'])
qubitDict = {'qubit1': qubits_to_assert[0],'qubit2':qubits_to_assert[1]}
print("new dict", qubitDict)
classicalQubitIndex = 1
for qubit in qubitDict.keys():
print("this qubit:",qubit)
for measurement in zMemory:
# print("this measurement", measurement)
if (measurement[2-classicalQubitIndex] == '0'):
# print("measure: ",measurement[2-classicalQubitIndex],"also: qubittoassert0",qubits_to_assert[0],"and qubittoassert1: ",qubits_to_assert[1])
if(qubit=='qubit1'):
q1.append(measurement[2-classicalQubitIndex])
# print("Added to q1 for measure0:", measurement[2-classicalQubitIndex])
else:
q2.append(measurement[2-classicalQubitIndex])
# print("Added to q2 for measure0:", measurement[2-classicalQubitIndex])
else:
# print("measureOTHER: ",measurement[2-classicalQubitIndex], "also: qubittoassert0",qubits_to_assert[0],"and qubittoassert1: ",qubits_to_assert[1])
if(qubit=='qubit1'):
q1.append(measurement[2-classicalQubitIndex])
# print("Added to q1 for measure1:", measurement[2-classicalQubitIndex])
else:
q2.append(measurement[2-classicalQubitIndex])
# print("Added to q2 for measure1:", measurement[2-classicalQubitIndex])
classicalQubitIndex+=1
measDict = dict.fromkeys(['qubit1','qubit2'])
measDict = {'qubit1': q1,'qubit2':q2}
measDf1 = pd.DataFrame.from_dict(measDict,orient='index')
measDf12=measDf1.transpose()
print(measDf12)
ct = pd.crosstab(measDf12.qubit1,measDf12.qubit2)
chiVal, pVal, dOfFreedom, exp = chi2_contingency(ct)
print("chi square value: ",chiVal,"p value: ",pVal,"expected values: ",exp)
if(pVal>alpha):
raise(AssertionError("states are not entangled"))
else:
print("states are entangled")
backend = Aer.get_backend('aer_simulator')
qr = QuantumRegister(2)
cr=ClassicalRegister(2)
qc3 = QuantumCircuit(qr,cr)
# qc3.x(1)
qc3.x(0)
qc3.h(0)
qc3.cnot(0,1)
# qc3.rx(np.pi/2,qr[0])
qc3.p(10*2*math.pi/100, 0)
# qc3.p(0.5*2*math.pi/100, 1)
# print(qc3)
assertEntangled(backend,qc3,[0,1],2000,0.05)
# circuit = QuantumCircuit(2)
# circuit.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits)
# assertEntangled(backend,circuit,[0,1],10,0.05)
def getDf(qc,qubits_to_assert,measurements_to_make,backend):
## classical register must be of same length as amount of qubits to assert
## if there is no classical register add them according to length of qubit list
if (qc.num_clbits == 0):
qc.add_register(ClassicalRegister(len(qubits_to_assert)))
elif (len(qubits_to_assert) != 2):
raise ValueError("QuantumCircuit classical register must be of length 2")
## divide measurements to make by 3 as we need to run measurements twice, one for x and one for y
measurements_to_make = measurements_to_make // 3
yQuantumCircuit = measure_y(qc.copy(), qubits_to_assert)
xQuantumCircuit = measure_x(qc.copy(), qubits_to_assert)
zQuantumCircuit = measure_z(qc, qubits_to_assert)
yJob = execute(yQuantumCircuit, backend, shots=measurements_to_make, memory=True)
yMemory = yJob.result().get_memory()
yCounts = yJob.result().get_counts()
## get x axis results
xJob = execute(xQuantumCircuit, backend, shots=measurements_to_make, memory=True)
xMemory = xJob.result().get_memory()
xCounts = xJob.result().get_counts()
## get z axis results
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
zMemory = zJob.result().get_memory()
zCounts = zJob.result().get_counts()
resDf = pd.DataFrame(columns=['0','1','+','i','-','-i'])
classical_qubit_index = 1
for qubit in qubits_to_assert:
zero_amount, one_amount, plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0,0,0
for experiment in xCounts:
if (experiment[2-classical_qubit_index] == '0'):
plus_amount += xCounts[experiment]
else:
minus_amount += xCounts[experiment]
for experiment in yCounts:
if (experiment[2-classical_qubit_index] == '0'):
i_amount += yCounts[experiment]
else:
minus_i_amount += yCounts[experiment]
for experiment in zCounts:
if (experiment[2-classical_qubit_index] == '0'):
zero_amount += zCounts[experiment]
else:
one_amount += zCounts[experiment]
df = {'0':zero_amount, '1':one_amount,
'+':plus_amount, 'i':i_amount,
'-':minus_amount,'-i':minus_i_amount}
resDf = resDf.append(df, ignore_index = True)
classical_qubit_index+=1
resDf['+'] = resDf['+'].astype(int)
resDf['i'] = resDf['i'].astype(int)
resDf['-'] = resDf['-'].astype(int)
resDf['-i'] = resDf['-i'].astype(int)
resDf['0'] = resDf['0'].astype(int)
resDf['1'] = resDf['1'].astype(int)
return resDf
# Completed but more testing required
## assert that qubits are equal
def assertEqual(backend, quantumCircuit, qubits_to_assert, measurements_to_make, alpha):
## needs to make at least 2 measurements, one for x axis, one for y axis
## realistically we need more for any statistical significance
if (measurements_to_make < 2):
raise ValueError("Must make at least 2 measurements")
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
# Get Df is a function I made to return a dataframe containing measurements for each each qubit across all axes and I use 5 such different measurements for my dataset
resDf1 = getDf(quantumCircuit,qubits_to_assert,measurements_to_make,backend)
resDf2 = getDf(quantumCircuit,qubits_to_assert,measurements_to_make,backend)
resDf3 = getDf(quantumCircuit,qubits_to_assert,measurements_to_make,backend)
resDf4 = getDf(quantumCircuit,qubits_to_assert,measurements_to_make,backend)
resDf5 = getDf(quantumCircuit,qubits_to_assert,measurements_to_make,backend)
q1Vals = []
q2Vals = []
q1Vals.extend([resDf1.at[0,'1'],resDf1.at[0,'-'],resDf1.at[0,'-i'], resDf2.at[0,'1'],resDf2.at[0,'-'],resDf2.at[0,'-i'], resDf3.at[0,'1'],resDf3.at[0,'-'],resDf3.at[0,'-i'], resDf4.at[0,'1'],resDf4.at[0,'-'],resDf4.at[0,'-i'], resDf5.at[0,'1'],resDf5.at[0,'-'],resDf5.at[0,'-i']])
print(q1Vals)
q2Vals.extend([resDf1.at[1,'1'],resDf1.at[1,'-'],resDf1.at[1,'-i'], resDf2.at[1,'1'],resDf2.at[1,'-'],resDf2.at[1,'-i'],resDf3.at[1,'1'],resDf3.at[1,'-'],resDf3.at[1,'-i'],resDf4.at[1,'1'],resDf4.at[1,'-'],resDf4.at[1,'-i'],resDf5.at[1,'1'],resDf5.at[1,'-'],resDf5.at[1,'-i'] ])
print(q2Vals)
tTest, pValue = ttest_ind(q1Vals, q2Vals, alternative = 'two-sided') # Apply t test
print("stat: ",tTest, "pValue: ", pValue)
if pValue > alpha:
print("The two qubits are equal (fail to reject null hypothesis) ")
else:
print("There is a significant difference between the two qubits (reject null hypothesis)")
qc = QuantumCircuit(2)
backend = Aer.get_backend('aer_simulator')
# qc.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], qc.qubits)
qc.h(0)
# qc.cnot(0,1)
qc.x(1)
qc.p(0.5*2*math.pi/100, 1)
# qc.h(1)
# qc.p(10*2*math.pi/100, 0)
# qc.p(20*2*math.pi/100, 1)
# assertEqual(backend, qc, [0,1], 300000, 0.05)
# assertEqual(backend, qc, [0,0], 300000, 0.05)
# Complete needs to be checked
# Assertion to check if expected probability of viewing a particular qubitstate is to its actual probaility
# Qubitchoice is an optional argument that if passed will only compare the expected probabilty with the probability of observing
# that particular qubit (first or second) in the desired qubitState for the qc
def assertProbability(qc, qubitState :str, expectedProbability, qubitChoice=None):
sv = Statevector.from_label("00") # Creates a statevector with states 00
evl = sv.evolve(qc) # Passes the qc into the statevector in order to evolve
# Performs a check to observe if qubitChoice has been passed or not
if(qubitChoice!=None):
probs = evl.probabilities_dict([qubitChoice]) # If passed we will get the probabilities for that particular qubit
else:
probs = evl.probabilities_dict()
probsRound = {key: round(values,2) for key,values in probs.items()} # rounds off the probabilities in the dictionary
# Loops over the prob dictionary with rounded values
for key,value in probsRound.items():
if(key==qubitState):
if(value==expectedProbability):
print("Expected Probability present")
return True
else:
raise(AssertionError("Probability not present"))
raise(AssertionError("Probability not present or Desired state has no probability"))
qc = QuantumCircuit(2)
qc.h(0)
assertProbability(qc,"0",1,1)
print("------")
assertProbability(qc,"00",0.5)
circuit = QuantumCircuit(2)
circuit.initialize([1, 0], 0)
circuit.initialize(random_statevector(2).data, 1)
print("another",circuit.global_phase)
# print(circuit)
qasm_circuit = circuit.decompose().decompose().decompose()
print(type(qasm_circuit))
print("here",qasm_circuit._global_phase)
qc = QuantumCircuit(2)
initial_state = qc.initialize(random_statevector(2).data, 0)
initial_state1 = qc.initialize(random_statevector(2).data, 1)
# print(qc)
qasm_circuit1 = qc.decompose().decompose().decompose()
print(qasm_circuit1)
import random
def generateQC(theta_range,phi_range,lam_range):
# make sure theta phi and lamba are all in lists
# make sure they have size of 2
lists = [theta_range,phi_range,lam_range]
for i in lists:
if (not isinstance(i, list)):
i = [i]
if len(i)!=2:
raise ValueError("Range has to be two")
qc = QuantumCircuit(2)
for i in range(2):
theta=random.randint(theta_range[0],theta_range[1])
phi=random.randint(phi_range[0],phi_range[1])
lam=random.randint(lam_range[0],lam_range[1])
qc.u(theta,phi,lam,i)
return qc
# In Qsharp qubit initialisation was perfromed as such:
# { q : Qubit (36 ,72) (0 ,360) };
first = generateQC([36,72],[0,360],[0,360])
# QUBITS TO ASSERT PROBLEM HOW WILL I KNOW IF QUBIT IS 0 OR 1
print(first)
class property:
def __init__(self,backend,theta_range,phi_range,lam_range,which_assertion,measurements_to_make,alpha,experiments,noOfTests):
self.backend = backend
self.theta_range = theta_range
self.phi_range = phi_range
self.lam_range = lam_range
# self.predicate = predicate
self.which_assertion = which_assertion
self.measurements_to_make = measurements_to_make
self.alpha = alpha
self.experiments = experiments
self.noOfTests = noOfTests
def generateQC(self):
# make sure theta phi and lamba are all in lists
# make sure they have size of 2
lists = [self.theta_range,self.phi_range,self.lam_range]
for i in lists:
if (not isinstance(i, list)):
i = [i]
if len(i)!=2:
raise ValueError("Range has to be two")
qc = QuantumCircuit(2)
for i in range(2):
theta=random.randint(self.theta_range[0],self.theta_range[1])
phi=random.randint(self.phi_range[0],self.phi_range[1])
lam=random.randint(self.lam_range[0],self.lam_range[1])
qc.u(theta,phi,lam,i)
return qc
def run(self, qcToTest):
# assertEntangled(backend,qc3,[1,0],2000,0.05)
# assertEqual(backend, qc, [0,1], 300000, 3, 0.05)
# qcToTest = generateQC(theta_range)
# if(which_assertion=assertEntangled)
return self.which_assertion(backend,qcToTest,[0,1], self.measurements_to_make,self.experiments,self.alpha)
# number_of_test_cases = 7
# number_of_measurements = 2000
# number_of_experiments = 20
# for tc in range(testcases):, testcases
# qc = new qc()
# for e in range(experiment):, experiments
# AssertEntangles(qc), measurements done here
def check(self):
for j in range(self.noOfTests):
qcToTest = generateQC(self.theta_range,self.phi_range,self.lam_range)
initial_state = qcToTest.copy()
# final_state =
# print(qcToTest)
# for i in range(self.experiments):
try:
self.run(qcToTest)
except AssertionError:
raise AssertionError("Property failed after run", self.noOfTests * j)
pbt = property(backend,[36,72],[0,360],[0,360],assertEntangled,2000,0.05,10,3)
pbt.check()
pbt2 = property(backend,[36,72],[0,360],[0,360],assertEqual,2000,0.05,10,3)
pbt2.check()
#pass created qubits into whichever function
#then pass that into assertions
class property:
def __init__(self,backend,theta_range,phi_range,lam_range,which_assertion,measurements_to_make,alpha,experiments,noOfTests):
self.backend = backend
self.theta_range = theta_range
self.phi_range = phi_range
self.lam_range = lam_range
# self.predicate = predicate
self.which_assertion = which_assertion
self.measurements_to_make = measurements_to_make
self.alpha = alpha
self.experiments = experiments
self.noOfTests = noOfTests
def generateQC(self):
# make sure theta phi and lamba are all in lists
# make sure they have size of 2
lists = [self.theta_range,self.phi_range,self.lam_range]
for i in lists:
if (not isinstance(i, list)):
i = [i]
if len(i)!=2:
raise ValueError("Range has to be two")
qc = QuantumCircuit(2)
for i in range(2):
theta=random.randint(self.theta_range[0],self.theta_range[1])
phi=random.randint(self.phi_range[0],self.phi_range[1])
lam=random.randint(self.lam_range[0],self.lam_range[1])
qc.u(theta,phi,lam,i)
return qc
def run(self, qcToTest):
# assertEntangled(backend,qc3,[1,0],2000,0.05)
# assertEqual(backend, qc, [0,1], 300000, 3, 0.05)
# qcToTest = generateQC(theta_range)
# if(which_assertion=assertEntangled)
return self.which_assertion(backend,qcToTest,[0,0], self.measurements_to_make,self.experiments,self.alpha)
# number_of_test_cases = 7
# number_of_measurements = 2000
# number_of_experiments = 20
# for tc in range(testcases):, testcases
# qc = new qc()
# for e in range(experiment):, experiments
# AssertEntangles(qc), measurements done here
def check(self):
for j in range(self.noOfTests):
qcToTest = generateQC(self.theta_range,self.phi_range,self.lam_range)
# print(qcToTest)
# for i in range(self.experiments):
try:
self.run(qcToTest)
except AssertionError:
raise AssertionError("Property failed after run", self.noOfTests * j)
pbt = property(backend,[36,72],[0,360],[0,360],assertEntangled,2000,0.05,10,3)
pbt.check()
pbt2 = property(backend,[36,72],[0,360],[0,360],assertEqual,2000,0.05,10,3)
pbt2.check()
#pass created qubits into whichever function
#then pass that into assertions
def assertEntangled(backend,qc,qubits_to_assert,measurements_to_make,experiments,alpha = 0.05):
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
## classical register must be of same length as amount of qubits to assert
## if there is no classical register add them according to length of qubit list
if (qc.num_clbits == 0):
qc.add_register(ClassicalRegister(len(qubits_to_assert)))
elif (len(qubits_to_assert) != 2):
raise ValueError("QuantumCircuit classical register must be of length 2")
q1=[]
q2=[]
for i in range (experiments):
zQuantumCircuit = measure_z(qc, qubits_to_assert)
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
zMemory = zJob.result().get_memory()
qubitDict = dict.fromkeys(['qubit1','qubit2'])
qubitDict = {'qubit1': qubits_to_assert[0],'qubit2':qubits_to_assert[1]}
# print("new dict", qubitDict)
classicalQubitIndex = 1
for qubit in qubitDict.keys():
# print("this qubit:",qubit)
for measurement in zMemory:
# print("this measurement", measurement)
if (measurement[2-classicalQubitIndex] == '0'):
# print("measure: ",measurement[2-classicalQubitIndex],"also: qubittoassert0",qubits_to_assert[0],"and qubittoassert1: ",qubits_to_assert[1])
if(qubit=='qubit1'):
q1.append(measurement[2-classicalQubitIndex])
# print("Added to q1 for measure0:", measurement[2-classicalQubitIndex])
else:
q2.append(measurement[2-classicalQubitIndex])
# print("Added to q2 for measure0:", measurement[2-classicalQubitIndex])
else:
# print("measureOTHER: ",measurement[2-classicalQubitIndex], "also: qubittoassert0",qubits_to_assert[0],"and qubittoassert1: ",qubits_to_assert[1])
if(qubit=='qubit1'):
q1.append(measurement[2-classicalQubitIndex])
# print("Added to q1 for measure1:", measurement[2-classicalQubitIndex])
else:
q2.append(measurement[2-classicalQubitIndex])
# print("Added to q2 for measure1:", measurement[2-classicalQubitIndex])
classicalQubitIndex+=1
measDict = dict.fromkeys(['qubit1','qubit2'])
measDict = {'qubit1': q1,'qubit2':q2}
measDf1 = pd.DataFrame.from_dict(measDict,orient='index')
measDf12=measDf1.transpose()
print(measDf12)
# print(measDf12)
ct = pd.crosstab(measDf12.qubit1,measDf12.qubit2)
chiVal, pVal, dOfFreedom, exp = chi2_contingency(ct)
print("chi square value: ",chiVal,"p value: ",pVal,"expected values: ",exp)
if(pVal>alpha):
raise(AssertionError("states are not entangled"))
else:
print("states are entangled")
backend = Aer.get_backend('aer_simulator')
qr = QuantumRegister(2)
cr=ClassicalRegister(2)
qc3 = QuantumCircuit(qr,cr)
# qc3.x(1)
qc3.x(0)
qc3.h(0)
qc3.cnot(0,1)
# qc3.rx(np.pi/2,qr[0])
qc3.p(10*2*math.pi/100, 0)
# qc3.p(0.5*2*math.pi/100, 1)
# print(qc3)
qc4 = QuantumCircuit(2)
qc4.u(64,343,57,0)
qc4.u(65,43,226,1)
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.x(1)
circ = qft_rotations(qc1,2)
print(circ)
assertEntangled(backend,circ,[1,1],2000,1,0.05)
# Completed but more testing required
## assert that qubits are equal
def assertEqual(backend, quantumCircuit, qubits_to_assert, measurements_to_make, experiments, alpha):
## needs to make at least 2 measurements, one for x axis, one for y axis
## realistically we need more for any statistical significance
if (measurements_to_make < 2):
raise ValueError("Must make at least 2 measurements")
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
q1Vals = []
q2Vals = []
# Get Df is a function I made to return a dataframe containing measurements for each each qubit across all axes and I use 5 such different measurements for my dataset
for i in range(experiments):
resDf1 = getDf(quantumCircuit,qubits_to_assert,measurements_to_make,backend)
q1Vals.extend([resDf1.at[0,'1'],resDf1.at[0,'-'],resDf1.at[0,'-i']])
q2Vals.extend([resDf1.at[1,'1'],resDf1.at[1,'-'],resDf1.at[1,'-i']])
print(q1Vals)
print(q2Vals)
tTest, pValue = ttest_ind(q1Vals, q2Vals, alternative = 'two-sided') # Apply t test
print("stat: ",tTest, "pValue: ", pValue)
if pValue > alpha:
print("The two qubits are equal (fail to reject null hypothesis) ")
else:
print("There is a significant difference between the two qubits (reject null hypothesis)")
qc = QuantumCircuit(2)
backend = Aer.get_backend('aer_simulator')
# qc.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], qc.qubits)
qc.h(0)
# qc.cnot(0,1)
qc.x(1)
# qc.p(0.5*2*math.pi/100, 1)
# qc.h(1)
# qc.p(10*2*math.pi/100, 0)
# qc.p(20*2*math.pi/100, 1)
# assertEqual(backend, qc, [0,1], 300000, 3, 0.05)
# assertEqual(backend, qc, [0,0], 300000, 0.05)
qc1 = QuantumCircuit(2)
# qc1.x(0)
qc1.h(0)
qc1.cnot(0,1)
# circ = qft_rotations(qc1,2)
assertEqual(backend, qc, [0,1], 300000, 10, 0.05)
# assertEntangled(backend,circ,[1,0],3000,10,0.05)
# Completed but more testing required
## assert that qubits are equal
def assertEqual(backend, quantumCircuit, qubits_to_assert, measurements_to_make, experiments, alpha):
## needs to make at least 2 measurements, one for x axis, one for y axis
## realistically we need more for any statistical significance
if (measurements_to_make < 2):
raise ValueError("Must make at least 2 measurements")
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
q1Vals = []
q2Vals = []
# Get Df is a function I made to return a dataframe containing measurements for each each qubit across all axes and I use 5 such different measurements for my dataset
for i in range(experiments):
# resDf1 = getDf(quantumCircuit,qubits_to_assert,measurements_to_make,backend)
# q1Vals.extend([resDf1.at[0,'1'],resDf1.at[0,'-'],resDf1.at[0,'-i']])
# q2Vals.extend([resDf1.at[1,'1'],resDf1.at[1,'-'],resDf1.at[1,'-i']])
zQuantumCircuit = measure_z(quantumCircuit,qubits_to_assert)
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
# zMemory = zJob.result().get_memory()
zCounts = zJob.result().get_counts()
# print(i,zCounts)
# for k,v in zCounts.items():
# print(i,k,v)
# if(i==0):
# q1Vals.extend([v])
# else:
# q2Vals.extend([v])
resDf = pd.DataFrame(columns=['0','1'])
classical_qubit_index = 1
for qubit in qubits_to_assert:
zero_amount, one_amount = 0,0
for experiment in zCounts:
if (experiment[2-classical_qubit_index] == '0'):
zero_amount += zCounts[experiment]
else:
one_amount += zCounts[experiment]
# print(i,"0:",zero_amount)
# print(i,"1:",one_amount)
df = {'0':zero_amount, '1':one_amount}
resDf = resDf.append(df, ignore_index = True)
classical_qubit_index+=1
resDf['0'] = resDf['0'].astype(int)
resDf['1'] = resDf['1'].astype(int)
q1Vals.extend([resDf.at[0,'1']/measurements_to_make])
q2Vals.extend([resDf.at[1,'1']/measurements_to_make])
# print("here",q1Vals)
# print("here",q2Vals)
equalTest(q1Vals,q2Vals,alpha)
def equalTest(q1Vals,q2Vals,alpha):
# q1Vals.extend([resDf.at[0,'1'],resDf.at[0,'0']])
# q2Vals.extend([resDf1.at[1,'1'],resDf1.at[1,'-'],resDf1.at[1,'-i']])
# q2Vals.extend([resDf.at[1,'1'],resDf.at[1,'0']])
print("q1",q1Vals)
print("q2",q2Vals)
tTest, pValue = ttest_ind(q1Vals, q2Vals, alternative = 'two-sided') # Apply t test
print("stat: ",tTest, "pValue: ", pValue)
if pValue > alpha:
print("The two qubits are equal (fail to reject null hypothesis) ")
else:
print("There is a significant difference between the two qubits (reject null hypothesis)")
qc = QuantumCircuit(2,2)
backend = Aer.get_backend('aer_simulator')
# qc.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], qc.qubits)
qc.h(0)
qc.x(1)
qc.h(1)
# qc.cnot(0,1)
# qc.x(1)
qc.p(0.5*2*math.pi/100, 1)
# qc.h(1)
# qc.p(10*2*math.pi/100, 0)
# qc.p(20*2*math.pi/100, 1)
# assertEqual(backend, qc, [0,1], 300000, 3, 0.05)
# assertEqual(backend, qc, [0,0], 300000, 0.05)
qc1 = QuantumCircuit(2)
# qc1.x(0)
qc1.x(0)
qc1.cnot(0,1)
# circ = qft_rotations(qc1,2)
assertEqual(backend, qc, [0,1], 300000, 30, 0.05)
# assertEntangled(backend,circ,[1,0],3000,10,0.05)
|
https://github.com/Manish-Sudhir/QiskitCheck
|
Manish-Sudhir
|
import warnings
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, Aer, transpile, IBMQ, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_bloch_multivector, plot_histogram, array_to_latex
warnings.filterwarnings("ignore", category=DeprecationWarning)
import numpy as np
import pandas as pd
import math
from math import sqrt
from scipy.stats import chi2_contingency, ttest_ind, chisquare, ttest_rel, normaltest
from statsmodels.stats.proportion import proportions_ztest
from statsmodels.stats.weightstats import ztest
pi = np.pi
def flip_endian(dict):
newdict = {}
for key in list(dict):
newdict[key[::-1]] = dict.pop(key)
return newdict
def set_measure_x(circuit, n):
for num in range(n):
circuit.h(num)
def set_measure_y(circuit, n):
for num in range(n):
circuit.sdg(num)
circuit.h(num)
def qft_rotations(circuit, n):
#if qubit amount is 0, then do nothing and return
if n == 0:
#set it to measure the x axis
set_measure_x(qc, 2)
qc.measure_all()
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
return qft_rotations(circuit, n)
backend = Aer.get_backend('aer_simulator')
qc = QuantumCircuit(2)
qc.x(0)
circ = qft_rotations(qc,2)#call the recursive qft method
print(circ)
#set it to measure the x axis
set_measure_x(qc, 2)
job = execute(qc, backend, shots=100000)#run the circuit 1000000 times
print(flip_endian(job.result().get_counts()))#return the result counts
def measure_z(circuit, qubit_indexes):
cBitIndex = 0
for index in qubit_indexes:
# print(index)
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def measure_x(circuit, qubitIndexes):
cBitIndex = 0
for index in qubitIndexes:
circuit.h(index)
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def measure_y(circuit, qubit_indexes):
cBitIndex = 0
for index in qubit_indexes:
circuit.sdg(index)
circuit.h(index)
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
qc1 = QuantumCircuit(2,2)
qc1.h(0)
qc1.cnot(0,1)
qc1.measure(0,0)
qc1.measure(1,1)
# print(qc1)
qc2 = QuantumCircuit(2,2)
qc2.x(0)
qc2.h(0)
qc2.cnot(0,1)
# qc2.swap(0,1)
qc2.measure(0,1)
qc2.measure(1,0)
# qc2.measure_all()
# print(qc2)
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute([qc1, qc2], backend_sim, shots=10)
result_sim = job_sim.result()
counts1 = result_sim.get_memory(qc1,memory=True)
counts2 = result_sim.get_memory(qc2,memory=True)
print(counts1, counts2)
qc3 = QuantumCircuit(2,2)
qc3.h(1)
qc3.h(0)
qubits_to_assert = [0,1]
yQuantumCircuit = measure_y(qc3.copy(), qubits_to_assert)
xQuantumCircuit = measure_x(qc3.copy(), qubits_to_assert)
zQuantumCircuit = measure_z(qc3, qubits_to_assert)
yJob = execute(yQuantumCircuit, backend, shots=20, memory=True)
yMemory = yJob.result().get_memory()
yCounts = yJob.result().get_counts()
print(type(yMemory))
def qft_dagger(qc, n):
for j in range(n):
for m in range(j):
qc.cp(math.pi/float(2**(j-m)), m, j)
qc.h(j)
return qc
q = QuantumCircuit(2)
# qc.x(0)
q.x(0)
q.x(1)
q.measure_all()
print(q)
qft_rotations(q,2)
q2 = qft_dagger(q,2)# #call the recursive qft method
backend = Aer.get_backend('aer_simulator')
job = execute([q,q2], backend, shots=1000000)#run the circuit 1000000 times
counts = job.result().get_counts(q)
counts2 = job.result().get_counts(q2)
print(counts)#return the result counts
print(counts2)
def getDf(qc,qubits_to_assert,measurements_to_make,backend):
## classical register must be of same length as amount of qubits to assert
## if there is no classical register add them according to length of qubit list
if (qc.num_clbits == 0):
qc.add_register(ClassicalRegister(len(qubits_to_assert)))
elif (len(qubits_to_assert) != 2):
raise ValueError("QuantumCircuit classical register must be of length 2")
## divide measurements to make by 3 as we need to run measurements twice, one for x and one for y
measurements_to_make = measurements_to_make // 3
yQuantumCircuit = measure_y(qc.copy(), qubits_to_assert)
xQuantumCircuit = measure_x(qc.copy(), qubits_to_assert)
zQuantumCircuit = measure_z(qc, qubits_to_assert)
yJob = execute(yQuantumCircuit, backend, shots=measurements_to_make, memory=True)
yMemory = yJob.result().get_memory()
yCounts = yJob.result().get_counts()
# print("yCounts",yCounts)
## get x axis results
xJob = execute(xQuantumCircuit, backend, shots=measurements_to_make, memory=True)
xMemory = xJob.result().get_memory()
xCounts = xJob.result().get_counts()
# print("xCounts",xCounts)
## get z axis results
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
zMemory = zJob.result().get_memory()
zCounts = zJob.result().get_counts()
# print("zCounts",zCounts)
resDf = pd.DataFrame(columns=['0','1','+','i','-','-i'])
# resDf = pd.DataFrame(columns=['zAxis','xAxis','yAxis'])
classical_qubit_index = 1
for qubit in qubits_to_assert:
zero_amount, one_amount, plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0,0,0
for experiment in xCounts:
if (experiment[2-classical_qubit_index] == '0'):
plus_amount += xCounts[experiment]
else:
minus_amount += xCounts[experiment]
for experiment in yCounts:
if (experiment[2-classical_qubit_index] == '0'):
i_amount += yCounts[experiment]
else:
minus_i_amount += yCounts[experiment]
for experiment in zCounts:
if (experiment[2-classical_qubit_index] == '0'):
zero_amount += zCounts[experiment]
else:
one_amount += zCounts[experiment]
df = {'0':zero_amount, '1':one_amount,
'+':plus_amount, 'i':i_amount,
'-':minus_amount,'-i':minus_i_amount}
# df = {'zAxis':zero_amount+one_amount,
# 'xAxis':plus_amount+ minus_amount,
# 'yAxis':i_amount+minus_i_amount}
resDf = resDf.append(df, ignore_index = True)
classical_qubit_index+=1
resDf['+'] = resDf['+'].astype(int)
resDf['i'] = resDf['i'].astype(int)
resDf['-'] = resDf['-'].astype(int)
resDf['-i'] = resDf['-i'].astype(int)
resDf['0'] = resDf['0'].astype(int)
resDf['1'] = resDf['1'].astype(int)
# resDf['zAxis'] = resDf['zAxis'].astype(int)
# resDf['xAxis'] = resDf['xAxis'].astype(int)
# resDf['yAxis'] = resDf['yAxis'].astype(int)
return resDf
# Completed but more testing required
## assert that qubits are equal
def assertEqual(backend, quantumCircuit1,quantumCircuit2, qubits_to_assert, measurements_to_make, experiments, alpha):
## needs to make at least 2 measurements, one for x axis, one for y axis
## realistically we need more for any statistical significance
if (measurements_to_make < 2):
raise ValueError("Must make at least 2 measurements")
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
measqc1 = measure_z(quantumCircuit1.copy(),qubits_to_assert)
measqc2 = measure_z(quantumCircuit2.copy(),qubits_to_assert)
# quantumCircuit1.measure()
# quantumCircuit2.measure()
job_sim = execute([measqc1, measqc2], backend, shots=100)
result_sim = job_sim.result()
counts1 = result_sim.get_counts(measqc1)
print("c1:", counts1)
counts2 = result_sim.get_counts(measqc2)
print("c2:", counts2)
dict3={k:[v] for k,v in counts2.items()}
for k,v in counts1.items():
dict3[k]= dict3[k] + [v] if k in dict3 else [v]
print(dict3)
# measurements=[]
for k,v in dict3.items():
if len(v) <= 1:
raise(AssertionError("Measurements are not in the same states"))
# measurements.append(v)
q1Vals = []
q2Vals = []
# Get Df is a function I made to return a dataframe containing measurements for each each qubit across all axes and I use 5 such different measurements for my dataset
for i in range(experiments):
resDf1 = getDf(quantumCircuit1,qubits_to_assert,measurements_to_make,backend)
# print("resdf 1:")
# print(resDf1)
q1Vals.extend(resDf1['1'].tolist()+resDf1['-'].tolist()+resDf1['-i'].tolist())
resDf2 = getDf(quantumCircuit2,qubits_to_assert,measurements_to_make,backend)
# print("resdf 2: ")
# print(resDf2)
q2Vals.extend(resDf2['1'].tolist()+resDf2['-'].tolist()+resDf2['-i'].tolist())
# resDf1['1']
# print(resDf1['1'].tolist())
# q2Vals.extend([resDf1.at[1,'1'],resDf1.at[1,'-'],resDf1.at[1,'-i']])
# zStat_z, zPvalue = proportions_ztest(count=[resDf1['1'][0],resDf2['1'][1]], nobs=[measurements_to_make, measurements_to_make], alternative='two-sided')
print("q1: ",q1Vals)
print("q2: ",q2Vals)
tTest, pValue = ttest_ind(q1Vals, q2Vals, alternative = 'two-sided') # Apply t test
# zStat_z, zPvalue = proportions_ztest(count=[q1Vals,q2Vals], nobs=[measurements_to_make, measurements_to_make], alternative='two-sided')
print("stat: ",tTest ,"pValue: ", pValue)
if pValue > alpha:
print("The two qubits are equal (fail to reject null hypothesis) ")
else:
print("There is a significant difference between the two qubits (reject null hypothesis)")
qc = QuantumCircuit(2,2)
backend = Aer.get_backend('aer_simulator')
# qc.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], qc.qubits)
qc.x(0)
qc.h(0)
# qc.h(1)
qc.cnot(0,1)
# qc.p(0.5*2*math.pi/100, 1)
# qc.h(1)
# qc.p(10*2*math.pi/100, 0)
# qc.p(20*2*math.pi/100, 1)
qc.measure(0,0)
qc.measure(1,1)
# qc.measure_all()
qc1 = QuantumCircuit(2,2)
# qc1.x(1)
qc1.h(0)
qc1.cnot(0,1)
# qc1.measure_all()
qc1.measure(0,0)
qc1.measure(1,1)
qc3 = QuantumCircuit(2,2)
qc3.x(0)
qc3.x(1)
qc4=qft_dagger(qc3,2)
# from qiskit.quantum_info import Operator
# Op1 = Operator(qc)
# Op2 = Operator(qc1)
# if Op1.equiv(Op2):
# print("True")
# else:
# print("False")
assertEqual(backend, qc1,qc2, [0,1], 30000, 30, 0.05)
# assertEntangled(backend,circ,[1,0],3000,10,0.05)
qc1 = QuantumCircuit(2,2)
qc1.x(0)
qc1.h(0)
qc1.cnot(0,1)
# qc1.h(1)
print(qc1)
# qc1.measure_z()
qc1.measure(0,0)
qc1.measure(1,1)
# qc1.copy()
job = execute(qc1,backend,shots=10000,memory=True)
counts = job.result().get_counts()
# counts2 = job.result().get_counts(c1)
print(counts)
# zQuantumCircuit1 = measure_z(qc1, qubits_to_assert)
# zJob1 = execute(zQuantumCircuit1,backend,shots=10000,memory=True)
# zCounts1=zJob1.result().get_counts()
# print("z1", zCounts1)
# xQuantumCircuit1 = measure_x(qc1, qubits_to_assert)
# xJob1 = execute(xQuantumCircuit1,backend,shots=10000,memory=True)
# xCounts1=xJob1.result().get_counts()
# print("x1", xCounts1)
# yQuantumCircuit1 = measure_y(qc1, qubits_to_assert)
# yJob1 = execute(yQuantumCircuit1,backend,shots=10000,memory=True)
# yCounts1=yJob1.result().get_counts()
# print("y1", yCounts1)
qc2 = QuantumCircuit(2,2)
qc2.x(1)
qc2.h(0)
qc2.cnot(1,0)
print(qc2)
# qc2.h(0)
qc2.measure(0,0)
qc2.measure(1,1)
job2 = execute(qc2,backend,shots=10000,memort=True)
counts2 = job2.result().get_counts()
print(counts2)
# zQuantumCircuit2 = measure_z(qc2, qubits_to_assert)
# zJob2 = execute(zQuantumCircuit2,backend,shots=10000,memory=True)
# zCounts2=zJob2.result().get_counts()
# print("z2",zCounts2)
# xQuantumCircuit2 = measure_x(qc2, qubits_to_assert)
# xJob2 = execute(xQuantumCircuit2,backend,shots=10000,memory=True)
# xCounts2=xJob2.result().get_counts()
# print("x2", xCounts2)
# yQuantumCircuit2 = measure_y(qc2, qubits_to_assert)
# yJob2 = execute(yQuantumCircuit2,backend,shots=10000,memory=True)
# yCounts2=yJob2.result().get_counts()
# print("y2", yCounts2)
# tempD = { k: [counts[k],counts2[k]] for k in counts}
# print(tempD)
# from collections import defaultdict
# dd = defaultdict(list)
# dics=[counts,counts2]
# for dic in dics:
# for key,val in dic.items():
# dd[key].append(val)
# print(dd)
dict3={k:[v] for k,v in counts2.items()}
for k,v in counts.items():
dict3[k]= dict3[k] + [v] if k in dict3 else [v]
print(dict3)
measurements=[]
for k,v in dict3.items():
if len(v) <= 1:
raise(AssertionError("There exists key(s) with just 1 measurement"))
measurements.append(v)
meas1 = measurements[0]
meas2 = measurements[1]
size = [10000,10000]
# testStat,pValue1 = proportions_ztest(meas1,size,alternative='two-sided')
# testStat,pValue2 = proportions_ztest(meas2,size,alternative='two-sided')
zStat_z, pValue1 = proportions_ztest(count=[meas1[0],meas1[1]],nobs=size, alternative='two-sided')
zStat_z, pValue2 = proportions_ztest(count=[meas2[0],meas2[1]],nobs=size, alternative='two-sided')
print(pValue1)
print(pValue2)
if pValue1 > 0.05 and pValue2 > 0.05:
print("The two qubits are equal (fail to reject null hypothesis) ")
elif(pValue1<=0.05):
print("There is a significant difference between the two qubits (reject null hypothesis)")
elif (pValue2 <= 0.05):
print("There is a significant difference between the two qubits (reject null hypothesis)")
# qcList = [qc1,qc2]
# index=0
# for i in qcList:
# index+=1
# measurements_to_make=30000
# qubits_to_assert=[0,1]
# measurements_to_make = measurements_to_make // 3
# yQuantumCircuit = measure_y(i.copy(), qubits_to_assert)
# xQuantumCircuit = measure_x(i.copy(), qubits_to_assert)
# zQuantumCircuit = measure_z(i, qubits_to_assert)
# yJob = execute(yQuantumCircuit, backend, shots=measurements_to_make, memory=True)
# yMemory = yJob.result().get_memory()
# yCounts = yJob.result().get_counts()
# print("y counts for", index, yCounts)
# ## get x axis results
# xJob = execute(xQuantumCircuit, backend, shots=measurements_to_make, memory=True)
# xMemory = xJob.result().get_memory()
# xCounts = xJob.result().get_counts()
# print("x counts for", index,xCounts)
# ## get z axis results
# zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
# zMemory = zJob.result().get_memory()
# zCounts = zJob.result().get_counts()
# print("z counts for", index,zCounts)
# for i in range(5):
# job_sim = execute([qc, qc1], backend_sim, shots=10000)
# result_sim = job_sim.result()
# counts1 = result_sim.get_counts(qc)
# # print(counts1)
# yo.extend(list(counts1.values()))
# # print(yo)
# counts2 = result_sim.get_counts(qc1)
# print(counts2)
# yo2.extend(list(counts2.values()))
# # print(yo2)
# # print(counts1, counts2)
qc1 = QuantumCircuit(2,2)
qc1.x(0)
qc1.h(0)
qc1.cnot(0,1)
# qc1.h(1)
print(qc1)
qc1.measure(0,0)
qc1.measure(1,1)
qc2 = QuantumCircuit(2,2)
# qc2.x(1)
qc2.h(0)
qc2.cnot(0,1)
print(qc2)
# qc2.h(0)
qc2.measure(0,0)
qc2.measure(1,1)
yo=[]
yo2=[]
for i in range(2):
job_sim = execute([qc1.copy(), qc2.copy()], backend, shots=10000)
result_sim = job_sim.result()
counts1 = result_sim.get_counts(qc1)
print(i,"c1:", counts1)
counts2 = result_sim.get_counts(qc2)
print(i,"c2:",counts2)
dict3={k:[v] for k,v in counts2.items()}
for k,v in counts1.items():
dict3[k]= dict3[k] + [v] if k in dict3 else [v]
print(dict3)
measurements=[]
for k,v in dict3.items():
if len(v) <= 1:
raise(AssertionError("There exists key(s) with just 1 measurement"))
measurements.append(v)
# print("meas",measurements)
resDf1 = getDf(qc1,[0,1],30000,backend)
print("resdf1:")
print(resDf1)
resDf2 = getDf(qc2,[0,1],30000,backend)
print("resdf2:")
print(resDf2)
yo.extend(resDf1['1'].tolist()+resDf1['-'].tolist()+resDf1['-i'].tolist())
yo2.extend(resDf2['1'].tolist()+resDf2['-'].tolist()+resDf2['-i'].tolist())
print("yo:",yo)
print("yo2:",yo2)
tTest, pValue = ttest_ind(yo, yo2, alternative = 'two-sided') # Apply t test
print("stat: ",tTest, "pValue: ", pValue)
if pValue > 0.05:
print("The two qubits are equal (fail to reject null hypothesis) ")
else:
print("There is a significant difference between the two qubits (reject null hypothesis)")
from qiskit.aqua.components.uncertainty_models import NormalDistribution
q = QuantumRegister(2)
c= ClassicalRegister(2)
qc2 = QuantumCircuit(q,c)
qc2.x(0)
qc2.h(0)
# qc2.h(0)
qc2.cnot(0,1)
normal = NormalDistribution(num_target_qubits=2,mu=0,sigma=1,low=-1,high=1)
normal.build(qc2,q)
print(qc2)
# qc2.h(0)
qc2.measure(0,0)
qc2.measure(1,1)
q1=[]
q2=[]
resDf2 = getDf(qc2,[0,1],10000,backend)
print("resdf2:")
print(resDf2)
job = execute(qc2,backend,shots=10000)
result = job.result()
counts1 = result.get_counts()
q1.extend(counts1.values())
print(q1)
# q1 = np.array([488, 488, 520, 508, 509, 521, 495, 495, 519, 529, 497, 522, 472, 472, 501, 509, 511, 480, 516, 516, 491, 513, 487, 493])
# q2 = np.array([498, 502, 475, 477, 497, 524, 492, 508, 511, 490, 533, 491, 482, 518, 500, 513, 506, 515, 484, 516, 488, 503, 499, 497])
# q1= np.array([4897, 4897, 4992, 4998, 4940, 5092, 5014, 5014, 4939, 5047, 4970, 4938, 5015, 5015, 4962, 4956, 5057, 4993, 5086, 5086, 4961, 5069, 4939, 4979, 4984, 4984, 4943, 4965, 5010, 4956])
# q2= np.array([5098, 10000, 5075, 5044, 5087, 5081, 5013, 10000, 5011, 4948, 5042, 4944, 5043, 10000, 5002, 4980, 4991, 5015, 5003, 10000, 4933, 4961, 5037, 5024, 4997, 10000, 5044, 5019, 4989, 4966])
# q3 = np.array([483, 483, 508, 531, 469, 501, 517, 517, 492, 469, 531, 499, 492, 492, 486, 528, 505, 505, 508, 508, 514, 472, 495, 495, 501, 501, 498, 486, 522, 475, 499, 499, 502, 514, 478, 525, 513, 513, 508, 529, 487, 524, 487, 487, 492, 471, 513, 476])
# q4 = np.array([504, 496, 509, 484, 519, 501, 496, 504, 491, 516, 481, 499, 521, 479, 481, 507, 483, 507, 479, 521, 519, 493, 517, 493, 482, 518, 523, 506, 486, 502, 518, 482, 477, 494, 514, 498, 515, 485, 486, 468, 497, 488, 485, 515, 514, 532, 503, 512])
# q5 = np.array([5062, 5062, 4989, 4967, 4969, 5024, 4938, 4938, 5011, 5033, 5031, 4976, 5016, 5016, 4956, 4998, 5083, 5006, 4984, 4984, 5044, 5002, 4917, 4994, 4992, 4992, 4987, 4988, 4995, 5073, 5008, 5008, 5013, 5012, 5005, 4927, 5014, 5014, 4982, 5093, 5085, 4915, 4986, 4986, 5018, 4907, 4915, 5085, 5092, 5092, 5003, 4923, 5081, 5014, 4908, 4908, 4997, 5077, 4919, 4986])
# q6 = np.array([4994, 5006, 4907, 5012, 4982, 4988, 5006, 4994, 5093, 4988, 5018, 5012, 4988, 5012, 4988, 4965, 4962, 5033, 5012, 4988, 5012, 5035, 5038, 4967, 4979, 5021, 4976, 4978, 5042, 4976, 5021, 4979, 5024, 5022, 4958, 5024, 4801, 5199, 4953, 4971, 4968, 5083, 5199, 4801, 5047, 5029, 5032, 4917, 4961, 5039, 4986, 5018, 4961, 5030, 5039, 4961, 5014, 4982, 5039, 4970])
# #both normal
q1=np.array([4902, 5098, 4908, 5042, 5013, 4993, 5098, 4902, 5092, 4958, 4987, 5007, 5078, 4922, 4956, 4979, 4984, 4890, 4922, 5078, 5044, 5021, 5016, 5110, 4912, 5088, 5023, 5068, 5101, 5039, 5088, 4912, 4977, 4932, 4899, 4961, 5028, 4972, 5046, 5020, 5085, 4969, 4972, 5028, 4954, 4980, 4915, 5031, 5015, 4985, 4996, 4939, 5003, 5002, 4985, 5015, 5004, 5061, 4997, 4998])
q2=np.array([5011, 4989, 4981, 5002, 4984, 5010, 4989, 5011, 5019, 4998, 5016, 4990, 5023, 4977, 4960, 5011, 4944, 4914, 4977, 5023, 5040, 4989, 5056, 5086, 4944, 5056, 4946, 5034, 4984, 5071, 5056, 4944, 5054, 4966, 5016, 4929, 4983, 5017, 5108, 5099, 5097, 5112, 5017, 4983, 4892, 4901, 4903, 4888, 4995, 5005, 4976, 5001, 4909, 5075, 5005, 4995, 5024, 4999, 5091, 4925])
# q9= np.array([5064, 5064, 4968, 5067, 5031, 5055, 4936, 4936, 5032, 4933, 4969, 4945, 4914, 4914, 5007, 5066, 5053, 5103, 5086, 5086, 4993, 4934, 4947, 4897, 4970, 4970, 5012, 5057, 4987, 5032, 5030, 5030, 4988, 4943, 5013, 4968, 5039, 5039, 4987, 5004, 4993, 5050, 4961, 4961, 5013, 4996, 5007, 4950, 5084, 5084, 5012, 5035, 4972, 4979, 4916, 4916, 4988, 4965, 5028, 5021])
# q10= np.array([4967, 10000, 4950, 4979, 4892, 4925, 5033, 0, 5050, 5021, 5108, 5075, 4953, 10000, 5069, 4994, 5009, 4912, 5047, 0, 4931, 5006, 4991, 5088, 5004, 10000, 5087, 4976, 4996, 4976, 4996, 0, 4913, 5024, 5004, 5024, 4995, 10000, 5054, 4979, 4950, 4984, 5005, 0, 4946, 5021, 5050, 5016, 5013, 10000, 4956, 4991, 5071, 5011, 4987, 0, 5044, 5009, 4929, 4989])
# q11=np.array([4958, 4958, 5037, 5058, 4987, 5007, 5050, 5050, 4975, 4978, 5006, 5026, 4940, 4940, 5047, 4957, 4970, 4964, 5069, 5069, 4977, 5057, 4919, 4960, 5021, 5021, 5030, 4942, 4917, 4971])
resDf=pd.DataFrame(columns=['q1','q2'])
# df1=pd.DataFrame(columns=['q1'])
df1={'q1':q3,'q2':q4}
# df2=pd.DataFrame(columns=['q2'])
# df2={'q2':[1,2,3,4,5]}
resDf = resDf.append(df1,ignore_index=True)
# resDf = resDf.append(df2,ignore_index=True)
print(resDf)
from sklearn.preprocessing import PowerTransformer
# pt = PowerTransformer(method='yeo-johnson')
# pt2 = PowerTransformer(method='yeo-johnson')
# q11=q11.reshape(-1,1)
# pt2.fit(q11)
# transf2=pt2.transform(q11)
from scipy.stats import rankdata
n=len(q1)
newQ1 = (rankdata(q1)/(n+1))*2 -1
newQ1 = np.arctanh(newQ1)
# k2,p2 = normaltest(transf2)
k2,p2 = normaltest(newQ1)
print("lol:",p2)
# interpret
alpha = 0.05
if p2 > alpha:
print('Sample looks Gaussian (fail to reject H0)')
else:
print('Sample does not look Gaussian (reject H0)')
# q10=q10.reshape(-1,1)
# pt.fit(q10)
# transf1=pt.transform(q10)
# n=len(q2)
newQ2 = (rankdata(q2)/(n+1))*2 -1
newQ2 = np.arctanh(newQ2)
k1,p1 = normaltest(newQ2)
print("lol:",p1)
if p1 > alpha:
print('Sample looks Gaussian (fail to reject H0)')
else:
print('Sample does not look Gaussian (reject H0)')
ttest,pVal = ttest_ind(newQ1,newQ2,alternative='two-sided')
print("stat: ",tTest, "pValue: ", pValue)
if pVal > 0.05:
print("The two qubits are equal (fail to reject null hypothesis) ")
else:
print("There is a significant difference between the two qubits (reject null hypothesis)")
# qc1.x(0)
|
https://github.com/Manish-Sudhir/QiskitCheck
|
Manish-Sudhir
|
from qiskit import Aer, IBMQ, transpile
from qiskit.providers.ibmq import least_busy
import numpy as np
import pandas as pd
"""
INPUTS: a string that specifies the backend to select, and a QuantumCircuit,
used for checking requirements for IBMQ
OUTPUTS: a backend to run QuantumCircuits with
"""
def select_backend(backend, qc):
if backend.lower() == "ibmq":
if IBMQ.active_account() == None:
IBMQ.load_account()
provider = IBMQ.get_provider(hub="ibm-q")
available_backends = provider.backends(filters=lambda x: x.configuration().n_qubits >= len(qc.qubits) and \
not x.configuration().selectedBackendulator and x.status().operational==True)
if len(available_backends) == 0:
raise Exception("No suitable quantum backend found")
return least_busy(available_backends)
else:
return Aer.get_backend(backend)
def measureX(qc, qubit, classicalBit):
qc.h(qubit)
qc.measure(qubit, classicalBit)
return qc
def measureY(qc, qubit, classicalBit):
qc.sdg(qubit)
qc.h(qubit)
qc.measure(qubit, classicalBit)
return qc
class TestExecutor:
"""
INPUTS:
- qc: QuantumCircuit to run the tests
- noOfExperiments: number of times the the qc will be run
- noOfMeasurements: number of times the qc will be measured after each run
- qubit0: the first qubit to compare
- qubit1: the second qubit to comapre
- classicalBit0: the bit where the first qubit will be measured in
- classicalBit1: the bit where the second qubit will be measured in
- basis: the basis of the measurement
- backend: the backend used to run the tests
OUTPUT: the data of the execution of the tests, meaning
a tuple of two numpy arrays, one for each qubit.
Each numpy array contains a list of probabilities (float between 0 and 1)
that the qubit was measured in state |0> during one trial
Each trial is measured as many times as noOfMeasurements specifies
"""
def runTestAssertEqual(self,
qc,
noOfExperiments,
noOfMeasurements,
qubit0,
qubit1,
classicalBit0,
classicalBit1,
basis,
backend):
selectedBackend = select_backend(backend, qc)
if basis.lower() == "x":
measureX(qc, qubit0, classicalBit0)
measureX(qc, qubit1, classicalBit1)
elif basis.lower() == "y":
measureY(qc, qubit0, classicalBit0)
measureY(qc, qubit1, classicalBit1)
else:
qc.measure(qubit0, classicalBit0)
qc.measure(qubit1, classicalBit1)
qc_trans = transpile(qc, backend=selectedBackend)
trialProbas0 = np.empty(noOfExperiments)
trialProbas1 = np.empty(noOfExperiments)
for trialIndex in range(noOfExperiments):
result = selectedBackend.run(qc_trans, shots=noOfMeasurements).result()
counts = result.get_counts()
nb0s_qubit0 = 0
nb0s_qubit1 = 0
for elem in counts:
if elem[::-1][classicalBit0] == '0': nb0s_qubit0 += counts[elem]
if elem[::-1][classicalBit1] == '0': nb0s_qubit1 += counts[elem]
trialProbas0[trialIndex] = nb0s_qubit0 / noOfMeasurements
trialProbas1[trialIndex] = nb0s_qubit1 / noOfMeasurements
return (trialProbas0, trialProbas1)
"""
INPUTS: same as runTestAssertEqual except the first one, which is a
list of QuantumCircuit instead of just one
OUTPUT: a list of the results of runTestsAssertEqual for each test
"""
def runTestsAssertEqual(self,
initialisedTests,
noOfExperiments,
noOfMeasurements,
qubit0,
qubit1,
classicalBit0,
classicalBit1,
basis,
backend):
return [self.runTestAssertEqual(qc, noOfExperiments, noOfMeasurements, qubit0, qubit1, classicalBit0, classicalBit1, basis, backend)
for qc in initialisedTests]
"""
INPUTS:
- qc: QuantumCircuit to run the tests
- noOfExperiments: number of times the the qc will be run
- noOfMeasurements: number of times the qc will be measured after each run
- qubit0: the first qubit to compare
- qubit1: the second qubit to comapre
- classicalBit0: the bit where the first qubit will be measured in
- classicalBit1: the bit where the second qubit will be measured in
- basis: the basis of the measurement
- backend: the backend used to run the tests
OUTPUT:
- the data of the execution of the tests,
which is a list of statevectors (aka lists)
"""
#Return for each test the recreated "statevector" of 2 bits
def runTestAssertEntangled(self,
qc,
noOfExperiments,
noOfMeasurements,
qubit0,
qubit1,
classicalBit0,
classicalBit1,
basis,
backend):
selectedBackend = select_backend(backend, qc)
if basis.lower() == "x":
measureX(qc, qubit0, classicalBit0)
measureX(qc, qubit1, classicalBit1)
elif basis.lower() == "y":
measureY(qc, qubit0, classicalBit0)
measureY(qc, qubit1, classicalBit1)
else:
qc.measure(qubit0, classicalBit0)
qc.measure(qubit1, classicalBit1)
q1=[]
q2=[]
job = execute(qc, selectedBackend, shots=noOfMeasurements, memory=True)
memory = job.result().get_memory()
qubitDict = dict.fromkeys(['qubit0','qubit1'])
qubitDict = {'qubit0': qubit0,'qubit1':qubit1}
# print("new dict", qubitDict)
classicalQubitIndex = 1
for i in range (noOfExperiments):
for qubit in qubitDict.keys():
# print("this qubit:",qubit)
for measurement in memory:
# print("this measurement", measurement)
if (measurement[2-classicalQubitIndex] == '0'):
# print("measure: ",measurement[2-classicalQubitIndex],"also: qubittoassert0",qubitList[0],"and qubittoassert1: ",qubitList[1])
if(qubit=='qubit0'):
q1.append(measurement[2-classicalQubitIndex])
# print("Added to q1 for measure0:", measurement[2-classicalQubitIndex])
else:
q2.append(measurement[2-classicalQubitIndex])
# print("Added to q2 for measure0:", measurement[2-classicalQubitIndex])
else:
# print("measureOTHER: ",measurement[2-classicalQubitIndex], "also: qubittoassert0",qubitList[0],"and qubittoassert1: ",qubitList[1])
if(qubit=='qubit0'):
q1.append(measurement[2-classicalQubitIndex])
# print("Added to q1 for measure1:", measurement[2-classicalQubitIndex])
else:
q2.append(measurement[2-classicalQubitIndex])
# print("Added to q2 for measure1:", measurement[2-classicalQubitIndex])
classicalQubitIndex+=1
measDict = dict.fromkeys(['qubit1','qubit2'])
measDict = {'qubit1': q1,'qubit2':q2}
measDf1 = pd.DataFrame.from_dict(measDict,orient='index')
measDf12=measDf1.transpose()
print(measDf12)
# print(measDf12)
ct = pd.crosstab(measDf12.qubit1,measDf12.qubit2)
return ct
"""
INPUTS:
- qc: QuantumCircuit to run the tests
- noOfExperiments: number of times the the qc will be run
- noOfMeasurements: number of times the qc will be measured after each run
- qubit0: the first qubit to compare
- qubit1: the second qubit to comapre
- classicalBit0: the bit where the first qubit will be measured in
- classicalBit1: the bit where the second qubit will be measured in
- basis: the basis of the measurement
- backend: the backend used to run the tests
OUTPUT:
- the data of the execution of the tests,
which is a list of lists of statevectors (aka lists)
"""
def runTestsAssertEntangled(self,
initialisedTests,
noOfExperiments,
noOfMeasurements,
qubit0,
qubit1,
classicalBit0,
classicalBit1,
basis,
backend):
return [self.runTestAssertEntangled(qc, noOfExperiments, noOfMeasurements, qubit0, qubit1, classicalBit0, classicalBit1, basis, backend)
for qc in initialisedTests]
"""
INPUTS:
- qc: QuantumCircuit to run the tests
- noOfExperiments: number of times the the qc will be run
- noOfMeasurements: number of times the qc will be measured after each run
- qubit0: the first qubit to compare
- measuredBit: the bit where the qubit will be measured in
- basis: the basis of the measurement
- backend: the backend used to run the tests
OUTPUT:
- the data of the execution of the tests,
which is like runTestAssertEqual but without but for only one qubit instead of two
"""
def runTestAssertProbability(self,
qc,
noOfExperiments,
noOfMeasurements,
qubit0,
measuredBit,
basis,
backend):
selectedBackend = select_backend(backend, qc)
if basis.lower() == "x":
measureX(qc, qubit0, measuredBit)
elif basis.lower() == "y":
measureY(qc, qubit0, measuredBit)
else:
qc.measure(qubit0, measuredBit)
qc_trans = transpile(qc, backend=selectedBackend)
trialProbas = np.empty(noOfExperiments)
for trialIndex in range(noOfExperiments):
result = selectedBackend.run(qc_trans, shots = noOfMeasurements).result()
counts = result.get_counts()
nb0s = 0
for elem in counts:
#Bit oredering is in the reverse order for get_count
#(if we measure the last bit, it will get its value in index 0 of the string for some reason)
if elem[::-1][measuredBit] == '0': nb0s += counts[elem]
trialProba = nb0s / noOfMeasurements
trialProbas[trialIndex] = trialProba
return trialProbas
"""
INPUTS:
- initialisedTests: list of QuantumCircuits to run the tests
- noOfExperiments: number of times the the qc will be run
- noOfMeasurements: number of times the qc will be measured after each run
- qubit0: the first qubit to compare
- measuredBit: the bit where the qubit will be measured in
- basis: the basis of the measurement
- backend: the backend used to run the tests
OUTPUT:
- the data of the execution of the tests,
which is like runTestsAssertEqual but without but for only one qubit instead of two
"""
def runTestsAssertProbability(self,
initialisedTests,
noOfExperiments,
noOfMeasurements,
qubit0,
measuredBit,
basis,
backend):
return [self.runTestAssertProbability(qc, noOfExperiments, noOfMeasurements, qubit0, measuredBit, basis, backend)
for qc in initialisedTests]
"""
INPUTS:
- initialisedTests: list of QuantumCircuits to run the tests
- noOfExperiments: number of times the the qc will be run
- noOfMeasurements: number of times the qc will be measured after each run
- qubit0: the first qubit to compare
- measuredBit: the bit where the qubit will be measured in
- backend: the backend used to run the tests
OUTPUT:
- the data of the execution of the tests,
which is like runTestsAssertEqual but for 3 bases
"""
def runTestsAssertState(self,
initialisedTests,
noOfExperiments,
noOfMeasurements,
qubit0,
measuredBit,
backend):
tests_Y = [qc.copy() for qc in initialisedTests]
tests_X = [qc.copy() for qc in initialisedTests]
return (self.runTestsAssertProbability(initialisedTests, noOfExperiments, noOfMeasurements, qubit0, measuredBit, "z", backend),
self.runTestsAssertProbability(tests_Y, noOfExperiments, noOfMeasurements, qubit0, measuredBit, "y", backend),
self.runTestsAssertProbability(tests_X, noOfExperiments, noOfMeasurements, qubit0, measuredBit, "x", backend))
"""
INPUTS:
- qc: QuantumCircuit to run the tests
- noOfMeasurements: number of measurements
- backend: the backend used to run the tests
OUTPUT:
- the data of the execution of the tests
"""
def runTestAssertMostProbable(self,
qc,
noOfMeasurements,
backend):
selectedBackend = select_backend(backend, qc)
nbBits = len(qc.clbits)
qc.measure_all()
qc_trans = transpile(qc, backend=selectedBackend)
result = selectedBackend.run(qc_trans, shots=noOfMeasurements).result()
counts = result.get_counts()
cut_counts = {}
for key, value in counts.items():
if key[:-(nbBits+1)] in counts:
cut_counts[key[:-(nbBits+1)]] += value
else:
cut_counts[key[:-(nbBits+1)]] = value
return sorted(cut_counts.items(), key=lambda x:x[1])
"""
INPUTS:
- initialisedTests: list of QuantumCircuits to run the tests
- noOfMeasurements: number of measurements
- backend: the backend used to run the tests
OUTPUT:
- the data of the execution of the tests
"""
def runTestsAssertMostProbable(self,
initialisedTests,
noOfMeasurements,
backend):
return [self.runTestAssertMostProbable(qc, noOfMeasurements, backend) for qc in initialisedTests]
# def runTestsAssertPhase(self,qc,noOfMeasurements,qubit0,qubit1,expectedPhases,classicalbit0,classicalbit1,noOfExperiments):
# selectedBackend = select_backend(backend, qc)
# qubitList = [qubit0,qubit1]
# for trialIndex in range(noOfExperiments):
# (x,y) = getDf(qc,qubitList,noOfMeasurements,selectedBackend)
# ## make a dataframe that contains p values of chi square tests to analyse results
# ## if x and y counts are both 25/25/25/25, it means that we cannot calculate a phase
# ## we assume that a qubit that is in |0> or |1> position to have 50% chance to fall
# ## either way, like a coin toss: We treat X and Y results like coin tosses
# pValues = pd.DataFrame(columns=['X','Y'])
# pValues['X'] = resDf.apply(lambda row: applyChiSquareX(row, measurements_to_make/2), axis=1)
# pValues['Y'] = resDf.apply(lambda row: applyChiSquareY(row, measurements_to_make/2), axis=1)
# def getDf(qc,qubitList,noOfMeasurements,selectedBackend):
# ## divide measurements to make by 3 as we need to run measurements twice, one for x and one for y
# ## divide measurements to make by 2 as we need to run measurements twice, one for x and one for y
# noOfMeasurements = noOfMeasurements // 2
# ## copy the circit and set measurement to y axis
# yQuantumCircuit = measureY(qc.copy(), qubitList)
# ## measure the x axis
# xQuantumCircuit = measureX(qc.copy(), qubitList)
# ## get y axis results
# yJob = execute(yQuantumCircuit, selectedBackend, shots=noOfMeasurements, memory=True)
# yCounts = yJob.result().get_counts()
# ## get x axis results
# xJob = execute(xQuantumCircuit, selectedBackend, shots=noOfMeasurements, memory=True)
# xCounts = xJob.result().get_counts()
# ## make a df to keep track of the predicted angles
# resDf = pd.DataFrame(columns=['+','i','-','-i'])
# ## fill the df with the x and y results of each qubit that is being asserted
# classicalQubitIndex = 1
# for qubit in qubitList:
# plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0
# for experiment in xCounts:
# if (experiment[len(qubitList)-classicalQubitIndex] == '0'):
# plus_amount += xCounts[experiment]
# else:
# minus_amount += xCounts[experiment]
# for experiment in yCounts:
# if (experiment[len(qubitList)-classicalQubitIndex] == '0'):
# i_amount += yCounts[experiment]
# else:
# minus_i_amount += yCounts[experiment]
# df = {'+':plus_amount, 'i':i_amount,
# '-':minus_amount, '-i':minus_i_amount}
# resDf = resDf.append(df, ignore_index = True)
# classicalQubitIndex+=1
# ## convert the columns to a strict numerical type
# resDf['+'] = resDf['+'].astype(int)
# resDf['i'] = resDf['i'].astype(int)
# resDf['-'] = resDf['-'].astype(int)
# resDf['-i'] = resDf['-i'].astype(int)
# xAmount = resDf['-'].tolist()
# yAmount = resDf['-i'].tolist()
# return (xAmount,yAmount)
|
https://github.com/Manish-Sudhir/QiskitCheck
|
Manish-Sudhir
|
from qiskit import QuantumCircuit
from TestProperty import TestProperty
import cmath
import numpy as np
from math import cos, sin, radians, degrees
import random
class Generator:
"""
This method generates one concrete test case and provides the exact parameters
used to initialise the qubits
Inputs: a TestProperty
Output: a tuple containing the initialised test (a QantumCircuit),
and two dictionaries, that store the theta (first one) and phi (second one)
of each qubit in degrees
"""
def generateTest(self, testProperties: TestProperty):
preConditions = testProperties.preConditions
phiVal = {}
thetaVal = {}
#Adds 2 classical bits to read the results of any assertion
#Those bits will not interfere with the normal functioning of the program
if testProperties.minQubits == testProperties.maxQubits:
noOfQubits = testProperties.minQubits
else:
noOfQubits = np.random.randint(testProperties.minQubits, testProperties.maxQubits)
qc = QuantumCircuit(noOfQubits, testProperties.noOfClassicalBits + 2)
for key, value in preConditions.items():
#ignores the keys that are outside of the range
if key >= noOfQubits:
continue
#converts from degrees to radian
randPhi = random.randint(value.minPhi, value.maxPhi)
randTheta = random.randint(value.minTheta, value.maxTheta)
#stores the random values generated
phiVal[key] = randPhi
thetaVal[key] = randTheta
randPhiRad = radians(randPhi)
randThetaRad = radians(randTheta)
"""WHY THIS HAPPEN"""
value0 = cos(randThetaRad/2)
value1 = cmath.exp(randPhiRad * 1j) * sin(randThetaRad / 2)
qc.initialize([value0, value1], key)
return (qc, thetaVal, phiVal)
"""
This method runs self.generateTest to generate the specified amount of tests in
the TestProperty
Inputs: a TestProperty
Outputs: a list of what self.generateTests returns (a tuple containing a QuantumCircuit,
a dictionary for the thetas used and a dictionary for the phi used in degrees)
"""
def generateTests(self, testProperties: TestProperty):
return [self.generateTest(testProperties) for _ in range(testProperties.noOfTests)]
|
https://github.com/Manish-Sudhir/QiskitCheck
|
Manish-Sudhir
|
from TestProperty import TestProperty, Precondition
from Generator import Generator
from ExecutionEngine import TestExecutor
from StatisticalEngine import StatAnalyser
from qiskit import QuantumCircuit
from math import cos, radians
from abc import ABC, abstractmethod
"""
INPUTS:
- list of quantum circuits
- function to filter the quantum circuits (that takes as input a QuantumCircuit)
OUTPUT:
- tuple of 2 values:
0. a list storing the indexes of the tests that passed the filtering process
1. another list storing the tests that passed the filtering
"""
def getFilteredInfo(inputTests, filter_qc):
if filter_qc != None:
filteredNumbered = list(filter(lambda x: filter_qc(x[1]), enumerate(inputTests)))
filteredIndexes = [x[0] for x in filteredNumbered]
filteredTests = [x[1] for x in filteredNumbered]
else:
filteredIndexes = range(len(inputTests))
filteredTests = inputTests
return (filteredIndexes, filteredTests)
class QiskitPropertyTest(ABC):
"""
This method handles all the required data to evaluate the equality between two qubits
INPUTS:
- qu0: int = the index of the first qubit to compare
- qu1: int = the index of the second qubit to compare
- qu0_pre: boolean = whether the first qubit should be compared
before running quantumFunction()
- qu1_pre: boolean = whether the second qubit should be compared
before running quantumFunction()
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the first and the second qubit
"""
#Manish- This is a helper function which takes in initTest which calls the test case generator to generate qc's, based on the
# preconditions, which are going to be used to be used in our tests. the two underscores are theta and phi.
def genListQC(self, sit):
genQCList = []
for qc, _, _ in sit:
genQCList.append(qc.copy())
return genQCList
def assertEqualData(self, qu0, qu1, qu0_pre, qu1_pre, basis, filter_qc):
generatedTests = self.genListQC(self.initTests)
filteredIndexes, filteredTests = getFilteredInfo(generatedTests, filter_qc)
#executes the tests twice faster if they're on the same circuit, but only possible if both pre values are the same
if qu0_pre == qu1_pre:
#Applies the function to the generated tests only if they are both sampled after running the full program
if not qu0_pre and not qu1_pre:
for circuit in generatedTests:
self.quantumFunction(circuit)
dataFromExec = TestExecutor().runTestsAssertEqual(filteredTests, self.testProperty.noOfExperiments, \
self.testProperty.noOfMeasurements, qu0, qu1, self.testProperty.noOfClassicalBits, \
self.testProperty.noOfClassicalBits + 1, basis, self.testProperty.backend)
testResults = StatAnalyser().testAssertEqual(self.testProperty.pVal, dataFromExec)
#gets the theta/phi each qubit was initialised with
qu0Params = [(self.initTests[index][1].get(qu0, 0),
self.initTests[index][2].get(qu0, 0)) for index in filteredIndexes]
qu1Params = [(self.initTests[index][1].get(qu1, 0),
self.initTests[index][2].get(qu1, 0)) for index in filteredIndexes]
params = tuple(zip(qu0Params, qu1Params))
testResultsWithInit = tuple(zip(testResults, params))
else:
for circuit in generatedTests:
self.quantumFunction(circuit)
generatedTestPre = [x[0].copy() for x in self.initTests]
filteredTestsPre = [generatedTestPre[index] for index in filteredIndexes]
if not qu0_pre:
tests_qu0 = filteredTests
tests_qu1 = filteredTestsPre
else:
tests_qu0 = filteredTestsPre
tests_qu1 = filteredTests
#can reuse testAssertEqual with data from 2 runTestsAssertProbability zipped together
dataFrom_qu0 = TestExecutor().runTestsAssertProbability(tests_qu0, self.testProperty.noOfExperiments, \
self.testProperty.noOfMeasurements, qu0, self.testProperty.noOfClassicalBits + 1, basis, self.testProperty.backend)
dataFrom_qu1 = TestExecutor().runTestsAssertProbability(tests_qu1, self.testProperty.noOfExperiments, \
self.testProperty.noOfMeasurements, qu1, self.testProperty.noOfClassicalBits + 1, basis, self.testProperty.backend)
formattedData = tuple(zip(dataFrom_qu0, dataFrom_qu1))
testResults = StatAnalyser().testAssertEqual(self.testProperty.pVal, formattedData)
#gets the theta/phi each qubit was initialised with
qu0Params = [(self.initTests[index][1].get(qu0, 0),
self.initTests[index][2].get(qu0, 0)) for index in filteredIndexes]
qu1Params = [(self.initTests[index][1].get(qu1, 0),
self.initTests[index][2].get(qu1, 0)) for index in filteredIndexes]
params = tuple(zip(qu0Params, qu1Params))
testResultsWithInit = tuple(zip(testResults, params))
return testResultsWithInit
"""
This method is a wrapper around assertEqualData that outputs the results
to the users
INPUTS:
- qu0: int = the index of the first qubit to compare
- qu1: int = the index of the second qubit to compare
- qu0_pre: boolean = whether the first qubit should be compared
before running quantumFunction()
- qu1_pre: boolean = whether the second qubit should be compared
before running quantumFunction()
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the first and the second qubits
"""
def assertEqual(self, qu0, qu1, qu0_pre=False, qu1_pre=False, basis="z", filter_qc=None):
results = self.assertEqualData(qu0, qu1, qu0_pre, qu1_pre, basis, filter_qc)
print(f"AssertEqual({qu0}{'_pre' if qu0_pre else ''}, {qu1}{'_pre' if qu1_pre else ''}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0][0]} Phi = {testResult[1][0][1]}")
print(f"qu1: Theta = {testResult[1][1][0]} Phi = {testResult[1][1][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method is a wrapper around assertEqualData that outputs the results
to the users
The "Not" is evaluated by negating all booleans returned by assertEqualData
INPUTS:
- qu0: int = the index of the first qubit to compare
- qu1: int = the index of the second qubit to compare
- qu0_pre: boolean = whether the first qubit should be compared
before running quantumFunction()
- qu1_pre: boolean = whether the second qubit should be compared
before running quantumFunction()
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the first and the second qubits
"""
def assertNotEqual(self, qu0, qu1, qu0_pre=False, qu1_pre=False, basis="z", filter_qc=None):
oppositeResults = self.assertEqualData(qu0, qu1, qu0_pre, qu1_pre, basis, filter_qc)
results = [(not x[0], x[1]) for x in oppositeResults]
print(f"AssertNotEqual({qu0}{'_pre' if qu0_pre else ''}, {qu1}{'_pre' if qu1_pre else ''}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0][0]} Phi = {testResult[1][0][1]}")
print(f"qu1: Theta = {testResult[1][1][0]} Phi = {testResult[1][1][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method handles all the required data to evaluate whether two qubits are entangled
INPUTS:
- qu0: int = the index of the first qubit to compare
- qu1: int = the index of the second qubit to compare
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the first and the second qubits
"""
def assertEntangledData(self, qu0, qu1, basis, filter_qc):
# generatedTests = [qc.copy() for qc, theta, phi in self.initTests]
generatedTests = self.genListQC(self.initTests)
for generatedTest in generatedTests:
self.quantumFunction(generatedTest)
filteredIndexes, filteredTests = getFilteredInfo(generatedTests, filter_qc)
dataFromExec = TestExecutor().runTestsAssertEntangled(filteredTests,
self.testProperty.noOfExperiments,
self.testProperty.noOfMeasurements,
qu0,
qu1,
self.testProperty.noOfClassicalBits,
self.testProperty.noOfClassicalBits + 1,
basis,
self.testProperty.backend)
testResults = StatAnalyser().testAssertEntangled(self.testProperty.pVal, dataFromExec)
qu0Params = [(self.initTests[index][1].get(qu0, 0),
self.initTests[index][2].get(qu0, 0)) for index in filteredIndexes]
qu1Params = [(self.initTests[index][1].get(qu1, 0),
self.initTests[index][2].get(qu1, 0)) for index in filteredIndexes]
params = tuple(zip(qu0Params, qu1Params))
testResultsWithInit = tuple(zip(testResults, params))
return testResultsWithInit
"""
This method is a wrapper of assertEntangledData that outputs the results to the user
INPUTS:
- qu0: int = the index of the first qubit to compare
- qu1: int = the index of the second qubit to compare
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the first and the second qubits
"""
def assertEntangled(self, qu0, qu1, basis="z", filter_qc=None):
results = self.assertEntangledData(qu0, qu1, basis, filter_qc)
print(f"AssertEntangled({qu0}, {qu1}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0][0]} Phi = {testResult[1][0][1]}")
print(f"qu1: Theta = {testResult[1][1][0]} Phi = {testResult[1][1][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method is a wrapper of assertEntangledData that outputs the results to the user
The result booleans are negated for the "Not" evaluation
INPUTS:
- qu0: int = the index of the first qubit to compare
- qu1: int = the index of the second qubit to compare
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the first and the second qubits
"""
def assertNotEntangled(self, qu0, qu1, basis="z", filter_qc=None):
oppositeResults = self.assertEntangledData(qu0, qu1, basis, filter_qc)
results = [(not x[0], x[1]) for x in oppositeResults]
print(f"AsserNotEntangled({qu0}, {qu1}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0][0]} Phi = {testResult[1][0][1]}")
print(f"qu1: Theta = {testResult[1][1][0]} Phi = {testResult[1][1][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method evaluates wether a given qubit is in state |0> with a given probability
INPUTS:
- qu0: int = the index of the qubit to test
- expectedProba: float = expected probability of the qubit to be in state |0>
- qu0_pre: bool = whether the data will be sampled before the application of the quantumFunction
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertProbabilityData(self, qu0, expectedProba, qu0_pre, basis, filter_qc):
expectedProbas = [expectedProba for _ in range(self.testProperty.nbTests)]
generatedTests = [qc.copy() for qc, theta, phi in self.initTests]
#Only apply the functions if specified
if not qu0_pre:
for generatedTest in generatedTests:
self.quantumFunction(generatedTest)
filteredIndexes, filteredTests = getFilteredInfo(generatedTests, filter_qc)
dataFromExec = TestExecutor().runTestsAssertProbability(filteredTests,
self.testProperty.noOfExperiments,
self.testProperty.noOfMeasurements,
qu0,
self.testProperty.noOfClassicalBits + 1,
basis,
self.testProperty.backend)
testResults = StatAnalyser().testAssertProbability(self.testProperty.pVal, expectedProbas, dataFromExec)
qu0Params = [(self.initTests[index][1].get(qu0, 0),
self.initTests[index][2].get(qu0, 0)) for index in filteredIndexes]
testResultsWithInit = tuple(zip(testResults, qu0Params))
return testResultsWithInit
"""
This method is a wrapper around assertprobabilitydata that outputs the results
to the user
INPUTS:
- qu0: int = the index of the qubit to test
- expectedproba: float = expected probability of the qubit to be in state |0>
- qu0_pre: bool = whether the data will be sampled before the application of the quantumfunction
- basis: str = the basis in which the measurements can take place
- filter_qc: function[quantumcircuit => bool] or none = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of the results for each test:
~ a result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertProbability(self, qu0, expectedProba, qu0_pre=False, basis="z", filter_qc=None):
results = self.assertProbabilityData(qu0, expectedProba, qu0_pre, basis, filter_qc)
print(f"AssertProbability({qu0}{'_pre' if qu0_pre else ''}, {expectedProba}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0]} Phi = {testResult[1][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method is a wrapper around assertProbabilityData that outputs the results
to the user
It negates the boolean values
INPUTS:
- qu0: int = the index of the qubit to test
- expectedProba: float = expected probability of the qubit to be in state |0>
- qu0_pre: bool = whether the data will be sampled before the application of the quantumFunction
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertNotProbability(self, qu0, expectedProba, qu0_pre=False, basis="z", filter_qc=None):
oppositeResults = self.assertProbabilityData(qu0, expectedProba, qu0_pre, basis, filter_qc)
results = [(not x[0], x[1]) for x in oppositeResults]
print(f"AssertNotProbability({qu0}{'_pre' if qu0_pre else ''}, {expectedProba}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0]} Phi = {testResult[1][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method asserts that a qubit's state has teleported from "sent" to "received"
INPUTS:
- sent: int = the index of the first qubit to test
- received: int = the index of the second qubit to test
- basis: str = the basis in which the measurements can take place
- filter_qc: function[quantumcircuit => bool] or none = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of the results for each test:
~ a result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertTeleportedData(self, sent, received, basis, filter_qc):
generatedTests = [qc.copy() for qc, theta, phi in self.initTests]
for generatedTest in generatedTests:
self.quantumFunction(generatedTest)
filteredIndexes, filteredTests = getFilteredInfo(generatedTests, filter_qc)
expectedProbas = []
for qc, thetas, phis in self.initTests:
expectedProba = cos(radians(thetas[sent]) / 2) ** 2
expectedProbas.append(expectedProba)
dataFromReceived = TestExecutor().runTestsAssertProbability(filteredTests,
self.testProperty.noOfExperiments,
self.testProperty.noOfMeasurements,
received,
self.testProperty.noOfClassicalBits + 1,
basis,
self.testProperty.backend)
testResults = StatAnalyser().testAssertProbability(self.testProperty.pVal, expectedProbas, dataFromReceived)
qu0Params = [(self.initTests[index][1].get(sent, 0),
self.initTests[index][2].get(sent, 0)) for index in filteredIndexes]
qu1Params = [(self.initTests[index][1].get(received, 0),
self.initTests[index][2].get(received, 0)) for index in filteredIndexes]
params = tuple(zip(qu0Params, qu1Params))
testResultsWithInit = tuple(zip(testResults, params))
return testResultsWithInit
"""
This method is a wrapper of assertTeleportedData that outputs its results to the user
INPUTS:
- sent: int = the index of the first qubit to test
- received: int = the index of the second qubit to test
- basis: str = the basis in which the measurements can take place
- filter_qc: function[quantumcircuit => bool] or none = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of the results for each test:
~ a result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertTeleported(self, sent, received, basis="z", filter_qc=None):
results = self.assertTeleportedData(sent, received, basis, filter_qc)
print(f"AssertTeleported({sent}, {received}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"sent: Theta = {testResult[1][0][0]} Phi = {testResult[1][0][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method is a wrapper of assertTeleportedData that reverses the booleans
and outputs its results to the user
INPUTS:
- sent: int = the index of the first qubit to test
- received: int = the index of the second qubit to test
- basis: str = the basis in which the measurements can take place
- filter_qc: function[quantumcircuit => bool] or none = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of the results for each test:
~ a result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertNotTeleported(self, sent, received, basis="z", filter_qc=None):
oppositeResults = self.assertTeleportedData(sent, received, basis, filter_qc)
results = [(not x[0], x[1]) for x in oppositeResults]
print(f"AssertTeleported({sent}, {received}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"sent: Theta = {testResult[1][0][0]} Phi = {testResult[1][0][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method asserts that a qubit's state is equal to an input state
(described with a theta and a phi)
INPUTS:
- qu0: int = the index of the qubit to test
- theta: int/float = the angle of the theta
- phi: int/float = the angle of the phi
- isRadian: bool = specifies whether theta and phi are in degrees or radians
- qu0_pre: bool = specifies whether the data is sampled before or after the initialisation
- filter_qc: function[quantumcircuit => bool]/None = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of the results for each test:
~ a result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertStateData(self, qu0, theta, phi, isRadian, qu0_pre, filter_qc):
generatedTests = [qc.copy() for qc, theta, phi in self.initTests]
#Only apply the functions if specified
if not qu0_pre:
for generatedTest in generatedTests:
self.quantumFunction(generatedTest)
filteredIndexes, filteredTests = getFilteredInfo(generatedTests, filter_qc)
dataFromExec = TestExecutor().runTestsAssertState(filteredTests,
self.testProperty.noOfExperiments,
self.testProperty.noOfMeasurements,
qu0,
self.testProperty.noOfClassicalBits + 1,
self.testProperty.backend)
testCircuit = QuantumCircuit(1, 1)
testCircuit.initialize(thetaPhiToStateVector(theta, phi, isRadian), 0)
testCircuits = [testCircuit.copy() for _ in range(len(filteredTests))]
dataFromTestCircuit = TestExecutor().runTestsAssertState(testCircuits,
self.testProperty.noOfExperiments,
self.testProperty.noOfMeasurements,
0,
0,
self.testProperty.backend)
testResultsZ = StatAnalyser().testAssertEqual(self.testProperty.pVal,
tuple(zip(dataFromExec[0], dataFromTestCircuit[0])))
testResultsY = StatAnalyser().testAssertEqual(self.testProperty.pVal,
tuple(zip(dataFromExec[1], dataFromTestCircuit[1])))
testResultsX = StatAnalyser().testAssertEqual(self.testProperty.pVal,
tuple(zip(dataFromExec[2], dataFromTestCircuit[2])))
testResults = [testResultsZ[index] and testResultsY[index] and testResultsX[index] for index in range(len(filteredTests))]
if filter_qc == None:
qu0Params = [(x[1].get(qu0, 0), x[2].get(qu0, 0)) for x in self.initTests]
else:
qu0Params = [(self.initTests[index][1].get(qu0, 0), self.initTests[index][2].get(qu0, 0)) for index in self.indexNotFilteredOut]
testResultsWithInit = tuple(zip(testResults, qu0Params))
return testResultsWithInit
"""
This method is a wrapper around assertStateData which outputs the results to the user
INPUTS:
- qu0: int = the index of the qubit to test
- theta: int/float = the angle of the theta
- phi: int/float = the angle of the phi
- isRadian: bool = specifies whether theta and phi are in degrees or radians
- qu0_pre: bool = specifies whether the data is sampled before or after the initialisation
- filter_qc: function[quantumcircuit => bool]/None = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of the results for each test:
~ a result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertState(self, qu0, theta, phi, isRadian=False, qu0_pre=False, filter_qc=None):
results = self.assertStateData(qu0, theta, phi, isRadian, qu0_pre, filter_qc)
print(f"AssertState({qu0}{'_pre' if qu0_pre else ''}, {theta}, {phi}) results:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0]} Phi = {testResult[1][1]} degrees")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method is a wrapper around assertStateData which negates the booleans and outputs the results to the user
INPUTS:
- qu0: int = the index of the qubit to test
- theta: int/float = the angle of the theta
- phi: int/float = the angle of the phi
- isRadian: bool = specifies whether theta and phi are in degrees or radians
- qu0_pre: bool = specifies whether the data is sampled before or after the initialisation
- filter_qc: function[quantumcircuit => bool]/None = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of the results for each test:
~ a result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertNotState(self, qu0, theta, phi, isRadian=False, qu0_pre=False, filter_qc=None):
oppositeResults = self.assertStateData(qu0, theta, phi, isRadian, qu0_pre, filter_qc)
results = [(not x[0], x[1]) for x in oppositeResults]
print(f"AssertNotState({qu0}{'_pre' if qu0_pre else ''}, {theta}, {phi}) results:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0]} Phi = {testResult[1][1]} degrees")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method evaluates which multi-qubit states are the most common
INPUTS:
- outcome: str/list[str] = multi-state outcomes that should be the most common
- filter_qc: function[quantumcircuit => bool]/None = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of booleans
"""
def assertMostCommonData(self,
outcome,
filter_qc):
if isinstance(outcome, str):
outcome = outcome[::-1]
else:
outcome = [x[::-1] for x in outcome]
generatedTests = self.genListQC(self.initTests)
for generatedTest in generatedTests:
self.quantumFunction(generatedTest)
filteredIndexes, filteredTests = getFilteredInfo(generatedTests, filter_qc)
dataFromExec = TestExecutor().runTestsAssertMostProbable(filteredTests,
self.testProperty.noOfMeasurements, self.testProperty.backend)
results = StatAnalyser().testAssertMostCommon(dataFromExec, outcome)
return results
"""
This method is a wrapper that outputs the data of assertMostCommonData
INPUTS:
- outcome: str/list[str] = multi-state outcomes that should be the most common
- filter_qc: function[quantumcircuit => bool]/None = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of booleans
"""
def assertMostCommon(self,
outcome,
filter_qc=None):
results = self.assertMostCommonData(outcome, filter_qc)
print(f"AssertMostCommon({outcome}) results:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
# def assertEqualData(self, qu0, qu1, qu0_pre, qu1_pre, basis, filter_qc):
# def assertEqual(backend, quantumCircuit, qubit1, qubit2, measurements_to_make, alpha):
# def assertPhase(backend, quantumCircuit, qubits_to_assert, expected_phases, measurements_to_make, alpha):
# def assertPhaseData(self,qubit0,qubit1,expectedPhases,filter_qc):
# generatedTests = self.genListQC(self.initTests)
# filteredIndexes, filteredTests = getFilteredInfo(generatedTests, filter_qc)
# for generatedTest in generatedTests:
# self.quantumFunction(generatedTest)
# dataFromExec = TestExecutor().runTestsAssertPhase(filteredTests,
# self.testProperty.noOfExperiments,
# self.testProperty.noOfMeasurements,
# qu0,
# self.testProperty.noOfClassicalBits + 1,
# basis,
# self.testProperty.backend)
# testResults = StatAnalyser().testAssertPhase(self.testProperty.pVal, expectedProbas, dataFromExec)
# qu0Params = [(self.initTests[index][1].get(qu0, 0),
# self.initTests[index][2].get(qu0, 0)) for index in filteredIndexes]
# testResultsWithInit = tuple(zip(testResults, qu0Params))
# return testResultsWithInit
#Default functions that will be usually overwritten by the user
@abstractmethod
def property(self):
return TestProperty()
def quantumFunction(self, qc):
pass
@abstractmethod
def assertions(self):
pass
"""
This method runs the entirety of the tests
"""
def run(self):
print(f"Running tests for {type(self).__name__}:\n")
self.testProperty = self.property()
self.initTests = Generator().generateTests(self.testProperty)
self.assertions()
print(f"Tests for {type(self).__name__} finished\n")
|
https://github.com/chriszapri/qiskitDemo
|
chriszapri
|
from qiskit import QuantumCircuit, assemble, Aer # Qiskit features imported
from qiskit.visualization import plot_bloch_multivector, plot_histogram # For visualization
from qiskit.quantum_info import Statevector # Intermediary statevector saving
import numpy as np # Numpy math library
sim = Aer.get_backend('aer_simulator') # Simulation that this notebook relies on
### For real quantum computer backend, replace Aer.get_backend with backend object of choice
# Widgets for value sliders
import ipywidgets as widgets
from IPython.display import display
# Value sliders
theta = widgets.FloatSlider(
value=0,
min=0,
max=180,
step=0.5,
description='θ',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='.1f',
)
phi = widgets.FloatSlider(
value=0,
min=0,
max=360,
step=0.5,
description='φ',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='.1f',
)
display(theta) # Zenith angle in degrees
display(phi) # Azimuthal angle in degrees
## Careful! These act as zenith and azimuthal only when applied to |0> statevector in rx(theta), rz(phi) order
qc = QuantumCircuit(1) # 1 qubit quantum circuit, every qubits starts at |0>
qc.rx(theta.value/180.0*np.pi,0) # Rotation about Bloch vector x-axis
qc.rz(phi.value/180.0*np.pi,0) # Rotation about Bloch vector y-axis
qc.save_statevector() # Get final statevector after measurement
qc.measure_all() # Measurement: collapses the statevector to either |0> or |1>
qobj = assemble(qc) # Quantum circuit saved to an object
interStateV = sim.run(qobj).result().get_statevector()
finalStates = sim.run(qobj).result().get_counts()
qc.draw()
plot_bloch_multivector(interStateV) # Plot intermediary statevector after two gates on Bloch sphere
plot_histogram(finalStates) # Probability of |0> or |1> from measuring above statevector
|
https://github.com/chriszapri/qiskitDemo
|
chriszapri
|
from qiskit import QuantumCircuit, assemble, Aer # Qiskit features imported
from qiskit.visualization import plot_bloch_multivector, plot_histogram # For visualization
from qiskit.quantum_info import Statevector # Intermediary statevector saving
import numpy as np # Numpy math library
sim = Aer.get_backend('aer_simulator') # Simulation that this notebook relies on
### For real quantum computer backend, replace Aer.get_backend with backend object of choice
# Widgets for value sliders
import ipywidgets as widgets
from IPython.display import display
# Value sliders
theta = widgets.FloatSlider(
value=0,
min=0,
max=180,
step=0.5,
description='θ',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='.1f',
)
phi = widgets.FloatSlider(
value=0,
min=0,
max=360,
step=0.5,
description='φ',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='.1f',
)
display(theta) # Zenith angle in degrees
display(phi) # Azimuthal angle in degrees
## Careful! These act as zenith and azimuthal only when applied to |0> statevector in rx(theta), rz(phi) order
qc = QuantumCircuit(1) # 1 qubit quantum circuit, every qubits starts at |0>
qc.rx(theta.value/180.0*np.pi,0) # Rotation about Bloch vector x-axis
qc.rz(phi.value/180.0*np.pi,0) # Rotation about Bloch vector y-axis
qc.save_statevector() # Get final statevector after measurement
qc.measure_all() # Measurement: collapses the statevector to either |0> or |1>
qobj = assemble(qc) # Quantum circuit saved to an object
interStateV = sim.run(qobj).result().get_statevector()
finalStates = sim.run(qobj).result().get_counts()
qc.draw()
plot_bloch_multivector(interStateV) # Plot intermediary statevector after two gates on Bloch sphere
plot_histogram(finalStates) # Probability of |0> or |1> from measuring above statevector
|
https://github.com/Hayatto9217/Qiskit15
|
Hayatto9217
|
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
import random
circ = QuantumCircuit(40, 40)
circ.h(range(40))
qubit_indices = [i for i in range(40)]
for i in range(10):
control, target, t = random.sample(qubit_indices, 3)
circ.cx(control, target)
circ.t(t)
circ.measure(range(40), range(40))
# Create statevector method simulator
statevector_simulator = AerSimulator(method='statevector')
# Transpile circuit for backend
tcirc = transpile(circ, statevector_simulator)
# Try and run circuit
statevector_result = statevector_simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(statevector_result.success))
print('Why not? {}'.format(statevector_result.status))
extended_stabilizer_simulator =AerSimulator(method='extended_stabilizer')
tcirc = transpile(circ, extended_stabilizer_simulator)
extended_stabilizier_result = extended_stabilizer_simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(extended_stabilizier_result.success))
#Extended Stabilizerメソッドは2つの部分から構成
small_circ = QuantumCircuit(2,2)
small_circ.h(0)
small_circ.cx(0, 1)
small_circ.t(0)
small_circ.measure([0,1],[0,1])
expected_results={'00':50, '11':50}
tsmall_circ =transpile(small_circ,extended_stabilizer_simulator)
result = extended_stabilizer_simulator.run(
tsmall_circ, shots=100).result()
counts =result.get_counts(0)
print('100 shots in {}s'.format(result.time_taken))
plot_histogram([expected_results, counts],
legend=['Expected', 'Extended Stabilizer'])
# Add runtime options for extended stabilizer simulator
opts = {'extended_stabilizer_approximation_error': 0.03}
reduced_error = extended_stabilizer_simulator.run(
tsmall_circ, shots=100, **opts).result()
reduced_error_counts = reduced_error.get_counts(0)
print('100 shots in {}s'.format(reduced_error.time_taken))
plot_histogram([expected_results, reduced_error_counts],
legend=['Expected', 'Extended Stabilizer'])
print("The curcuit above, with 100 shots at precision 0.03 "
"and default mixing time, needed {}s".format(int(reduced_error.time_taken)))
opts = {
'extended_stabilizer_approximation_error': 0.03,
'extended_stabilizer_mixing_time':100
}
optimized = extended_stabilizer_simulator.run(
tsmall_circ, shots=100, **opts).result()
print('Dialing down the mixing time, we completed in just {}s'.format(optimized.time_taken))
opts = {'extended_stabilizer_mixing_time': 150}
multishot = extended_stabilizer_simulator.run(
tcirc, shots=150, **opts).result()
print("100 shots took {} s".format(multishot.time_taken))
opts = {
'extended_stabilizer_measure_sampling': True,
'extended_stabilizer_mixing_time': 150
}
measure_sampling = extended_stabilizer_simulator.run(
circ, shots=150, **opts).result()
print("With the optimization, 100 shots took {} s".format(result.time_taken))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.