repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
print('\nPhase Flip Code')
print('----------------')
from qiskit import QuantumRegister
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
IBMQ.enable_account('Enter API key here')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(3,'q')
c = ClassicalRegister(1,'c')
circuit = QuantumCircuit(q,c)
circuit.cx(q[0],q[1])
circuit.cx(q[0],q[2])
circuit.h(q[0])
circuit.h(q[1])
circuit.h(q[2])
circuit.z(q[0]) #Add this to simulate a phase flip error
circuit.h(q[0])
circuit.h(q[1])
circuit.h(q[2])
circuit.cx(q[0],q[1])
circuit.cx(q[0],q[2])
circuit.ccx(q[2],q[1],q[0])
circuit.measure(q[0],c[0])
job = execute(circuit, backend, shots=1000)
job_monitor(job)
counts = job.result().get_counts()
print("\nPhase flip code with error")
print("----------------------")
print(counts)
input()
|
https://github.com/DEBARGHYA4469/quantum-compiler
|
DEBARGHYA4469
|
from qiskit import ClassicalRegister,QuantumRegister,QuantumJob
from qiskit import available_backends,execute,register,get_backend
from qiskit.tools.visualization import plot_histogram
from qiskit import QuantumCircuit
from zy_decomposition import *
from control_U2 import *
#.................................................................
def swaper(ckt,ctr,tgt,q): # swap control and target bit
ckt.cx(q[ctr],q[tgt])
ckt.h(q[ctr])
ckt.h(q[tgt])
ckt.cx(q[ctr],q[tgt])
ckt.h(q[ctr])
ckt.h(q[tgt])
ckt.cx(q[ctr],q[tgt])
return ckt
#.................................................................
#.........................................................n-Q Toffolli...................................................
def nQ_tofolli(ckt,n,q): # always take first n-1 as ctr,n as tgt
i = 0
anc = n # ancillas are from n to 2*n-1
while(i < n-2):
if(i==0):
ckt.ccx(q[0],q[1],q[anc])
else :
ckt.ccx(q[i+1],q[anc+i-1],q[anc+i])
i = i + 1
i = i - 1
# Perform the controlled operations
ckt.cx(q[anc+i],q[n-1]) # Controlled-U operation
# Free the ancillas....
while(i >= 0):
if(i==0):
ckt.ccx(q[0],q[1],q[anc])
else :
ckt.ccx(q[i+1],q[anc+i-1],q[anc+i])
i = i - 1
return ckt
#.......................................................n-Q Tofolli ......................................................
#................................................Controlled-U operations .................................................
def Control_U(ckt,V_tilde,q,n): # n is no of qubits
i = 0
anc = n # ancillas are from n to 2*n-1
while(i < n-2):
if(i==0):
ckt.ccx(q[0],q[1],q[anc])
else :
ckt.ccx(q[i+1],q[anc+i-1],q[anc+i])
i = i + 1
i = i - 1
# Perform the controlled operations
ckt = CU2(V_tilde,ckt,q,n) # Controlled-U operation
# Free the ancillas....
while(i >= 0):
if(i==0):
ckt.ccx(q[0],q[1],q[anc])
else :
ckt.ccx(q[i+1],q[anc+i-1],q[anc+i])
i = i - 1
return ckt
#................................................Controlled-U operations .................................................
def test_block():
q = QuantumRegister(5+4) # Quantum bits
c = ClassicalRegister(9) #Classical Register
U = np.array([[1,1],[1,-1]])/math.sqrt(2.0)
ckt = QuantumCircuit(q,c)
for j in range(5):
ckt.x(q[j])
ckt.x(q[4])
ckt = Control_U(ckt,U,q,5)
for i in range(9):
ckt.measure(q[i],c[i])
get_result(ckt)
|
https://github.com/BoschSamuel/QizGloria
|
BoschSamuel
|
# -- coding: utf-8 --
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import torch
from torch.autograd import Function
import torch.optim as optim
from qiskit import QuantumRegister,QuantumCircuit,ClassicalRegister,execute
from qiskit.circuit import Parameter
from qiskit import Aer
import numpy as np
from tqdm import tqdm
from matplotlib import pyplot as plt
%matplotlib inline
def to_numbers(tensor_list):
num_list = []
for tensor in tensor_list:
num_list += [tensor.item()]
return num_list
class QiskitCircuit():
def __init__(self,shots):
self.theta = Parameter('Theta')
self.phi = Parameter('Phi')
self.shots = shots
def create_circuit():
qr = QuantumRegister(1,'q')
cr = ClassicalRegister(1,'c')
ckt = QuantumCircuit(qr,cr)
ckt.h(qr[0])
# ckt.barrier()
ckt.u2(self.theta,self.phi,qr[0])
ckt.barrier()
ckt.measure(qr,cr)
return ckt
self.circuit = create_circuit()
def N_qubit_expectation_Z(self,counts, shots, nr_qubits):
expects = np.zeros(nr_qubits)
for key in counts.keys():
perc = counts[key]/shots
check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)])
expects += check
return expects
def bind(self, parameters):
[self.theta,self.phi] = to_numbers(parameters)
self.circuit.data[1][0]._params = to_numbers(parameters)
def run(self, i):
self.bind(i)
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(self.circuit,backend,shots=self.shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(self.circuit)
return self.N_qubit_expectation_Z(counts,self.shots,1)
class TorchCircuit(Function):
@staticmethod
def forward(ctx, i):
if not hasattr(ctx, 'QiskitCirc'):
ctx.QiskitCirc = QiskitCircuit(shots=10000)
exp_value = ctx.QiskitCirc.run(i[0])
result = torch.tensor([exp_value])
ctx.save_for_backward(result, i)
return result
@staticmethod
def backward(ctx, grad_output):
eps = 0.01
forward_tensor, i = ctx.saved_tensors
input_numbers = to_numbers(i[0])
gradient = [0,0]
for k in range(len(input_numbers)):
input_eps = input_numbers
input_eps[k] = input_numbers[k] + eps
exp_value = ctx.QiskitCirc.run(torch.tensor(input_eps))[0]
result_eps = torch.tensor([exp_value])
gradient_result = (exp_value - forward_tensor[0][0].item())/eps
gradient[k] = gradient_result
# print(gradient)
result = torch.tensor([gradient])
# print(result)
return result.float() * grad_output.float()
# x = torch.tensor([np.pi/4, np.pi/4, np.pi/4], requires_grad=True)
x = torch.tensor([[0.0, 0.0]], requires_grad=True)
qc = TorchCircuit.apply
y1 = qc(x)
y1.backward()
print(x.grad)
qc = TorchCircuit.apply
def cost(x):
target = -1
expval = qc(x)
return torch.abs(qc(x) - target) ** 2, expval
x = torch.tensor([[0.0, np.pi/4]], requires_grad=True)
opt = torch.optim.Adam([x], lr=0.1)
num_epoch = 100
loss_list = []
expval_list = []
for i in tqdm(range(num_epoch)):
# for i in range(num_epoch):
opt.zero_grad()
loss, expval = cost(x)
loss.backward()
opt.step()
loss_list.append(loss.item())
expval_list.append(expval.item())
# print(loss.item())
plt.plot(loss_list)
# print(circuit(phi, theta))
# print(cost(x))
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import torchvision
from torchvision import datasets, transforms
batch_size_train = 1
batch_size_test = 1
learning_rate = 0.01
momentum = 0.5
log_interval = 10
torch.backends.cudnn.enabled = False
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor()])
mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
labels = mnist_trainset.targets #get labels
labels = labels.numpy()
idx1 = np.where(labels == 0) #search all zeros
idx2 = np.where(labels == 1) # search all ones
idx = np.concatenate((idx1[0][0:100],idx2[0][0:100])) # concatenate their indices
mnist_trainset.targets = labels[idx]
mnist_trainset.data = mnist_trainset.data[idx]
print(mnist_trainset)
train_loader = torch.utils.data.DataLoader(mnist_trainset, batch_size=batch_size_train, shuffle=True)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 2)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
# return F.softmax(x)
# x = np.pi*F.tanh(x)
# print(x)
x = qc(x)
x = (x+1)/2
x = torch.cat((x, 1-x), -1)
return x
network = Net()
# optimizer = optim.SGD(network.parameters(), lr=learning_rate,
# momentum=momentum)
optimizer = optim.Adam(network.parameters(), lr=learning_rate/10)
epochs = 10
loss_list = []
for epoch in range(epochs):
total_loss = []
target_list = []
for batch_idx, (data, target) in enumerate(train_loader):
target_list.append(target.item())
# print(batch_idx)
optimizer.zero_grad()
output = network(data)
# loss = F.nll_loss(output, target)
loss = F.cross_entropy(output, target)
# print(output)
# print(output[0][1].item(), target.item())
loss.backward()
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print(loss_list[-1])
plt.plot(loss_list)
|
https://github.com/Simultonian/hamilutor-qiskit
|
Simultonian
|
from qiskit import QuantumCircuit
from qiskit.opflow import X, Y, Z, I
from ..utils import qiskit_string_repr, circuit_eq
from .simple import trotter, trotter_from_terms, trotter_from_term
import pytest
repr_hams = [
{"xiizi": 1.0, "iyiiy": 2.0},
{"iiizi": 1.0, "iyiiy": 2.0},
]
q_objs = [
(1.0 * X ^ I ^ I ^ Z ^ I) + (2.0 * I ^ Y ^ I ^ I ^ Y),
((1.0) * I ^ I ^ I ^ Z ^ I) + ((2.0) * I ^ Y ^ I ^ I ^ Y),
]
gate_list = [["i", "i"], ["h", "i"], ["h", "hs"], ["i", "i"], ["i", "h"]]
@pytest.mark.parametrize("h,q_obj", zip(repr_hams, q_objs))
def test_qiskit_repr(h, q_obj):
result = eval(qiskit_string_repr(h))
assert result == q_obj
hamiltonians = [
{"xiizi": 1.0},
{"xiizi": 1.0, "iyiiy": 2.0},
]
@pytest.mark.parametrize("h", hamiltonians)
def test_trotter(h):
result = trotter(h, 1.0)
num_qubits = len(list(h.keys())[0])
# It is equivalent of constructing individual term exponentiated and then
# concatanating them.
expected = QuantumCircuit(num_qubits)
for pauli, coeff in h.items():
cur = trotter({pauli: coeff})
expected = expected.compose(cur)
assert circuit_eq(expected, result)
terms_list = [
[("xy", 1.0), ("iy", 2.0)],
[("xi", 1.0), ("iy", 2.0), ("xi", 3.0)],
[("xi", 1.0), ("iy", 2.0), ("xi", 3.0), ("ii", -1.0)],
]
@pytest.mark.parametrize("terms", terms_list)
def test_from_terms(terms):
num_qubits = len(terms[0][0])
result = trotter_from_terms(terms)
expected = QuantumCircuit(num_qubits)
for pauli, coeff in terms:
cur = trotter({pauli: coeff})
expected = expected.compose(cur)
assert circuit_eq(expected, result)
term_list = [
("xy", 1.0),
("iy", 2.0),
("zz", -3.0),
]
@pytest.mark.parametrize("term", term_list)
def test_from_term(term: tuple[str, float]):
num_qubits = len(term[0])
result = trotter_from_term(term)
expected = QuantumCircuit(num_qubits)
pauli, coeff = term
expected = trotter({pauli: coeff})
assert circuit_eq(expected, result)
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
import math
b_max = math.pi / 5 # upper limit of integral
nbit = 3 # change this value to get discretized result closer to analytical results
analyticResult = (b_max / 2.0 - math.sin(2 * b_max) / 4.0 ) / b_max # the target integral can be analytically solved
print("Analytical Result:", analyticResult)
ndiv = 2**nbit #number of discretization
discretizedResult = 0.0
for i in range(ndiv):
discretizedResult += math.sin(b_max / ndiv * (i + 0.5))**2
discretizedResult = discretizedResult / ndiv
print("Discretized Result:", discretizedResult)
def P(qc, qx, nbit):
"""
Generating uniform probability distribution
qc: quantum circuit
qx: quantum register
nbit: number of qubits
The inverse of P = P
"""
qc.h(qx)
def R(qc, qx, qx_measure, nbit, b_max):
"""
Computing the integral function f()
qc: quantum circuit
qx: quantum register
qx_measure: quantum register for measurement
nbit: number of qubits
b_max: upper limit of integral
"""
qc.ry(b_max / 2**nbit * 2 * 0.5, qx_measure)
for i in range(nbit):
qc.cu3(2**i * b_max / 2**nbit * 2, 0, 0, qx[i], qx_measure[0])
def Rinv(qc, qx, qx_measure, nbit, b_max):
"""
The inverse of R
qc: quantum circuit
qx: quantum register
qx_measure : quantum register for measurement
nbit: number of qubits
b_max: upper limit of integral
"""
for i in range(nbit)[::-1]:
qc.cu3(-2**i * b_max / 2**nbit * 2, 0, 0, qx[i], qx_measure[0])
qc.ry(-b_max / 2**nbit * 2 * 0.5, qx_measure)
#Preparing qiskit environment
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import execute
from qiskit import IBMQ
from qiskit import Aer
from scipy import optimize
import sys, time
import mpmath as mp
import numpy as np
import matplotlib.pyplot as plt
# Functions to construct circuits for Grover operators
def multi_control_NOT(qc, qx, qx_measure, qx_ancilla, nbit, b_max):
"""
Computing multi controlled NOT gate
qc: quantum circuit
qx: quantum register
qx_measure: quantum register for measurement
qx_ancilla: temporal quantum register for decomposing multi controlled NOT gate
nbit: number of qubits
b_max: upper limit of integral
"""
if nbit == 1:
qc.cz(qx[0], qx_measure[0])
elif nbit == 2:
qc.h(qx_measure[0])
qc.ccx(qx[0], qx[1], qx_measure[0])
qc.h(qx_measure[0])
elif nbit > 2.0:
qc.ccx(qx[0], qx[1], qx_ancilla[0])
for i in range(nbit - 3):
qc.ccx(qx[i + 2], qx_ancilla[i], qx_ancilla[i + 1])
qc.h(qx_measure[0])
qc.ccx(qx[nbit - 1], qx_ancilla[nbit - 3], qx_measure[0])
qc.h(qx_measure[0])
for i in range(nbit - 3)[::-1]:
qc.ccx(qx[i + 2], qx_ancilla[i], qx_ancilla[i + 1])
qc.ccx(qx[0], qx[1], qx_ancilla[0])
def reflect(qc, qx, qx_measure, qx_ancilla, nbit, b_max):
"""
Computing reflection operator (I - 2|0><0|)
qc: quantum circuit
qx: quantum register
qx_measure: quantum register for measurement
qx_ancilla: temporal quantum register for decomposing multi controlled NOT gate
nbit: number of qubits
b_max: upper limit of integral
"""
for i in range(nbit):
qc.x(qx[i])
qc.x(qx_measure[0])
qc.barrier() #format the circuits visualization
multi_control_NOT(qc, qx, qx_measure, qx_ancilla, nbit, b_max)
qc.barrier() #format the circuits visualization
qc.x(qx_measure[0])
for i in range(nbit):
qc.x(qx[i])
# This is to implement Grover Operator
def Q_grover(qc, qx, qx_measure, qx_ancilla, nbit, b_max):
"""
The Grover operator: R P (I - 2|0><0|) P^+ R^+ U_psi_0
qc: quantum circuit
qx: quantum register
qx_measure: quantum register for measurement
qx_ancilla: temporal quantum register for decomposing multi controlled NOT gate
nbit: number of qubits
b_max: upper limit of integral
"""
qc.z(qx_measure[0])
Rinv(qc, qx, qx_measure, nbit, b_max)
qc.barrier() #format the circuits visualization
P(qc, qx, nbit)
reflect(qc, qx, qx_measure, qx_ancilla, nbit, b_max)
P(qc, qx, nbit)
qc.barrier() #format the circuits visualization
R(qc, qx, qx_measure, nbit, b_max)
def create_grover_circuit(numebr_grover_list, nbit, b_max):
"""
To generate quantum circuits running Grover operators with number of iterations in number_grover_list
numebr_grover_list: list of number of Grover operators
nbit: number of qubits (2**nbit = ndiv is the number of discretization in the Monte Carlo integration)
b_max: upper limit of integral
Return:
qc_list: quantum circuits with Grover operators as in number_grover_list
"""
qc_list = []
for igrover in range(len(numebr_grover_list)):
qx = QuantumRegister(nbit)
qx_measure = QuantumRegister(1)
cr = ClassicalRegister(1)
if (nbit > 2):
qx_ancilla = QuantumRegister(nbit - 2)
qc = QuantumCircuit(qx, qx_ancilla, qx_measure, cr)
else:
qx_ancilla = 0
qc = QuantumCircuit(qx, qx_measure, cr)
P(qc, qx, nbit)
R(qc, qx, qx_measure, nbit, b_max)
for ikAA in range(numebr_grover_list[igrover]):
Q_grover(qc, qx, qx_measure, qx_ancilla, nbit, b_max)
qc.measure(qx_measure[0], cr[0])
qc_list.append(qc)
return qc_list
qc_list = create_grover_circuit([2], nbit, b_max)
my_style = {'usepiformat': True, 'cregbundle': True,'compress': True }
qc_list[0].draw(output="mpl", style=my_style, plot_barriers=False )
def run_grover(qc_list, number_grover_list, shots_list, backend):
"""
Run the quantum circuits returned by create_grover_circuit()
qc_list: list of quantum circuits
numebr_grover_list: list of number of Grover operators
shots_list: list of number of shots
backend: name of backends
Return:
hit_list: list of count of obserbving "1" for qc_list
"""
hit_list = []
for k in range(len(number_grover_list)):
job = execute(qc_list[k], backend=backend, shots=shots_list[k])
lapse = 0
interval = 0.00001
time.sleep(interval)
while job.status().name != 'DONE':
time.sleep(interval)
lapse += 1
counts = job.result().get_counts(qc_list[k]).get("1", 0)
hit_list.append(counts)
return hit_list
def calculate_theta(hit_list, number_grover_list, shots_list):
"""
calculate optimal theta values
hit_list: list of count of obserbving "1" for qc_list
numebr_grover_list: list of number of Grover operators
shots_list: list of number of shots
Return:
thetaCandidate_list: list of optimal theta
"""
small = 1.e-15 # small valued parameter to avoid zero division
confidenceLevel = 5 # confidence level to determine the search range
thetaCandidate_list = []
rangeMin = 0.0 + small
rangeMax = 1.0 - small
for igrover in range(len(number_grover_list)):
def loglikelihood(p):
ret = np.zeros_like(p)
theta = np.arcsin(np.sqrt(p))
for n in range(igrover + 1):
ihit = hit_list[n]
arg = (2 * number_grover_list[n] + 1) * theta
ret = ret + 2 * ihit * np.log(np.abs(np.sin(arg))) + 2 * (
shots_list[n] - ihit) * np.log(np.abs(np.cos(arg)))
return -ret
searchRange = (rangeMin, rangeMax)
searchResult = optimize.brute(loglikelihood, [searchRange])
pCandidate = searchResult[0]
thetaCandidate_list.append(np.arcsin(np.sqrt(pCandidate)))
perror = CalcErrorCramérRao(igrover, shots_list, pCandidate, number_grover_list)
rangeMax = min(pCandidate+confidenceLevel*perror,1.0 - small)
rangeMin = max(pCandidate-confidenceLevel*perror,0.0 + small)
return thetaCandidate_list
#setting the number of shots and Grover operators.
shots_list = [100, 100, 100, 100, 100, 100, 100] # list of number of shots
number_grover_list = [0, 1, 2, 4, 8, 16, 32] # list of number of Grover operators
if len(shots_list) != len(number_grover_list):
raise Exception(
'The length of shots_list should be equal to the length of number_grover_list.'
)
backend = Aer.get_backend('qasm_simulator')
def CalcErrorCramérRao(M, shot_list, p0, number_grover_list):
"""
calculate Cramér-Rao lower bound
M: upper limit of the sum in Fisher information
shots_list: list of number of shots
p0: the true parameter value to be estimated
numebr_grover_list: list of number of Grover operators
Return:
square root of Cramér-Rao lower bound: lower bound on the standard deviation of unbiased estimators
"""
FisherInfo = 0
for k in range(M + 1):
Nk = shot_list[k]
mk = number_grover_list[k]
FisherInfo += Nk / (p0 * (1 - p0)) * (2 * mk + 1)**2
return np.sqrt(1 / FisherInfo)
def CalcNumberOracleCalls(M, shot_list, number_grover_list):
"""
calculate the total number of oracle calls
M: upper limit of the sum in Fisher information
shots_list: list of number of shots
numebr_grover_list: list of number of Grover operators
Return:
Norac: the total number of oracle calls
"""
Norac = 0
for k in range(M + 1):
Nk = shots_list[k]
mk = number_grover_list[k]
Norac += Nk * (2 * mk + 1)
return Norac
qc_list = create_grover_circuit(number_grover_list, nbit,
b_max) # list of Grover circuits
hit_list = run_grover(qc_list, number_grover_list, shots_list,
backend) # list of number of grover operators
thetaCandidate_list = calculate_theta(
hit_list, number_grover_list, shots_list) # list of estimated theta values
error_list = np.abs(np.sin(thetaCandidate_list)**2 - discretizedResult) # list of estimation errors
OracleCall_list = [] # list of number of oracle calls
ErrorCramérRao_list = [] # list of Cramér-Rao lower bound
for i in range(len(number_grover_list)):
OracleCall_list.append(
CalcNumberOracleCalls(i, shots_list, number_grover_list))
ErrorCramérRao_list.append(
CalcErrorCramérRao(i, shots_list, discretizedResult, number_grover_list))
p1 = plt.plot(OracleCall_list, error_list, 'o')
p2 = plt.plot( OracleCall_list, ErrorCramérRao_list)
plt.xscale('log')
plt.xlabel("Number of oracle calls")
plt.yscale('log')
plt.ylabel("Estimation Error")
plt.legend((p1[0], p2[0]), ("Estimated Value", "Cramér-Rao"))
plt.show()
n_trial = 100
error_list= np.zeros_like(number_grover_list,dtype=float)
qc_list = create_grover_circuit(number_grover_list, nbit, b_max)
for i in range(n_trial):
sys.stdout.write("n_trial=(%d/%d)\r" % ((i + 1), n_trial))
sys.stdout.flush()
hit_list = run_grover(qc_list, number_grover_list, shots_list, backend)
thetaCandidate_list = calculate_theta(hit_list, number_grover_list, shots_list)
error_list += (np.sin(thetaCandidate_list)**2 - discretizedResult)**2 # list of estimation errors
error_list = (error_list / (n_trial-1))**(1/2)
p1 = plt.plot(OracleCall_list, error_list, 'o')
p2 = plt.plot(OracleCall_list, ErrorCramérRao_list)
plt.xscale('log')
plt.xlabel("Number of oracle calls")
plt.yscale('log')
plt.ylabel("Estimation Error")
plt.legend((p1[0], p2[0]), ("Estimated Value", "Cramér-Rao"))
plt.show()
|
https://github.com/erinaldi/bmn2-qiskit
|
erinaldi
|
# %%
import time
import fire
import numpy as np
import pandas as pd
from scipy.sparse import diags
from scipy.sparse import identity
from scipy.sparse import kron
from scipy.sparse.linalg import eigsh
from qiskit import Aer
from qiskit.opflow import MatrixOp
from qiskit.circuit.library import EfficientSU2
from qiskit.algorithms import NumPyEigensolver, VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, L_BFGS_B, NELDER_MEAD
from qiskit.utils import algorithm_globals, QuantumInstance
# %%
def build_operators(L: int, N: int) -> list:
"""Generate all the annihilation operators needed to build the hamiltonian
Args:
L (int): the cutoff of the single site Fock space
N (int): the number of colors of gauge group SU(N)
Returns:
list: a list of annihilation operators, length=N_bos
"""
# The annihilation operator for the single boson
a_b = diags(np.sqrt(np.linspace(1, L - 1, L - 1)), offsets=1)
# The identity operator of the Fock space of a single boson
i_b = identity(L)
# Bosonic Hilbert space
N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> fixed for mini-BMN 2
product_list = [i_b] * N_bos # only the identity for bosons repeated N_bos times
a_b_list = [] # this will contain a1...a6
for i in np.arange(0, N_bos): # loop over all bosonic operators
operator_list = product_list.copy() # all elements are the identity operator
operator_list[
i
] = a_b # the i^th element is now the annihilation operator for a single boson
a_b_list.append(
operator_list[0]
) # start taking tensor products from first element
for a in operator_list[1:]:
a_b_list[i] = kron(
a_b_list[i], a
) # do the outer product between each operator_list element
return a_b_list
# %%
def build_gauge_casimir(L: int, N: int):
"""Generate the gauge generators operators
Args:
L (int): the single site cutoff of the Fock space
N (int): the number of colors in the gauge group SU(N)
Returns:
scipy.sparse : The sparse matrix for \sum_i G_i^2
"""
# generate the annihilation operators
bosons = build_operators(L, N)
# define the generator list for SU(2)
g_list = [0] * 3
g_list[0] = 1j * (
bosons[1].conjugate().transpose() * bosons[2]
- bosons[2].conjugate().transpose() * bosons[1]
+ bosons[4].conjugate().transpose() * bosons[5]
- bosons[5].conjugate().transpose() * bosons[4]
)
g_list[1] = 1j * (
bosons[2].conjugate().transpose() * bosons[0]
- bosons[0].conjugate().transpose() * bosons[2]
+ bosons[5].conjugate().transpose() * bosons[3]
- bosons[3].conjugate().transpose() * bosons[5]
)
g_list[2] = 1j * (
bosons[0].conjugate().transpose() * bosons[1]
- bosons[1].conjugate().transpose() * bosons[0]
+ bosons[3].conjugate().transpose() * bosons[4]
- bosons[4].conjugate().transpose() * bosons[3]
)
return g_list[0] * g_list[0] + g_list[1] * g_list[1] + g_list[2] * g_list[2]
# %%
def bmn2_hamiltonian(L: int = 2, N: int = 2, g2N: float = 0.2):
"""Construct the Hamiltonian of the bosonic BMN model as a sparse matrix.
The cutoff for each boson is L while the 't Hooft coupling in g2N for a gauge group SU(N).
The limited number of qubits only let us simulate N=2 and L=4 => for 6 bosons this is a 12 qubits problem.
Args:
L (int, optional): The cutoff of the bosonic modes (the annihilation operators will be LxL matrices). Defaults to 2.
N (int, optional): The number of colors of a SU(N) gauge group. The degrees of freedom of one matrix will be N^2-1. Defaults to 2.
g2N (float, optional): The 't Hooft coupling. Defaults to 0.2.
"""
print(
f"Building bosonic BMN Hamiltonian for SU({N}) with cutoff={L} and coupling={g2N}\n"
)
a_b_list = build_operators(L,N)
N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> FIXED for mini-BMN 2
# Build the Hamiltonian
# Start piece by piece
x_list = []
# only use the bosonic operators
for op in a_b_list:
x_list.append(1 / np.sqrt(2) * (op.conjugate().transpose() + op))
# Free Hamiltonian
H_k = 0
for a in a_b_list:
H_k = H_k + a.conjugate().transpose() * a
# vacuum energy
H_k = H_k + 0.5 * N_bos * identity(L ** N_bos)
# Interaction among bosons
V_b = (
x_list[2] * x_list[2] * x_list[3] * x_list[3]
+ x_list[2] * x_list[2] * x_list[4] * x_list[4]
+ x_list[1] * x_list[1] * x_list[3] * x_list[3]
+ x_list[1] * x_list[1] * x_list[5] * x_list[5]
+ x_list[0] * x_list[0] * x_list[4] * x_list[4]
+ x_list[0] * x_list[0] * x_list[5] * x_list[5]
- 2 * x_list[0] * x_list[2] * x_list[3] * x_list[5]
- 2 * x_list[0] * x_list[1] * x_list[3] * x_list[4]
- 2 * x_list[1] * x_list[2] * x_list[4] * x_list[5]
)
# full hamiltonian
return H_k + g2N / N * V_b
def eigenvalues_scipy(H, k: int = 10):
"""Compute the lowest k eigenvalues of a sparse symmetric matrix H.
Args:
H (scipy.sparse matrix): The Hamiltonian in the form of a sparse matrix
k (int): The number of lowest eigenvalues to compute. Defaults to 10.
"""
eigv = eigsh(H, k, which="SA", return_eigenvectors=False, tol=0)
return np.real(eigv[::-1])
def eigenvalues_qiskit(qOp: MatrixOp, k: int = 10):
"""Compute the lowest k eigenvalues of a quantum operator in matrix form qOp.
Internally it uses numpy.
Args:
qOp (MatrixOp): The quantum operator build from a matrix.
k (int, optional): The number of lowest eigenvalues. Defaults to 10.
"""
mes = NumPyEigensolver(k) # k is the number of eigenvalues to compute
result = mes.compute_eigenvalues(qOp)
return np.real(result.eigenvalues)
# %%
def check_expectation(H, O, k: int = 1):
"""Compute the lowest k eigenstates of a sparse symmetric matrix H
and then compute the expectation value of O.
Args:
H (scipy.sparse matrix): The Hamiltonian in the form of a sparse matrix
O (scipy.sparse matrix): The operator to "measure" in the form of a sparse matrix
k (int): The number of lowest eigenstates to compute. Defaults to 1.
"""
_, eigk = eigsh(H, k, which="SA", return_eigenvectors=True, tol=0)
expect = []
for i in np.arange(k):
bra = eigk[:,i].conjugate().transpose()
ket = eigk[:,i]
expect.append(bra.dot(O.dot(ket)))
return np.real(np.array(expect))
# %%
def run_vqe(
L: int = 2,
N: int = 2,
g2N: float = 0.2,
optimizer: str = "COBYLA",
maxit: int = 5000,
varform: list = ["ry"],
depth: int = 3,
nrep: int = 10,
rngseed: int = 0,
G2: bool = False,
h5: bool = True,
):
"""Run the main VQE solver for a bosonic BMN Hamiltonian where bosons are LxL matrices and the 't Hooft coupling is g2N for a SU(N) gauge group.
The VQE is initialized with a specific optimizer and a specific variational quantum circuit based on EfficientSU2.
Args:
L (int, optional): Cutoff of each bosonic degree of freedom. Defaults to 2.
N (int, optional): Colors for the SU(N) gauge group. Defaults to 2.
g2N (float, optional): 't Hooft coupling. Defaults to 0.2.
optimizer (str, optional): VQE classical optimizer. Defaults to "COBYLA".
maxit (int, optional): Max number of iterations for the optimizer. Defaults to 5000.
varform (str, optional): EfficientSU2 rotation gates. Defaults to 'ry'.
depth (int, optional): Depth of the variational form. Defaults to 3.
nrep (int, optional): Number of different random initializations of parameters. Defaults to 1.
rngseed (int, optional): The random seed. Defaults to 0.
G2 (bool, optional): The flag to compute the expectation value of the gauge Casimir. Defaults to False.
h5 (bool, optional): The flag to save in HDF5 format. Defaults to True.
"""
# Create the matrix Hamiltonian
H = bmn2_hamiltonian(L, N, g2N)
# Now, we take the Hamiltonian matrix and map it onto a qubit operator.
qubitOp = MatrixOp(primitive=H)
# check the exact eigenvalues
print(f"Exact Result of discrete hamiltonian (matrix): {eigenvalues_scipy(H)}")
print(
f"Exact Result of discrete hamiltonian (qubit): {eigenvalues_qiskit(qubitOp)}"
)
# create the gauge casimir and check it if requested
if G2:
G = build_gauge_casimir(L,N)
print(f"Exact Result of Casimir on GS (matrix): {check_expectation(H,G)}")
gOp = MatrixOp(primitive=G)
# Next, we create the variational form.
var_form = EfficientSU2(
qubitOp.num_qubits, su2_gates=varform, entanglement="full", reps=depth
)
# start a quantum instance
# fix the random seed of the simulator to make values reproducible
rng = np.random.default_rng(seed=rngseed)
algorithm_globals.random_seed = rngseed
backend = Aer.get_backend(
"statevector_simulator", max_parallel_threads=6, max_parallel_experiments=0
)
q_instance = QuantumInstance(
backend, seed_transpiler=rngseed, seed_simulator=rngseed
)
# initialize optimizers' parameters: number of iterations
optimizers = {
"COBYLA": COBYLA(maxiter=maxit),
"L-BFGS-B": L_BFGS_B(maxfun=maxit),
"SLSQP": SLSQP(maxiter=maxit),
"NELDER-MEAD": NELDER_MEAD(maxfev=maxit),
}
print(f"\nRunning VQE main loop ...")
start_time = time.time()
try:
optim = optimizers[optimizer]
print(f"{optimizer} settings: {optim.settings}")
except KeyError:
print(
f"Optimizer {optimizer} not found in our list. Try one of {[x for x in optimizers.keys()]}"
)
return
results = {"counts": [], "energy": [], "casimir": []}
casimir_result = 'NaN' # initialize to NaN since it will not be defined if we do not measure it
# callback functions to store the counts from each iteration of the VQE
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
# run multiple random initial points
for i in np.arange(nrep):
counts = []
values = []
# initital points for the angles of the rotation gates
random_init = rng.uniform(-2 * np.pi, 2 * np.pi, var_form.num_parameters)
# Setup the VQE algorithm
vqe = VQE(
ansatz=var_form,
optimizer=optim,
initial_point=random_init,
quantum_instance=q_instance,
callback=store_intermediate_result,
)
# run the VQE with our Hamiltonian operator
if G2:
result = vqe.compute_minimum_eigenvalue(qubitOp,aux_operators=[gOp])
vqe_result = np.real(result.eigenvalue)
casimir_result = np.real(result.aux_operator_eigenvalues[0,0])
print(f"[{i}] - {varform} - [{optimizer}]: VQE gs energy: {vqe_result} | VQE gs gauge casimir: {casimir_result}")
else:
result = vqe.compute_minimum_eigenvalue(qubitOp)
vqe_result = np.real(result.eigenvalue)
print(f"[{i}] - {varform} - [{optimizer}]: VQE gs energy: {vqe_result}")
# collect results
results["counts"].append(counts)
results["energy"].append(values)
results["casimir"].append(casimir_result)
end_time = time.time()
runtime = end_time - start_time
print(f"Program runtime: {runtime} s")
# make a dataframe from the results
df = pd.DataFrame.from_dict(results)
data_types_dict = {"counts": int, "energy": float}
df = df.explode(["counts", "energy"]).astype(data_types_dict).rename_axis("rep")
# report summary of energy across reps
converged = df["energy"].groupby("rep").apply(min).values
print(f"Statistics across {nrep} repetitions:\n-------------------")
print(
f"Least upper bound: {np.min(converged)}\nWorst upper bound: {np.max(converged)}\nMean bound: {np.mean(converged)}\nStd bound: {np.std(converged)}"
)
# save results on disk
varname = "-".join(varform)
g2Nstr = str(g2N).replace(".", "")
if h5:
outfile = f"data/bosBMN_L{L}_l{g2Nstr}_convergence_{optimizer}_{varname}_depth{depth}_reps{nrep}_max{maxit}.h5"
print(f"Save results on disk: {outfile}")
df.to_hdf(outfile, "vqe")
else:
outfile = f"data/bosBMN_L{L}_l{g2Nstr}_convergence_{optimizer}_{varname}_depth{depth}_reps{nrep}_max{maxit}.gz"
print(f"Save results on disk: {outfile}")
df.to_pickle(outfile)
return
# %%
if __name__ == "__main__":
fire.Fire(run_vqe)
|
https://github.com/quantum-melbourne/qiskit-challenge-22
|
quantum-melbourne
|
import warnings
from h5py.h5py_warnings import H5pyDeprecationWarning
warnings.filterwarnings(action="ignore", category=H5pyDeprecationWarning)
from qiskit_nature.drivers import Molecule
molecule = Molecule(
# coordinates are given in Angstrom
geometry=[
["O", [0.0, 0.0, 0.115]],
["H", [0.0, 0.754, -0.459]],
["H", [0.0, -0.754, -0.459]],
],
multiplicity=1, # = 2*spin + 1
charge=0,
)
from qiskit_nature.drivers.second_quantization import ElectronicStructureMoleculeDriver, ElectronicStructureDriverType
driver = ElectronicStructureMoleculeDriver(
molecule=molecule,
basis="sto3g",
driver_type=ElectronicStructureDriverType.PYSCF,
)
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
problem = ElectronicStructureProblem(driver)
# this will call driver.run() internally
second_q_ops = problem.second_q_ops()
from qiskit_nature.operators.second_quantization import FermionicOp
# we increase the truncation value of the FermionicOp applied while printing
FermionicOp.set_truncation(500)
hamiltonian = second_q_ops[0]
print(hamiltonian)
from qiskit_nature.transformers.second_quantization.electronic import ActiveSpaceTransformer
transformer = ActiveSpaceTransformer(
num_electrons=2,
num_molecular_orbitals=3,
)
problem_reduced = ElectronicStructureProblem(driver, [transformer])
second_q_ops_reduced = problem_reduced.second_q_ops()
hamiltonian_reduced = second_q_ops_reduced[0]
print(hamiltonian_reduced)
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
jw_mapper = JordanWignerMapper()
jw_converter = QubitConverter(jw_mapper)
qubit_op_jw = jw_converter.convert(hamiltonian_reduced)
print(qubit_op_jw)
from qiskit_nature.mappers.second_quantization import ParityMapper
parity_mapper = ParityMapper()
parity_converter = QubitConverter(parity_mapper, two_qubit_reduction=True)
qubit_op_parity = parity_converter.convert(hamiltonian_reduced, num_particles=problem_reduced.num_particles)
print(qubit_op_parity)
from qiskit.algorithms.optimizers import SLSQP
from qiskit.providers.aer import StatevectorSimulator, QasmSimulator
from qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import VQEUCCFactory
vqe_factory = VQEUCCFactory(
quantum_instance=StatevectorSimulator(),
#quantum_instance=QasmSimulator(),
optimizer=SLSQP(),
)
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver
solver = GroundStateEigensolver(parity_converter, vqe_factory)
result = solver.solve(problem_reduced)
print(result)
from urllib3.connection import SystemTimeWarning
warnings.filterwarnings(action="ignore", category=SystemTimeWarning)
import numpy as np
np.random.seed(42)
from qiskit.circuit.library import EfficientSU2
ansatz = EfficientSU2(num_qubits=qubit_op_parity.num_qubits, reps=1, entanglement='linear', insert_barriers=True)
ansatz.decompose().draw('mpl', style='iqx')
from qiskit.providers.ibmq import IBMQ, IBMQAccountError
try:
IBMQ.load_account()
provider = IBMQ.get_provider(group="open")
except IBMQAccountError:
print("No IBMQ account credentials available")
provider = None
else:
print("Provider supports runtime: ", provider.has_service("runtime"))
backend = provider.get_backend("ibmq_qasm_simulator")
from qiskit_nature.runtime import VQEClient
optimizer = {
"name": "SPSA",
"maxiter": 50,
}
initial_point = np.random.random(ansatz.num_parameters)
if provider is not None:
runtime_vqe = VQEClient(
ansatz=ansatz,
optimizer=optimizer,
initial_point=initial_point,
provider=provider,
backend=backend,
shots=1024,
measurement_error_mitigation=True,
)
if provider is not None:
runtime_vqe_solver = GroundStateEigensolver(parity_converter, runtime_vqe)
if provider is not None:
runtime_result = runtime_vqe_solver.solve(problem_reduced)
if provider is not None:
print(runtime_result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_qsphere(state)
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
# We import the necessary functions from Qiskit
from qiskit.visualization import plot_bloch_multivector, visualize_transition
from qiskit import QuantumCircuit, Aer, execute
from math import pi
# We create a quantum circuit with one qubit
qc = QuantumCircuit(1)
# We execute the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
result = execute(qc, backend).result()
# We get the statevector of the quantum circuit
statevector = result.get_statevector(qc)
# We plot the statevector on the Bloch sphere
plot_bloch_multivector(statevector)
qc.ry(pi/2, 0)
qc.draw(output='mpl')
visualize_transition(qc)
qc1 = QuantumCircuit(1)
qc1.rx(pi/3, 0)
qc1.draw(output='mpl')
visualize_transition(qc1)
qc2 = QuantumCircuit(1)
qc2.rz(pi, 0)
qc2.draw(output='mpl')
visualize_transition(qc2)
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
"""Imports for the notebook."""
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
import qiskit
"""Defining circuits with parameters."""
# Get a circuit and registers
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circ = qiskit.QuantumCircuit(qreg, creg)
# Add gates with particular parameters
circ.h(qreg)
circ.rx(0.2, qreg[0])
circ.cx(qreg[0], qreg[1])
circ.ry(0.1, qreg[1])
# Visualize the circuit
print(circ)
def circuit(alpha1: float, alpha2: float):
"""Returns the circuit above with the input parameters."""
### Your code here!
# Get a circuit and registers
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circ = qiskit.QuantumCircuit(qreg, creg)
# Add gates with particular parameters
circ.h(qreg)
circ.rx(alpha1, qreg[0])
circ.cx(qreg[0], qreg[1])
circ.ry(alpha2, qreg[1])
return (circ, qreg, creg)
"""Estimating a one qubit expectation value."""
qreg = qiskit.QuantumRegister(1)
creg = qiskit.ClassicalRegister(1)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg)
### Your code here!
shots = 100000
circ.measure(qreg, creg)
print(circ)
backend = qiskit.BasicAer.get_backend("qasm_simulator")
job = qiskit.execute(circ, backend, shots=shots)
counts = job.result().get_counts()
expec_value = (counts.get("0") - counts.get("1")) / shots
print("Expectation value =", expec_value)
"""Estimating a one qubit expectation value."""
qreg = qiskit.QuantumRegister(1)
creg = qiskit.ClassicalRegister(1)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.x(qreg)
circ.h(qreg)
### Your code here!
shots = 10000
circ.h(qreg)
circ.measure(qreg, creg)
print(circ)
backend = qiskit.BasicAer.get_backend("qasm_simulator")
job = qiskit.execute(circ, backend, shots=shots)
counts = job.result().get_counts()
if "0" in counts.keys():
zero = counts.get("0")
else:
zero = 0
expec_value = (zero - counts.get("1")) / shots
print("Expectation value =", expec_value)
"""Estimating a two qubit expectation value."""
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg[1])
### Your code here!
shots = 10000
circ.h(qreg[1])
circ.measure(qreg, creg)
print(circ)
backend = qiskit.BasicAer.get_backend("qasm_simulator")
job = qiskit.execute(circ, backend, shots=shots)
counts = job.result().get_counts()
# Note: Only 00 will be in the counts, so the line below will throw an error.
# expec_value = (counts.get("00") - counts.get("01") - counts.get("10") + counts.get("11")) / shots
expec_value = counts.get("00") / shots
print("Expectation value =", expec_value)
"""Helper function to evaluate the expectation of any valid Pauli string."""
def expectation_circuit(circuit: qiskit.QuantumCircuit, pauli_string: str) -> qiskit.QuantumCircuit:
"""Returns a circuit to compute expectation of the Pauli string in the
state prepared by the input circuit.
Args:
circuit: Prepares the state |\psi> from |0>.
pauli_string: String (tensor product) of Paulis to evaluate
an expectation of. The length of pauli_string
must be equal to the total number of qubits in
the circuit. (Use identities for no operator!)
"""
if len(circuit.qregs) != 1:
raise ValueError("Circuit should have only one quantum register.")
if len(circuit.cregs) != 1:
print("# cregs =", len(circuit.cregs))
raise ValueError("Circuit should have only one classical register.")
### Your code here!
qreg = circuit.qregs[0]
creg = circuit.cregs[0]
nqubits = len(qreg)
pauli_string = pauli_string.upper().strip()
if len(pauli_string) != nqubits:
raise ValueError(
f"Circuit has {nqubits} qubits but pauli_string has {len(pauli_string)} operators."
)
for (qubit, pauli) in enumerate(pauli_string):
if pauli == "I":
continue
elif pauli == "X":
circuit.h(qreg[qubit])
circuit.measure(qreg[qubit], creg[qubit])
elif pauli == "Y":
circuit.s(qreg[qubit])
circuit.h(qreg[qubit])
circuit.measure(qreg[qubit], creg[qubit])
elif pauli == "Z":
circuit.measure(qreg[qubit], creg[qubit])
else:
raise ValueError(f"{pauli} is an invalid Pauli string key. Should be I, X, Y, or Z.")
return circuit
"""Test your function here."""
circ, qreg, creg = circuit(np.pi / 2, np.pi / 4)
print("Bare circuit:")
print(circ)
### Your code here!
print("\n'Expectation circuit:'")
print(expectation_circuit(circ, "XY"))
"""Function to execute the circuit and do the postprocessing."""
def run_and_process(circuit: qiskit.QuantumCircuit, shots: int = 10000) -> float:
"""Runs an 'expectation circuit' and returns the expectation value of the
measured Pauli string.
Args:
circuit: Circuit to execute.
shots: Number of circuit executions.
"""
### Your code here!
# Execute the circuit
backend = qiskit.BasicAer.get_backend("qasm_simulator")
job = qiskit.execute(circuit, backend, shots=shots)
counts = job.result().get_counts()
# Do the postprocessing
val = 0.0
for bitstring, count in counts.items():
sign = (-1) ** bitstring.count("0")
val += sign * count
return val / shots
"""Define your function here!"""
def expectation(circuit: qiskit.QuantumCircuit, pauli_string: str, shots: int = 10000) -> float:
"""Returns the expectation value of the pauli string in the state prepared by the circuit."""
### Your code here!
to_run = expectation_circuit(circuit, pauli_string)
return run_and_process(to_run, shots)
"""Test your function here."""
### Your code here!
circ, qreg, creg = circuit(0, 0)
print(circ)
expectation(circ, "IX")
"""Compute the expectation of a Hamiltonian."""
# Provided circuit
qreg = qiskit.QuantumRegister(3)
creg = qiskit.ClassicalRegister(3)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg)
circ.rx(np.pi / 4, qreg[0])
circ.cz(qreg[0], qreg[1])
circ.cz(qreg[1], qreg[2])
print(circ)
weights = (0.5, -0.3, 1.2)
paulis = ("IZZ", "ZZI", "ZIZ")
### Your code here
val = 0.0
for w, p in zip(weights, paulis):
val += w * expectation(circ, p)
print("<H> =", val)
"""Function to compute the cost of any Hamiltonian in the state prepared by the circuit."""
def cost(circuit, weights, paulis):
"""Returns <psi|H|psi> where |psi> is prepared by the circuit
and the weights and paulis define a Hamiltonian H.
Args:
circuit: Circuit which prepares a state.
weights: List of floats which are the coeffs/weights of each Pauli string.
paulis: List of strings which specify the Paulis.
"""
if len(weights) != len(paulis):
raise ValueError("Args weights and paulis must have the same length.")
### Your code here!
val = 0.0
for coeff, pauli in zip(weights, paulis):
val += coeff * expectation(circuit, pauli, shots=10000)
return val
"""Evaluate your cost here!"""
### Your code here!
print("Cost =", cost(circ, weights, paulis))
"""Plot a cost landscape."""
def oneq_circ(param):
qreg = qiskit.QuantumRegister(1)
creg = qiskit.ClassicalRegister(1)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.rx(param, qreg)
return circ
weights = (1.0,)
paulis = ("Z",)
pvals = np.linspace(-np.pi, np.pi, 100)
cvals = []
### Your code here!
for pval in pvals:
cvals.append(cost(oneq_circ(pval), weights, paulis))
plt.figure(figsize=(17, 6))
plt.plot(pvals, cvals, "--o", linewidth=3)
plt.grid()
plt.ylabel("<H>")
plt.xlabel(r"$\alpha$")
plt.show()
"""Get a parameterized circuit."""
def circuit(params):
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg)
circ.cx(qreg[0], qreg[1])
circ.rx(params[0], qreg[0])
circ.ry(params[1], qreg[1])
circ.cz(qreg[0], qreg[1])
circ.s(qreg[0])
circ.t(qreg[1])
return circ
"""Visualize the circuit."""
print(circuit([1, 2]))
"""Hamiltonian cost to minimize."""
weights = (1.2, -0.2)
paulis = ("IZ", "ZX")
"""Define a cost/objective function."""
def obj(params):
"""Returns the cost for the given parameters."""
### Your code here
circ = circuit(params)
val = cost(circ, weights, paulis)
print("Current cost:", val, end="\r")
return val
"""Test your function on this set of parameters."""
obj([0, 0])
"""Run an optimization algorithm to return the lowest cost and best parameters."""
result = minimize(obj, x0=[0, 0], method="COBYLA")
"""See the optimization results."""
print("Lowest cost function value found:", result.fun)
print("Best parameters:", result.x)
|
https://github.com/Bikramaditya0154/Quantum-Simulation-of-the-ground-state-of-LiH-molecule-using-Variational-Quantum-Eigensolver
|
Bikramaditya0154
|
from qiskit.algorithms import VQE
from qiskit_nature.algorithms import (GroundStateEigensolver,
NumPyMinimumEigensolverFactory)
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureMoleculeDriver, ElectronicStructureDriverType)
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import ParityMapper
import matplotlib.pyplot as plt
import numpy as np
from qiskit_nature.circuit.library import UCCSD, HartreeFock
from qiskit.circuit.library import EfficientSU2
from qiskit.algorithms.optimizers import COBYLA, SPSA, SLSQP
from qiskit.opflow import TwoQubitReduction
from qiskit import BasicAer, Aer
from qiskit.utils import QuantumInstance
from qiskit.utils.mitigation import CompleteMeasFitter
from qiskit.providers.aer.noise import NoiseModel
def get_qubit_op(dist):
# Define Molecule
molecule = Molecule(
# Coordinates in Angstrom
geometry=[
["Li", [0.0, 0.0, 0.0] ],
["H", [dist, 0.0, 0.0] ]
],
multiplicity=1, # = 2*spin + 1
charge=0,
)
driver = ElectronicStructureMoleculeDriver(
molecule=molecule,
basis="sto3g",
driver_type=ElectronicStructureDriverType.PYSCF)
# Get properties
properties = driver.run()
num_particles = (properties
.get_property("ParticleNumber")
.num_particles)
num_spin_orbitals = int(properties
.get_property("ParticleNumber")
.num_spin_orbitals)
# Define Problem, Use freeze core approximation, remove orbitals.
problem = ElectronicStructureProblem(
driver,
[FreezeCoreTransformer(freeze_core=True,
remove_orbitals=[-3,-2])])
second_q_ops = problem.second_q_ops() # Get 2nd Quant OP
num_spin_orbitals = problem.num_spin_orbitals
num_particles = problem.num_particles
mapper = ParityMapper() # Set Mapper
hamiltonian = second_q_ops[0] # Set Hamiltonian
# Do two qubit reduction
converter = QubitConverter(mapper,two_qubit_reduction=True)
reducer = TwoQubitReduction(num_particles)
qubit_op = converter.convert(hamiltonian)
qubit_op = reducer.convert(qubit_op)
return qubit_op, num_particles, num_spin_orbitals, problem, converter
def exact_solver(problem, converter):
solver = NumPyMinimumEigensolverFactory()
calc = GroundStateEigensolver(converter, solver)
result = calc.solve(problem)
return result
backend = BasicAer.get_backend("statevector_simulator")
distances = np.arange(0.5, 4.0, 0.2)
exact_energies = []
vqe_energies = []
optimizer = SLSQP(maxiter=5)
for dist in distances:
(qubit_op, num_particles, num_spin_orbitals,
problem, converter) = get_qubit_op(dist)
result = exact_solver(problem,converter)
exact_energies.append(result.total_energies[0].real)
init_state = HartreeFock(num_spin_orbitals, num_particles, converter)
var_form = UCCSD(converter,
num_particles,
num_spin_orbitals,
initial_state=init_state)
vqe = VQE(var_form, optimizer, quantum_instance=backend)
vqe_calc = vqe.compute_minimum_eigenvalue(qubit_op)
vqe_result = problem.interpret(vqe_calc).total_energies[0].real
vqe_energies.append(vqe_result)
print(f"Interatomic Distance: {np.round(dist, 2)}",
f"VQE Result: {vqe_result:.5f}",
f"Exact Energy: {exact_energies[-1]:.5f}")
print("All energies have been calculated")
plt.plot(distances, exact_energies, label="Exact Energy")
plt.plot(distances, vqe_energies, label="VQE Energy")
plt.xlabel('Interatomic distance(Angstrom)')
plt.ylabel('Energy(Hartree)')
plt.legend()
plt.show()
|
https://github.com/Qiskit/feedback
|
Qiskit
|
%load_ext autoreload
%autoreload 2
import warnings
warnings.filterwarnings("ignore")
from qiskit_metal import designs, MetalGUI
from qiskit_metal.qlibrary.sample_shapes.rectangle import Rectangle
from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket
from qiskit_metal.qlibrary.tlines.straight_path import RouteStraight
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
from qiskit_metal.qlibrary.terminations.open_to_ground import OpenToGround
from qiskit_metal.qlibrary.terminations.short_to_ground import ShortToGround
design = designs.MultiPlanar({}, overwrite_enabled=True, layer_stack_filename="layer_stack.txt")
design.variables.sample_holder_top = '320 um'
design.variables.sample_holder_bottom ='250 um'
gui = MetalGUI(design)
design.ls.ls_df
design.delete_all_components()
# Define a dictionary for connection pad options for the transmon
conn_pads1 = dict(connection_pads = dict(coupler = dict(loc_W=1, loc_H=1),
readout = dict(loc_W=-1, loc_H=-1)))
conn_pads2 = dict(pad_width = '550 um',
pad_gap = '15um',
connection_pads = dict(coupler = dict(loc_W=-1, loc_H=1,pad_width='275um', pad_cpw_shift = '12.5um'),
readout = dict(loc_W=1, loc_H=-1,pad_width='275um')))
# Create a TransmonPocket6 object
q1 = TransmonPocket(design, "Q1", options=dict(pos_x='-0.5mm', pos_y='+0.0mm', layer=1, **conn_pads1))
q2 = TransmonPocket(design, "Q2", options=dict(pos_x='+0.5mm', pos_y='+0.0mm', layer=1, **conn_pads2))
# Rebuild and autoscale the GUI
gui.rebuild()
gui.autoscale()
gui.screenshot()
# Connect Transmons with direct coupler
coupler_options = dict(pin_inputs = dict(start_pin=dict(component=q2.name, pin='coupler'),
end_pin=dict(component=q1.name, pin='coupler')))
coupler_connector = RouteStraight(design, 'coupler_connector', options= coupler_options)
# Rebuild and autoscale the GUI
gui.rebuild()
gui.autoscale()
gui.screenshot()
# Create open-to-ground elements for readout resonators
otg11_options = dict(pos_x='-1.5mm', pos_y='0.0mm', orientation='180', layer='3')
otg21_options = dict(pos_x='+1.5mm', pos_y='0.0mm', orientation='0', layer='3')
otg12_options = dict(pos_x='-0.955mm', pos_y='-0.195mm', orientation='0', layer='3')
otg22_options = dict(pos_x='+0.955mm', pos_y='-0.1875mm', orientation='180', layer='3')
otg11 = OpenToGround(design, 'otg11', options=otg11_options)
otg21 = OpenToGround(design, 'otg21', options=otg21_options)
otg12 = OpenToGround(design, 'otg12', options=otg12_options)
otg22 = OpenToGround(design, 'otg22', options=otg22_options)
# Create readout resonators
readout1_options = dict(total_length = '5.97mm',
fillet = '40um',
pin_inputs = dict(start_pin = dict(component = otg11.name, pin = 'open'),
end_pin = dict(component = otg12.name, pin = 'open')),
lead=dict(start_straight='150um'),
meander=dict(spacing = '100um', asymmetry = '0'),
layer = '3')
readout2_options = dict(total_length = '5.97mm',
fillet = '40um',
pin_inputs = dict(start_pin = dict(component = otg22.name, pin = 'open'),
end_pin = dict(component = otg21.name, pin = 'open')),
lead=dict(start_straight='120um'),
meander=dict(spacing = '100um', asymmetry = '0.2'),
layer = '3')
readout1 = RouteMeander(design, 'readout1', options=readout1_options)
readout2 = RouteMeander(design, 'readout2', options=readout2_options)
# Rebuild and autoscale the GUI
gui.rebuild()
gui.autoscale()
gui.screenshot()
# Create via components
via_positions = [('-0.94mm','-0.1950mm'),('+0.94mm','-0.1875mm')]
for layer in ['1','2','3']:
for via, positions in enumerate(via_positions):
for subtract in zip([False,True],['30um','42um']):
via_size = '20um' if layer == '2' else subtract[1]
actual_layer = '5' if (layer == '2' and subtract[0]) else layer
via_options = dict(width = via_size,
height = via_size,
pos_x = positions[0],
pos_y = positions[1],
subtract = subtract[0],
layer = actual_layer,
orientation = '0',
helper = 'False',
chip = 'main')
name = 'via'+str(via+1)+'_layer'+actual_layer+('' if not subtract[0] else '_sub')
Rectangle(design, name, via_options)
# Rebuild and autoscale the GUI
gui.rebuild()
gui.autoscale()
gui.screenshot()
from qiskit_metal.renderers.renderer_elmer.elmer_renderer import QElmerRenderer
elmer_renderer = QElmerRenderer(design, layer_types=dict(metal=[1,2,3], dielectric=[4,5]))
elmer_renderer.render_design(mesh_geoms=True,
skip_junctions=True,
open_pins=[("Q1", "readout"),("Q2", "readout")],
omit_ground_for_layers=[2])
#elmer_renderer.launch_gmsh_gui()
elmer_renderer.export_mesh()
elmer_renderer.add_solution_setup('capacitance')
elmer_renderer.run('capacitance')
# Display capacitance matrix in [fF]
cap_matrix = elmer_renderer.capacitance_matrix
cap_matrix
elmer_renderer.display_post_processing_data()
elmer_renderer.close()
# Mesh Q1-only design
elmer_renderer = QElmerRenderer(design, layer_types=dict(metal=[1,2,3], dielectric=[4,5]))
select = ['Q1', 'via1_layer1', 'via1_layer2', 'via1_layer3',
'via1_layer1_sub', 'via1_layer5_sub', 'via1_layer3_sub']
elmer_renderer.render_design(selection=select,
open_pins=[('Q1', 'coupler'), ('Q1', 'readout')],
skip_junctions=True,
omit_ground_for_layers=[2])
elmer_renderer.launch_gmsh_gui()
# Solve Q1-only mode and save Cap Matrix
elmer_renderer.export_mesh()
elmer_renderer.add_solution_setup('capacitance')
elmer_renderer.run('capacitance')
cap_matrix_q1 = elmer_renderer.capacitance_matrix
#elmer_renderer.close()
cap_matrix_q1
elmer_renderer.display_post_processing_data()
elmer_renderer.close()
# Mesh Q2-only design
elmer_renderer = QElmerRenderer(design, layer_types=dict(metal=[1,2,3], dielectric=[4,5]))
select = ['Q2', 'via2_layer1', 'via2_layer2', 'via2_layer3',
'via2_layer1_sub', 'via2_layer5_sub', 'via2_layer3_sub']
elmer_renderer.render_design(selection=select,
open_pins=[('Q2', 'coupler'), ('Q2', 'readout')],
skip_junctions=True, omit_ground_for_layers=[2])
#elmer_renderer.launch_gmsh_gui()
# Solve Q2-only mode and save Cap Matrix
elmer_renderer.export_mesh()
elmer_renderer.add_solution_setup('capacitance')
elmer_renderer.run('capacitance')
cap_matrix_q2 = elmer_renderer.capacitance_matrix
elmer_renderer.close()
cap_matrix_q2
%matplotlib inline
import scqubits as scq
from scipy.constants import speed_of_light as c_light
import matplotlib.pyplot as plt
from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix
from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem, QuantumSystemRegistry
# cell 1: 1st transmon (Q1)
opt1 = dict(node_rename = {'Q1_coupler_connector_pad': 'coupling', 'via1_layer3_rectangle': 'readout_1'},
cap_mat = cap_matrix_q1,
ind_dict = {('Q1_pad_top', 'Q1_pad_bot'):10}, # junction inductance in nH
jj_dict = {('Q1_pad_top', 'Q1_pad_bot'):'j1'},
cj_dict = {('Q1_pad_top', 'Q1_pad_bot'):2} # junction capacitance in fF
)
cell_1 = Cell(opt1)
# cell 2: 2nd transmon (Q2)
opt2 = dict(node_rename = {'Q2_coupler_connector_pad': 'coupling', 'via2_layer3_rectangle': 'readout_2'},
cap_mat = cap_matrix_q2,
ind_dict = {('Q2_pad_top', 'Q2_pad_bot'): 12}, # junction inductance in nH
jj_dict = {('Q2_pad_top', 'Q2_pad_bot'):'j2'},
cj_dict = {('Q2_pad_top', 'Q2_pad_bot'):2} # junction capacitance in fF
)
cell_2 = Cell(opt2)
# subsystem 1: transmon 1
transmon_1 = Subsystem(name='transmon_1', sys_type='TRANSMON', nodes=['j1'])
# subsystem 2: transmon 2
transmon_2 = Subsystem(name='transmon_2', sys_type='TRANSMON', nodes=['j2'])
# subsystem 3: readout resonator 1
q_opts = dict(f_res = 8, # resonator dressed frequency in GHz
Z0 = 50, # characteristic impedance in Ohm
vp = 0.404314 * c_light # phase velocity
)
res_1 = Subsystem(name='readout_1', sys_type='TL_RESONATOR', nodes=['readout_1'], q_opts=q_opts)
# subsystem 4: readout resonator 2
q_opts = dict(f_res = 7.6, # resonator dressed frequency in GHz
Z0 = 50, # characteristic impedance in Ohm
vp = 0.404314 * c_light # phase velocity
)
res_2 = Subsystem(name='readout_2', sys_type='TL_RESONATOR', nodes=['readout_2'], q_opts=q_opts)
composite_sys = CompositeSystem(subsystems=[transmon_1, transmon_2, res_1, res_2],
cells=[cell_1, cell_2],
grd_node='ground_plane',
nodes_force_keep=['readout_1', 'readout_2'])
cg = composite_sys.circuitGraph()
print(cg)
hilbertspace = composite_sys.create_hilbertspace()
print(hilbertspace)
hilbertspace = composite_sys.add_interaction()
hilbertspace.hamiltonian()
hamiltonian_results = composite_sys.hamiltonian_results(hilbertspace, evals_count=30)
composite_sys.compute_gs()
|
https://github.com/qismib/TraNQI
|
qismib
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.tools.monitor import *
import matplotlib.pyplot as plt
import torch
from torch.autograd import Function
from torchvision import datasets, transforms
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import qiskit
from qiskit import transpile, assemble
import time
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
#backend_overview()
# In[2]:
#GLOBAL VARIABLES
n_qubits = 1
n_shots = 1000
shift = np.pi/2
n_parameters = 3
momentum = 0.5
simulator = qiskit.Aer.get_backend('qasm_simulator')
#can choose the simulator or the real quantum computer. The name of the variable is always 'simulator'
from qiskit.providers.ibmq import least_busy
from qiskit import IBMQ
# We execute on the least busy device (among the actual quantum computers)
#simulator = least_busy(provider.backends(operational = True, simulator=False, status_msg='active',
#filters=lambda x: x.configuration().n_qubits > 1))
simulator = provider.get_backend('ibmq_athens')
print("We are executing on...",simulator)
print("It has",simulator.status().pending_jobs,"pending jobs")
#IMPLEMENTING QUANTUM CLASS: 3 trainable parameters
#Hadamard gate (superposition) + U_gate (3 trainable parameters) + Measure_Z. Returning the expectation value over n_shots
class QuantumCircuit:
"""
This class provides an interface to interact with our Quantum Circuit
"""
def __init__(self, n_qubits, backend, shots):
#-----Circuit definition
self._circuit = qiskit.QuantumCircuit(n_qubits)
self.parameters = qiskit.circuit.ParameterVector('parameters', 3)
all_qubits = [i for i in range (n_qubits)]#qubits vector
self._circuit.h(all_qubits)
self._circuit.barrier()
self._circuit.u(self.parameters[0], self.parameters[1], self.parameters[2], all_qubits)
self._circuit.measure_all()
#-----
self.backend = backend
self.shots = shots
self.n_qubits = n_qubits
def draw(self):
self._circuit.draw(output ='mpl')
def expectation_Z(self,counts, shots, n_qubits):
expects = np.zeros(n_qubits)
for key in counts.keys():
percentage = counts[key]/shots
check = np.array([(float(key[i]))*percentage for i in range(n_qubits)])
expects += check
return expects
def run(self, thetas):
#acting on a simulator
thetas = thetas.squeeze()
p_circuit = self._circuit.bind_parameters({self.parameters[k]: thetas[k].item() for k in range(len(thetas))})
job_sim = qiskit.execute(p_circuit,
self.backend,
shots=self.shots)
result = job_sim.result()
counts = result.get_counts(p_circuit)
#print(counts['0'], counts['1'])
return self.expectation_Z(counts, self.shots, self.n_qubits)
#testing the implementation
circuit = QuantumCircuit(n_qubits, simulator, n_shots)
print(circuit._circuit)
circuit._circuit.draw(output = 'mpl', filename = 'U3_circuit.png')#to print as a pyplot figure (new library needed)
rotation = torch.Tensor([np.pi/4]*3)
exp = circuit.run(rotation)
print('Expected value for rotation pi: {}'.format(exp))
#######################
#CREATING A QUANTUM CLASSICAL CLASS
#extending autograd functions for a quantum layer(forward and backward)
class HybridFunction(Function):
"""Hybrid quantum-classical function definition"""
@staticmethod
def forward(ctx, input, quantum_circuit, shift):
"""Forward pass computation"""
ctx.shift = shift
ctx.quantum_circuit = quantum_circuit
# context variable (it may take multiple values and return them related to the context). Used to keep track for backpropagation
expectation_z = ctx.quantum_circuit.run(input) # evaluating model with trainable parameter
result = torch.tensor([expectation_z])
ctx.save_for_backward(input, result) # saves a given tensor for a future call to backward (trainable parameter and the result obtained)
# input=parameters (3), result=resut of quantum operation (1)
return result
@staticmethod
def backward(ctx, grad_output): #grad_output os previous gradient
"""Backward computation"""
input, expectation = ctx.saved_tensors #evaluated in forward
input = torch.reshape(input, (-1,))
gradients = torch.Tensor()
#iterating to evaluate gradient
for k in range(len(input)):
#shifting parameters
shift_right, shift_left = input.detach().clone(), input.detach().clone()
shift_right[k] += ctx.shift
shift_left[k] -= ctx.shift
# evaluating model after shift
expectation_right = ctx.quantum_circuit.run(shift_right)
expectation_left = ctx.quantum_circuit.run(shift_left)
#evaluating gradient with finite difference formula
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients = torch.cat((gradients, gradient.float()))
result = gradients.float() * grad_output.float()
return (result).T, None, None
#returns the chain of previous gradient and evaluated gradient
class Hybrid(nn.Module):
"""Hybrid quantum-cassical layer definition"""
def __init__(self, n_qubits ,backend, shots, shift):
super(Hybrid, self).__init__()
self.quantum_circuit = QuantumCircuit(n_qubits, backend, shots)
self.shift = shift #parameter shift
def forward(self, input):
return HybridFunction.apply(input, self.quantum_circuit, self.shift) #calling forward and backward
class AddGaussianNoise(object):
def __init__(self, mean=0., std=5):
self.std = std
self.mean = mean
def __call__(self, tensor):
return tensor + torch.randn(tensor.size()) * self.std + self.mean
def __repr__(self):
return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std)
#DATA LOADING
#training data, can chose whether to use a noisy set of training data
n_samples = 100
std_dv, mean = 0.3, 0
X_train = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor()]))
#X_train = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor(),
# AddGaussianNoise(mean, std_dv)]))
#keeping only labels 0 and 1
idx = np.append(np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples])
X_train.data = X_train.data[idx] #tensor values
X_train.targets = X_train.targets[idx]#tensor labels
#making batches (dim = 1). Ir returns an iterable(pytorch tensor)
train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True)
data_iter = iter(train_loader)#making the iterable an iterator, an object with the next method that can be used in a for cycle
#showing samples
n_samples_show = 6
fig, axes = plt.subplots(nrows=1, ncols=int(n_samples_show), figsize=(10, 3))
#subolot returns the figure and axis that are indipendent as default
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[int(n_samples_show) - 1].imshow(images[0].numpy().squeeze(), cmap='gray')#squeeze removes unuseful dim(1). Converting into a numpy vector
axes[int(n_samples_show) - 1].set_xticks([])
axes[int(n_samples_show) - 1].set_yticks([])
axes[int(n_samples_show) - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
#validation data
n_samples = 2000
X_test = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
idx = np.append(np.where(X_test.targets == 0)[0][:n_samples],
np.where(X_test.targets == 1)[0][:n_samples])
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True)
#CREATING THE NN
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, kernel_size=5) #input = gray scale
self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
self.dropout = nn.Dropout2d() #deactivating randomly some neurons to avoid overfitting
self.fc1 = nn.Linear(256, 64) #input dimension: CH(16) x Matrix_dim
self.fc2 = nn.Linear(64,3)
self.hybrid = Hybrid(n_qubits, simulator, n_shots, shift )
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)),2)
x = F.max_pool2d(F.relu(self.conv2(x)),2)
x = self.dropout(x)
x = x.view(1,-1) #reshaping tensor
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x) #calling the forward method
return torch.cat((x, 1-x),-1)#returning probabilities
#######################
#TRAINING AND TESTING
#function to train the nn
def training_loop (n_epochs, optimizer, model, loss_fn, train_loader):
loss_values = []
for epoch in range(0, n_epochs, +1):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()#getting rid of previous gradients
output = model(data)#forward pass
loss = loss_fn(output, target)
loss.backward()
optimizer.step()#updating parameters
total_loss.append(loss.item())#item transforms into a number
loss_values.append(sum(total_loss)/len(total_loss))#obtainign the average loss
print('Training [{:.0f}%] Loss: {:.4f}'.format(100*(epoch+1)/n_epochs, loss_values[-1]))
return loss_values
#Training the NN
#we can use any optimizer, learning rate and cost/loss function to train over multiple epochs
model = Net()
params = list(model.parameters())
epochs = 20
optimizer = optim.SGD(params, learning_rate, momentum=momentum)
loss_func = nn.CrossEntropyLoss()
loss_list = []
model.train() #training the module in training mode(specifying the intention to the layers). Used for dropout or batchnorm
begin = time.time()
loss_list = (training_loop(epochs, optimizer, model, loss_func, train_loader))
end = time.time()
#plotting the training graph
plt.figure(num=2)
plt.plot(loss_list)
plt.title('Hybrid NN Training convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
plt.savefig('TC_U3.pdf')
#defining a function to test our net
def validate(model, test_loader, loss_function, n_test, axes):
correct = 0
total_loss = []
count = 0
with torch.no_grad(): # disabling the gradient as we don't want to update parameters
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data) #evaluating the model on test data
# evaluating the accuracy of our model
pred = output.argmax(dim=1,
keepdim=True) # we are interested in the max value of probability
correct += pred.eq(target.view_as(pred)).sum().item() # checking if it matches with label
#evluating loss function
loss = loss_function(output, target)
total_loss.append(loss.item())
#printing the resut as images
if count >= n_test:
continue
else:
axes[count].imshow(data[0].numpy().squeeze(), cmap='gray')
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title('P: {}'.format(pred.item()))
count += 1
print('Performance on test data: \n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'
.format(sum(total_loss)/len(total_loss),(correct / len(test_loader))*100))
#TESTING THE NN
n_test_show = 6
model.eval()
validate(model, test_loader, loss_func, n_test_show, axes)
print('The program took: ', end- begin, 's to complete')
plt.show()
##########################
#testing the NN with noisy validation data
class AddGaussianNoise(object):
def __init__(self, mean=0., std=5):
self.std = std
self.mean = mean
def __call__(self, tensor):
return tensor + torch.randn(tensor.size()) * self.std + self.mean
def __repr__(self):
return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std)
stop,mean, std_dv= 9, 0, 0.2
for i in range (1, stop):
std_dv = std_dv + 0.1
print('Gaussian noise with std deviation: ', std_dv)
X_test_n = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([transforms.ToTensor(), AddGaussianNoise(mean, std_dv)]))
idx = np.append(np.where(X_test_n.targets == 0)[0][:n_samples],
np.where(X_test_n.targets == 1)[0][:n_samples])
X_test_n.data = X_test_n.data[idx] # tensor values
X_test_n.targets = X_test_n.targets[idx] # tensor labels
test_loader_n = torch.utils.data.DataLoader(X_test_n, batch_size=1, shuffle=True)
test_iter_n = iter(test_loader_n)
fig_1, axes_1 = plt.subplots(nrows=1, ncols=n_test_show, figsize=(10, 3))
model.eval()
validate(model, test_loader_n, loss_func, n_test_show, axes_1)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
from qiskit import QuantumCircuit, execute, IBMQ, Aer
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.noise import NoiseModel
# contruir modelo de ruido a partir das propriedades do chip
nshots = 8192
provider = IBMQ.load_account()
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
noise_model = NoiseModel.from_backend(device) # essa funcao constroi o modelo de ruido
print(noise_model)
# obter mapa de acoplamento do chip
coupling_map = device.configuration().coupling_map
print(coupling_map)
# obter base de portas logicas a partir do modelo de ruido
basis_gates = noise_model.basis_gates
print(basis_gates)
# construir o circuit
qc = QuantumCircuit(3, 3)
qc.h(0); qc.cx(0, 1); qc.cx(0, 2); qc.measure([0, 1, 2], [0, 1, 2])
qc.draw(output = 'mpl')
jobS = execute(qc, backend = simulator, shots = nshots)
plot_histogram(jobS.result().get_counts())
# faz a simulacao com o ruido ja incluido
jobNS = execute(qc, backend = simulator, coupling_map = coupling_map, basis_gates = basis_gates,
noise_model = noise_model, shots = nshots)
plot_histogram(jobNS.result().get_counts())
from qiskit.tools.monitor import job_monitor
jobE = execute(qc, backend = device, shots = nshots)
job_monitor(jobE)
plot_histogram(jobE.result().get_counts())
plot_histogram([jobS.result().get_counts(0), jobNS.result().get_counts(0), jobE.result().get_counts(0)],
bar_labels = False, legend = ['sim', 'noise_sim', 'exp'])
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from qiskit import compiler, BasicAer, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
def convert_to_basis_gates(circuit):
# unroll the circuit using the basis u1, u2, u3, cx, and id gates
unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id'])
pm = PassManager(passes=[unroller])
qc = compiler.transpile(circuit, BasicAer.get_backend('qasm_simulator'), pass_manager=pm)
return qc
def is_qubit(qb):
# check if the input is a qubit, which is in the form (QuantumRegister, int)
return isinstance(qb, tuple) and isinstance(qb[0], QuantumRegister) and isinstance(qb[1], int)
def is_qubit_list(qbs):
# check if the input is a list of qubits
for qb in qbs:
if not is_qubit(qb):
return False
return True
def summarize_circuits(circuits):
"""Summarize circuits based on QuantumCircuit, and four metrics are summarized.
Number of qubits and classical bits, and number of operations and depth of circuits.
The average statistic is provided if multiple circuits are inputed.
Args:
circuits (QuantumCircuit or [QuantumCircuit]): the to-be-summarized circuits
"""
if not isinstance(circuits, list):
circuits = [circuits]
ret = ""
ret += "Submitting {} circuits.\n".format(len(circuits))
ret += "============================================================================\n"
stats = np.zeros(4)
for i, circuit in enumerate(circuits):
dag = circuit_to_dag(circuit)
depth = dag.depth()
width = dag.width()
size = dag.size()
classical_bits = dag.num_cbits()
op_counts = dag.count_ops()
stats[0] += width
stats[1] += classical_bits
stats[2] += size
stats[3] += depth
ret = ''.join([ret, "{}-th circuit: {} qubits, {} classical bits and {} operations with depth {}\n op_counts: {}\n".format(
i, width, classical_bits, size, depth, op_counts)])
if len(circuits) > 1:
stats /= len(circuits)
ret = ''.join([ret, "Average: {:.2f} qubits, {:.2f} classical bits and {:.2f} operations with depth {:.2f}\n".format(
stats[0], stats[1], stats[2], stats[3])])
ret += "============================================================================\n"
return ret
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123456
from sklearn.datasets import make_blobs
features, labels = make_blobs(
n_samples=20,
centers=2,
center_box=(-1, 1),
cluster_std=0.1,
random_state=algorithm_globals.random_seed,
)
from qiskit import BasicAer
from qiskit.utils import QuantumInstance
sv_qi = QuantumInstance(
BasicAer.get_backend("statevector_simulator"),
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed,
)
from qiskit.circuit.library import ZZFeatureMap
from qiskit_machine_learning.kernels import QuantumKernel
feature_map = ZZFeatureMap(2)
previous_kernel = QuantumKernel(feature_map=feature_map, quantum_instance=sv_qi)
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=previous_kernel)
qsvc.fit(features, labels)
qsvc.score(features, labels)
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit.primitives import Sampler
fidelity = ComputeUncompute(sampler=Sampler())
from qiskit_machine_learning.kernels import FidelityQuantumKernel
feature_map = ZZFeatureMap(2)
new_kernel = FidelityQuantumKernel(feature_map=feature_map, fidelity=fidelity)
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=new_kernel)
qsvc.fit(features, labels)
qsvc.score(features, labels)
from qiskit import QuantumCircuit
from qiskit.circuit.library import RealAmplitudes
num_inputs = 2
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs, reps=1)
circuit = QuantumCircuit(num_inputs)
circuit.compose(feature_map, inplace=True)
circuit.compose(ansatz, inplace=True)
def parity(x):
return "{:b}".format(x).count("1") % 2
initial_point = algorithm_globals.random.random(ansatz.num_parameters)
from qiskit_machine_learning.neural_networks import CircuitQNN
circuit_qnn = CircuitQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=2,
quantum_instance=sv_qi,
)
from qiskit.algorithms.optimizers import COBYLA
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
classifier = NeuralNetworkClassifier(
neural_network=circuit_qnn,
loss="cross_entropy",
one_hot=True,
optimizer=COBYLA(maxiter=40),
initial_point=initial_point,
)
classifier.fit(features, labels)
classifier.score(features, labels)
from qiskit.primitives import Sampler
sampler = Sampler()
from qiskit_machine_learning.neural_networks import SamplerQNN
sampler_qnn = SamplerQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=2,
sampler=sampler,
)
classifier = NeuralNetworkClassifier(
neural_network=sampler_qnn,
loss="cross_entropy",
one_hot=True,
optimizer=COBYLA(maxiter=40),
initial_point=initial_point,
)
classifier.fit(features, labels)
classifier.score(features, labels)
import numpy as np
num_samples = 20
eps = 0.2
lb, ub = -np.pi, np.pi
features = (ub - lb) * np.random.rand(num_samples, 1) + lb
labels = np.sin(features[:, 0]) + eps * (2 * np.random.rand(num_samples) - 1)
from qiskit.circuit import Parameter
num_inputs = 1
feature_map = QuantumCircuit(1)
feature_map.ry(Parameter("input"), 0)
ansatz = QuantumCircuit(1)
ansatz.ry(Parameter("weight"), 0)
circuit = QuantumCircuit(num_inputs)
circuit.compose(feature_map, inplace=True)
circuit.compose(ansatz, inplace=True)
initial_point = algorithm_globals.random.random(ansatz.num_parameters)
from qiskit.opflow import PauliSumOp, StateFn
from qiskit_machine_learning.neural_networks import OpflowQNN
observable = PauliSumOp.from_list([("Z", 1)])
operator = StateFn(observable, is_measurement=True) @ StateFn(circuit)
opflow_qnn = OpflowQNN(
operator=operator,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
quantum_instance=sv_qi,
)
from qiskit.algorithms.optimizers import L_BFGS_B
from qiskit_machine_learning.algorithms import NeuralNetworkRegressor
regressor = NeuralNetworkRegressor(
neural_network=opflow_qnn,
optimizer=L_BFGS_B(maxiter=5),
initial_point=initial_point,
)
regressor.fit(features, labels)
regressor.score(features, labels)
from qiskit.primitives import Estimator
estimator = Estimator()
from qiskit_machine_learning.neural_networks import EstimatorQNN
estimator_qnn = EstimatorQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
estimator=estimator,
)
from qiskit.algorithms.optimizers import L_BFGS_B
from qiskit_machine_learning.algorithms import VQR
regressor = NeuralNetworkRegressor(
neural_network=estimator_qnn,
optimizer=L_BFGS_B(maxiter=5),
initial_point=initial_point,
)
regressor.fit(features, labels)
regressor.score(features, labels)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/avkhadiev/schwinger-vqe
|
avkhadiev
|
#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/martynscn/Masters-Thesis-on-Quantum-Cryptography
|
martynscn
|
# This code has been adapted and modified from IBM Qiskit 2021 and
# uses the constant optimized modular exponentiation circuit for mod 15 as contained
# in https://arxiv.org/abs/1202.6614.
import numpy as np
import math
from decimal import *
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.visualization import plot_histogram
from qiskit import Aer, transpile, assemble
import pandas as pd
from fractions import Fraction
#
# import math
# from math import gcd
# from numpy.random import randint
#
#
# from decimal import *
print("Imports Successful")
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
def my_mod(a,n):
getcontext().prec = 27
return round((Decimal(a)/Decimal(n) - Decimal(a)//Decimal(n) ) * n)
def constant_optimized_modular_exponentation_modulus15(a, power):
if a not in [2,7,8,11,13]:
raise ValueError("'a' must be 2,7,8,11 or 13")
U = QuantumCircuit(4)
for iteration in range(power):
if a in [2,13]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
if a in [7,8]:
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
if a == 11:
U.swap(1,3)
U.swap(0,2)
if a in [7,11,13]:
for q in range(4):
U.x(q)
U = U.to_gate()
U.name = "%i^%i mod 15" % (a, power)
control_U = U.control()
return control_U
def inverse_qft(n):
circuit = QuantumCircuit(n)
for i in range(n//2):
circuit.swap(i, n-1-i)
for j in range(n):
for m in range(j):
circuit.cp(-np.pi/float(2**(j-m)), m, j)
circuit.h(j)
circuit.name = "QFT†"
return circuit
N = 15
a = 7
n_count = 8
counting_register = QuantumRegister(size = n_count, name = "counting_register")
acting_register = QuantumRegister(size = 4, name="acting_register")
classic_register = ClassicalRegister(size = n_count, name="classic_register")
qc = QuantumCircuit(counting_register, acting_register ,classic_register)
initial_state = [1,0]
for q in range(8):
qc.initialize(initial_state, q)
qc.draw(output = 'mpl', filename = "Step0")
for q in range(n_count):
qc.h(q)
qc.draw(output = 'mpl', filename = "Step1")
qc.x(3+n_count)
qc.draw(output = 'mpl', filename = "Step1b")
for q in range(n_count):
qc.append(constant_optimized_modular_exponentation_modulus15(a, 2**q),
[q] + [i+n_count for i in range(4)])
qc.measure(range(n_count,n_count + 4), range(4))
qc.barrier()
qc.draw(output = 'mpl', filename = "Step2")
qc.append(inverse_qft(n_count), range(n_count))
qc.draw(output = 'mpl', filename = "Step3")
# Measure circuit
qc.measure(range(n_count), range(n_count))
qc.draw(output = 'mpl', filename = "Step4")
qasm_sim = Aer.get_backend('qasm_simulator')
t_qc = transpile(qc, qasm_sim)
qobj = assemble(t_qc)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
rows, measured_phases = [], []
for output in counts:
decimal = int(output, 2)
phase = decimal/(2**n_count)
measured_phases.append(phase)
rows.append([f"{output}(bin) = {decimal:>3}(dec)",
f"{decimal}/{2**n_count} = {phase:.2f}"])
headers=["Register Output", "Phase"]
df = pd.DataFrame(rows, columns=headers)
df
rows = []
for phase in measured_phases:
frac = Fraction(phase).limit_denominator(15)
rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator])
headers=["Phase", "Fraction", "Guess for r"]
df = pd.DataFrame(rows, columns=headers)
my_period_r = max(df["Guess for r"])
print("My period (r) is %i" % my_period_r)
# Confirm that the period is 4
xvals = np.arange(N)
xvals = [x.item() for x in xvals]
yvals = [my_mod(a**x, N) for x in xvals]
fig, ax = plt.subplots();
ax.plot(xvals, yvals, linewidth=1, linestyle='dotted', marker='x');
ax.set(xlabel='$x$', ylabel='$%i^x$ mod $%i$' % (a, N),
title="Example of Periodic Function in Shor's Algorithm");
try:
r = yvals[1:].index(1) +1
plt.annotate(s = '', xy=(0,1), xytext=(r,1), arrowprops=dict(arrowstyle='<->'));
plt.annotate(s = '$r=%i$' % r, xy=(r/3,1.5));
except ValueError:
print('Could not find a period')
first_shared_factor = math.gcd((7**(int(my_period_r/2)) + 1), 15)
first_shared_factor
second_shared_factor = math.gcd((7**(int(my_period_r/2)) - 1), 15)
second_shared_factor
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A collection of discrete probability metrics."""
from __future__ import annotations
import numpy as np
def hellinger_distance(dist_p: dict, dist_q: dict) -> float:
"""Computes the Hellinger distance between
two counts distributions.
Parameters:
dist_p (dict): First dict of counts.
dist_q (dict): Second dict of counts.
Returns:
float: Distance
References:
`Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_
"""
p_sum = sum(dist_p.values())
q_sum = sum(dist_q.values())
p_normed = {}
for key, val in dist_p.items():
p_normed[key] = val / p_sum
q_normed = {}
for key, val in dist_q.items():
q_normed[key] = val / q_sum
total = 0
for key, val in p_normed.items():
if key in q_normed:
total += (np.sqrt(val) - np.sqrt(q_normed[key])) ** 2
del q_normed[key]
else:
total += val
total += sum(q_normed.values())
dist = np.sqrt(total) / np.sqrt(2)
return dist
def hellinger_fidelity(dist_p: dict, dist_q: dict) -> float:
"""Computes the Hellinger fidelity between
two counts distributions.
The fidelity is defined as :math:`\\left(1-H^{2}\\right)^{2}` where H is the
Hellinger distance. This value is bounded in the range [0, 1].
This is equivalent to the standard classical fidelity
:math:`F(Q,P)=\\left(\\sum_{i}\\sqrt{p_{i}q_{i}}\\right)^{2}` that in turn
is equal to the quantum state fidelity for diagonal density matrices.
Parameters:
dist_p (dict): First dict of counts.
dist_q (dict): Second dict of counts.
Returns:
float: Fidelity
Example:
.. code-block::
from qiskit import QuantumCircuit, execute, BasicAer
from qiskit.quantum_info.analysis import hellinger_fidelity
qc = QuantumCircuit(5, 5)
qc.h(2)
qc.cx(2, 1)
qc.cx(2, 3)
qc.cx(3, 4)
qc.cx(1, 0)
qc.measure(range(5), range(5))
sim = BasicAer.get_backend('qasm_simulator')
res1 = execute(qc, sim).result()
res2 = execute(qc, sim).result()
hellinger_fidelity(res1.get_counts(), res2.get_counts())
References:
`Quantum Fidelity @ wikipedia <https://en.wikipedia.org/wiki/Fidelity_of_quantum_states>`_
`Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_
"""
dist = hellinger_distance(dist_p, dist_q)
return (1 - dist**2) ** 2
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Providers that support BackendV2 interface"""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeProvider
from qiskit.providers.fake_provider.fake_backend_v2 import FakeBackendSimple
from qiskit.utils import QuantumInstance
from qiskit_algorithms import VQE, Grover, AmplificationProblem
from qiskit.opflow import X, Z, I
from qiskit_algorithms.optimizers import SPSA
from qiskit.circuit.library import TwoLocal
class TestBackendV2(QiskitAlgorithmsTestCase):
"""test BackendV2 interface"""
def setUp(self):
super().setUp()
self._provider = FakeProvider()
self._qasm = FakeBackendSimple()
self.seed = 50
def test_vqe_qasm(self):
"""Test the VQE on QASM simulator."""
optimizer = SPSA(maxiter=300, last_avg=5)
wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
with self.assertWarns(DeprecationWarning):
h2_op = (
-1.052373245772859 * (I ^ I)
+ 0.39793742484318045 * (I ^ Z)
- 0.39793742484318045 * (Z ^ I)
- 0.01128010425623538 * (Z ^ Z)
+ 0.18093119978423156 * (X ^ X)
)
qasm_simulator = QuantumInstance(
self._qasm, shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed
)
with self.assertWarns(DeprecationWarning):
vqe = VQE(
ansatz=wavefunction,
optimizer=optimizer,
max_evals_grouped=1,
quantum_instance=qasm_simulator,
)
result = vqe.compute_minimum_eigenvalue(operator=h2_op)
self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05)
def test_run_circuit_oracle(self):
"""Test execution with a quantum circuit oracle"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=["11"])
with self.assertWarns(DeprecationWarning):
qi = QuantumInstance(
self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32
)
with self.assertWarns(DeprecationWarning):
grover = Grover(quantum_instance=qi)
result = grover.amplify(problem)
self.assertIn(result.top_measurement, ["11"])
def test_run_circuit_oracle_single_experiment_backend(self):
"""Test execution with a quantum circuit oracle"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=["11"])
backend = self._provider.get_backend("fake_yorktown")
backend._configuration.max_experiments = 1
with self.assertWarns(DeprecationWarning):
qi = QuantumInstance(
self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32
)
with self.assertWarns(DeprecationWarning):
grover = Grover(quantum_instance=qi)
result = grover.amplify(problem)
self.assertIn(result.top_measurement, ["11"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/alexao8/QC-Qiskit
|
alexao8
|
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ, assemble, transpile
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.ibmq import least_busy
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# Build
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
#Add a NOT gate on qubit 1
circuit.x(1)
# Add a H gate on qubit 0 and 1
circuit.h(0)
circuit.h(1)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Add a H gate on qubit 0 and 1
circuit.h(0)
circuit.h(1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
circuit.draw(output = 'mpl')
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Return counts
counts = result.get_counts(circuit)
print("\nTotal count for 00 and 11 are:",counts)
# Import draw_circuit, then use it to draw the circuit
from ibm_quantum_widgets import draw_circuit
draw_circuit(circuit)
# Analyze
#--------
# Plot a histogram
plot_histogram(counts)
# Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits
n=2
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
transpiled_dj_circuit = transpile(circuit, backend, optimization_level=3)
job = backend.run(transpiled_dj_circuit)
job_monitor(job, interval=2)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# If you introduce a list with less colors than bars, the color of the bars will
# alternate following the sequence from the list.
import numpy as np
from qiskit.quantum_info import DensityMatrix
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0, 1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
matrix = DensityMatrix(qc)
plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
|
https://github.com/quantumjim/qreative
|
quantumjim
|
import sys
sys.path.append('../')
import CreativeQiskit
stats = CreativeQiskit.bitstring_superposer(['0000','0101'],shots=1)
print(" Random string from superposition: ",list(stats.keys())[0])
stats = CreativeQiskit.bitstring_superposer(['0000','1111'])
print(" Strings and their fractions: ",stats)
stats = CreativeQiskit.bitstring_superposer(['0000','1111'],bias=0.8)
print(" Strings and their fractions: ",stats)
stats = CreativeQiskit.bitstring_superposer(['00','01','10','11'],bias=0.8)
print(" Strings and their fractions: ",stats)
stats = CreativeQiskit.emoticon_superposer([';)','8)'])
print(" Emoticons and their fractions: ",stats)
import sys
sys.path.append('../')
import CreativeQiskit
stats = CreativeQiskit.emoticon_superposer([';)','8)'],noisy=True)
stats = CreativeQiskit.emoticon_superposer([ [';)','8)'] , [':D','8|'] ])
print(stats)
CreativeQiskit.image_superposer(['butterfly','moth','heron'],[['moth','heron'],['moth','butterfly']])
import sys
sys.path.append('../')
import CreativeQiskit
CreativeQiskit.audio_superposer(['8bit_Dungeon_Level','Bit_Quest','8bit_Dungeon_Boss','Bit_Shift'],['8bit_Dungeon_Level','Bit_Quest'],noisy=True)
|
https://github.com/crabster/qiskit-learning
|
crabster
|
"""
Test Script
"""
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
qrx = QuantumRegister(1, 'q0')
qry = QuantumRegister(1, 'q1')
cr = ClassicalRegister(1, 'c')
qc = QuantumCircuit(qrx, qry, cr)
qc.h(qrx)
qc.x(qry)
qc.h(qry)
qc.barrier()
qc.x(qry)
qc.barrier()
qc.h(qrx)
qc.h(qry)
qc.measure(qrx, cr)
qc.draw("mpl")
from qiskit import execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
sim = AerSimulator()
job = execute(qc, backend = sim, shots = 1000)
result = job.result()
counts = result.get_counts(qc)
print("Counts: ", counts)
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import execute, pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), d0)
pulse_prog.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Import requisite modules
import math
import datetime
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Import Qiskit packages
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit_aer.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
# The data providers of stock-market data
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_finance.applications.optimization import PortfolioDiversification
# Generate a pairwise time-series similarity matrix
seed = 123
stocks = ["TICKER1", "TICKER2"]
n = len(stocks)
data = RandomDataProvider(
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=seed,
)
data.run()
rho = data.get_similarity_matrix()
q = 1 # q less or equal than n
class ClassicalOptimizer:
def __init__(self, rho, n, q):
self.rho = rho
self.n = n # number of inner variables
self.q = q # number of required selection
def compute_allowed_combinations(self):
f = math.factorial
return int(f(self.n) / f(self.q) / f(self.n - self.q))
def cplex_solution(self):
# refactoring
rho = self.rho
n = self.n
q = self.q
my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)]
my_ub = [1 for x in range(0, n**2 + n)]
my_lb = [0 for x in range(0, n**2 + n)]
my_ctype = "".join(["I" for x in range(0, n**2 + n)])
my_rhs = (
[q]
+ [1 for x in range(0, n)]
+ [0 for x in range(0, n)]
+ [0.1 for x in range(0, n**2)]
)
my_sense = (
"".join(["E" for x in range(0, 1 + n)])
+ "".join(["E" for x in range(0, n)])
+ "".join(["L" for x in range(0, n**2)])
)
try:
my_prob = cplex.Cplex()
self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs)
my_prob.solve()
except CplexError as exc:
print(exc)
return
x = my_prob.solution.get_values()
x = np.array(x)
cost = my_prob.solution.get_objective_value()
return x, cost
def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs):
n = self.n
prob.objective.set_sense(prob.objective.sense.minimize)
prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype)
prob.set_log_stream(None)
prob.set_error_stream(None)
prob.set_warning_stream(None)
prob.set_results_stream(None)
rows = []
col = [x for x in range(n**2, n**2 + n)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
for ii in range(0, n):
col = [x for x in range(0 + n * ii, n + n * ii)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
for ii in range(0, n):
col = [ii * n + ii, n**2 + ii]
coef = [1, -1]
rows.append([col, coef])
for ii in range(0, n):
for jj in range(0, n):
col = [ii * n + jj, n**2 + jj]
coef = [1, -1]
rows.append([col, coef])
prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs)
# Instantiate the classical optimizer class
classical_optimizer = ClassicalOptimizer(rho, n, q)
# Compute the number of feasible solutions:
print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations()))
# Compute the total number of possible combinations (feasible + unfeasible)
print("Total number of combinations= " + str(2 ** (n * (n + 1))))
# Visualize the solution
def visualize_solution(xc, yc, x, C, n, K, title_str):
plt.figure()
plt.scatter(xc, yc, s=200)
for i in range(len(xc)):
plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r")
plt.grid()
for ii in range(n**2, n**2 + n):
if x[ii] > 0:
plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20)
for ii in range(0, n**2):
if x[ii] > 0:
iy = ii // n
ix = ii % n
plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2")
plt.title(title_str + " cost = " + str(int(C * 100) / 100.0))
plt.show()
from qiskit.utils import algorithm_globals
class QuantumOptimizer:
def __init__(self, rho, n, q):
self.rho = rho
self.n = n
self.q = q
self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q)
self.qp = self.pdf.to_quadratic_program()
# Obtains the least eigenvalue of the Hamiltonian classically
def exact_solution(self):
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(self.qp)
return self.decode_result(result)
def vqe_solution(self):
algorithm_globals.random_seed = 100
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full")
vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(self.qp)
return self.decode_result(result)
def qaoa_solution(self):
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(self.qp)
return self.decode_result(result)
def decode_result(self, result, offset=0):
quantum_solution = 1 - (result.x)
ground_level = self.qp.objective.evaluate(result.x)
return quantum_solution, ground_level
# Instantiate the quantum optimizer class with parameters:
quantum_optimizer = QuantumOptimizer(rho, n, q)
# Check if the binary representation is correct. This requires CPLEX
try:
import cplex
# warnings.filterwarnings('ignore')
quantum_solution, quantum_cost = quantum_optimizer.exact_solution()
print(quantum_solution, quantum_cost)
classical_solution, classical_cost = classical_optimizer.cplex_solution()
print(classical_solution, classical_cost)
if np.abs(quantum_cost - classical_cost) < 0.01:
print("Binary formulation is correct")
else:
print("Error in the formulation of the Hamiltonian")
except Exception as ex:
print(ex)
ground_state, ground_level = quantum_optimizer.exact_solution()
print(ground_state)
classical_cost = 1.000779571614484 # obtained from the CPLEX solution
try:
if np.abs(ground_level - classical_cost) < 0.01:
print("Ising Hamiltonian in Z basis is correct")
else:
print("Error in the Ising Hamiltonian formulation")
except Exception as ex:
print(ex)
vqe_state, vqe_level = quantum_optimizer.vqe_solution()
print(vqe_state, vqe_level)
try:
if np.linalg.norm(ground_state - vqe_state) < 0.01:
print("SamplingVQE produces the same solution as the exact eigensolver.")
else:
print(
"SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected."
)
except Exception as ex:
print(ex)
xc, yc = data.get_coordinates()
visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical")
visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/petr-ivashkov/qiskit-cert-workbook
|
petr-ivashkov
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
#ignore deprecation warnings because they are annoying (not recommened generally)
from warnings import simplefilter
simplefilter(action='ignore', category=DeprecationWarning)
# Importing standard Qiskit libraries
from qiskit import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.quantum_info import *
from qiskit.circuit.library import *
from ibm_quantum_widgets import *
NUM_QUBITS = 2
# let's construct a multi-qubit quantum register
qr = QuantumRegister(NUM_QUBITS, 'q')
qc = QuantumCircuit(qr, name='my-circuit')
# let's create a Bell's state
qc.h(0)
qc.cx(0,1)
qc.measure_all()
qc.draw()
# let's construct a multi-bit classical register
cr = ClassicalRegister(NUM_QUBITS, 'c')
qc = QuantumCircuit(qr, cr, name='my-circuit')
# explicitly measure qubits [0,1] into classical bits [0,1]
qc.measure(qr, cr)
# alternatively: qc.measure([0,1], [0,1])
qc.draw()
# Bell state 0
bell_0 = QuantumCircuit(2)
bell_0.h(0)
bell_0.cx(0,1)
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell1 = sv.evolve(bell_0)
sv_bell1.draw('latex')
# Bell state 1
bell_1 = QuantumCircuit(2)
bell_1.x(0)
bell_1.h(0)
bell_1.cx(0,1)
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell2 = sv.evolve(bell_1)
sv_bell2.draw('latex')
# Bell state 2
bell_2 = QuantumCircuit(2)
bell_2.x(0)
bell_2.h(1)
bell_2.cx(1,0)
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell3 = sv.evolve(bell_2)
sv_bell3.draw('latex')
# create the last remaining Bell state on your own
bell_3 = QuantumCircuit(2)
### ADD CODE BELOW
bell_3.x(0)
bell_3.x(1)
bell_3.h(1)
bell_3.cx(1,0)
### DON'T ADD CODE BELOW
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell3 = sv.evolve(bell_3)
sv_bell3.draw('latex')
# state of equal superposition of basis states
max_sp = QuantumCircuit(2)
max_sp.h(0)
max_sp.h(1)
sv = Statevector.from_label('00')
# evolve the initial state through the circuit
### ADD CODE BELOW
sv_ev = sv.evolve(max_sp)
sv_ev.draw('latex')
### DON'T ADD CODE BELOW
qc = QuantumCircuit(1)
qc.h(0)
qc.h(0)
qc.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
qc = QuantumCircuit(1)
qc.h(0)
qc.h(0)
transpile(qc, backend=backend).draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
qc = QuantumCircuit(1)
qc.h(0)
qc.barrier()
qc.h(0)
transpile(qc, backend=backend).draw('mpl')
# try it out yourself with different gates: instead of Hadamard, try Pauili gates
my_qc = QuantumCircuit(1)
### ADD CODE BELOW
my_qc.x(0)
my_qc.barrier()
my_qc.x(0)
### DON'T ADD CODE BELOW
transpile(my_qc, backend=backend).draw('mpl')
# did you get what you expected?
qc = QuantumCircuit(1)
qc.x(0)
qc.depth()
qc = QuantumCircuit(2)
qc.x([0,1])
qc.x(1)
qc.depth()
# draw the circuit yourself to see why the depth has increased now
### ADD CODE BELOW
qc.draw()
### DON'T ADD CODE BELOW
qc = QuantumCircuit(2)
qc.x(0)
qc.barrier(0)
qc.h(0)
qc.cx(0,1)
qc.depth()
# draw the circuit yourself to see why the depth has increased now
# hint: the longest path is not always the lenth of the longest sequence along one channel
qc.draw('mpl')
# the second qubit only has a CX gate applied to it, but has to "wait" for the first qubit to provide the control
# also, barier doesn't count
# in the following we will use the implementation of Grover's algorithm in Qiskit
from qiskit.algorithms import Grover, AmplificationProblem
# let's construct an oracle with a single solution
sv = Statevector.from_label('010')
problem = AmplificationProblem(oracle=sv)
grover = Grover(iterations=2).construct_circuit(problem=problem)
# the original circuit contains unitaries
# transpile the circuit in terms of basis gates to see what it is "made of"
t_grover = transpile(grover, basis_gates=['cx', 'u3'])
t_grover.draw('mpl', fold=-1)
# draw the original cicuit yourself
grover.draw('mpl', fold=-1)
# lets's try to evolve the initial state through the circuit like we have done for Bell states
sv = Statevector.from_label('000')
sv_ev = sv.evolve(grover)
sv_ev.draw('latex')
# it is obvious from statevector evolutions, that the state 010
# has the best chances to be measured, as desired
# now let's obtain the same result from the QASM simulation
# for that we need to measure the qubits in the end of our circuit
grover.measure_all()
backend= BasicAer.get_backend('qasm_simulator')
job = execute(grover, backend, shots=1024)
result = job.result()
plot_histogram(result.get_counts())
# finally let's see how our circuit performs on actual hardware
# you will need your IBM Quantum account
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
# sometimes you might need to wait when running on real devices
# let's monitor the status of our job
from qiskit.tools import job_monitor
# to call a real backend let's pick the least busy one, which satisfies out requirments
from qiskit.providers.ibmq import least_busy
suitable_devices = provider.backends(filters = lambda b: b.configuration().n_qubits >= 3
and not b.configuration().simulator
and b.status().operational==True)
backend = least_busy(backends=suitable_devices)
print("We are runnig our circuit on ", backend)
#job = execute(grover, backend=backend)
#job_monitor(job)
# we see that results from a real device also match our expectations
# the algorithm successfully finds the marked string
result = job.result()
counts = result.get_counts()
### ADD CODE BELOW
# plot the histogramm yourself
plot_histogram(counts)
### DON'T ADD CODE BELOW
# let's again use our transpiled Grover circuit to demonstarte the idea
# Notice: QASM doesn't look "nice". This is a low-level language which can be understood by quantum hardware.
# If you want to take a look at the QASM code make sure to specify 'formatted=True' which makes the code readable by a human being.
t_grover.qasm(formatted=True)
# store the circuit to a file in the follwing way
qasm_code = t_grover.qasm(filename='grover.qasm')
# to get the circuit back from QASM file execute the following
my_qc = QuantumCircuit.from_qasm_file('grover.qasm')
my_qc.draw('mpl', fold=-1)
# let's create an arbitrary Operator from a matrix
A = np.array([[0,1,0], [1,0,0], [0,1,1]])
op = Operator(A)
# Operator contains information about its matrix representation and input and output dimensions
op
# create an Operator from a circuit yourself
qc = QuantumCircuit(2)
qc.h([0,1])
qc.cx(0,1)
op = Operator(qc)
op
A = Operator(Pauli(label='X'))
B = Operator(Pauli(label='Z'))
A.expand(B) # B x A
A = Operator(Pauli(label='X'))
B = Operator(Pauli(label='Z'))
A.tensor(B) # result A x B
III = Operator(np.eye(2 ** 3))
XX = Operator(Pauli(label='XX'))
XIX = III.compose(XX, qargs=[0,2])
XIX # the resulting operator is X x I x X
# compose an XIXZ Operator from IIII and XX and Z Operators
### ADD CODE BELOW
IIII = Operator(np.eye(2 ** 4))
XX = Operator(Pauli(label='XX'))
Z = Operator(Pauli('Z'))
XIXI = IIII.compose(XX, qargs=[1,3])
XIXZ = XIXI.compose(Z, qargs=[0])
### DON'T ADD CODE BELOW
print(XIXZ)
# with Qiskit you can find the state fidelity between two quantum states
# let's investigate Bell states
state_fidelity(sv_bell3, sv_bell1)
basis_state_00 = Statevector.from_label('00')
state_fidelity(basis_state_00, sv_bell1)
basis_state_00 = Statevector.from_label('00')
state_fidelity(basis_state_00, sv_bell3)
# let's find process fidelity of X and H Operators
op_1 = Operator([[0,1],[0,1]])
op_2 = Operator([[1,1],[1,-1]])/np.sqrt(2)
F = process_fidelity(op_1, op_2)
F
# what about fidelity of X Operator with itself multiplied with a complex phase
op_1 = Operator([[0,1],[0,1]])
op_2 = op_1*np.exp(0.5j)
# calculate the process fidelity yourself
### ADD CODE BELOW
F = process_fidelity(op_1, op_2)
F
### DON'T ADD CODE BELOW
# as you expected, the fidelity is independent of global phase
# encountered a compatibility error? Check which version of Qiskit you are using
import qiskit
qiskit.__qiskit_version__
# display the entire version table
%qiskit_version_table
# Let's have an overview information on all the IBMQ backends that are available
%qiskit_backend_overview
# now let's pick one device and investigate it
from qiskit.visualization import plot_gate_map
backend = provider.get_backend('ibmq_bogota')
plot_gate_map(backend, plot_directed=True)
plot_error_map(backend)
# let's plot the layout of our Bell state circuit transpiled for our target backend
transpiled_bell = transpile(bell_0, backend=backend)
plot_circuit_layout(transpiled_bell, backend=backend)
# display the layout of transpiled Grover's circuit on our target backend
transpiled_grover = transpile(grover, backend=backend)
plot_circuit_layout(transpiled_grover, backend=backend)
# what if we want to specify a custom mapping of our circuit qubits to device qubits?
# let's create an initial layout
initial_layout = [2,3,4] # virtual to physical: virtual qubits are ordered
transpiled_qc = transpile(grover, backend=backend, initial_layout=initial_layout)
plot_circuit_layout(transpiled_qc, backend=backend)
# for example, let's draw our Bell's state circuit in text mode
bell_0.draw('text')
# qubits in reversed order
bell_0.draw('mpl', reverse_bits=True)
# More customization
style = {'linecolor': 'red', 'backgroundcolor': 'grey'}
bell_0.draw('mpl',scale = 1.2, style=style, fold=-1)
plot_bloch_vector([0,1,0])
plot_state_city(bell_0)
# to understand why the 'city' looks like this consider the density matrix of this state
plot_state_hinton(bell_0)
plot_state_qsphere(bell_0)
plot_state_paulivec(bell_0)
plot_bloch_multivector(bell_0)
# here, the bloch spheres represent maximally entangled qubits as zero-length vectors. Hence, no arrows.
# a more informative example
psi = Statevector.from_label('+1')
plot_bloch_multivector(psi)
# the first qubit is in state |1>
# the second qubit is in the superposition of |0> and |1>
rho = DensityMatrix.from_instruction(bell_0)
rho.draw('latex', prefix='\\rho_{Bell_0} = ')
plot_state_city(rho.data, title='Density Matrix')
# prepare a density matrix for the state of the equal superposition of 2 basis states
my_qc = QuantumCircuit(2)
my_qc.h([0,1])
my_rho = DensityMatrix.from_instruction(my_qc)
my_rho.draw('latex', prefix='\\rho_{equal} = ')
# prepare a density matrix for a mixed one-qubit state in an equal mixture of |0> and |1>
### ADD CODE BELOW
my_rho_M = np.array([[0.5, 0], [0, 0.5]])
my_rho = DensityMatrix(my_rho_M)
my_rho.draw('latex', prefix='\\rho_{mixture} = ')
### DON'T ADD CODE BELOW
qr = QuantumRegister(3, name='q')
qc = QuantumCircuit(qr)
qc.ccx(control_qubit1=qr[1], control_qubit2=qr[2], target_qubit=qr[0])
qc.draw('mpl')
# Toffoli gate has the following matrix representation for the above configuration
matrix = Operator(qc).data
array_to_latex(matrix, prefix="CCX = ")
qr = QuantumRegister(2, name='q')
qc = QuantumCircuit(qr)
qc.swap(qubit1=qr[0], qubit2=[1])
qc.draw('mpl')
# SWAP gate has the following matrix representation for the above configuration
matrix = Operator(qc).data
# display the matrix in latex
array_to_latex(matrix, prefix="SWAP = ")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
ghz.draw(output='mpl')
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the optimize-1q-gate pass"""
import unittest
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Optimize1qGates, Unroller
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.circuit import Parameter
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, UGate, PhaseGate
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.target import Target
class TestOptimize1qGates(QiskitTestCase):
"""Test for 1q gate optimizations."""
def test_dont_optimize_id(self):
"""Identity gates are like 'wait' commands.
They should never be optimized (even without barriers).
See: https://github.com/Qiskit/qiskit-terra/issues/2373
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.i(qr)
circuit.i(qr)
dag = circuit_to_dag(circuit)
pass_ = Optimize1qGates()
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_optimize_h_gates_pass_manager(self):
"""Transpile: qr:--[H]-[H]-[H]-- == qr:--[u2]--"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.h(qr[0])
expected = QuantumCircuit(qr)
expected.append(U2Gate(0, np.pi), [qr[0]])
passmanager = PassManager()
passmanager.append(Unroller(["u2"]))
passmanager.append(Optimize1qGates())
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_1q_gates_collapse_identity_equivalent(self):
"""test optimize_1q_gates removes u1(2*pi) rotations.
See: https://github.com/Qiskit/qiskit-terra/issues/159
"""
# ┌───┐┌───┐┌────────┐┌───┐┌─────────┐┌───────┐┌─────────┐┌───┐ ┌─┐»
# qr_0: ┤ H ├┤ X ├┤ U1(2π) ├┤ X ├┤ U1(π/2) ├┤ U1(π) ├┤ U1(π/2) ├┤ X ├─────────┤M├»
# └───┘└─┬─┘└────────┘└─┬─┘└─────────┘└───────┘└─────────┘└─┬─┘┌───────┐└╥┘»
# qr_1: ───────■──────────────■───────────────────────────────────■──┤ U1(π) ├─╫─»
# └───────┘ ║ »
# cr: 2/═══════════════════════════════════════════════════════════════════════╩═»
# 0 »
# «
# «qr_0: ────────────
# « ┌───────┐┌─┐
# «qr_1: ┤ U1(π) ├┤M├
# « └───────┘└╥┘
# «cr: 2/══════════╩═
# « 1
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.cx(qr[1], qr[0])
qc.append(U1Gate(2 * np.pi), [qr[0]])
qc.cx(qr[1], qr[0])
qc.append(U1Gate(np.pi / 2), [qr[0]]) # these three should combine
qc.append(U1Gate(np.pi), [qr[0]]) # to identity then
qc.append(U1Gate(np.pi / 2), [qr[0]]) # optimized away.
qc.cx(qr[1], qr[0])
qc.append(U1Gate(np.pi), [qr[1]])
qc.append(U1Gate(np.pi), [qr[1]])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
dag = circuit_to_dag(qc)
simplified_dag = Optimize1qGates().run(dag)
num_u1_gates_remaining = len(simplified_dag.named_nodes("u1"))
self.assertEqual(num_u1_gates_remaining, 0)
def test_optimize_1q_gates_collapse_identity_equivalent_phase_gate(self):
"""test optimize_1q_gates removes u1(2*pi) rotations.
See: https://github.com/Qiskit/qiskit-terra/issues/159
"""
# ┌───┐┌───┐┌───────┐┌───┐┌────────┐┌──────┐┌────────┐┌───┐ ┌─┐»
# qr_0: ┤ H ├┤ X ├┤ P(2π) ├┤ X ├┤ P(π/2) ├┤ P(π) ├┤ P(π/2) ├┤ X ├────────┤M├»
# └───┘└─┬─┘└───────┘└─┬─┘└────────┘└──────┘└────────┘└─┬─┘┌──────┐└╥┘»
# qr_1: ───────■─────────────■────────────────────────────────■──┤ P(π) ├─╫─»
# └──────┘ ║ »
# cr: 2/══════════════════════════════════════════════════════════════════╩═»
# 0 »
# «
# «qr_0: ───────────
# « ┌──────┐┌─┐
# «qr_1: ┤ P(π) ├┤M├
# « └──────┘└╥┘
# «cr: 2/═════════╩═
# « 1
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.cx(qr[1], qr[0])
qc.append(PhaseGate(2 * np.pi), [qr[0]])
qc.cx(qr[1], qr[0])
qc.append(PhaseGate(np.pi / 2), [qr[0]]) # these three should combine
qc.append(PhaseGate(np.pi), [qr[0]]) # to identity then
qc.append(PhaseGate(np.pi / 2), [qr[0]]) # optimized away.
qc.cx(qr[1], qr[0])
qc.append(PhaseGate(np.pi), [qr[1]])
qc.append(PhaseGate(np.pi), [qr[1]])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
dag = circuit_to_dag(qc)
simplified_dag = Optimize1qGates(["p", "u2", "u", "cx", "id"]).run(dag)
num_u1_gates_remaining = len(simplified_dag.named_nodes("p"))
self.assertEqual(num_u1_gates_remaining, 0)
def test_ignores_conditional_rotations(self):
"""Conditional rotations should not be considered in the chain.
qr0:--[U1]-[U1]-[U1]-[U1]- qr0:--[U1]-[U1]-
|| || || ||
cr0:===.================== == cr0:===.====.===
|| ||
cr1:========.============= cr1:========.===
"""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(U1Gate(0.1), [qr]).c_if(cr, 1)
circuit.append(U1Gate(0.2), [qr]).c_if(cr, 3)
circuit.append(U1Gate(0.3), [qr])
circuit.append(U1Gate(0.4), [qr])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.append(U1Gate(0.1), [qr]).c_if(cr, 1)
expected.append(U1Gate(0.2), [qr]).c_if(cr, 3)
expected.append(U1Gate(0.7), [qr])
pass_ = Optimize1qGates()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_ignores_conditional_rotations_phase_gates(self):
"""Conditional rotations should not be considered in the chain.
qr0:--[U1]-[U1]-[U1]-[U1]- qr0:--[U1]-[U1]-
|| || || ||
cr0:===.================== == cr0:===.====.===
|| ||
cr1:========.============= cr1:========.===
"""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(PhaseGate(0.1), [qr]).c_if(cr, 1)
circuit.append(PhaseGate(0.2), [qr]).c_if(cr, 3)
circuit.append(PhaseGate(0.3), [qr])
circuit.append(PhaseGate(0.4), [qr])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.append(PhaseGate(0.1), [qr]).c_if(cr, 1)
expected.append(PhaseGate(0.2), [qr]).c_if(cr, 3)
expected.append(PhaseGate(0.7), [qr])
pass_ = Optimize1qGates(["p", "u2", "u", "cx", "id"])
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_in_the_back(self):
"""Optimizations can be in the back of the circuit.
See https://github.com/Qiskit/qiskit-terra/issues/2004.
qr0:--[U1]-[U1]-[H]-- qr0:--[U1]-[H]--
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U1Gate(0.3), [qr])
circuit.append(U1Gate(0.4), [qr])
circuit.h(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.append(U1Gate(0.7), [qr])
expected.h(qr)
pass_ = Optimize1qGates()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_in_the_back_phase_gate(self):
"""Optimizations can be in the back of the circuit.
See https://github.com/Qiskit/qiskit-terra/issues/2004.
qr0:--[U1]-[U1]-[H]-- qr0:--[U1]-[H]--
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(PhaseGate(0.3), [qr])
circuit.append(PhaseGate(0.4), [qr])
circuit.h(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.append(PhaseGate(0.7), [qr])
expected.h(qr)
pass_ = Optimize1qGates(["p", "u2", "u", "cx", "id"])
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_single_parameterized_circuit(self):
"""Parameters should be treated as opaque gates."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.append(U1Gate(0.3), [qr])
qc.append(U1Gate(0.4), [qr])
qc.append(U1Gate(theta), [qr])
qc.append(U1Gate(0.1), [qr])
qc.append(U1Gate(0.2), [qr])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(qr)
expected.append(U1Gate(theta + 1.0), [qr])
after = Optimize1qGates().run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_parameterized_circuits(self):
"""Parameters should be treated as opaque gates."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.append(U1Gate(0.3), [qr])
qc.append(U1Gate(0.4), [qr])
qc.append(U1Gate(theta), [qr])
qc.append(U1Gate(0.1), [qr])
qc.append(U1Gate(0.2), [qr])
qc.append(U1Gate(theta), [qr])
qc.append(U1Gate(0.3), [qr])
qc.append(U1Gate(0.2), [qr])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(qr)
expected.append(U1Gate(2 * theta + 1.5), [qr])
after = Optimize1qGates().run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_parameterized_expressions_in_circuits(self):
"""Expressions of Parameters should be treated as opaque gates."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
product_ = theta * phi
qc.append(U1Gate(0.3), [qr])
qc.append(U1Gate(0.4), [qr])
qc.append(U1Gate(theta), [qr])
qc.append(U1Gate(phi), [qr])
qc.append(U1Gate(sum_), [qr])
qc.append(U1Gate(product_), [qr])
qc.append(U1Gate(0.3), [qr])
qc.append(U1Gate(0.2), [qr])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(qr)
expected.append(U1Gate(2 * theta + 2 * phi + product_ + 1.2), [qr])
after = Optimize1qGates().run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_global_phase_u3_on_left(self):
"""Check proper phase accumulation with instruction with no definition."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
u1 = U1Gate(0.1)
u1.definition.global_phase = np.pi / 2
qc.append(u1, [0])
qc.global_phase = np.pi / 3
qc.append(U3Gate(0.1, 0.2, 0.3), [0])
dag = circuit_to_dag(qc)
after = Optimize1qGates().run(dag)
self.assertAlmostEqual(after.global_phase, 5 * np.pi / 6, 8)
def test_global_phase_u_on_left(self):
"""Check proper phase accumulation with instruction with no definition."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
u1 = U1Gate(0.1)
u1.definition.global_phase = np.pi / 2
qc.append(u1, [0])
qc.global_phase = np.pi / 3
qc.append(UGate(0.1, 0.2, 0.3), [0])
dag = circuit_to_dag(qc)
after = Optimize1qGates(["u1", "u2", "u", "cx"]).run(dag)
self.assertAlmostEqual(after.global_phase, 5 * np.pi / 6, 8)
class TestOptimize1qGatesParamReduction(QiskitTestCase):
"""Test for 1q gate optimizations parameter reduction, reduce n in Un"""
def test_optimize_u3_to_u2(self):
"""U3(pi/2, pi/3, pi/4) -> U2(pi/3, pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U2Gate(np.pi / 3, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates())
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_to_u2_round(self):
"""U3(1.5707963267948961, 1.0471975511965971, 0.7853981633974489) -> U2(pi/3, pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(1.5707963267948961, 1.0471975511965971, 0.7853981633974489), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U2Gate(np.pi / 3, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates())
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_to_u1(self):
"""U3(0, 0, pi/4) -> U1(pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U1Gate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates())
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_to_phase_gate(self):
"""U3(0, 0, pi/4) -> U1(pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(PhaseGate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["p", "u2", "u", "cx", "id"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_to_u1_round(self):
"""U3(1e-16, 1e-16, pi/4) -> U1(pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(1e-16, 1e-16, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U1Gate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates())
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_to_phase_round(self):
"""U3(1e-16, 1e-16, pi/4) -> U1(pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(1e-16, 1e-16, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(PhaseGate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["p", "u2", "u", "cx", "id"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
class TestOptimize1qGatesBasis(QiskitTestCase):
"""Test for 1q gate optimizations parameter reduction with basis"""
def test_optimize_u3_basis_u3(self):
"""U3(pi/2, pi/3, pi/4) (basis[u3]) -> U3(pi/2, pi/3, pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u3"]))
result = passmanager.run(circuit)
self.assertEqual(circuit, result)
def test_optimize_u3_basis_u(self):
"""U3(pi/2, pi/3, pi/4) (basis[u3]) -> U(pi/2, pi/3, pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u"]))
result = passmanager.run(circuit)
expected = QuantumCircuit(qr)
expected.append(UGate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]])
self.assertEqual(expected, result)
def test_optimize_u3_basis_u2(self):
"""U3(pi/2, 0, pi/4) -> U2(0, pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U2Gate(0, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_basis_u2_with_target(self):
"""U3(pi/2, 0, pi/4) -> U2(0, pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U2Gate(0, np.pi / 4), [qr[0]])
target = Target(num_qubits=1)
target.add_instruction(U2Gate(Parameter("theta"), Parameter("phi")))
passmanager = PassManager()
passmanager.append(Optimize1qGates(target=target))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u_basis_u(self):
"""U(pi/2, pi/3, pi/4) (basis[u3]) -> U(pi/2, pi/3, pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(UGate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u"]))
result = passmanager.run(circuit)
self.assertEqual(circuit, result)
def test_optimize_u3_basis_u2_cx(self):
"""U3(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, cx]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]])
circuit.cx(qr[0], qr[1])
expected = QuantumCircuit(qr)
expected.append(U2Gate(0, np.pi / 4), [qr[0]])
expected.cx(qr[0], qr[1])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2", "cx"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u_basis_u2_cx(self):
"""U(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, cx]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(UGate(np.pi / 2, 0, np.pi / 4), [qr[0]])
circuit.cx(qr[0], qr[1])
expected = QuantumCircuit(qr)
expected.append(U2Gate(0, np.pi / 4), [qr[0]])
expected.cx(qr[0], qr[1])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2", "cx"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u1_basis_u2_u3(self):
"""U1(pi/4) -> U3(0, 0, pi/4). Basis [u2, u3]."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U1Gate(np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U3Gate(0, 0, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2", "u3"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u1_basis_u2_u(self):
"""U1(pi/4) -> U3(0, 0, pi/4). Basis [u2, u3]."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U1Gate(np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(UGate(0, 0, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2", "u"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u1_basis_u2(self):
"""U1(pi/4) -> Raises. Basis [u2]"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U1Gate(np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U3Gate(0, 0, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2"]))
with self.assertRaises(TranspilerError):
_ = passmanager.run(circuit)
def test_optimize_u3_basis_u2_u1(self):
"""U3(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, u1]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U2Gate(0, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2", "u1"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_basis_u2_phase_gate(self):
"""U3(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, p]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U2Gate(0, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2", "p"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_basis_u1(self):
"""U3(0, 0, pi/4) -> U1(pi/4). Basis [u1]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U1Gate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u1"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_basis_phase_gate(self):
"""U3(0, 0, pi/4) -> p(pi/4). Basis [p]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(PhaseGate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["p"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u_basis_u1(self):
"""U(0, 0, pi/4) -> U1(pi/4). Basis [u1]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(UGate(0, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U1Gate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u1"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u_basis_phase_gate(self):
"""U(0, 0, pi/4) -> p(pi/4). Basis [p]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(UGate(0, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(PhaseGate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["p"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_with_parameters(self):
"""Test correct behavior for u3 gates."""
phi = Parameter("φ")
alpha = Parameter("α")
qr = QuantumRegister(1, "qr")
qc = QuantumCircuit(qr)
qc.ry(2 * phi, qr[0])
qc.ry(alpha, qr[0])
qc.ry(0.1, qr[0])
qc.ry(0.2, qr[0])
passmanager = PassManager([Unroller(["u3"]), Optimize1qGates()])
result = passmanager.run(qc)
expected = QuantumCircuit(qr)
expected.append(U3Gate(2 * phi, 0, 0), [qr[0]])
expected.append(U3Gate(alpha, 0, 0), [qr[0]])
expected.append(U3Gate(0.3, 0, 0), [qr[0]])
self.assertEqual(expected, result)
if __name__ == "__main__":
unittest.main()
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
### replaced z gate ###
qc.x(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/kosakhro/QAOA-for-exact-cover
|
kosakhro
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector
from qiskit.visualization import plot_histogram
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
IBMQ.load_account()
matplotlib inline
simulator = Aer.get_backend('qasm_simulator')
# Making the quantum circuit
def circuitI(gamma, beta, J, h1, h2):
qc = QuantumCircuit(2, 2)
qc.h([0, 1])
qc.h(1)
qc.cz(0,1)
qc.rx(2*gamma*J, 1)
qc.cz(0,1)
qc.h(1)
qc.i(0)
qc.rz(2*gamma*h1, 0)
qc.rz(2*gamma*h2, 1)
qc.rx(2*beta, 0)
qc.rx(2*beta, 1)
qc.measure([0,1], [0,1])
return qc
# Initializing the variables for A.
J = 0.5
h1 = -0.5
h2 = 0
#Setting the dimesions of the pasephase. The amount of simulated points = n**2
n = 61
p = np.pi/(n-1)
resA = np.zeros([n, n, 4])
qc_list = []
# Running a simulation for each point
for i in range(n):
gamma = i*p
for j in range(n):
beta = j*p
qc = circuitI(gamma, beta, J, h1, h2)
counts = execute(qc, backend = simulator, shots=1000).result().get_counts()
resA[i][j][:] = np.array([int(counts.get('00', 0)), int(counts.get('01', 0)), int(counts.get('10', 0)),
int(counts.get('11', 0))])
#Draw the current circuit
qc.draw(output='mpl')
# Making a heatmap plot
sns.heatmap(resA[:, :, 0]*0 + resA[:, :, 1] + resA[:, :, 2]*0 + resA[:, :, 3]*0 )
# Initializing the variables for B.
J = 0
h1 = -1
h2 = 0
#Setting the dimesions of the pasephase. The amount of simulated points = n**2
n = 61
p = np.pi/(n-1)
resB = np.zeros([n, n, 4])
# Running a simulation for each point
for i in range(n):
gamma = i*p
for j in range(n):
beta = j*p
qc = circuitI(gamma, beta, J, h1, h2)
counts = execute(qc, backend = simulator, shots=1000).result().get_counts()
resB[i][j][:] = np.array([int(counts.get('00', 0)), int(counts.get('01', 0)), int(counts.get('10', 0)),
int(counts.get('11', 0))])
#Draw the current circuit
qc.draw(output='mpl')
# Making a heatmap plot
sns.heatmap(resB[:, :, 0]*0 + resB[:, :, 1] + resB[:, :, 2]*0 + resB[:, :, 3] )
# Initializing the variables for C.
J = 0
h1 = -0.5
h2 = -0.5
#Setting the dimesions of the pasephase. The amount of simulated points = n**2
n = 61
p = np.pi/(n-1)
resC = np.zeros([n, n, 4])
# Running a simulation for each point
for i in range(n):
gamma = i*p
for j in range(n):
beta = j*p
qc = circuitI(gamma, beta, J, h1, h2)
counts = execute(qc, backend = simulator, shots=1000).result().get_counts()
resC[i][j][:] = np.array([int(counts.get('00', 0)), int(counts.get('01', 0)), int(counts.get('10', 0)),
int(counts.get('11', 0))])
#Draw the current circuit
qc.draw(output='mpl')
# Making a heatmap plot
sns.heatmap(resC[:, :, 3])
# Initializing the variables for D.
J = 1
h1 = 0
h2 = 0
#Setting the dimesions of the pasephase. The amount of simulated points = n**2
n = 61
p = np.pi/(n-1)
resD = np.zeros([n, n, 4])
# Running a simulation for each point
for i in range(n):
gamma = i*p
for j in range(n):
beta = j*p
qc = circuitI(gamma, beta, J, h1, h2)
counts = execute(qc, backend = simulator, shots=1000).result().get_counts()
resD[i][j][:] = np.array([int(counts.get('00', 0)), int(counts.get('01', 0)), int(counts.get('10', 0)),
int(counts.get('11', 0))])
#Draw the current circuit
qc.draw(output='mpl')
# Making a heatmap plot
sns.heatmap(resD[:, :, 0]*0 + resD[:, :, 1] + resD[:, :, 2] + resD[:, :, 3] *0 )
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for core modules of timeline drawer."""
from qiskit import QuantumCircuit, transpile
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import core, stylesheet, generators, layouts
class TestCanvas(QiskitTestCase):
"""Test for canvas."""
def setUp(self):
super().setUp()
self.style = stylesheet.QiskitTimelineStyle()
circ = QuantumCircuit(4)
circ.h(0)
circ.barrier()
circ.cx(0, 2)
circ.cx(1, 3)
self.circ = transpile(
circ,
scheduling_method="alap",
basis_gates=["h", "cx"],
instruction_durations=[("h", 0, 200), ("cx", [0, 2], 1000), ("cx", [1, 3], 1000)],
optimization_level=0,
)
def test_time_range(self):
"""Test calculating time range."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter = {"margin.left_percent": 0.1, "margin.right_percent": 0.1}
canvas.time_range = (0, 100)
ref_range = [-10.0, 110.0]
self.assertListEqual(list(canvas.time_range), ref_range)
def test_load_program(self):
"""Test loading program."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [],
"barriers": [],
"gate_links": [],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 8)
ref_coord = {
self.circ.qregs[0][0]: -1.0,
self.circ.qregs[0][1]: -2.0,
self.circ.qregs[0][2]: -3.0,
self.circ.qregs[0][3]: -4.0,
}
self.assertDictEqual(canvas.assigned_coordinates, ref_coord)
def test_gate_link_overlap(self):
"""Test shifting gate link overlap."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update(
{
"margin.link_interval_percent": 0.01,
"margin.left_percent": 0,
"margin.right_percent": 0,
}
)
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 2)
self.assertListEqual(drawings_tested[0][1].xvals, [706.0])
self.assertListEqual(drawings_tested[1][1].xvals, [694.0])
ref_keys = list(canvas._collections.keys())
self.assertEqual(drawings_tested[0][0], ref_keys[0])
self.assertEqual(drawings_tested[1][0], ref_keys[1])
def test_object_outside_xlimit(self):
"""Test eliminating drawings outside the horizontal limit."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [generators.gen_bit_name, generators.gen_timeslot],
"barriers": [],
"gate_links": [],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.set_time_range(t_start=400, t_end=600)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 12)
def test_non_transpiled_delay_circuit(self):
"""Test non-transpiled circuit containing instruction which is trivial on duration."""
circ = QuantumCircuit(1)
circ.delay(10, 0)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [],
"barriers": [],
"gate_links": [],
}
with self.assertWarns(DeprecationWarning):
canvas.load_program(circ)
self.assertEqual(len(canvas._collections), 1)
def test_multi_measurement_with_clbit_not_shown(self):
"""Test generating bit link drawings of measurements when clbits is disabled."""
circ = QuantumCircuit(2, 2)
circ.measure(0, 0)
circ.measure(1, 1)
circ = transpile(
circ,
scheduling_method="alap",
basis_gates=[],
instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)],
optimization_level=0,
)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({"control.show_clbits": False})
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.load_program(circ)
canvas.update()
self.assertEqual(len(canvas._output_dataset), 0)
def test_multi_measurement_with_clbit_shown(self):
"""Test generating bit link drawings of measurements when clbits is enabled."""
circ = QuantumCircuit(2, 2)
circ.measure(0, 0)
circ.measure(1, 1)
circ = transpile(
circ,
scheduling_method="alap",
basis_gates=[],
instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)],
optimization_level=0,
)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({"control.show_clbits": True})
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.load_program(circ)
canvas.update()
self.assertEqual(len(canvas._output_dataset), 2)
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
#
# your code is here
#
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
q = QuantumRegister(2,"q") # quantum register with 2 qubits
c = ClassicalRegister(2,"c") # classical register with 2 bits
qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers
# the up qubit is in |0>
# set the down qubit to |1>
qc.x(q[0]) # apply x-gate (NOT operator)
qc.barrier()
# apply Hadamard to both qubits.
qc.h(q[0])
qc.h(q[1])
# apply CNOT operator, where the controller qubit is the up qubit and the target qubit is the down qubit.
qc.cx(1,0)
# apply Hadamard to both qubits.
qc.h(q[0])
qc.h(q[1])
# measure both qubits
qc.measure(q,c)
# draw the circuit in Qiskit reading order
display(qc.draw(output='mpl',reverse_bits=True))
# execute the circuit 100 times in the local simulator
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(qc)
print(counts)
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
#
# your code is here
#
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# Create a circuit with 7 qubits.
q = QuantumRegister(7,"q") # quantum register with 7 qubits
c = ClassicalRegister(7) # classical register with 7 bits
qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers
# the top six qubits are already in |0>
# set the bottom qubit to |1>
qc.x(0) # apply x-gate (NOT operator)
# define a barrier
qc.barrier()
# apply Hadamard to all qubits.
for i in range(7):
qc.h(q[i])
# define a barrier
qc.barrier()
# apply CNOT operator (q[1],q[0])
# apply CNOT operator (q[4],q[0])
# apply CNOT operator (q[5],q[0])
qc.cx(q[1],q[0])
qc.cx(q[4],q[0])
qc.cx(q[5],q[0])
# define a barrier
qc.barrier()
# apply Hadamard to all qubits.
for i in range(7):
qc.h(q[i])
# define a barrier
qc.barrier()
# measure all qubits
qc.measure(q,c)
# draw the circuit in Qiskit reading order
display(qc.draw(output='mpl',reverse_bits=True))
# execute the circuit 100 times in the local simulator
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(qc)
print(counts)
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
import json
import csv
# Array of JSON Objects
header = ['instance', 'iteration', 'distance']
length_instances = 40
with open('qaoa_multiple_distance.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
for instance in range(length_instances):
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution()
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
index = -1
for sample in UNIFORM_CONVERGENCE_SAMPLE:
mean = sample["mean"]
index += 1
distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"]))
UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state
iteration = 0
for sample in UNIFORM_CONVERGENCE_SAMPLE:
iteration += 1
mean = sample["mean"]
distance = sample["distance_pgs"]
writer.writerow([instance,iteration, distance])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
es_problem = driver.run()
from qiskit_nature.second_q.mappers import JordanWignerMapper
mapper = JordanWignerMapper()
from qiskit.algorithms.eigensolvers import NumPyEigensolver
numpy_solver = NumPyEigensolver(filter_criterion=es_problem.get_default_filter_criterion())
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.algorithms import GroundStateEigensolver, QEOM
from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD
ansatz = UCCSD(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
mapper,
initial_state=HartreeFock(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
mapper,
),
)
estimator = Estimator()
# This first part sets the ground state solver
# see more about this part in the ground state calculation tutorial
solver = VQE(estimator, ansatz, SLSQP())
solver.initial_point = [0.0] * ansatz.num_parameters
gse = GroundStateEigensolver(mapper, solver)
# The qEOM algorithm is simply instantiated with the chosen ground state solver and Estimator primitive
qeom_excited_states_solver = QEOM(gse, estimator, "sd")
from qiskit_nature.second_q.algorithms import ExcitedStatesEigensolver
numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, numpy_solver)
numpy_results = numpy_excited_states_solver.solve(es_problem)
qeom_results = qeom_excited_states_solver.solve(es_problem)
print(numpy_results)
print("\n\n")
print(qeom_results)
import numpy as np
def filter_criterion(eigenstate, eigenvalue, aux_values):
return np.isclose(aux_values["ParticleNumber"][0], 2.0)
new_numpy_solver = NumPyEigensolver(filter_criterion=filter_criterion)
new_numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, new_numpy_solver)
new_numpy_results = new_numpy_excited_states_solver.solve(es_problem)
print(new_numpy_results)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit import QuantumCircuit, transpile
import ipywidgets as widgets
from IPython.display import HTML
import logging
class WidgetLayout:
timeline_layout = {
'border': '1px inset #eee',
'padding': '2px',
'height': '275px',
'overflow': 'auto',
'width': '70%'
}
accordion_layout = {
'border': '1px inset #eee',
'padding': '0',
'height': '275px',
'width': '30%'
}
tabular_data_layout = {
'padding': '5px',
'grid_template_columns': 'repeat(2, 50%)'
}
timeline_panel = widgets.VBox([], layout = { 'width': '100%' })
timeline_wpr = widgets.Box([timeline_panel], layout = WidgetLayout.timeline_layout)
stats_labels = [
widgets.Label('1Q ops'), widgets.Label(''),
widgets.Label('2Q ops'), widgets.Label(''),
widgets.Label('Depth'), widgets.Label(''),
widgets.Label('Size'), widgets.Label(''),
widgets.Label('Width'), widgets.Label(''),
]
stats_panel = widgets.GridBox(stats_labels, layout = WidgetLayout.tabular_data_layout)
properties_panel = widgets.GridBox([], layout = WidgetLayout.tabular_data_layout)
accordion = widgets.Accordion(children = [stats_panel, properties_panel], layout = WidgetLayout.accordion_layout)
accordion.set_title(0, 'Circuit Stats')
accordion.set_title(1, 'Property Set')
main_view = widgets.HBox([timeline_wpr, accordion], layout = { 'width': '100%' })
modal = widgets.Output(layout = { 'width': '100%' })
tp_widget = widgets.VBox([
main_view,
modal
], layout = { 'width': '100%' })
tp_widget.add_class('tp-widget')
import sys
from types import ModuleType, FunctionType
from gc import get_referents
# Custom objects know their class.
# Function objects seem to know way too much, including modules.
# Exclude modules as well.
BLACKLIST = type, ModuleType, FunctionType
def getsize(obj):
"""sum size of object & members."""
#if isinstance(obj, BLACKLIST):
# raise TypeError('getsize() does not take argument of type: '+ str(type(obj)))
seen_ids = set()
size = 0
objects = [obj]
while objects:
need_referents = []
for obj in objects:
if not isinstance(obj, BLACKLIST) and id(obj) not in seen_ids:
# if id(obj) not in seen_ids:
seen_ids.add(id(obj))
size += sys.getsizeof(obj)
need_referents.append(obj)
objects = get_referents(*need_referents)
return size
from enum import Enum
class PassType(Enum):
ANALYSIS = 'A'
TRANSFORMATION = 'T'
class Property:
LARGE_VALUE_THRESHOLD = 2 ** 20
def __init__(self, name, type, value) -> None:
self.name = name
self.type = type
if getsize(value) > self.LARGE_VALUE_THRESHOLD:
self.value = 'LARGE_VALUE'
else:
self.value = value
def __repr__(self) -> str:
return f"{self.name} ({self.type.__name__}) : {self.value}"
class CircuitStats:
def __init__(self) -> None:
self.width = None
self.size = None
self.depth = None
self.ops_1q = None
self.ops_2q = None
def __eq__(self, other):
return self.width == other.width and self.size == other.size and self.depth == other.depth and self.ops_1q == other.ops_1q and self.ops_2q == other.ops_2q
def __repr__(self) -> str:
return f"CircuitStats(width={self.width}, size={self.size}, depth={self.depth}, 1Q ops={self.ops_1q}, 2Q ops={self.ops_2q})"
from time import time
class LogEntry:
def __init__(self, levelname, msg, args) -> None:
self.levelname = levelname
self.msg = msg
self.args = args
self.time = time()
def __repr__(self) -> str:
return f"[{self.levelname}] {self.msg}"
class TranspilationStep:
def __init__(self, name, type) -> None:
self.name = name
self.type = type
self.docs = ''
self.run_docs = ''
self.duration = 0
self.circuit_stats = CircuitStats()
self.property_set = {}
self.logs = []
self.dag = None
def __repr__(self) -> str:
return f"(name={self.name}, type={self.type})"
class ButtonWithValue(widgets.Button):
def __init__(self, *args, **kwargs):
self.value = kwargs['value']
kwargs.pop('value', None)
super(ButtonWithValue, self).__init__(*args, **kwargs)
from datetime import datetime
import html
%matplotlib inline
def on_logs(btn):
step = transpilation_sequence.steps[int(btn.value)]
logs = step.logs
#TEMP:
if len(logs) > 22:
logs[7].levelname = 'WARNING'
logs[10].levelname = 'ERROR'
logs[13].levelname = 'CRITICAL'
logs[15].levelname = 'INFO'
logs[16].levelname = 'INFO'
logs[20].levelname = 'ERROR'
logs[21].levelname = 'CRITICAL'
#END-TEMP
html_str = '<div class="logs-wpr">'
for entry in logs:
html_str = html_str + "<pre class='date'>{0}</pre><pre class='level {1}'>[{1}]</pre><pre class='log-entry {1}'>{2}</pre>".format(datetime.fromtimestamp(entry.time).strftime("%H:%M:%S.%f")[:-3], entry.levelname, entry.msg % entry.args)
html_str = html_str + '</div>'
show_modal(step.name + ' Logs', html_str, '')
def on_circ(btn):
from qiskit.converters import dag_to_circuit
from io import BytesIO
from binascii import b2a_base64
circ = dag_to_circuit(transpilation_sequence.steps[int(btn.value)].dag)
fig = circ.draw('mpl', idle_wires = False, with_layout = False, scale = 0.8, fold = 20)
bio = BytesIO()
#fig.canvas.print_png(bio)
fig.savefig(bio, format = 'png', bbox_inches = 'tight')
img_data = b2a_base64(bio.getvalue()).decode()
img_html = '<img src="data:image/png;base64,{} ">'.format(img_data)
show_modal('Circuit Plot', img_html, '840px')
def on_info(btn):
step = transpilation_sequence.steps[int(btn.value)]
html_str = '<pre class="help">' + step.docs + '</pre>'
html_str = html_str + '<div class="help-header"><span style="color: #e83e8c;">' + step.name + '</span>.run(<span style="color: #0072c3;">dag</span>)</div>'
html_str = html_str + '<pre class="help">' + step.run_docs + '</pre>'
show_modal(step.name, html_str, '')
def on_property(btn):
step_index, property_name = btn.value.split(',')
property_set = transpilation_sequence.steps[int(step_index)].property_set
property = property_set[property_name]
html_str = '<table>'
for v in property.value:
###
# ??? if type(v) == tuple:
if property_name == 'block_list':
html_str = html_str + '<tr><td><pre>' + html.escape(str([node.name for node in v])) + '</pre></td></tr>'
else:
html_str = html_str + '<tr><td><pre>' + html.escape(str(v)) + '</pre></td></tr>'
html_str = html_str + '</table>'
show_modal('Property: ' + property_name, html_str, '')
def show_modal(title, content, width):
modal.remove_class('show')
html_str = """
<script>
// Fix z-index issue:
var stackingContextRoot = document.querySelector(".tp-widget").closest("div.cell");
if(stackingContextRoot) {{
stackingContextRoot.classList.add("stacking-context");
}}
var closeButton = document.getElementsByClassName("close-wdgt-modal")[0];
closeButton.addEventListener("click", function(ev) {{
document.querySelectorAll(".output_wrapper").forEach(function(div) {{
div.classList.remove("show");
}});
}});
</script>
<div class="wdgt-modal-background"></div>
<div class="wdgt-modal" style="width: {width}">
<div class="wdgt-modal-header">
<h3>{title}</h3>
<span class="close-wdgt-modal">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAdVBMVEUAAABNTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU0N3NIOAAAAJnRSTlMAAQIDBAUGBwgRFRYZGiEjQ3l7hYaqtLm8vsDFx87a4uvv8fP1+bbY9ZEAAAB8SURBVBhXXY5LFoJAAMOCIP4VBRXEv5j7H9HFDOizu2TRFljedgCQHeocWHVaAWStXnKyl2oVWI+kd1XLvFV1D7Ng3qrWKYMZ+MdEhk3gbhw59KvlH0eTnf2mgiRwvQ7NW6aqNmncukKhnvo/zzlQ2PR/HgsAJkncH6XwAcr0FUY5BVeFAAAAAElFTkSuQmCC" width="16" height="16" alt="">
</span>
</div>
<div class="wdgt-modal-content">{content}</div></div>
""".format(title = title, content = content, width = width)
modal.outputs = []
modal.append_display_data(HTML(html_str))
modal.add_class('show')
class TranspilationSequence:
def __init__(self) -> None:
self.steps = []
self._collected_logs = {}
self._prop_labels_map = {}
def add_step(self, step) -> None:
if step.name in self._collected_logs:
step.logs = self._collected_logs[step.name]
self._collected_logs.pop(step.name, None)
######
if len(transpilation_sequence.steps) == 0:
prev_stats = CircuitStats()
else:
prev_stats = self.steps[-1].circuit_stats
if prev_stats.ops_1q != step.circuit_stats.ops_1q:
stats_labels[1].value = str(step.circuit_stats.ops_1q)
stats_labels[1].add_class('highlight')
else:
stats_labels[1].remove_class('highlight')
if prev_stats.ops_2q != step.circuit_stats.ops_2q:
stats_labels[3].value = str(step.circuit_stats.ops_2q)
stats_labels[3].add_class('highlight')
else:
stats_labels[3].remove_class('highlight')
if prev_stats.depth != step.circuit_stats.depth:
stats_labels[5].value = str(step.circuit_stats.depth)
stats_labels[5].add_class('highlight')
else:
stats_labels[5].remove_class('highlight')
if prev_stats.size != step.circuit_stats.size:
stats_labels[7].value = str(step.circuit_stats.size)
stats_labels[7].add_class('highlight')
else:
stats_labels[7].remove_class('highlight')
if prev_stats.width != step.circuit_stats.width:
stats_labels[9].value = str(step.circuit_stats.width)
stats_labels[9].add_class('highlight')
else:
stats_labels[9].remove_class('highlight')
######
for prop_name in step.property_set:
property = step.property_set[prop_name]
if property.name in self._prop_labels_map:
index = self._prop_labels_map[property.name]
else:
####
u = widgets.Label(value = property.name)
if type(property.value) == list:
prop_label = widgets.Label('(list)', layout = { 'width': '80%' })
prop_button = ButtonWithValue(value = str(len(self.steps)) + ',' + property.name, description = '...', layout = { 'width': '20%' })
prop_button.on_click(on_property)
v = widgets.HBox([prop_label, prop_button], layout = { 'width': '100%' })
else:
v = widgets.Label(value = str(property.value))
index = len(properties_panel.children)
properties_panel.children = properties_panel.children + (u, v)
####
self._prop_labels_map[property.name] = index
u = widgets.Label(value = property.name)
if type(property.value) != list:
properties_panel.children[index + 1].value = str(property.value)
######
a = widgets.Label(step.type.value)
a.add_class(step.type.name.lower())
b = widgets.Label(step.name)
from math import log10
if step.duration > 0:
duration_font_size = 10
duration_font_size = 10 + round(log10(step.duration))
t = widgets.Label(str(round(step.duration, 1)) + ' ms')
t.add_class('fs' + str(duration_font_size))
else:
t = widgets.Label('')
if type(step.logs) == list and len(step.logs) > 0:
c = ButtonWithValue(value = str(len(self.steps)), tooltip = str(len(step.logs)) + ' logs entries', icon = 'align-justify', layout = { 'width': '32px' })
c.on_click(on_logs)
else:
c = widgets.Label('', layout = { 'width': '32px' })
# Due to a bug in DAGCircuit.__eq__, we can not use ``step.dag != None``
from qiskit.dagcircuit import DAGCircuit
if isinstance(step.dag, DAGCircuit):
d = ButtonWithValue(value = str(len(self.steps)), icon = 'sliders', layout = { 'width': '32px' })
d.on_click(on_circ)
else:
d = widgets.Label('', layout = { 'width': '32px' })
e = ButtonWithValue(value = str(len(self.steps)), icon = 'info-circle', layout = { 'width': '32px' })
e.on_click(on_info)
item = widgets.GridBox([a, b, t, c, d, e], layout = { 'width': '100%', 'grid_template_columns': '20px auto 70px 35px 35px 35px', 'min_height': '35px' })
item.add_class('transpilation-step')
timeline_panel.children = timeline_panel.children + (item, )
######
self.steps.append(step)
def add_log_entry(self, pass_name, log_entry) -> None:
if not pass_name in self._collected_logs:
self._collected_logs[pass_name] = []
self._collected_logs[pass_name].append(log_entry)
transpilation_sequence = TranspilationSequence()
class TranspilerLoggingHandler(logging.Handler):
def __init__(self, *args, **kwargs):
self.loggers_map = kwargs['loggers_map']
kwargs.pop('loggers_map', None)
super(TranspilerLoggingHandler, self).__init__(*args, **kwargs)
def emit(self, record):
log_entry = LogEntry(record.levelname, record.msg, record.args)
transpilation_sequence.add_log_entry(self.loggers_map[record.name], log_entry)
from qiskit.transpiler.basepasses import AnalysisPass, TransformationPass
all_loggers = logging.Logger.manager.loggerDict
passes_loggers = {key:value for (key, value) in all_loggers.items() if key.startswith('qiskit.transpiler.passes.')}
loggers_map = {}
for _pass in AnalysisPass.__subclasses__():
if _pass.__module__ in passes_loggers.keys():
loggers_map[_pass.__module__] = _pass.__name__
for _pass in TransformationPass.__subclasses__():
if _pass.__module__ in passes_loggers.keys():
loggers_map[_pass.__module__] = _pass.__name__
handler = TranspilerLoggingHandler(loggers_map = loggers_map)
logger = logging.getLogger('qiskit.transpiler.passes')
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
_properties = {}
def transpiler_callback(**kwargs):
pass_ = kwargs['pass_']
pass_name = pass_.name()
pass_type = ''
if pass_.is_analysis_pass:
pass_type = PassType.ANALYSIS
elif pass_.is_transformation_pass:
pass_type = PassType.TRANSFORMATION
transpilation_step = TranspilationStep(pass_name, pass_type)
transpilation_step.docs = pass_.__doc__
transpilation_step.run_docs = getattr(pass_, 'run').__doc__
duration_value = round(1000 * kwargs['time'], 2)
transpilation_step.duration = duration_value
# Properties
_props_updated = False
property_set = kwargs['property_set']
for key in property_set:
if key not in _properties.keys():
_props_updated = True
_properties[key] = property_set[key]
if _props_updated:
from collections import defaultdict
for property_name in property_set:
#if property_name == 'commutation_set':
# print(property_set[property_name])
property_type = type(property_set[property_name])
property_value = None
if property_type in (int, float, bool, str):
property_value = property_set[property_name]
elif property_type == list:
property_value = []
for value in property_set[property_name]:
property_value.append(value)
elif property_type == defaultdict:
#print('defaultdict')
property_value = []
for key, value in property_set[property_name].items():
#print(key, value)
#print('------------------------')
property_value.append(str(key) + ': ' + str(value))
else:
property_value = '(' + property_type.__name__ + ')'
transpilation_step.property_set[property_name] = Property(property_name, property_type, property_value)
# circuit stats:
dag = kwargs['dag']
transpilation_step.circuit_stats.width = dag.width()
transpilation_step.circuit_stats.size = dag.size()
transpilation_step.circuit_stats.depth = dag.depth()
nodes = dag.op_nodes(include_directives = False)
circ_ops_1q = 0
circ_ops_2q = 0
for node in nodes:
if len(node.qargs) > 1:
circ_ops_2q += 1
else:
circ_ops_1q += 1
transpilation_step.circuit_stats.ops_1q = circ_ops_1q
transpilation_step.circuit_stats.ops_2q = circ_ops_2q
# ???
if transpilation_step.type == PassType.TRANSFORMATION and transpilation_step.circuit_stats.depth < 200:
# if len(transpilation_sequence.steps) == 0 or transpilation_sequence.steps[-1].circuit_stats != transpilation_step.circuit_stats:
transpilation_step.dag = dag
transpilation_sequence.add_step(transpilation_step)
%%html
<style>
.tp-widget { border:1px solid #aaa; }
.p-TabPanel-tabContents { padding: 10px !important; }
.p-Collapse-header { padding: 1px 5px; background: #eee; }
.p-Collapse-open > .p-Collapse-header { background: #ddd; }
.p-Collapse-contents { padding-top: 0; padding-left: 0; padding-bottom: 0;
padding-right: 0; height: 220px; background: #f5f5f5; }
.p-Collapse-contents button {
width: 20%;
background: #fff;
text-align: center;
padding: 0;
font-weight: bold; }
.widget-gridbox { background: #f5f5f5; }
.widget-checkbox { padding-left: 40px; }
div.output_scroll { box-shadow: none }
.p-Accordion .widget-gridbox .widget-label { background-color: #fff; padding: 0 3px;
font-family: 'Roboto Mono', monospace; font-size: 14px; }
.highlight { background-color: #ffc !important; font-weight: bold; }
.transpilation-step { background: #fff; border-bottom: 1px solid #ccc; }
.transpilation-step button { background: #fff; }
.transpilation-step .transformation { color: red; }
.transpilation-step .analysis { color: green; }
.transpilation-step div.fs10 { font-size: 10px; }
.transpilation-step div.fs11 { font-size: 11px; }
.transpilation-step div.fs12 { font-size: 12px; }
.transpilation-step div.fs13 { font-size: 13px; }
.transpilation-step div.fs14 { font-size: 14px; }
.transpilation-step div.fs15 { font-size: 15px; }
.transpilation-step > :nth-child(1) { text-align: center; font-weight: bold; font-size: 14px; }
.transpilation-step > :nth-child(2) { font-family: 'Roboto Mono', monospace; font-size: 15px; }
.transpilation-step > :nth-child(3) { font-family: 'Roboto Mono', monospace; font-size: 10px; color: #900;}
.transpilation-step > :nth-child(4) { color: #ff9d85; }
.transpilation-step > :nth-child(5) { color: #b587f7; }
.transpilation-step > :nth-child(6) { color: #6ea2c9; }
.logs-wpr { display: grid; grid-template-columns: 70px 60px auto; }
.logs-wpr pre.date { font-size: 10px; }
.logs-wpr pre.level { font-size: 10px; text-align: right; padding-right: 5px; }
.logs-wpr pre.log-entry { font-size: 12px; }
.logs-wpr pre.DEBUG { color: #000000; }
.logs-wpr pre.INFO { color: #1c84a2; }
.logs-wpr pre.WARNING { color: #ed7723; }
.logs-wpr pre.ERROR { color: #d64e4a; }
.logs-wpr pre.CRITICAL { color: white; background: #d64e4a; }
div.output_area pre.help { font-family: Helvetica,Arial,sans-serif; font-size: 13px;
border: 1px solid #ccc; padding: 10px;}
div.help-header {
font-family: 'Roboto Mono', monospace;
font-size: 12px;
border: 1px solid #ccc;
border-bottom: none;
margin-top: 4px;
padding: 5px 10px;
font-weight: bold;
background: #f5f5f5;
}
.stacking-context { position: relative; z-index: 99997; }
.wdgt-modal-background {
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
position: fixed;
top: 0;
left: 0;
display: none;
z-index: 99998;
}
.wdgt-modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
display: none;
width: 700px;
height: 300px;
background-color: #fff;
box-sizing: border-box;
border: 1px solid #eee;
border-radius: 5px;
overflow:hidden;
z-index: 99999;
}
.wdgt-modal-header {
background-color: #ccc;
border-bottom: 1px solid #dddddd;
box-sizing: border-box;
height: 50px;
padding: 0;
}
.wdgt-modal-header h3 {
margin: 0 !important;
box-sizing: border-box;
padding-left: 15px;
line-height: 50px;
color: #4d4d4d;
font-size: 16px;
display: inline-block;
}
.wdgt-modal-header span.close-wdgt-modal {
box-sizing: border-box;
border-left: 1px solid #dddddd;
float: right;
line-height: 50px;
margin-top: 18px;
padding: 0 15px 0 15px;
cursor: pointer;
}
.wdgt-modal-header span.close-wdgt-modal:hover img {
opacity: 0.6;
}
.wdgt-modal-content { overflow-y: auto; height: 250px; margin: 0; padding: 10px; }
.wdgt-modal-content pre { background: #fff; text-align: left; }
.show .wdgt-modal, .show .wdgt-modal-background { display: block; }
div.output_area .wdgt-modal-content img { max-width: none; /*height: 100%;*/ }
</style>
from qiskit.circuit.random import random_circuit
from qiskit.test.mock import FakeAlmaden
backend = FakeAlmaden()
transpilation_sequence = TranspilationSequence()
circ = random_circuit(5, 20, measure = True)
tp_widget
start_time = time()
circ_tr = transpile(circ, backend, optimization_level = 3, callback = transpiler_callback)
print(time() - start_time)
|
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
|
nahumsa
|
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries
from qiskit import IBMQ, QuantumCircuit, execute, assemble, schedule, transpile
from qiskit.providers.ibmq.job import job_monitor
from qiskit.tools.visualization import plot_histogram
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# Get backend
backend = provider.get_backend('ibmq_belem')
config = backend.configuration()
config.supported_instructions
h_x_circ = QuantumCircuit(1, 1)
h_x_circ.h(0)
h_x_circ.x(0)
h_x_circ.measure(0, 0)
def h_reset_x_circ(n_resets):
"""Do h, then n_resets reset instructions, then x on a single qubit."""
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.reset([0]*n_resets)
qc.x(0)
qc.measure(0,0)
return qc
circs0 = [h_x_circ, h_reset_x_circ(1), h_reset_x_circ(3), h_reset_x_circ(5)]
job1q_0 = execute(circs0, backend, initial_layout=[0])
job_monitor(job1q_0)
counts1 = job1q_0.result().get_counts()
legend_1q = ['h -> x', 'h -> reset -> x', 'h -> 3*reset -> x', 'h -> 5*reset -> x' ]
plot_histogram(counts1, legend=legend_1q, figsize=(9, 6))
initialize_x_circ = QuantumCircuit(1, 1)
initialize_x_circ.initialize([1/np.sqrt(3), np.sqrt(2/3)])
initialize_x_circ.x(0)
initialize_x_circ.measure(0, 0)
def initialize_reset_x_circ(n_resets):
"""Initialize, then n_resets reset instructions, then x on a single qubit."""
qc = QuantumCircuit(1, 1)
qc.initialize([1/np.sqrt(3), np.sqrt(2/3)])
qc.reset([0]*n_resets)
qc.x(0)
qc.measure(0,0)
return qc
circs1 = [initialize_x_circ, initialize_reset_x_circ(1), initialize_reset_x_circ(3), initialize_reset_x_circ(5)]
job1q_1 = execute(circs1, backend, initial_layout=[0])
job_monitor(job1q_1)
counts2 = job1q_1.result().get_counts()
legend_1q1 = ['initialize -> x', 'initialize -> reset -> x', 'initialize -> 3*reset -> x', 'initialize -> 5*reset -> x' ]
plot_histogram(counts2, legend=legend_1q1, figsize=(9, 6))
def multiq_custom_circ(n_resets):
"""Multi-qubit circuit on qubits 0, 1, 2 with ``n_resets`` reset instructions used."""
qc = QuantumCircuit(3, 3)
qc.h(0)
qc.h(1)
qc.h(2)
qc.reset([0]*n_resets)
qc.cx(0, 2)
qc.reset([1]*n_resets)
qc.x(1)
qc.measure(range(2), range(2))
return qc
multiq_circs = [multiq_custom_circ(0), multiq_custom_circ(1), multiq_custom_circ(3)]
# verify expected output
from qiskit import Aer
job_multiq_sim = execute(multiq_circs,
backend=Aer.get_backend('qasm_simulator'))
counts_multiq_sim = job_multiq_sim.result().get_counts()
print("No reset sim counts, custom circ: ", counts_multiq_sim[0])
print("1 Reset sim counts, custom circ: ", counts_multiq_sim[1])
job_multiq = execute(multiq_circs, backend)
job_monitor(job_multiq)
counts_multiq = job_multiq.result().get_counts()
legend_multiq = ['no reset', '1 reset', '3 resets']
plot_histogram(counts_multiq, legend=legend_multiq, figsize=(9, 6))
|
https://github.com/QForestCommunity/launchpad
|
QForestCommunity
|
import qiskit
qiskit.__qiskit_version__
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import Aer, execute, QuantumCircuit
from qiskit.circuit.library.standard_gates import RYGate
from numpy import pi, e, sqrt, arccos, log2
from scipy.integrate import quad
%matplotlib inline
import matplotlib.pyplot as plt
def distribution(x):
"""
Returns the value of a chosen probability distribution at the given value
of x. Mess around with this function to see how the encoder works!
The current distribution being used is N(0, 2).
"""
# Use these with normal distributions
mu = 0
sigma = 2
return (((e ** (-0.5 * ((x - mu) / sigma) ** 2)) / (sigma * sqrt(2 * pi))) / 0.99993665)
def integrate(dist, lower, upper):
"""
Perform integration using numpy's quad method. We can use parametrized
distributions as well by using this syntax instead:
quad(integrand, lower, upper, args=(tupleOfArgsForIntegrand))
"""
return quad(dist, lower, upper)[0]
def computeRegionProbability(dist, regBounds, numRegions, j):
"""
Given a distribution dist, a list of adjacent regions regBounds, the
current level of discretization numRegions, a region number j, computes
the probability that the value random variable following dist lies in
region j given that it lies in the larger region made up of regions
[(j // 2) * 2, ((j + 2) // 2) * 2]
"""
totalRegions = len(regBounds) - 1
k = 2 * j
prob = integrate(dist, regBounds[(totalRegions // numRegions) * k],
regBounds[(totalRegions // numRegions) * (k + 1)]) / integrate(
dist, regBounds[(totalRegions // numRegions) * ((k // 2) * 2)],
regBounds[(totalRegions // numRegions) * (((k + 2) // 2) * 2)])
return prob
def encodeDist(dist, regBounds):
numQubits = int(log2(len(regBounds) - 1))
a = QuantumRegister(2 * numQubits - 2)
c = ClassicalRegister(numQubits)
qc = QuantumCircuit(a, c)
for i in range(numQubits):
numRegions = int(2 ** (i + 1))
for j in range(numRegions // 2):
prob = computeRegionProbability(dist, regBounds, numRegions, j)
if not i:
qc.ry(2 * arccos(sqrt(prob)), a[2 * numQubits - 3])
else:
cGate = RYGate(2 * arccos(sqrt(prob))).control(i)
def getFlipList(i, j, numQubits):
"""
Given the current level of desired level of discretization, the
current level of discretization i and a region number j,
returns the binary bit string associated with j in the form of
a list of bits to be flipped.
"""
binString = str(bin(j))[2:]
binString = ("0" * (numQubits - len(binString))) + binString
bitFlips = []
for k in range(numQubits - i, numQubits):
if binString[k] == '0':
bitFlips.append(3 * numQubits - 3 - k - i)
return bitFlips
for k in listOfFlips:
qc.x(a[k])
qubitsUsed = [a[k] for k in
range(2 * numQubits - 2 - i, 2 * numQubits - 2)]
qubitsUsed.append(a[2 * numQubits - 3 - i])
qc.append(cGate, qubitsUsed)
for k in listOfFlips:
qc.x(a[k])
return qc, a, c
def encodeDist(dist, regBounds):
"""
Discretize the distribution dist into multiple regions with boundaries
given by regBounds, and store the associated quantum superposition
state in a new quantum register reg. Please make sure the number of
regions is a power of 2, i.e. len(regBounds) = (2 ** n) + 1.
Additionally, the number of regions is limited to a maximum of
2^(n // 2 + 1), where n is the number of qubits available in the backend
being used - this is due to the requirement of (n - 2) ancilla qubits in
order to perform (n - 1) control operations with minimal possible depth.
Returns a new quantum circuit containing the instructions and registers
needed to create the superposition state, along with the size of the
quantum register.
"""
numQubits = int(log2(len(regBounds) - 1))
a = QuantumRegister(2 * numQubits - 2)
c = ClassicalRegister(numQubits)
qc = QuantumCircuit(a, c)
for i in range(numQubits):
numRegions = int(2 ** (i + 1))
for j in range(numRegions // 2):
prob = computeRegionProbability(dist, regBounds, numRegions, j)
if not i:
qc.ry(2 * arccos(sqrt(prob)), a[2 * numQubits - 3])
else:
cGate = RYGate(2 * arccos(sqrt(prob))).control(i)
listOfFlips = getFlipList(i, j, numQubits)
for k in listOfFlips:
qc.x(a[k])
qubitsUsed = [a[k] for k in
range(2 * numQubits - 2 - i, 2 * numQubits - 2)]
qubitsUsed.append(a[2 * numQubits - 3 - i])
qc.append(cGate, qubitsUsed)
for k in listOfFlips:
qc.x(a[k])
return qc, a, c
def pad(x, numQubits):
"""
Utility function that returns a left padded version of the bit string
passed.
"""
string = str(x)[2:]
string = ('0' * (numQubits - len(string))) + string
return string
regBounds = [i for i in range(-16, 17)]
qc, a, c = encodeDist(distribution, regBounds)
numQubits = (qc.num_qubits + 2) // 2
for i in range(numQubits - 2, 2 * numQubits - 2):
qc.measure(a[i], c[i - (numQubits - 2)])
backend = Aer.get_backend('qasm_simulator')
shots = 100000
job = execute(qc, backend=backend, shots=shots)
results = job.result().get_counts()
resultsX = []
resultsY = []
for i in [pad(bin(x), numQubits) for x in range(2 ** (numQubits))]:
resultsX.append(i)
if i in results.keys():
resultsY.append(results[i])
else:
resultsY.append(0)
truthDisc = [integrate(distribution, regBounds[i], regBounds[i + 1]) * shots for i in range(
len(regBounds) - 1)]
plt.figure(figsize=[16, 9])
plt.plot(resultsX, resultsY)
plt.plot(resultsX, truthDisc, '--')
plt.legend(['quantum estimate', 'classical estimate'])
plt.show()
circuit_drawer(qc, output='latex')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
"""
Bernstein-Vazirani Benchmark Program - QSim
"""
import sys
import time
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
sys.path[1:1] = [ "_common", "_common/qsim" ]
sys.path[1:1] = [ "../../_common", "../../_common/qsim" ]
import execute as ex
import metrics as metrics
from execute import BenchmarkResult
# Benchmark Name
benchmark_name = "Bernstein-Vazirani"
np.random.seed(0)
verbose = False
# Variable for number of resets to perform after mid circuit measurements
num_resets = 1
# saved circuits for display
QC_ = None
Uf_ = None
############### Circuit Definition
def create_oracle(num_qubits, input_size, secret_int):
# Initialize first n qubits and single ancilla qubit
qr = QuantumRegister(num_qubits)
qc = QuantumCircuit(qr, name=f"Uf")
# perform CX for each qubit that matches a bit in secret string
s = ('{0:0' + str(input_size) + 'b}').format(secret_int)
for i_qubit in range(input_size):
if s[input_size - 1 - i_qubit] == '1':
qc.cx(qr[i_qubit], qr[input_size])
return qc
def BersteinVazirani (num_qubits, secret_int, method = 1):
# size of input is one less than available qubits
input_size = num_qubits - 1
if method == 1:
# allocate qubits
qr = QuantumRegister(num_qubits); cr = ClassicalRegister(input_size);
qc = QuantumCircuit(qr, cr, name=f"bv({method})-{num_qubits}-{secret_int}")
# put ancilla in |1> state
qc.x(qr[input_size])
# start with Hadamard on all qubits, including ancilla
for i_qubit in range(num_qubits):
qc.h(qr[i_qubit])
qc.barrier()
#generate Uf oracle
Uf = create_oracle(num_qubits, input_size, secret_int)
qc.append(Uf,qr)
qc.barrier()
# start with Hadamard on all qubits, including ancilla
for i_qubit in range(num_qubits):
qc.h(qr[i_qubit])
# uncompute ancilla qubit, not necessary for algorithm
qc.x(qr[input_size])
qc.barrier()
# measure all data qubits
for i in range(input_size):
qc.measure(i, i)
global Uf_
if Uf_ == None or num_qubits <= 6:
if num_qubits < 9: Uf_ = Uf
elif method == 2:
# allocate qubits
qr = QuantumRegister(2); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name="main")
# put ancilla in |-> state
qc.x(qr[1])
qc.h(qr[1])
qc.barrier()
# perform CX for each qubit that matches a bit in secret string
s = ('{0:0' + str(input_size) + 'b}').format(secret_int)
for i in range(input_size):
if s[input_size - 1 - i] == '1':
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.h(qr[0])
qc.measure(qr[0], cr[i])
# Perform num_resets reset operations
qc.reset([0]*num_resets)
# save smaller circuit example for display
global QC_
if QC_ == None or num_qubits <= 15:
if num_qubits < 15: QC_ = qc
# return a handle on the circuit
return qc
############### Result Data Analysis
# Analyze and print measured results
# Expected result is always the secret_int, so fidelity calc is simple
def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots):
# size of input is one less than available qubits
input_size = num_qubits - 1
if result.backend_name == 'dm_simulator':
benchmark_result = BenchmarkResult(result, num_shots)
probs = benchmark_result.get_probs(num_shots) # get results as measured probability
else:
probs = result.get_counts(qc) # get results as measured counts
if verbose: print(f"For secret int {secret_int} measured: {probs}")
# create the key that is expected to have all the measurements (for this circuit)
key = format(secret_int, f"0{input_size}b")
# correct distribution is measuring the key 100% of the time
correct_dist = {key: 1.0}
# use our polarization fidelity rescaling
fidelity = metrics.polarization_fidelity(probs, correct_dist)
return probs, fidelity
################ Benchmark Loop
# Execute program with default parameters
def run (min_qubits=3, max_qubits=14, skip_qubits=1, max_circuits=3, num_shots=100,
backend_id='dm_simulator', method = 1, provider_backend=None,
# hub="ibm-q", group="open", project="main",
exec_options=None, context=None):
print(f"{benchmark_name} ({method}) Benchmark Program - QSim")
# validate parameters (smallest circuit is 3 qubits)
max_qubits = max(3, max_qubits)
min_qubits = min(max(3, min_qubits), max_qubits)
skip_qubits = max(1, skip_qubits)
#print(f"min, max qubits = {min_qubits} {max_qubits}")
# create context identifier
if context is None: context = f"{benchmark_name} ({method}) Benchmark"
##########
# Variable for new qubit group ordering if using mid_circuit measurements
mid_circuit_qubit_group = []
# If using mid_circuit measurements, set transform qubit group to true
transform_qubit_group = True if method ==2 else False
# Initialize metrics module
metrics.init_metrics()
# Define custom result handler
def execution_handler (qc, result, num_qubits, s_int, num_shots):
# determine fidelity of result set
num_qubits = int(num_qubits)
counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots)
metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity)
# Initialize execution module using the execution result handler above and specified backend_id
ex.init_execution(execution_handler)
ex.set_execution_target(backend_id, provider_backend=provider_backend,
# hub=hub, group=group, project=project,
exec_options=exec_options, context=context)
# for noiseless simulation, set noise model to be None
# ex.set_noise_model(None)
##########
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits):
input_size = num_qubits - 1
# determine number of circuits to execute for this group
num_circuits = min(2**(input_size), max_circuits)
print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}")
# determine range of secret strings to loop over
if 2**(input_size) <= max_circuits:
s_range = list(range(num_circuits))
else:
s_range = np.random.choice(2**(input_size), num_circuits, False)
# loop over limited # of secret strings for this
for s_int in s_range:
# If mid circuit, then add 2 to new qubit group since the circuit only uses 2 qubits
if method == 2:
mid_circuit_qubit_group.append(2)
# create the circuit for given qubit size and secret string, store time metric
ts = time.time()
qc = BersteinVazirani(num_qubits, s_int, method).reverse_bits() # reverse_bits() is to change the endianness
print(qc)
metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts)
# collapse the sub-circuit levels used in this benchmark (for qiskit)
qc2 = qc.decompose()
# submit circuit for execution on target (simulator, cloud simulator, or hardware)
ex.submit_circuit(qc2, num_qubits, s_int, shots=num_shots)
# Wait for some active circuits to complete; report metrics when groups complete
ex.throttle_execution(metrics.finalize_group)
# Wait for all active circuits to complete; report metrics when groups complete
ex.finalize_execution(metrics.finalize_group)
##########
# print a sample circuit
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!")
# Plot metrics for all circuit sizes
metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim",
transform_qubit_group = transform_qubit_group, new_qubit_group = mid_circuit_qubit_group)
# if main, execute method
if __name__ == '__main__': run()
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
"""
Hamiltonian-Simulation Benchmark Program - QSim
"""
import json
import os
import sys
import time
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
sys.path[1:1] = ["_common", "_common/qsim"]
sys.path[1:1] = ["../../_common", "../../_common/qsim"]
import execute as ex
import metrics as metrics
from execute import BenchmarkResult
# Benchmark Name
benchmark_name = "Hamiltonian Simulation"
np.random.seed(0)
verbose = False
# saved circuits and subcircuits for display
QC_ = None
XX_ = None
YY_ = None
ZZ_ = None
XXYYZZ_ = None
# for validating the implementation of XXYYZZ operation
_use_XX_YY_ZZ_gates = False
# import precalculated data to compare against
# filename = os.path.join(os.path.dirname(__file__), os.path.pardir, "_common", "precalculated_data.json")
filename = os.path.join(os.path.pardir, "_common", "precalculated_data.json")
with open(filename, 'r') as file:
data = file.read()
precalculated_data = json.loads(data)
############### Circuit Definition
def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z):
'''
Construct a Qiskit circuit for Hamiltonian Simulation
:param n_spins:The number of spins to simulate
:param K: The Trotterization order
:param t: duration of simulation
:return: return a Qiskit circuit for this Hamiltonian
'''
num_qubits = n_spins
secret_int = f"{K}-{t}"
# allocate qubits
qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins);
qc = QuantumCircuit(qr, cr, name=f"hamsim-{num_qubits}-{secret_int}")
tau = t / K
# start with initial state of 1010101...
for k in range(0, n_spins, 2):
qc.x(qr[k])
qc.barrier()
# loop over each trotter step, adding gates to the circuit defining the hamiltonian
for k in range(K):
# the Pauli spin vector product
[qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)]
[qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)]
qc.barrier()
# Basic implementation of exp(i * t * (XX + YY + ZZ))
if _use_XX_YY_ZZ_gates:
# XX operator on each pair of qubits in linear chain
for j in range(2):
for i in range(j%2, n_spins - 1, 2):
qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]])
# YY operator on each pair of qubits in linear chain
for j in range(2):
for i in range(j%2, n_spins - 1, 2):
qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]])
# ZZ operation on each pair of qubits in linear chain
for j in range(2):
for i in range(j%2, n_spins - 1, 2):
qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]])
# Use an optimal XXYYZZ combined operator
# See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf
else:
# optimized XX + YY + ZZ operator on each pair of qubits in linear chain
for j in range(2):
for i in range(j % 2, n_spins - 1, 2):
qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]])
qc.barrier()
# measure all the qubits used in the circuit
for i_qubit in range(n_spins):
qc.measure(qr[i_qubit], cr[i_qubit])
# save smaller circuit example for display
global QC_
if QC_ == None or n_spins <= 6:
if n_spins < 9: QC_ = qc
return qc
############### XX, YY, ZZ Gate Implementations
# Simple XX gate on q0 and q1 with angle 'tau'
def xx_gate(tau):
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate")
qc.h(qr[0])
qc.h(qr[1])
qc.cx(qr[0], qr[1])
qc.rz(3.1416*tau, qr[1])
qc.cx(qr[0], qr[1])
qc.h(qr[0])
qc.h(qr[1])
# save circuit example for display
global XX_
XX_ = qc
return qc
# Simple YY gate on q0 and q1 with angle 'tau'
def yy_gate(tau):
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate")
qc.s(qr[0])
qc.s(qr[1])
qc.h(qr[0])
qc.h(qr[1])
qc.cx(qr[0], qr[1])
qc.rz(3.1416*tau, qr[1])
qc.cx(qr[0], qr[1])
qc.h(qr[0])
qc.h(qr[1])
qc.sdg(qr[0])
qc.sdg(qr[1])
# save circuit example for display
global YY_
YY_ = qc
return qc
# Simple ZZ gate on q0 and q1 with angle 'tau'
def zz_gate(tau):
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate")
qc.cx(qr[0], qr[1])
qc.rz(3.1416*tau, qr[1])
qc.cx(qr[0], qr[1])
# save circuit example for display
global ZZ_
ZZ_ = qc
return qc
# Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau'
def xxyyzz_opt_gate(tau):
alpha = tau; beta = tau; gamma = tau
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt")
qc.rz(3.1416/2, qr[1])
qc.cx(qr[1], qr[0])
qc.rz(3.1416*gamma - 3.1416/2, qr[0])
qc.ry(3.1416/2 - 3.1416*alpha, qr[1])
qc.cx(qr[0], qr[1])
qc.ry(3.1416*beta - 3.1416/2, qr[1])
qc.cx(qr[1], qr[0])
qc.rz(-3.1416/2, qr[0])
# save circuit example for display
global XXYYZZ_
XXYYZZ_ = qc
return qc
############### Result Data Analysis
# Analyze and print measured results
# Compute the quality of the result based on operator expectation for each state
def analyze_and_print_result(qc, result, num_qubits, type, num_shots):
if result.backend_name == 'dm_simulator':
benchmark_result = BenchmarkResult(result, num_shots)
probs = benchmark_result.get_probs(num_shots) # get results as measured probability
else:
probs = result.get_counts(qc) # get results as measured counts
# print(f"probs ===== {probs}")
if verbose: print(f"For type {type} measured: {probs}")
# we have precalculated the correct distribution that a perfect quantum computer will return
# it is stored in the json file we import at the top of the code
correct_dist = precalculated_data[f"Qubits - {num_qubits}"]
if verbose: print(f"\nCorrect dist: {correct_dist}")
correct_dist_reversed = {key[::-1]: value for key, value in correct_dist.items()}
# print(f"correct_dist_reversed ===== {correct_dist_reversed}")
# use our polarization fidelity rescaling
fidelity = metrics.polarization_fidelity(probs, correct_dist_reversed)
# print(f"fidelity ===== {fidelity}")
return probs, fidelity
################ Benchmark Loop
# Execute program with default parameters
def run(min_qubits=2, max_qubits=8, max_circuits=3, skip_qubits=1, num_shots=100,
use_XX_YY_ZZ_gates = False,
backend_id='dm_simulator', provider_backend=None,
#hub="ibm-q", group="open", project="main",
exec_options=None,
context=None):
print(f"{benchmark_name} Benchmark Program - QSim")
# validate parameters (smallest circuit is 2 qubits)
max_qubits = max(2, max_qubits)
min_qubits = min(max(2, min_qubits), max_qubits)
if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even
skip_qubits = max(1, skip_qubits)
#print(f"min, max qubits = {min_qubits} {max_qubits}")
# create context identifier
#if context is None: context = f"{benchmark_name} ({method}) Benchmark"
if context is None: context = f"{benchmark_name} Benchmark"
# set the flag to use an XX YY ZZ shim if given
global _use_XX_YY_ZZ_gates
_use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates
if _use_XX_YY_ZZ_gates:
print("... using unoptimized XX YY ZZ gates")
##########
# Initialize metrics module
metrics.init_metrics()
# Define custom result handler
def execution_handler(qc, result, num_qubits, type, num_shots):
# determine fidelity of result set
num_qubits = int(num_qubits)
probs, expectation_a = analyze_and_print_result(qc, result, num_qubits, type, num_shots)
metrics.store_metric(num_qubits, type, 'fidelity', expectation_a)
# Initialize execution module using the execution result handler above and specified backend_id
ex.init_execution(execution_handler)
ex.set_execution_target(backend_id, provider_backend=provider_backend,
# hub=hub, group=group, project=project,
exec_options=exec_options,
context=context)
##########
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits):
# reset random seed
np.random.seed(0)
# determine number of circuits to execute for this group
num_circuits = max(1, max_circuits)
print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}")
# parameters of simulation
#### CANNOT BE MODIFIED W/O ALSO MODIFYING PRECALCULATED DATA #########
w = precalculated_data['w'] # strength of disorder
k = precalculated_data['k'] # Trotter error.
# A large Trotter order approximates the Hamiltonian evolution better.
# But a large Trotter order also means the circuit is deeper.
# For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation.
t = precalculated_data['t'] # time of simulation
#######################################################################
# loop over only 1 circuit
for circuit_id in range(num_circuits):
#print(circuit_id)
# create the circuit for given qubit size and simulation parameters, store time metric
ts = time.time()
h_x = precalculated_data['h_x'][:num_qubits] # precalculated random numbers between [-1, 1]
h_z = precalculated_data['h_z'][:num_qubits]
qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z)
print(qc)
metrics.store_metric(num_qubits, circuit_id, 'create_time', time.time() - ts)
# collapse the sub-circuits used in this benchmark (for qiskit)
qc2 = qc.decompose()
# submit circuit for execution on target (simulator, cloud simulator, or hardware)
ex.submit_circuit(qc2, num_qubits, circuit_id, num_shots)
# Wait for some active circuits to complete; report metrics when groups complete
ex.throttle_execution(metrics.finalize_group)
# Wait for all active circuits to complete; report metrics when groups complete
ex.finalize_execution(metrics.finalize_group)
##########
# print a sample circuit
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
if _use_XX_YY_ZZ_gates:
print("\nXX, YY, ZZ =")
print(XX_); print(YY_); print(ZZ_)
else:
print("\nXXYYZZ_opt =")
print(XXYYZZ_)
# Plot metrics for all circuit sizes
metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim")
# if main, execute method
if __name__ == '__main__': run()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.visualization.timeline import draw as timeline_draw
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeBoeblingen
backend = FakeBoeblingen()
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
circ = transpile(ghz, backend, scheduling_method="asap")
timeline_draw(circ)
|
https://github.com/GabrielPontolillo/QiskitPBT
|
GabrielPontolillo
|
# class that inherits from property based test
from qiskit import QuantumCircuit
import numpy as np
from qiskit.circuit.library import UnitaryGate
from QiskitPBT.property import Property
from QiskitPBT.input_generators import RandomEigenvectorUnitaryPair, RandomTensorProductOfUnitary, Integer
from QiskitPBT.case_studies.quantum_phase_estimation.quantum_phase_estimation import qpe_general
class PhaseEstimationSumEigenvectors(Property):
# specify the inputs that are to be generated
def get_input_generators(self):
eigenvector_unitary_pair = RandomEigenvectorUnitaryPair(RandomTensorProductOfUnitary(1, 2), 2)
estimation_qubits = Integer(1, 3)
return [eigenvector_unitary_pair, estimation_qubits]
# specify the preconditions for the test
def preconditions(self, eigenvector_unitary_pair, estimation_qubits):
# TODO: this is truly a poor implementation.
# to fix, make a pseudorandom unitary generator to pass to RandomEigenvectorUnitaryPair, which allows for a range of eigenvalues
# but not infinite, as to allow for multiple eigenvectors with the same eigenvalue
# then send all the eigenvectors here instead of an already chosen pair
# check that the eigenvectors have the same eigenvalue
return eigenvector_unitary_pair[0][0][1] == eigenvector_unitary_pair[0][1][1]
# specify the operations to be performed on the input
def operations(self, eigenvector_unitary_pair, estimation_qubits):
eigenvectors, unitary = eigenvector_unitary_pair
for eigenvector, eigenvalue in eigenvectors:
print(eigenvalue)
n = unitary.num_qubits
# perform qpe on with an eigenvector in lower register
qpe = qpe_general(estimation_qubits, UnitaryGate(unitary), eigenvectors[0][0])
# sum of eigenvectors, then normalize
normalized_sum_eigenvectors = (eigenvectors[0][0] + eigenvectors[1][0]) / np.sqrt(2)
qpe2 = qpe_general(estimation_qubits, UnitaryGate(unitary), normalized_sum_eigenvectors)
print(qpe)
print(qpe2)
self.statistical_analysis.assert_equal(self, list(range(estimation_qubits)), qpe,
list(range(estimation_qubits)), qpe2)
|
https://github.com/QuSTaR/kaleidoscope
|
QuSTaR
|
#!/usr/bin/env python
#
# Copyright 2019 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pygame
from qiskit import BasicAer, execute
from qiskit.tools.visualization import plot_state_qsphere
from utils import load_image
class QSphere(pygame.sprite.Sprite):
"""Displays a qsphere"""
def __init__(self, circuit):
pygame.sprite.Sprite.__init__(self)
self.image = None
self.rect = None
self.set_circuit(circuit)
# def update(self):
# # Nothing yet
# a = 1
def set_circuit(self, circuit):
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circuit, backend_sv_sim)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circuit, decimals=3)
qsphere = plot_state_qsphere(quantum_state)
qsphere.savefig("utils/data/bell_qsphere.png")
self.image, self.rect = load_image('bell_qsphere.png', -1)
self.rect.inflate_ip(-100, -100)
self.image.convert()
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
from qiskit import QuantumRegister, QuantumCircuit, execute, Aer
cq = QuantumRegister(2,'code\_qubit')
lq = QuantumRegister(1,'link\_qubit')
qc = QuantumCircuit(cq,lq)
qc.cx(cq[0],lq[0])
qc.cx(cq[1],lq[0])
print(qc)
qc.draw('mpl')
from qiskit.ignis.verification.topological_codes import RepetitionCode
from qiskit.ignis.verification.topological_codes import GraphDecoder
from qiskit.ignis.verification.topological_codes import lookuptable_decoding, postselection_decoding
d = 2
T = 1
code = RepetitionCode(d,T)
code.circuit
print ( 'code_bits:', code.code_bit, ' d=', code.d, ' T=', code.T)
code.qubit_registers
code.code_qubit
for bit in ['0','1']:
print('\n========= logical',bit,'=========\n')
print( code.circuit[bit] )
d = 2
T = 1
code = RepetitionCode(d,T)
for bit in ['0','1']:
print('\n========= logical',bit,'=========\n')
print( code.circuit[bit] )
empty_code = RepetitionCode(3,0)
def print_circuits(code):
for log in ['0','1']:
print('\n========= logical',log,'=========\n')
print( code.circuit[log] )
print_circuits(empty_code)
empty_code.syndrome_measurement()
print_circuits(empty_code)
empty_code.x()
print_circuits(empty_code)
empty_code.readout()
print_circuits(empty_code)
circuits = code.get_circuit_list()
job = execute( circuits, Aer.get_backend('qasm_simulator') )
raw_results = {}
for log in ['0','1']:
raw_results[log] = job.result().get_counts(log)
print('\n========= logical',log,'=========\n')
print(raw_results[log])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
pw_approximation._build()
qc = QuantumCircuit(pw_approximation.num_qubits)
qc.h(list(range(num_state_qubits)))
qc.append(pw_approximation.to_instruction(), qc.qubits)
qc.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import MCXGate
gate = MCXGate(4)
from qiskit import QuantumCircuit
circuit = QuantumCircuit(5)
circuit.append(gate, [0, 1, 4, 2, 3])
circuit.draw('mpl')
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Class for holding evolution result."""
from __future__ import annotations
from qiskit import QuantumCircuit
from qiskit_algorithms.list_or_dict import ListOrDict
from qiskit.opflow import StateFn, OperatorBase
from qiskit.utils.deprecation import deprecate_func
from ..algorithm_result import AlgorithmResult
class EvolutionResult(AlgorithmResult):
"""Deprecated: Class for holding evolution result.
The EvolutionResult class has been superseded by the
:class:`qiskit_algorithms.time_evolvers.TimeEvolutionResult` class.
This class will be deprecated in a future release and subsequently
removed after that.
"""
@deprecate_func(
additional_msg=(
"Instead, use the class ``qiskit_algorithms.time_evolvers.TimeEvolutionResult``. "
"See https://qisk.it/algo_migration for a migration guide."
),
since="0.24.0",
)
def __init__(
self,
evolved_state: StateFn | QuantumCircuit | OperatorBase,
aux_ops_evaluated: ListOrDict[tuple[complex, complex]] | None = None,
):
"""
Args:
evolved_state: An evolved quantum state.
aux_ops_evaluated: Optional list of observables for which expected values on an evolved
state are calculated. These values are in fact tuples formatted as (mean, standard
deviation).
"""
self.evolved_state = evolved_state
self.aux_ops_evaluated = aux_ops_evaluated
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""The module to compute the state gradient with the parameter shift rule."""
from collections.abc import Iterable
from copy import deepcopy
from functools import partial
from typing import List, Union, Tuple, Dict
import scipy
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter, ParameterExpression, ParameterVector
from qiskit.utils.deprecation import deprecate_func
from .circuit_gradient import CircuitGradient
from ...operator_base import OperatorBase
from ...state_fns.state_fn import StateFn
from ...operator_globals import Zero, One
from ...state_fns.circuit_state_fn import CircuitStateFn
from ...primitive_ops.circuit_op import CircuitOp
from ...list_ops.summed_op import SummedOp
from ...list_ops.list_op import ListOp
from ...list_ops.composed_op import ComposedOp
from ...state_fns.dict_state_fn import DictStateFn
from ...state_fns.vector_state_fn import VectorStateFn
from ...state_fns.sparse_vector_state_fn import SparseVectorStateFn
from ...exceptions import OpflowError
from ..derivative_base import _coeff_derivative
class ParamShift(CircuitGradient):
"""Deprecated: Compute the gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the sampling
probabilities of the basis states of a state |ψ(ω)〉w.r.t. ω with the parameter shift
method.
"""
SUPPORTED_GATES = {"x", "y", "z", "h", "rx", "ry", "rz", "p", "u", "cx", "cy", "cz"}
@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(self, analytic: bool = True, epsilon: float = 1e-6):
r"""
Args:
analytic: If True use the parameter shift rule to compute analytic gradients,
else use a finite difference approach
epsilon: The offset size to use when computing finite difference gradients.
Ignored if analytic == True
Raises:
ValueError: If method != ``fin_diff`` and ``epsilon`` is not None.
"""
super().__init__()
self._analytic = analytic
self._epsilon = epsilon
@property
def analytic(self) -> bool:
"""Returns ``analytic`` flag.
Returns:
``analytic`` flag.
"""
return self._analytic
@property
def epsilon(self) -> float:
"""Returns ``epsilon``.
Returns:
``epsilon``.
"""
return self._epsilon
# pylint: disable=signature-differs
def convert(
self,
operator: OperatorBase,
params: Union[
ParameterExpression,
ParameterVector,
List[ParameterExpression],
Tuple[ParameterExpression, ParameterExpression],
List[Tuple[ParameterExpression, ParameterExpression]],
],
) -> OperatorBase:
"""
Args:
operator: The operator corresponding to our quantum state we are taking the
gradient of: |ψ(ω)〉
params: The parameters we are taking the gradient wrt: ω
If a ParameterExpression, ParameterVector or List[ParameterExpression] is given,
then the 1st order derivative of the operator is calculated.
If a Tuple[ParameterExpression, ParameterExpression] or
List[Tuple[ParameterExpression, ParameterExpression]]
is given, then the 2nd order derivative of the operator is calculated.
Returns:
An operator corresponding to the gradient resp. Hessian. The order is in accordance with
the order of the given parameters.
Raises:
OpflowError: If the parameters are given in an invalid format.
"""
if isinstance(params, (ParameterExpression, ParameterVector)):
return self._parameter_shift(operator, params)
elif isinstance(params, tuple):
return self._parameter_shift(self._parameter_shift(operator, params[0]), params[1])
elif isinstance(params, Iterable):
if all(isinstance(param, ParameterExpression) for param in params):
return self._parameter_shift(operator, params)
elif all(isinstance(param, tuple) for param in params):
return ListOp(
[
self._parameter_shift(self._parameter_shift(operator, pair[0]), pair[1])
for pair in params
]
)
else:
raise OpflowError(
"The linear combination gradient does only support "
"the computation "
"of 1st gradients and 2nd order gradients."
)
else:
raise OpflowError(
"The linear combination gradient does only support the computation "
"of 1st gradients and 2nd order gradients."
)
# pylint: disable=too-many-return-statements
def _parameter_shift(
self, operator: OperatorBase, params: Union[ParameterExpression, ParameterVector, List]
) -> OperatorBase:
r"""
Args:
operator: The operator containing circuits we are taking the derivative of.
params: The parameters (ω) we are taking the derivative with respect to. If
a ParameterVector is provided, each parameter will be shifted.
Returns:
param_shifted_op: An operator object which evaluates to the respective gradients.
Raises:
ValueError: If the given parameters do not occur in the provided operator
TypeError: If the operator has more than one circuit representing the quantum state
"""
if isinstance(params, (ParameterVector, list)):
param_grads = [self._parameter_shift(operator, param) for param in params]
absent_params = [
params[i] for i, grad_ops in enumerate(param_grads) if grad_ops is None
]
if len(absent_params) > 0:
raise ValueError(
"The following parameters do not appear in the provided operator: ",
absent_params,
)
return ListOp(absent_params)
# By this point, it's only one parameter
param = params
if isinstance(operator, ListOp) and not isinstance(operator, ComposedOp):
return_op = operator.traverse(partial(self._parameter_shift, params=param))
# Remove any branch of the tree where the relevant parameter does not occur
trimmed_oplist = [op for op in return_op.oplist if op is not None]
# If all branches are None, remove the parent too
if len(trimmed_oplist) == 0:
return None
# Rebuild the operator with the trimmed down oplist
properties = {"coeff": return_op._coeff, "abelian": return_op._abelian}
if return_op.__class__ == ListOp:
properties["combo_fn"] = return_op.combo_fn
return return_op.__class__(oplist=trimmed_oplist, **properties)
else:
circs = self.get_unique_circuits(operator)
if len(circs) > 1:
raise TypeError(
"Please define an operator with a single circuit representing "
"the quantum state."
)
if len(circs) == 0:
return operator
circ = circs[0]
if self.analytic:
# Unroll the circuit into a gate set for which the gradient may be computed
# using pi/2 shifts.
circ = ParamShift._transpile_to_supported_operations(circ, self.SUPPORTED_GATES)
operator = ParamShift._replace_operator_circuit(operator, circ)
if param not in circ._parameter_table:
return ~Zero @ One
shifted_ops = []
summed_shifted_op = None
iref_to_data_index = {id(inst.operation): idx for idx, inst in enumerate(circ.data)}
for param_reference in circ._parameter_table[param]:
original_gate, param_index = param_reference
m = iref_to_data_index[id(original_gate)]
pshift_op = deepcopy(operator)
mshift_op = deepcopy(operator)
# We need the circuit objects of the newly instantiated operators
pshift_circ = self.get_unique_circuits(pshift_op)[0]
mshift_circ = self.get_unique_circuits(mshift_op)[0]
pshift_gate = pshift_circ.data[m].operation
mshift_gate = mshift_circ.data[m].operation
p_param = pshift_gate.params[param_index]
m_param = mshift_gate.params[param_index]
# For analytic gradients the circuit parameters are shifted once by +pi/2 and
# once by -pi/2.
if self.analytic:
shift_constant = 0.5
pshift_gate.params[param_index] = p_param + (np.pi / (4 * shift_constant))
mshift_gate.params[param_index] = m_param - (np.pi / (4 * shift_constant))
# For finite difference gradients the circuit parameters are shifted once by
# +epsilon and once by -epsilon.
else:
shift_constant = 1.0 / (2 * self._epsilon)
pshift_gate.params[param_index] = p_param + self._epsilon
mshift_gate.params[param_index] = m_param - self._epsilon
# The results of the shifted operators are now evaluated according the parameter
# shift / finite difference formula.
if isinstance(operator, ComposedOp):
shifted_op = shift_constant * (pshift_op - mshift_op)
# If the operator represents a quantum state then we apply a special combo
# function to evaluate probability gradients.
elif isinstance(operator, StateFn):
shifted_op = ListOp(
[pshift_op, mshift_op],
combo_fn=partial(self._prob_combo_fn, shift_constant=shift_constant),
)
else:
raise TypeError(
"Probability gradients are not supported for the given operator type"
)
if isinstance(p_param, ParameterExpression) and not isinstance(p_param, Parameter):
expr_grad = _coeff_derivative(p_param, param)
shifted_op *= expr_grad
if not summed_shifted_op:
summed_shifted_op = shifted_op
else:
summed_shifted_op += shifted_op
shifted_ops.append(summed_shifted_op)
if not SummedOp(shifted_ops).reduce():
return ~StateFn(Zero) @ One
else:
return SummedOp(shifted_ops).reduce()
@staticmethod
def _prob_combo_fn(
x: Union[
DictStateFn,
VectorStateFn,
SparseVectorStateFn,
List[Union[DictStateFn, VectorStateFn, SparseVectorStateFn]],
],
shift_constant: float,
) -> Union[Dict, np.ndarray]:
"""Implement the combo_fn used to evaluate probability gradients
Args:
x: Output of an operator evaluation
shift_constant: Shifting constant factor needed for proper rescaling
Returns:
Array representing the probability gradients w.r.t. the given operator and parameters
Raises:
TypeError: if ``x`` is not DictStateFn, VectorStateFn or their list.
"""
# Note: In the probability gradient case, the amplitudes still need to be converted
# into sampling probabilities.
def get_primitives(item):
if isinstance(item, (DictStateFn, SparseVectorStateFn)):
item = item.primitive
if isinstance(item, VectorStateFn):
item = item.primitive.data
return item
is_statefn = False
if isinstance(x, list):
# Check if all items in x are a StateFn items
if all(isinstance(item, StateFn) for item in x):
is_statefn = True
items = [get_primitives(item) for item in x]
else:
# Check if x is a StateFn item
if isinstance(x, StateFn):
is_statefn = True
items = [get_primitives(x)]
if isinstance(items[0], dict):
prob_dict: Dict[str, float] = {}
for i, item in enumerate(items):
for key, prob_counts in item.items():
prob_dict[key] = (
prob_dict.get(key, 0) + shift_constant * ((-1) ** i) * prob_counts
)
return prob_dict
elif isinstance(items[0], scipy.sparse.spmatrix):
# If x was given as StateFn the state amplitudes need to be multiplied in order to
# evaluate the sampling probabilities which are then subtracted according to the
# parameter shift rule.
if is_statefn:
return shift_constant * np.subtract(
items[0].multiply(np.conj(items[0])), items[1].multiply(np.conj(items[1]))
)
# If x was not given as a StateFn the state amplitudes were already converted into
# sampling probabilities which are then only subtracted according to the
# parameter shift rule.
else:
return shift_constant * np.subtract(items[0], items[1])
elif isinstance(items[0], Iterable):
# If x was given as StateFn the state amplitudes need to be multiplied in order to
# evaluate the sampling probabilities which are then subtracted according to the
# parameter shift rule.
if is_statefn:
return shift_constant * np.subtract(
np.multiply(items[0], np.conj(items[0])),
np.multiply(items[1], np.conj(items[1])),
)
# If x was not given as a StateFn the state amplitudes were already converted into
# sampling probabilities which are then only subtracted according to the
# parameter shift rule.
else:
return shift_constant * np.subtract(items[0], items[1])
raise TypeError(
"Probability gradients can only be evaluated from VectorStateFs or DictStateFns."
)
@staticmethod
def _replace_operator_circuit(operator: OperatorBase, circuit: QuantumCircuit) -> OperatorBase:
"""Replace a circuit element in an operator with a single element given as circuit
Args:
operator: Operator for which the circuit representing the quantum state shall be
replaced
circuit: Circuit which shall replace the circuit in the given operator
Returns:
Operator with replaced circuit quantum state function
"""
if isinstance(operator, CircuitStateFn):
return CircuitStateFn(circuit, coeff=operator.coeff)
elif isinstance(operator, CircuitOp):
return CircuitOp(circuit, coeff=operator.coeff)
elif isinstance(operator, (ComposedOp, ListOp)):
return operator.traverse(partial(ParamShift._replace_operator_circuit, circuit=circuit))
else:
return operator
@classmethod
def get_unique_circuits(cls, operator: OperatorBase) -> List[QuantumCircuit]:
"""Traverse the operator and return all unique circuits
Args:
operator: An operator that potentially includes QuantumCircuits
Returns:
A list of all unique quantum circuits that appear in the operator
"""
if isinstance(operator, CircuitStateFn):
return [operator.primitive]
def get_circuit(op):
return op.primitive if isinstance(op, (CircuitStateFn, CircuitOp)) else None
unrolled_op = cls.unroll_operator(operator)
circuits = []
for ops in unrolled_op:
if not isinstance(ops, list):
ops = [ops]
for op in ops:
if isinstance(op, (CircuitStateFn, CircuitOp, QuantumCircuit)):
c = get_circuit(op)
if c and c not in circuits:
circuits.append(c)
return circuits
@classmethod
def unroll_operator(cls, operator: OperatorBase) -> Union[OperatorBase, List[OperatorBase]]:
"""Traverse the operator and return all OperatorBase objects flattened
into a single list. This is used as a subroutine to extract all
circuits within a large composite operator.
Args:
operator: An OperatorBase type object
Returns:
A single flattened list of all OperatorBase objects within the
input operator
"""
if isinstance(operator, ListOp):
return [cls.unroll_operator(op) for op in operator]
if hasattr(operator, "primitive") and isinstance(operator.primitive, ListOp):
return [operator.__class__(op) for op in operator.primitive]
return operator
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
for idx in range(5):
qc.h(idx)
qc.cx(idx, idx+5)
qc.cx(1, 7)
qc.x(8)
qc.cx(1, 9)
qc.x(7)
qc.cx(1, 11)
qc.swap(6, 11)
qc.swap(6, 9)
qc.swap(6, 10)
qc.x(6)
qc.draw('mpl')
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Decorator for using with Qiskit unit tests."""
import functools
import os
import sys
import unittest
from .utils import Path
from .http_recorder import http_recorder
from .testing_options import get_test_options
def is_aer_provider_available():
"""Check if the C++ simulator can be instantiated.
Returns:
bool: True if simulator executable is available
"""
# TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC
if sys.platform == 'darwin':
return False
try:
import qiskit.providers.aer # pylint: disable=unused-import
except ImportError:
return False
return True
def requires_aer_provider(test_item):
"""Decorator that skips test if qiskit aer provider is not available
Args:
test_item (callable): function or class to be decorated.
Returns:
callable: the decorated function.
"""
reason = 'Aer provider not found, skipping test'
return unittest.skipIf(not is_aer_provider_available(), reason)(test_item)
def slow_test(func):
"""Decorator that signals that the test takes minutes to run.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(*args, **kwargs):
skip_slow = not TEST_OPTIONS['run_slow']
if skip_slow:
raise unittest.SkipTest('Skipping slow tests')
return func(*args, **kwargs)
return _wrapper
def _get_credentials(test_object, test_options):
"""Finds the credentials for a specific test and options.
Args:
test_object (QiskitTestCase): The test object asking for credentials
test_options (dict): Options after QISKIT_TESTS was parsed by
get_test_options.
Returns:
Credentials: set of credentials
Raises:
ImportError: if the
Exception: when the credential could not be set and they are needed
for that set of options
"""
try:
from qiskit.providers.ibmq.credentials import (Credentials,
discover_credentials)
except ImportError:
raise ImportError('qiskit-ibmq-provider could not be found, and is '
'required for mocking or executing online tests.')
dummy_credentials = Credentials(
'dummyapiusersloginWithTokenid01',
'https://quantumexperience.ng.bluemix.net/api')
if test_options['mock_online']:
return dummy_credentials
if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS', ''):
# Special case: instead of using the standard credentials mechanism,
# load them from different environment variables. This assumes they
# will always be in place, as is used by the Travis setup.
return Credentials(os.getenv('IBMQ_TOKEN'), os.getenv('IBMQ_URL'))
else:
# Attempt to read the standard credentials.
discovered_credentials = discover_credentials()
if discovered_credentials:
# Decide which credentials to use for testing.
if len(discovered_credentials) > 1:
try:
# Attempt to use QE credentials.
return discovered_credentials[dummy_credentials.unique_id()]
except KeyError:
pass
# Use the first available credentials.
return list(discovered_credentials.values())[0]
# No user credentials were found.
if test_options['rec']:
raise Exception('Could not locate valid credentials. You need them for '
'recording tests against the remote API.')
test_object.log.warning('No user credentials were detected. '
'Running with mocked data.')
test_options['mock_online'] = True
return dummy_credentials
def requires_qe_access(func):
"""Decorator that signals that the test uses the online API:
It involves:
* determines if the test should be skipped by checking environment
variables.
* if the `USE_ALTERNATE_ENV_CREDENTIALS` environment variable is
set, it reads the credentials from an alternative set of environment
variables.
* if the test is not skipped, it reads `qe_token` and `qe_url` from
`Qconfig.py`, environment variables or qiskitrc.
* if the test is not skipped, it appends `qe_token` and `qe_url` as
arguments to the test function.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
if TEST_OPTIONS['skip_online']:
raise unittest.SkipTest('Skipping online tests')
credentials = _get_credentials(self, TEST_OPTIONS)
self.using_ibmq_credentials = credentials.is_ibmq()
kwargs.update({'qe_token': credentials.token,
'qe_url': credentials.url})
decorated_func = func
if TEST_OPTIONS['rec'] or TEST_OPTIONS['mock_online']:
# For recording or for replaying existing cassettes, the test
# should be decorated with @use_cassette.
vcr_mode = 'new_episodes' if TEST_OPTIONS['rec'] else 'none'
decorated_func = http_recorder(
vcr_mode, Path.CASSETTES.value).use_cassette()(decorated_func)
return decorated_func(self, *args, **kwargs)
return _wrapper
TEST_OPTIONS = get_test_options()
|
https://github.com/Keerthiraj-Nagaraj/IBM-quantum-challenge-2020
|
Keerthiraj-Nagaraj
|
from IPython.display import Image, display
Image("ryoko.png", width="70")
from IPython.display import Image, display
Image('unstructured_search.png', width="700")
Image("oracle.png", width="700")
Image("step0.png", width="700")
Image("step1.png", width="700")
Image("step2.png", width="700")
Image("grover_algorithm.png", width="700")
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
def phase_oracle(circuit, register):
circuit.cz(register[0], register[1])
qr = QuantumRegister(2)
oracleCircuit = QuantumCircuit(qr)
phase_oracle(oracleCircuit, qr)
oracleCircuit.draw(output="mpl")
def inversion_about_average(circuit, register):
"""Apply inversion about the average step of Grover's algorithm."""
circuit.h(register)
circuit.x(register)
circuit.h(register[1])
circuit.cx(register[0], register[1])
circuit.h(register[1])
circuit.x(register)
circuit.h(register)
qAverage = QuantumCircuit(qr)
inversion_about_average(qAverage, qr)
qAverage.draw(output='mpl')
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr)
phase_oracle(groverCircuit, qr)
inversion_about_average(groverCircuit, qr)
groverCircuit.measure(qr,cr)
groverCircuit.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend_lb = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
print("Least busy backend: ", backend_lb)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
backend = backend_lb
shots = 1024
job_exp = execute(groverCircuit, backend=backend, shots=shots)
job_monitor(job_exp, interval = 2)
# get the results from the computation
results = job_exp.result()
answer = results.get_counts(groverCircuit)
plot_histogram(answer)
# Initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# Importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# Import basic plot tools
from qiskit.tools.visualization import plot_histogram
def phase_oracle(circuit, register,oracle_register):
circuit.h(oracle_register)
circuit.ccx(register[0], register[1],oracle_register)
circuit.h(oracle_register)
qr = QuantumRegister(3)
oracleCircuit = QuantumCircuit(qr)
oracleCircuit.x(qr[2])
phase_oracle(oracleCircuit, qr,qr[2])
oracleCircuit.draw(output="mpl")
def inversion_about_average(circuit, register):
"""Apply inversion about the average step of Grover's algorithm."""
circuit.h(register)
circuit.x(register)
circuit.h(register[1])
circuit.cx(register[0], register[1])
circuit.h(register[1])
circuit.x(register)
circuit.h(register)
qAverage = QuantumCircuit(qr)
inversion_about_average(qAverage, qr[0:2])
qAverage.draw(output='mpl')
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr[0:2])
groverCircuit.x(qr[2])
phase_oracle(groverCircuit, qr,qr[2])
inversion_about_average(groverCircuit, qr[0:2])
groverCircuit.measure(qr,cr)
groverCircuit.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
backend = BasicAer.get_backend('qasm_simulator')
prob_of_ans = []
for x in range(12):
database = QuantumRegister(4)
oracle = QuantumRegister(1)
auxiliary = QuantumRegister(2)
cr = ClassicalRegister(4)
qc = QuantumCircuit(database, oracle, auxiliary, cr)
qc.h(database[:])
qc.x(oracle[0])
qc.h(oracle[0])
for j in range(x):
# oracle_4q
# search 7: 0111
qc.x(database[0])
qc.mct(database[:], oracle[0], auxiliary[:], mode='basic')
qc.x(database[0])
# diffusion_4q
qc.h(database[:])
qc.x(database[:])
qc.h(database[3])
qc.mct(database[0:3], database[3], auxiliary[:], mode='basic')
qc.h(database[3])
qc.x(database[:])
qc.h(database[:])
qc.h(oracle[0])
qc.x(oracle[0])
qc.measure(database,cr)
# Change the endian
qc = qc.reverse_bits()
job = execute(qc, backend=backend, shots=1000, seed_simulator=12345, backend_options={"fusion_enable":True})
result = job.result()
count = result.get_counts()
answer = count['0111']
prob_of_ans.append(answer)
import numpy as np
import matplotlib.pyplot as plt
iteration = [i for i in range(12)]
correct = prob_of_ans
plt.bar(iteration, correct)
plt.xlabel('# of iteration')
plt.ylabel('# of times the solution was obtained')
# Change ans of following code and check your answer.
# ans must be an interger.
from qc_grader import grade_ex1b
grade_ex1b(ans)
# Change ans of following code and submit it.
# ans must be interger.
from qc_grader import submit_ex1b
submit_ex1b(ans)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.quantum_info import SparsePauliOp
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit.primitives import Estimator
estimator = Estimator()
job = estimator.run(circuit, observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
circuit = random_circuit(2, 2, seed=1).decompose(reps=1)
observable = SparsePauliOp("IY")
job = estimator.run(circuit, observable)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Observable: {observable.paulis}")
print(f">>> Expectation value: {result.values[0]}")
circuits = (
random_circuit(2, 2, seed=0).decompose(reps=1),
random_circuit(2, 2, seed=1).decompose(reps=1),
)
observables = (
SparsePauliOp("XZ"),
SparsePauliOp("IY"),
)
job = estimator.run(circuits, observables)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f">>> Observables: {[obs.paulis for obs in observables]}")
print(f">>> Expectation values: {result.values.tolist()}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
observable = SparsePauliOp("ZI")
parameter_values = [0, 1, 2, 3, 4, 5]
job = estimator.run(circuit, observable, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Observable: {observable.paulis}")
print(f">>> Parameter values: {parameter_values}")
print(f">>> Expectation value: {result.values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibmq_qasm_simulator")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit_ibm_runtime import Estimator
estimator = Estimator(session=backend)
job = estimator.run(circuit, observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
options = Options(optimization_level=3, environment={"log_level": "INFO"})
from qiskit_ibm_runtime import Options
options = Options()
options.resilience_level = 1
options.execution.shots = 2048
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable).result()
print(f">>> Metadata: {result.metadata[0]}")
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable, shots=1024).result()
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
# optimization_level=3 adds dynamical decoupling
# resilience_level=1 adds readout error mitigation
options = Options(optimization_level=3, resilience_level=1)
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value: {result.values[0]}")
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Session, Estimator
with Session(backend=backend, max_time="1h"):
estimator = Estimator()
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the first run: {result.values[0]}")
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the second run: {result.values[0]}")
from qiskit.circuit.random import random_circuit
sampler_circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
sampler_circuit.measure_all()
display(circuit.draw("mpl"))
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
result = sampler.run(sampler_circuit).result()
print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}")
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the estimator job: {result.values[0]}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
sampler_job = sampler.run(sampler_circuit)
estimator_job = estimator.run(circuit, observable)
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options
# 1. Initialize account
service = QiskitRuntimeService(channel="ibm_quantum")
# 2. Specify options, such as enabling error mitigation
options = Options(resilience_level=1)
# 3. Select a backend.
backend = service.backend("ibmq_qasm_simulator")
# 4. Create a session
with Session(backend=backend):
# 5. Create primitive instances
sampler = Sampler(options=options)
estimator = Estimator(options=options)
# 6. Submit jobs
sampler_job = sampler.run(sampler_circuit)
estimator_job = estimator.run(circuit, observable)
# 7. Get results
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Class that holds a fermionic time-evolution problem."""
from typing import List, Union
from qiskit import QuantumCircuit
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_cold_atom.fermions.fermionic_state import FermionicState
from qiskit_cold_atom.fermions.fermionic_basis import FermionicBasis
from qiskit_cold_atom.fermions.fermion_gate_library import FermionicGate
from qiskit_cold_atom.exceptions import QiskitColdAtomError
from qiskit_cold_atom.applications.fermi_hubbard import FermionicLattice
class FermionicEvolutionProblem:
"""
Problem class corresponding to evaluating an observable of a fermionic system after a time
evolution under a hamiltonian from an initial state in an occupation number representation.
"""
def __init__(
self,
system: FermionicLattice,
initial_state: FermionicState,
evolution_times: Union[float, List[float]],
observable: FermionicOp,
):
"""
Initialize a fermionic time evolution problem.
Args:
system: The fermionic system under which the initial state will evolve.
initial_state: The fermionic state at time t=0.
evolution_times: List of times (or single time) after which the observable is measured.
observable: The observable to measure after the time evolution, given as a FermionicOp.
The observable must be diagonal in the fermionic occupation number basis.
Raises:
QiskitColdAtomError: - If the sizes of the system, initial state and the observable
do not match.
- If the observables is not diagonal in the fermionic occupation number
basis
"""
if system.size != initial_state.sites:
raise QiskitColdAtomError(
f"The size of the system {system.size} does not match "
f"the size of the initial state {initial_state.sites}."
)
if 2 * system.size != observable.register_length:
raise QiskitColdAtomError(
f"The fermionic modes of the system {2*system.size} do not match "
f"the size of the observable {observable.register_length}."
)
# check if matrix is diagonal
# can later be replaced when the FermionicOp from qiskit-nature has its own .to_matrix() method
basis = FermionicBasis.from_fermionic_op(observable)
observable_mat = FermionicGate.operator_to_mat(observable, num_species=1, basis=basis)
if list(observable_mat.nonzero()[0]) != list(observable_mat.nonzero()[1]):
raise QiskitColdAtomError(
"The fermionic observable needs to be diagonal in the computational basis, "
"as measuring general, non-diagonal observables is not yet implemented for "
"fermionic backends. This requires non-trivial basis transformations that "
"are in general difficult to find and depend on the backend's native gate set."
)
self._system = system
self._initial_state = initial_state
self._evolution_times = evolution_times
self._observable = observable
@property
def system(self) -> FermionicLattice:
"""Return the system of the problem."""
return self._system
@property
def initial_state(self) -> FermionicState:
"""Return the initial state of the system."""
return self._initial_state
@property
def evolution_times(self) -> List[float]:
"""Return the evolution times to simulate."""
return self._evolution_times
@property
def observable(self) -> FermionicOp:
"""Return the observable as a FermionicOp."""
return self._observable
def circuits(self, initial_state: QuantumCircuit) -> List[QuantumCircuit]:
"""
The problem embedded in a quantum circuit.
Args:
initial_state: A quantum circuit which corresponds to the initial state for the
time-evolution problem.
Return:
A list of quantum circuits. Circuit :math:`i` is a single instruction which
corresponds to :math:`exp(-i*H*t_i)` where :math:`t_i` is the time of the
the ith evolution time.
"""
circuits = []
for time in self.evolution_times:
circ = QuantumCircuit(initial_state.num_qubits)
circ.compose(initial_state, inplace=True)
circ.compose(self.system.to_circuit(time), inplace=True)
circuits.append(circ)
return circuits
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
A collection of functions that decide the layout of an output image.
See :py:mod:`~qiskit.visualization.timeline.types` for more info on the required data.
There are 2 types of layout functions in this module.
1. layout.bit_arrange
In this stylesheet entry the input data is a list of `types.Bits` and returns a
sorted list of `types.Bits`.
The function signature of the layout is restricted to:
```python
def my_layout(bits: List[types.Bits]) -> List[types.Bits]:
# your code here: sort input bits and return list of bits
```
2. layout.time_axis_map
In this stylesheet entry the input data is `Tuple[int, int]` that represents horizontal
axis limit of the output image. The layout function returns `types.HorizontalAxis` data
which is consumed by the plotter API to make horizontal axis.
The function signature of the layout is restricted to:
```python
def my_layout(time_window: Tuple[int, int]) -> types.HorizontalAxis:
# your code here: create and return axis config
```
Arbitrary layout function satisfying the above format can be accepted.
"""
import warnings
from typing import List, Tuple
import numpy as np
from qiskit import circuit
from qiskit.visualization.exceptions import VisualizationError
from qiskit.visualization.timeline import types
def qreg_creg_ascending(bits: List[types.Bits]) -> List[types.Bits]:
"""Sort bits by ascending order.
Bit order becomes Q0, Q1, ..., Cl0, Cl1, ...
Args:
bits: List of bits to sort.
Returns:
Sorted bits.
"""
qregs = []
cregs = []
for bit in bits:
if isinstance(bit, circuit.Qubit):
qregs.append(bit)
elif isinstance(bit, circuit.Clbit):
cregs.append(bit)
else:
raise VisualizationError(f"Unknown bit {bit} is provided.")
with warnings.catch_warnings():
warnings.simplefilter("ignore")
qregs = sorted(qregs, key=lambda x: x.index, reverse=False)
cregs = sorted(cregs, key=lambda x: x.index, reverse=False)
return qregs + cregs
def qreg_creg_descending(bits: List[types.Bits]) -> List[types.Bits]:
"""Sort bits by descending order.
Bit order becomes Q_N, Q_N-1, ..., Cl_N, Cl_N-1, ...
Args:
bits: List of bits to sort.
Returns:
Sorted bits.
"""
qregs = []
cregs = []
for bit in bits:
if isinstance(bit, circuit.Qubit):
qregs.append(bit)
elif isinstance(bit, circuit.Clbit):
cregs.append(bit)
else:
raise VisualizationError(f"Unknown bit {bit} is provided.")
qregs = sorted(qregs, key=lambda x: x.index, reverse=True)
cregs = sorted(cregs, key=lambda x: x.index, reverse=True)
return qregs + cregs
def time_map_in_dt(time_window: Tuple[int, int]) -> types.HorizontalAxis:
"""Layout function for the horizontal axis formatting.
Generate equispaced 6 horizontal axis ticks.
Args:
time_window: Left and right edge of this graph.
Returns:
Axis formatter object.
"""
# shift time axis
t0, t1 = time_window
# axis label
axis_loc = np.linspace(max(t0, 0), t1, 6)
axis_label = axis_loc.copy()
# consider time resolution
label = "System cycle time (dt)"
formatted_label = [f"{val:.0f}" for val in axis_label]
return types.HorizontalAxis(
window=(t0, t1), axis_map=dict(zip(axis_loc, formatted_label)), label=label
)
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
import json
import csv
# Array of JSON Objects
header = ['p', 'state', 'probability', 'mean']
length_p = 10
with open('qaoa_multiple_p.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
first_p = False
for p in range(length_p):
p = p+1
if first_p == False:
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p)
first_p = True
else:
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p)
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
mean = UNIFORM_CONVERGENCE_SAMPLE[0]["mean"]
print(mean)
state = 0
for probability in UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"]:
state += 1
writer.writerow([p,state, probability,mean])
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
# useful additional packages
import matplotlib.pyplot as plt
#%matplotlib inline
import numpy as np
from pprint import pprint
# importing QISKit
from qiskit import QuantumProgram, QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import available_backends, execute, register, least_busy
# import basic plot tools
from qiskit.tools.visualization import plot_histogram, circuit_drawer
qx_config = {
"APItoken": 'dcdb2d9414a625c1f57373c544add3711c78c3d7faf39397fe2c41887110e8b59caf81bcb2bc32714d936da41a261fea510f96df379afcbdfa9df6cc6bfe3829',
"url": 'https://quantumexperience.ng.bluemix.net/api'
}
backend = 'local_qasm_simulator' # run on local simulator by default
'''register(qx_config['APItoken'], qx_config['url'])
backend = least_busy(available_backends({'simulator': False, 'local': False}))
print("the best backend is " + backend)
'''
# Creating registers
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
# Quantum circuit ground
qc_ground = QuantumCircuit(qr, cr)
qc_ground.measure(qr[0], cr[0])
# Quantum circuit excited
qc_excited = QuantumCircuit(qr, cr)
qc_excited.x(qr)
qc_excited.measure(qr[0], cr[0])
# Quantum circuit superposition
qc_superposition = QuantumCircuit(qr, cr)
qc_superposition.h(qr)
qc_superposition.barrier()
qc_superposition.h(qr)
qc_superposition.measure(qr[0], cr[0])
circuits = [qc_ground, qc_excited, qc_superposition]
job = execute(circuits, backend)
result = job.result()
plot_histogram(result.get_counts(qc_superposition))
|
https://github.com/ArunSehrawat/Quantum_Machine_Learning_use_cases_with_Qiskit
|
ArunSehrawat
|
import numpy as np
import matplotlib.pyplot as plt
import time, copy, warnings
from sklearn import linear_model, svm
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
size = 4 # size of image
binaries = np.array([[int(i) for i in np.binary_repr(a, size)] for a in range(1, 2**size - 1)])
#--------------------------------------------------------------------------------------------------
ones = np.ones((size, size))
X = [] # X collects (size x size) feature matrices
y = [] # y collects class labels 1 or 0
for b in binaries:
x = b*ones
X.append(x.flatten()) # image with vertical strips, class 1
y.append(1)
X.append((x.T).flatten()) # image with horizontal strips, class 0
y.append(0)
X, y = np.array(X), np.array(y)
#--------------------------------------------------------------------------------------------------
num_examples, num_features = X.shape
print(f'number of examples = {num_examples}')
print(f'number of features = {num_features}')
num_features == size*size
idx = np.random.choice(num_examples)
x = X[idx].reshape(size,size)
print(f'x_{idx} of size {x.shape} :')
plt.imshow(x, cmap='gray', vmin=0, vmax=1)
plt.show()
if y[idx]==1:
class_ = 'vertical'
elif y[idx]==0:
class_ = 'horizontal'
print(f'true label = y = {y[idx]} = image of {class_} strips \n')
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0)
num_train_examples, num_test_examples = X_train.shape[0], X_test.shape[0]
print(f'number of train examples = {num_train_examples}')
print(f'number of test examples = {num_test_examples}\n')
print(f'number of features = {num_features}')
num_train_examples + num_test_examples == num_examples
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
'For angle encoding, num_qubits = num_features'
#fm = PauliFeatureMap(feature_dimension=num_features, reps=1, paulis=['Z'])
fm = ZZFeatureMap(feature_dimension=num_features, reps=1)
fm.decompose().draw()
from qiskit_machine_learning.circuit.library import RawFeatureVector
'For amplitude encoding, num_qubits = n = np.log2(num_features)''
fm = RawFeatureVector(feature_dimension=n)
fm.draw()
from qiskit.circuit.library import RealAmplitudes
'''
For angle encoding, num_qubits = num_features
For amplitude encoding, num_qubits = n = np.log2(num_features)
'''
pqc = RealAmplitudes(num_qubits=num_features, reps=3)
pqc.decompose().draw()
from qiskit.algorithms.optimizers import COBYLA
# This defines where to train our classifier: on a simulator or a real quantum computer
from qiskit.primitives import Sampler # here we have chosen a simulator
from qiskit_machine_learning.algorithms.classifiers import VQC # !pip install qiskit[machine-learning]
#------------------------------------------------------------------------------------------------
optimizer = COBYLA(maxiter=60) # maxiter = Maximum number of iterations (function evaluations)
sampler = Sampler()
#------------------------------------------------------------------------------------------------
from IPython.display import clear_output
objective_func_vals = []
# a callback that can access the intermediate data during the optimization
def callback(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
#------------------------------------------------------------------------------------------------
vqc = VQC(
sampler=sampler,
feature_map=fm,
ansatz=pqc,
optimizer=optimizer,
callback=callback,
)
%%time
'''Training time seems to increase with the number of features, examples, and learnable-parameters'''
vqc.fit(X_train, y_train)
%%time
def performance_VQC(X, y, name):
y_pred = vqc.predict(X)
print(classification_report(y, y_pred))
print(f'{confusion_matrix(y, y_pred)} = confusion matrix for {name} set \n')
return y_pred
y_pred_train = performance_VQC(X_train, y_train, 'train')
y_pred_test = performance_VQC(X_test, y_test, 'test')
idx = np.random.choice(len(X_test))
x = X_test[idx]
print(f'x of size {(size,size)} :')
plt.imshow(x.reshape(size,size), cmap='gray')
plt.show()
if y[idx]==1:
class_ = 'vertical'
elif y[idx]==0:
class_ = 'horizontal'
print(f'true label = y = {y[idx]} = image with {class_} strips \n')
y_pred_ = vqc.predict(x)
print(f'predicted label = {y_pred_}\n')
%%time
warnings.filterwarnings('ignore')
def train_test(ML_model):
print(20*' ', ML_model,'\n')
ML_model.fit(X_train, y_train) # fit model on train set
y_train_pred = ML_model.predict(X_train) # predict with the trained model
y_test_pred = ML_model.predict(X_test)
print(classification_report(y_train, y_train)) # evaluate model performance
print(confusion_matrix(y_train, y_train_pred), "= confusion matrix for train set \n")
print(classification_report(y_test, y_test_pred))
print(confusion_matrix(y_test, y_test_pred), "= confusion matrix for test set \n")
print(70*'=')
#----------------------------------------------------------------------------------
print(70*'=')
ML_model = linear_model.LogisticRegression() # create model instance
train_test(ML_model)
ML_model = MLPClassifier()
train_test(ML_model)
ML_model = svm.SVC()
train_test(ML_model)
ML_model = RandomForestClassifier()
train_test(ML_model)
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
import numpy as np
from qiskit import *
import matplotlib
qr = QuantumRegister(2)
#measurements from quantum bits = use classical register
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.draw()
# adding quantum gates to create entanglement (Hadamart gate)
circuit.h(qr[0])
%matplotlib inline
circuit.draw(output='mpl')
#two qubit operation control X (logical if)
circuit.cx(qr[0], qr[1])
circuit.draw(output='mpl') #entanglement achieved
#measurement, storing measurements into computational register
circuit.measure(qr,cr)
circuit.draw(output='mpl')
#performance simulations
simulator = Aer.get_backend('qasm_simulator')
execute(circuit, backend = simulator)
result = execute(circuit, backend = simulator).result()
#plotting results
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
#running circuit on quantum computer
IBMQ.load_account()
provider= IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmq_manila')
job= execute(circuit, backend=qcomp)
from qiskit.tools import job_monitor
job_monitor(job)
result = job.result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit), title='Performance metric on Quantum Computer')
|
https://github.com/matheusmtta/Quantum-Computing
|
matheusmtta
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_qsphere
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.tools.visualization import plot_histogram
from IPython.display import display, Math, Latex
#define a 1 qubit state |0>
sv = Statevector.from_label('0')
print('State_0 |x> = ', sv.data)
#build a circuit with the H gate
mycircuit = QuantumCircuit(1)
mycircuit.h(0)
#apply the circuit into |x>
sv = sv.evolve(mycircuit)
print('State_1 H|x> = ', sv.data)
mycircuit.draw('mpl')
'''
OUR FUNCTION F IS DEFINED AS
n = 2
f(0, 0) = 0
f(0, 1) = 1
f(1, 0) = 1
f(1, 1) = 1
'''
#input size
n = 2
#initialize qubits and measurement bits
input_qubits = QuantumRegister(n+1)
output_bits = ClassicalRegister(n)
#create circuit
my_circuit = QuantumCircuit(input_qubits, output_bits)
#apply X on the last qubit
my_circuit.x(n)
#apply Hadamard on all qubits
my_circuit.h(range(n+1))
my_circuit.barrier()
#Apply Uf, these CNOT gates will mark the desired |x_i>
my_circuit.cx(0, 1)
my_circuit.cx(1, 2)
my_circuit.cx(0, 1)
my_circuit.barrier()
#apply Hadamard on all qubits
my_circuit.h(range(n+1))
my_circuit.measure(range(n), range(n))
#Backend classical simulation
backend = BasicAer.get_backend('qasm_simulator')
atp = 1024
res = execute(my_circuit, backend=backend, shots=atp).result()
ans = res.get_counts()
my_circuit.draw(output='mpl')
#Quantum Backend
#SOON#
plot_histogram(ans)
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(group='open', project='main')
backend = provider.get_backend('ibmq_vigo')
job = execute(my_circuit, backend=backend)
result = job.result().get_counts()
plot_histogram(result)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
%matplotlib inline
from qiskit_finance import QiskitFinanceError
from qiskit_finance.data_providers import *
import datetime
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
data = RandomDataProvider(
tickers=["TICKER1", "TICKER2"],
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=1,
)
data.run()
means = data.get_mean_vector()
print("Means:")
print(means)
rho = data.get_similarity_matrix()
print("A time-series similarity measure:")
print(rho)
plt.imshow(rho)
plt.show()
cov = data.get_covariance_matrix()
print("A covariance matrix:")
print(cov)
plt.imshow(cov)
plt.show()
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
for (cnt, s) in enumerate(data._tickers):
print(s)
print(data._data[cnt])
data = RandomDataProvider(
tickers=["CompanyA", "CompanyB", "CompanyC"],
start=datetime.datetime(2015, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=1,
)
data.run()
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
stocks = ["GOOG", "AAPL"]
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
wiki = WikipediaDataProvider(
token=token,
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
)
wiki.run()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
if token != "REPLACE-ME":
if wiki._data:
if wiki._n <= 1:
print(
"Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers."
)
else:
rho = wiki.get_similarity_matrix()
print("A time-series similarity measure:")
print(rho)
plt.imshow(rho)
plt.show()
cov = wiki.get_covariance_matrix()
print("A covariance matrix:")
print(cov)
plt.imshow(cov)
plt.show()
else:
print("No wiki data loaded.")
if token != "REPLACE-ME":
if wiki._data:
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(stocks):
plt.plot(wiki._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
for (cnt, s) in enumerate(stocks):
print(s)
print(wiki._data[cnt])
else:
print("No wiki data loaded.")
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
nasdaq = DataOnDemandProvider(
token=token,
tickers=["GOOG", "AAPL"],
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 2),
)
nasdaq.run()
for (cnt, s) in enumerate(nasdaq._tickers):
plt.plot(nasdaq._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
lse = ExchangeDataProvider(
token=token,
tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"],
stockmarket=StockMarket.LONDON,
start=datetime.datetime(2018, 1, 1),
end=datetime.datetime(2018, 12, 31),
)
lse.run()
for (cnt, s) in enumerate(lse._tickers):
plt.plot(lse._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
try:
data = YahooDataProvider(
tickers=["MSFT", "AAPL", "GOOG"],
start=datetime.datetime(2021, 1, 1),
end=datetime.datetime(2021, 12, 31),
)
data.run()
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3)
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
data = None
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.x(0).c_if(cr, 0)
qc.measure(0, 0)
qc.draw('mpl')
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
#101
000 -put AND gate ->010
--- 3 step
# initialization
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.visualization import plot_histogram
n = 5# number of qubits used to represent s
s = '10011' # the hidden binary string
# We need a circuit with n qubits, plus one ancilla qubit
# Also need n classical bits to write the output to
bv_circuit = QuantumCircuit(n+1, n)
# put ancilla in state |->
bv_circuit.h(n)
bv_circuit.z(n)
# Apply Hadamard gates before querying the oracle
for i in range(n):
bv_circuit.h(i)
# Apply barrier
bv_circuit.barrier()
# Apply the inner-product oracle
s = s[::-1] # reverse s to fit qiskit's qubit ordering
for q in range(n):
if s[q] == '0':
bv_circuit.i(q)
else:
bv_circuit.cx(q, n)
# Apply barrier
bv_circuit.barrier()
#Apply Hadamard gates after querying the oracle
for i in range(n):
bv_circuit.h(i)
# Measurement
for i in range(n):
bv_circuit.measure(i, i)
bv_circuit.draw()
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(bv_circuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# consider the following list with 4 elements
L = [1,-2,0,5]
print(L)
# 3 * v
v = [1,-2,0,5]
print("v is",v)
# we use the same list for the result
for i in range(len(v)):
v[i] = 3 * v[i]
print("3v is",v)
# -0.6 * u
# reinitialize the list v
v = [1,-2,0,5]
for i in range(len(v)):
v[i] = -0.6 * v[i]
print("0.6v is",v)
u = [-3,-2,0,-1,4]
v = [-1,-1,2,-3,5]
result=[]
for i in range(len(u)):
result.append(u[i]+v[i])
print("u+v is",result)
# let's also print the result vector similar to a column vector
print() # print an empty line
print("the elements of u+v are")
for j in range(len(result)):
print(result[j])
from random import randrange
#
# your solution is here
#
#r=randrange(-10,11) # randomly pick a number from the list {-10,-9,...,-1,0,1,...,9,10}
#
# your solution is here
#
v = [-1,-3,5,3,1,2]
length_square=0
for i in range(len(v)):
print(v[i],":square ->",v[i]**2) # let's print each entry and its square value
length_square = length_square + v[i]**2 # let's sum up the square of each entry
length = length_square ** 0.5 # let's take the square root of the summation of the squares of all entries
print("the summation is",length_square)
print("then the length is",length)
# for square root, we can also use built-in function math.sqrt
print() # print an empty line
from math import sqrt
print("the sqaure root of",length_square,"is",sqrt(length_square))
#
# your solution is here
#
#
# your solution is here
#
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test dynamical decoupling insertion pass."""
import unittest
import numpy as np
from numpy import pi
from ddt import ddt, data
from qiskit.circuit import QuantumCircuit, Delay, Measure, Reset, Parameter
from qiskit.circuit.library import XGate, YGate, RXGate, UGate, CXGate, HGate
from qiskit.quantum_info import Operator
from qiskit.transpiler.instruction_durations import InstructionDurations
from qiskit.transpiler.passes import (
ASAPScheduleAnalysis,
ALAPScheduleAnalysis,
PadDynamicalDecoupling,
)
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.target import Target, InstructionProperties
from qiskit import pulse
from qiskit.test import QiskitTestCase
@ddt
class TestPadDynamicalDecoupling(QiskitTestCase):
"""Tests PadDynamicalDecoupling pass."""
def setUp(self):
"""Circuits to test DD on.
┌───┐
q_0: ┤ H ├──■────────────
└───┘┌─┴─┐
q_1: ─────┤ X ├──■───────
└───┘┌─┴─┐
q_2: ──────────┤ X ├──■──
└───┘┌─┴─┐
q_3: ───────────────┤ X ├
└───┘
┌──────────┐
q_0: ──■──┤ U(π,0,π) ├──────────■──
┌─┴─┐└──────────┘ ┌─┴─┐
q_1: ┤ X ├─────■───────────■──┤ X ├
└───┘ ┌─┴─┐ ┌─┐┌─┴─┐└───┘
q_2: ────────┤ X ├────┤M├┤ X ├─────
└───┘ └╥┘└───┘
c: 1/══════════════════╩═══════════
0
"""
super().setUp()
self.ghz4 = QuantumCircuit(4)
self.ghz4.h(0)
self.ghz4.cx(0, 1)
self.ghz4.cx(1, 2)
self.ghz4.cx(2, 3)
self.midmeas = QuantumCircuit(3, 1)
self.midmeas.cx(0, 1)
self.midmeas.cx(1, 2)
self.midmeas.u(pi, 0, pi, 0)
self.midmeas.measure(2, 0)
self.midmeas.cx(1, 2)
self.midmeas.cx(0, 1)
self.durations = InstructionDurations(
[
("h", 0, 50),
("cx", [0, 1], 700),
("cx", [1, 2], 200),
("cx", [2, 3], 300),
("x", None, 50),
("y", None, 50),
("u", None, 100),
("rx", None, 100),
("measure", None, 1000),
("reset", None, 1500),
]
)
def test_insert_dd_ghz(self):
"""Test DD gates are inserted in correct spots.
┌───┐ ┌────────────────┐ ┌───┐ »
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├──────┤ X ├──────»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌─────┴───┴─────┐»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(50[dt]) ├»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘»
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├──────»
└────────────────┘ └───┘ »
« ┌────────────────┐ ┌───┐ ┌────────────────┐
«q_0: ┤ Delay(200[dt]) ├──────┤ X ├───────┤ Delay(100[dt]) ├─────────────────
« └─────┬───┬──────┘┌─────┴───┴──────┐└─────┬───┬──────┘┌───────────────┐
«q_1: ──────┤ X ├───────┤ Delay(100[dt]) ├──────┤ X ├───────┤ Delay(50[dt]) ├
« └───┘ └────────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────────────────────────
«
"""
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(50), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(100), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(50), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_with_target(self):
"""Test DD gates are inserted in correct spots.
┌───┐ ┌────────────────┐ ┌───┐ »
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├──────┤ X ├──────»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌─────┴───┴─────┐»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(50[dt]) ├»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘»
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├──────»
└────────────────┘ └───┘ »
« ┌────────────────┐ ┌───┐ ┌────────────────┐
«q_0: ┤ Delay(200[dt]) ├──────┤ X ├───────┤ Delay(100[dt]) ├─────────────────
« └─────┬───┬──────┘┌─────┴───┴──────┐└─────┬───┬──────┘┌───────────────┐
«q_1: ──────┤ X ├───────┤ Delay(100[dt]) ├──────┤ X ├───────┤ Delay(50[dt]) ├
« └───┘ └────────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────────────────────────
«
"""
target = Target(num_qubits=4, dt=1)
target.add_instruction(HGate(), {(0,): InstructionProperties(duration=50)})
target.add_instruction(
CXGate(),
{
(0, 1): InstructionProperties(duration=700),
(1, 2): InstructionProperties(duration=200),
(2, 3): InstructionProperties(duration=300),
},
)
target.add_instruction(
XGate(), {(x,): InstructionProperties(duration=50) for x in range(4)}
)
target.add_instruction(
YGate(), {(x,): InstructionProperties(duration=50) for x in range(4)}
)
target.add_instruction(
UGate(Parameter("theta"), Parameter("phi"), Parameter("lambda")),
{(x,): InstructionProperties(duration=100) for x in range(4)},
)
target.add_instruction(
RXGate(Parameter("theta")),
{(x,): InstructionProperties(duration=100) for x in range(4)},
)
target.add_instruction(
Measure(), {(x,): InstructionProperties(duration=1000) for x in range(4)}
)
target.add_instruction(
Reset(), {(x,): InstructionProperties(duration=1500) for x in range(4)}
)
target.add_instruction(Delay(Parameter("t")), {(x,): None for x in range(4)})
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(target=target),
PadDynamicalDecoupling(target=target, dd_sequence=dd_sequence),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(50), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(100), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(50), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_one_qubit(self):
"""Test DD gates are inserted on only one qubit.
┌───┐ ┌────────────────┐ ┌───┐ »
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├──────┤ X ├───────»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌─────┴───┴──────┐»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(300[dt]) ├»
├───────────────┴┐└───┘ ┌─┴─┐ └────────────────┘»
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■─────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├───────»
└────────────────┘ └───┘ »
meas: 4/═══════════════════════════════════════════════════════════»
»
« ┌────────────────┐┌───┐┌────────────────┐ ░ ┌─┐
« q_0: ┤ Delay(200[dt]) ├┤ X ├┤ Delay(100[dt]) ├─░─┤M├─────────
« └────────────────┘└───┘└────────────────┘ ░ └╥┘┌─┐
« q_1: ──────────────────────────────────────────░──╫─┤M├──────
« ░ ║ └╥┘┌─┐
« q_2: ──────────────────────────────────────────░──╫──╫─┤M├───
« ░ ║ ║ └╥┘┌─┐
« q_3: ──────────────────────────────────────────░──╫──╫──╫─┤M├
« ░ ║ ║ ║ └╥┘
«meas: 4/═════════════════════════════════════════════╩══╩══╩══╩═
« 0 1 2 3
"""
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0]),
]
)
ghz4_dd = pm.run(self.ghz4.measure_all(inplace=False))
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(300), [1])
expected.measure_all()
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_everywhere(self):
"""Test DD gates even on initial idle spots.
┌───┐ ┌────────────────┐┌───┐┌────────────────┐┌───┐»
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├┤ Y ├┤ Delay(200[dt]) ├┤ Y ├»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘└───┘└────────────────┘└───┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├───────────────────────────────────────────■──»
├───────────────┴┐├───┤┌────────────────┐┌───┐┌────────────────┐┌─┴─┐»
q_2: ┤ Delay(162[dt]) ├┤ Y ├┤ Delay(326[dt]) ├┤ Y ├┤ Delay(162[dt]) ├┤ X ├»
├────────────────┤├───┤├────────────────┤├───┤├────────────────┤└───┘»
q_3: ┤ Delay(212[dt]) ├┤ Y ├┤ Delay(426[dt]) ├┤ Y ├┤ Delay(212[dt]) ├─────»
└────────────────┘└───┘└────────────────┘└───┘└────────────────┘ »
« ┌────────────────┐
«q_0: ┤ Delay(100[dt]) ├─────────────────────────────────────────────
« ├───────────────┬┘┌───┐┌────────────────┐┌───┐┌───────────────┐
«q_1: ┤ Delay(50[dt]) ├─┤ Y ├┤ Delay(100[dt]) ├┤ Y ├┤ Delay(50[dt]) ├
« └───────────────┘ └───┘└────────────────┘└───┘└───────────────┘
«q_2: ────────■──────────────────────────────────────────────────────
« ┌─┴─┐
«q_3: ──────┤ X ├────────────────────────────────────────────────────
« └───┘
"""
dd_sequence = [YGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, skip_reset_qubits=False),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(162), [2], front=True)
expected = expected.compose(YGate(), [2], front=True)
expected = expected.compose(Delay(326), [2], front=True)
expected = expected.compose(YGate(), [2], front=True)
expected = expected.compose(Delay(162), [2], front=True)
expected = expected.compose(Delay(212), [3], front=True)
expected = expected.compose(YGate(), [3], front=True)
expected = expected.compose(Delay(426), [3], front=True)
expected = expected.compose(YGate(), [3], front=True)
expected = expected.compose(Delay(212), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(50), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(100), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(50), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_xy4(self):
"""Test XY4 sequence of DD gates.
┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
q_0: ──────┤ H ├─────────■──┤ Delay(37[dt]) ├──────┤ X ├──────┤ Delay(75[dt]) ├»
┌─────┴───┴─────┐ ┌─┴─┐└───────────────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■────────┤ Delay(12[dt]) ├──────┤ X ├──────»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘ └───┘ »
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├──────────────■─────────────────────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├────────────────────────────┤ X ├───────────────────────»
└────────────────┘ └───┘ »
« ┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
«q_0: ──────┤ Y ├──────┤ Delay(76[dt]) ├──────┤ X ├──────┤ Delay(75[dt]) ├»
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
«q_1: ┤ Delay(25[dt]) ├──────┤ Y ├──────┤ Delay(26[dt]) ├──────┤ X ├──────»
« └───────────────┘ └───┘ └───────────────┘ └───┘ »
«q_2: ────────────────────────────────────────────────────────────────────»
« »
«q_3: ────────────────────────────────────────────────────────────────────»
« »
« ┌───┐ ┌───────────────┐
«q_0: ──────┤ Y ├──────┤ Delay(37[dt]) ├─────────────────
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌───────────────┐
«q_1: ┤ Delay(25[dt]) ├──────┤ Y ├──────┤ Delay(12[dt]) ├
« └───────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────
"""
dd_sequence = [XGate(), YGate(), XGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(37), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(75), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(76), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(75), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(37), [0])
expected = expected.compose(Delay(12), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(25), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(26), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(25), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(12), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_midmeas_hahn_alap(self):
"""Test a single X gate as Hahn echo can absorb in the downstream circuit.
global phase: 3π/2
┌────────────────┐ ┌───┐ ┌────────────────┐»
q_0: ────────■─────────┤ Delay(625[dt]) ├───────┤ X ├───────┤ Delay(625[dt]) ├»
┌─┴─┐ └────────────────┘┌──────┴───┴──────┐└────────────────┘»
q_1: ──────┤ X ├───────────────■─────────┤ Delay(1000[dt]) ├────────■─────────»
┌─────┴───┴──────┐ ┌─┴─┐ └───────┬─┬───────┘ ┌─┴─┐ »
q_2: ┤ Delay(700[dt]) ├──────┤ X ├───────────────┤M├──────────────┤ X ├───────»
└────────────────┘ └───┘ └╥┘ └───┘ »
c: 1/═════════════════════════════════════════════╩═══════════════════════════»
0 »
« ┌───────────────┐
«q_0: ┤ U(0,π/2,-π/2) ├───■──
« └───────────────┘ ┌─┴─┐
«q_1: ──────────────────┤ X ├
« ┌────────────────┐└───┘
«q_2: ┤ Delay(700[dt]) ├─────
« └────────────────┘
«c: 1/═══════════════════════
"""
dd_sequence = [XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
midmeas_dd = pm.run(self.midmeas)
combined_u = UGate(0, -pi / 2, pi / 2)
expected = QuantumCircuit(3, 1)
expected.cx(0, 1)
expected.delay(625, 0)
expected.x(0)
expected.delay(625, 0)
expected.compose(combined_u, [0], inplace=True)
expected.delay(700, 2)
expected.cx(1, 2)
expected.delay(1000, 1)
expected.measure(2, 0)
expected.cx(1, 2)
expected.cx(0, 1)
expected.delay(700, 2)
expected.global_phase = pi / 2
self.assertEqual(midmeas_dd, expected)
# check the absorption into U was done correctly
self.assertEqual(Operator(combined_u), Operator(XGate()) & Operator(XGate()))
def test_insert_midmeas_hahn_asap(self):
"""Test a single X gate as Hahn echo can absorb in the upstream circuit.
┌──────────────────┐ ┌────────────────┐┌─────────┐»
q_0: ────────■─────────┤ U(3π/4,-π/2,π/2) ├─┤ Delay(600[dt]) ├┤ Rx(π/4) ├»
┌─┴─┐ └──────────────────┘┌┴────────────────┤└─────────┘»
q_1: ──────┤ X ├────────────────■──────────┤ Delay(1000[dt]) ├─────■─────»
┌─────┴───┴──────┐ ┌─┴─┐ └───────┬─┬───────┘ ┌─┴─┐ »
q_2: ┤ Delay(700[dt]) ├───────┤ X ├────────────────┤M├───────────┤ X ├───»
└────────────────┘ └───┘ └╥┘ └───┘ »
c: 1/═══════════════════════════════════════════════╩════════════════════»
0 »
« ┌────────────────┐
«q_0: ┤ Delay(600[dt]) ├──■──
« └────────────────┘┌─┴─┐
«q_1: ──────────────────┤ X ├
« ┌────────────────┐└───┘
«q_2: ┤ Delay(700[dt]) ├─────
« └────────────────┘
«c: 1/═══════════════════════
«
"""
dd_sequence = [RXGate(pi / 4)]
pm = PassManager(
[
ASAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
midmeas_dd = pm.run(self.midmeas)
combined_u = UGate(3 * pi / 4, -pi / 2, pi / 2)
expected = QuantumCircuit(3, 1)
expected.cx(0, 1)
expected.compose(combined_u, [0], inplace=True)
expected.delay(600, 0)
expected.rx(pi / 4, 0)
expected.delay(600, 0)
expected.delay(700, 2)
expected.cx(1, 2)
expected.delay(1000, 1)
expected.measure(2, 0)
expected.cx(1, 2)
expected.cx(0, 1)
expected.delay(700, 2)
self.assertEqual(midmeas_dd, expected)
# check the absorption into U was done correctly
self.assertTrue(
Operator(XGate()).equiv(
Operator(UGate(3 * pi / 4, -pi / 2, pi / 2)) & Operator(RXGate(pi / 4))
)
)
def test_insert_ghz_uhrig(self):
"""Test custom spacing (following Uhrig DD [1]).
[1] Uhrig, G. "Keeping a quantum bit alive by optimized π-pulse sequences."
Physical Review Letters 98.10 (2007): 100504.
┌───┐ ┌──────────────┐ ┌───┐ ┌──────────────┐┌───┐»
q_0: ──────┤ H ├─────────■──┤ Delay(3[dt]) ├──────┤ X ├───────┤ Delay(8[dt]) ├┤ X ├»
┌─────┴───┴─────┐ ┌─┴─┐└──────────────┘┌─────┴───┴──────┐└──────────────┘└───┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├───────■────────┤ Delay(300[dt]) ├─────────────────────»
├───────────────┴┐└───┘ ┌─┴─┐ └────────────────┘ »
q_2: ┤ Delay(750[dt]) ├──────────┤ X ├──────────────■──────────────────────────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├───────────────────────────┤ X ├────────────────────────────»
└────────────────┘ └───┘ »
« ┌───────────────┐┌───┐┌───────────────┐┌───┐┌───────────────┐┌───┐┌───────────────┐»
«q_0: ┤ Delay(13[dt]) ├┤ X ├┤ Delay(16[dt]) ├┤ X ├┤ Delay(20[dt]) ├┤ X ├┤ Delay(16[dt]) ├»
« └───────────────┘└───┘└───────────────┘└───┘└───────────────┘└───┘└───────────────┘»
«q_1: ───────────────────────────────────────────────────────────────────────────────────»
« »
«q_2: ───────────────────────────────────────────────────────────────────────────────────»
« »
«q_3: ───────────────────────────────────────────────────────────────────────────────────»
« »
« ┌───┐┌───────────────┐┌───┐┌──────────────┐┌───┐┌──────────────┐
«q_0: ┤ X ├┤ Delay(13[dt]) ├┤ X ├┤ Delay(8[dt]) ├┤ X ├┤ Delay(3[dt]) ├
« └───┘└───────────────┘└───┘└──────────────┘└───┘└──────────────┘
«q_1: ────────────────────────────────────────────────────────────────
«
«q_2: ────────────────────────────────────────────────────────────────
«
«q_3: ────────────────────────────────────────────────────────────────
«
"""
n = 8
dd_sequence = [XGate()] * n
# uhrig specifies the location of the k'th pulse
def uhrig(k):
return np.sin(np.pi * (k + 1) / (2 * n + 2)) ** 2
# convert that to spacing between pulses (whatever finite duration pulses have)
spacing = []
for k in range(n):
spacing.append(uhrig(k) - sum(spacing))
spacing.append(1 - sum(spacing))
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0], spacing=spacing),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(3), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(8), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(13), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(16), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(20), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(16), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(13), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(8), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(3), [0])
expected = expected.compose(Delay(300), [1])
self.assertEqual(ghz4_dd, expected)
def test_asymmetric_xy4_in_t2(self):
"""Test insertion of XY4 sequence with unbalanced spacing.
global phase: π
┌───┐┌───┐┌────────────────┐┌───┐┌────────────────┐┌───┐┌────────────────┐»
q_0: ┤ H ├┤ X ├┤ Delay(450[dt]) ├┤ Y ├┤ Delay(450[dt]) ├┤ X ├┤ Delay(450[dt]) ├»
└───┘└───┘└────────────────┘└───┘└────────────────┘└───┘└────────────────┘»
« ┌───┐┌────────────────┐┌───┐
«q_0: ┤ Y ├┤ Delay(450[dt]) ├┤ H ├
« └───┘└────────────────┘└───┘
"""
dd_sequence = [XGate(), YGate()] * 2
spacing = [0] + [1 / 4] * 4
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, spacing=spacing),
]
)
t2 = QuantumCircuit(1)
t2.h(0)
t2.delay(2000, 0)
t2.h(0)
expected = QuantumCircuit(1)
expected.h(0)
expected.x(0)
expected.delay(450, 0)
expected.y(0)
expected.delay(450, 0)
expected.x(0)
expected.delay(450, 0)
expected.y(0)
expected.delay(450, 0)
expected.h(0)
expected.global_phase = pi
t2_dd = pm.run(t2)
self.assertEqual(t2_dd, expected)
# check global phase is correct
self.assertEqual(Operator(t2), Operator(expected))
def test_dd_after_reset(self):
"""Test skip_reset_qubits option works.
┌─────────────────┐┌───┐┌────────────────┐┌───┐┌─────────────────┐»
q_0: ─|0>─┤ Delay(1000[dt]) ├┤ H ├┤ Delay(190[dt]) ├┤ X ├┤ Delay(1710[dt]) ├»
└─────────────────┘└───┘└────────────────┘└───┘└─────────────────┘»
« ┌───┐┌───┐
«q_0: ┤ X ├┤ H ├
« └───┘└───┘
"""
dd_sequence = [XGate(), XGate()]
spacing = [0.1, 0.9]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(
self.durations, dd_sequence, spacing=spacing, skip_reset_qubits=True
),
]
)
t2 = QuantumCircuit(1)
t2.reset(0)
t2.delay(1000)
t2.h(0)
t2.delay(2000, 0)
t2.h(0)
expected = QuantumCircuit(1)
expected.reset(0)
expected.delay(1000)
expected.h(0)
expected.delay(190, 0)
expected.x(0)
expected.delay(1710, 0)
expected.x(0)
expected.h(0)
t2_dd = pm.run(t2)
self.assertEqual(t2_dd, expected)
def test_insert_dd_bad_sequence(self):
"""Test DD raises when non-identity sequence is inserted."""
dd_sequence = [XGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
with self.assertRaises(TranspilerError):
pm.run(self.ghz4)
@data(0.5, 1.5)
def test_dd_with_calibrations_with_parameters(self, param_value):
"""Check that calibrations in a circuit with parameters work fine."""
circ = QuantumCircuit(2)
circ.x(0)
circ.cx(0, 1)
circ.rx(param_value, 1)
rx_duration = int(param_value * 1000)
with pulse.build() as rx:
pulse.play(pulse.Gaussian(rx_duration, 0.1, rx_duration // 4), pulse.DriveChannel(1))
circ.add_calibration("rx", (1,), rx, params=[param_value])
durations = InstructionDurations([("x", None, 100), ("cx", None, 300)])
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence)]
)
self.assertEqual(pm.run(circ).duration, rx_duration + 100 + 300)
def test_insert_dd_ghz_xy4_with_alignment(self):
"""Test DD with pulse alignment constraints.
┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
q_0: ──────┤ H ├─────────■──┤ Delay(40[dt]) ├──────┤ X ├──────┤ Delay(70[dt]) ├»
┌─────┴───┴─────┐ ┌─┴─┐└───────────────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■────────┤ Delay(20[dt]) ├──────┤ X ├──────»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘ └───┘ »
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├──────────────■─────────────────────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├────────────────────────────┤ X ├───────────────────────»
└────────────────┘ └───┘ »
« ┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
«q_0: ──────┤ Y ├──────┤ Delay(70[dt]) ├──────┤ X ├──────┤ Delay(70[dt]) ├»
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
«q_1: ┤ Delay(20[dt]) ├──────┤ Y ├──────┤ Delay(20[dt]) ├──────┤ X ├──────»
« └───────────────┘ └───┘ └───────────────┘ └───┘ »
«q_2: ────────────────────────────────────────────────────────────────────»
« »
«q_3: ────────────────────────────────────────────────────────────────────»
« »
« ┌───┐ ┌───────────────┐
«q_0: ──────┤ Y ├──────┤ Delay(50[dt]) ├─────────────────
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌───────────────┐
«q_1: ┤ Delay(20[dt]) ├──────┤ Y ├──────┤ Delay(20[dt]) ├
« └───────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────
«
"""
dd_sequence = [XGate(), YGate(), XGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(
self.durations,
dd_sequence,
pulse_alignment=10,
extra_slack_distribution="edges",
),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(40), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(70), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(70), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(70), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(50), [0])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(20), [1])
self.assertEqual(ghz4_dd, expected)
def test_dd_can_sequentially_called(self):
"""Test if sequentially called DD pass can output the same circuit.
This test verifies:
- if global phase is properly propagated from the previous padding node.
- if node_start_time property is properly updated for new dag circuit.
"""
dd_sequence = [XGate(), YGate(), XGate(), YGate()]
pm1 = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0]),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[1]),
]
)
circ1 = pm1.run(self.ghz4)
pm2 = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0, 1]),
]
)
circ2 = pm2.run(self.ghz4)
self.assertEqual(circ1, circ2)
def test_respect_target_instruction_constraints(self):
"""Test if DD pass does not pad delays for qubits that do not support delay instructions
and does not insert DD gates for qubits that do not support necessary gates.
See: https://github.com/Qiskit/qiskit-terra/issues/9993
"""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.cx(1, 2)
target = Target(dt=1)
# Y is partially supported (not supported on qubit 2)
target.add_instruction(
XGate(), {(q,): InstructionProperties(duration=100) for q in range(2)}
)
target.add_instruction(
CXGate(),
{
(0, 1): InstructionProperties(duration=1000),
(1, 2): InstructionProperties(duration=1000),
},
)
# delays are not supported
# No DD instructions nor delays are padded due to no delay support in the target
pm_xx = PassManager(
[
ALAPScheduleAnalysis(target=target),
PadDynamicalDecoupling(dd_sequence=[XGate(), XGate()], target=target),
]
)
scheduled = pm_xx.run(qc)
self.assertEqual(qc, scheduled)
# Fails since Y is not supported in the target
with self.assertRaises(TranspilerError):
PassManager(
[
ALAPScheduleAnalysis(target=target),
PadDynamicalDecoupling(
dd_sequence=[XGate(), YGate(), XGate(), YGate()], target=target
),
]
)
# Add delay support to the target
target.add_instruction(Delay(Parameter("t")), {(q,): None for q in range(3)})
# No error but no DD on qubit 2 (just delay is padded) since X is not supported on it
scheduled = pm_xx.run(qc)
expected = QuantumCircuit(3)
expected.delay(1000, [2])
expected.cx(0, 1)
expected.cx(1, 2)
expected.delay(200, [0])
expected.x([0])
expected.delay(400, [0])
expected.x([0])
expected.delay(200, [0])
self.assertEqual(expected, scheduled)
if __name__ == "__main__":
unittest.main()
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import *
from qiskit.quantum_info import Statevector
from math import pi
# No barrier gate present
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.draw(output="mpl")
#Let's apply a barrier gate with no arguments
qc=QuantumCircuit(1)
qc.h(0)
qc.h(0)
qc.barrier()
qc.y(0)
qc.draw(output="mpl")
#Let's apply a barrier gate with no arguments for a 3-qubit Quantum Circuit
# If we don't specify any arguments, then the barrier is applied across all the qubits
qc=QuantumCircuit(3)
qc.h(range(2))
qc.barrier()
qc.x(2)
qc.draw(output="mpl")
#Let's apply a barrier gate with 1 arguments for a 3-qubit Quantum Circuit
# We want to apply a barrier only to the q0
qc=QuantumCircuit(3)
qc.h(range(2))
qc.barrier(0)
qc.x(2)
qc.draw(output="mpl")
qc=QuantumCircuit(3)
qc.h(range(2))
qc.barrier(0,1)
qc.x(2)
qc.draw(output="mpl")
# barrier is applied to q0 and q1
qc=QuantumCircuit(3)
qc.h(range(2))
qc.barrier(0,1,2)
qc.x(2)
qc.draw(output="mpl")
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.ccx(0,1,2)
qc.ry(pi,0)
qc.ch(1,2)
qc.tdg(2)
qc.cx(1,0)
qc.draw(output="mpl")
qc=QuantumCircuit(3)
qc.h(range(2))
qc.barrier()
qc.x(2)
qc.barrier()
qc.ccx(0,1,2)
qc.barrier()
qc.ry(pi,0)
qc.ch(1,2)
qc.barrier()
qc.tdg(2)
qc.barrier()
qc.cx(1,0)
qc.draw(output="mpl")
qr=QuantumRegister(3)
qc=QuantumCircuit(qr)
qc.x(0)
qc.barrier(qr)
qc.h(1)
qc.barrier(qr)
qc.s(1)
qc.barrier(qr)
qc.h(2)
qc.draw(output="mpl")
|
https://github.com/drobiu/quantum-project
|
drobiu
|
"""Example usage of the Quantum Inspire backend with the Qiskit SDK.
A simple example that demonstrates how to use the SDK to create
a circuit to demonstrate conditional gate execution.
For documentation on how to use Qiskit we refer to
[https://qiskit.org/](https://qiskit.org/).
Specific to Quantum Inspire is the creation of the QI instance, which is used to set the authentication
of the user and provides a Quantum Inspire backend that is used to execute the circuit.
Copyright 2018-19 QuTech Delft. Licensed under the Apache License, Version 2.0.
"""
import os
from qiskit import BasicAer, execute
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from quantuminspire.credentials import get_authentication
from quantuminspire.qiskit import QI
QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/')
authentication = get_authentication()
QI.set_authentication(authentication, QI_URL)
qi_backend = QI.get_backend('QX single-node simulator')
q = QuantumRegister(2, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
qc = QuantumCircuit(3, name="conditional")
qc.h([0, 2])
qc.cnot(q[0], q[1])
qc.measure_all()
qi_job = execute(qc, backend=qi_backend, shots=1024)
qi_result = qi_job.result()
histogram = qi_result.get_counts(qc)
print("\nResult from the remote Quantum Inspire backend:\n")
print('State\tCounts')
[print('{0}\t{1}'.format(state, counts)) for state, counts in histogram.items()]
print("\nResult from the local Qiskit simulator backend:\n")
backend = BasicAer.get_backend("qasm_simulator")
job = execute(qc, backend=backend, shots=1024)
result = job.result()
print(result.get_counts(qc))
qc.draw(output="latex")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
def udd10_pos(j):
return np.sin(np.pi*j/(2*10 + 2))**2
with pulse.build() as udd_sched:
pulse.play(x90, d0)
with pulse.align_func(duration=300, func=udd10_pos):
for _ in range(10):
pulse.play(x180, d0)
pulse.play(x90, d0)
udd_sched.draw()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
IBMQ.enable_account('Enter API key here')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(8, 'q')
c = ClassicalRegister(1, 'c')
circuit = QuantumCircuit(q, c)
circuit.x(q[0])
circuit.x(q[1])
circuit.x(q[2])
circuit.x(q[3])
circuit.ccx(q[0], q[1], q[4])
circuit.ccx(q[2], q[4], q[5])
circuit.ccx(q[3], q[5], q[6])
circuit.cx(q[6], q[7])
circuit.ccx(q[3], q[5], q[6])
circuit.ccx(q[2], q[4], q[5])
circuit.ccx(q[0], q[1], q[4])
circuit.measure(q[7], c[0])
job = execute(circuit, backend, shots=100)
job_monitor(job)
counts = job.result().get_counts()
print(circuit)
print(counts)
|
https://github.com/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
iterations = [i for i in range(5, 20, 2)]
iterations
from qiskit import IBMQ
import random
from qiskit import QuantumCircuit, execute, transpile, Aer
from qiskit.extensions import UnitaryGate, Initialize
from qiskit.quantum_info import Statevector
from qiskit.tools.visualization import plot_bloch_vector
from qiskit.tools.visualization import plot_histogram, plot_bloch_multivector
import numpy as np
from time import sleep
import sys
sys.path.append("../..")
import os
from scipy.stats import unitary_group
import matplotlib.pyplot as plt
%matplotlib inline
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-education')
# santiago = provider.get_backend('ibmq_santiago')
# casablanca = provider.get_backend('ibmq_casablanca')
# bogota = provider.get_backend('ibmq_bogota')
sim = Aer.get_backend('qasm_simulator')
# athens = provider.get_backend('ibmq_athens')
from Modules.normal_SPEA import SPEA
from Modules.changed_SPEA import global_max_SPEA
def generate_plots(unitary_size, costs, errors, overlaps, algorithm):
colors = ['red', 'brown', 'cyan', 'green',
'grey', 'blue', 'purple', 'black', 'orange']
c1, c2, c3 = random.sample(colors, 3)
# plot
os.makedirs("Experiment_2/"+str(unitary_size) +
"_qubit(random)/", exist_ok=True)
# plot 1
fig = plt.figure(figsize=(13, 6))
ax1 = fig.add_subplot(1, 2, 1)
ax1.set_title(str(unitary_size)+" qubit "+algorithm +
" Cost v/s Max iters", fontsize=16)
ax1.set_xlabel("Maximum iterations ", fontsize=15)
ax1.set_ylabel("Metrics Returned for unitary ", fontsize=15)
ax1.plot(iterations, costs, label='Costs of Unitary',
marker='o', color=c1, alpha=0.7)
ax1.plot(iterations, overlaps, label='Average overlap from nearest eigenvector',
marker='s', color=c2, alpha=0.6)
ax1.legend(loc='best')
ax1.grid()
# plot 2
ax2 = fig.add_subplot(1, 2, 2)
ax2.set_title(str(unitary_size)+" qubit "+algorithm +
" % error v/s Max iters", fontsize=16)
ax2.set_xlabel("Maximum iterations ", fontsize=15)
ax2.set_ylabel("% error for nearest eigenvalue", fontsize=15)
ax2.plot(iterations, errors, label='Average error from nearest eigenvalue',
marker='o', color=c3, alpha=0.6)
ax2.legend(loc='best')
ax2.grid()
# save axure
fig.savefig("Experiment_2/"+str(unitary_size)+"_qubit(random)/" +
algorithm+" Algorithm (alternate).JPG", dpi=200)
def get_results(eig_vals, eig_vect, bases, basis_indices, unitary, algorithm, experiments):
'''Return the results of running the algorithm for this particular unitary matrix'''
costs_g = []
errors_g = []
max_overlaps_g = []
# find how the cost converges with increasing iterations
for iters in iterations:
costs = []
errors = []
overlaps = []
i = 0
# run the experiments ...
while len(costs) < experiments:
if algorithm == 'original':
spea = SPEA(unitary, resolution=30, error=3, max_iters=iters)
else:
spea = global_max_SPEA(
unitary, resolution=30, error=3, max_iters=iters)
result = spea.get_eigen_pair(
progress=False, backend=sim, basis=bases[i], basis_ind=basis_indices[i],
algo='alternate', randomize=False,shots = 256)
if result['cost'] < 0.65:
continue
i+=1
# find the costs
costs.append(result['cost'])
theta = result['theta']
res_state = result['state']
# find the abs difference in this theta with the closest eigenvalue
# and append that to the errors ...
min_error = 1e5
for e in eig_vals:
error = abs(e - theta)
if error < min_error:
min_error = error
perc_error = ((error)/e)*100
errors.append(perc_error)
# find overlaps
max_overlap = -1
for k in eig_vect:
dot = np.linalg.norm(np.dot(k, res_state.conjugate().T))**2
max_overlap = max(max_overlap, dot)
overlaps.append(max_overlap)
print("Result with", iters, " iterations :")
print("AVG. COST :", np.average(costs),
"AVG. ERROR :", np.average(errors))
# append the average result of your algorithm ...
costs_g.append(np.average(costs))
errors_g.append(np.average(errors))
max_overlaps_g.append(np.average(overlaps))
return costs_g, errors_g, max_overlaps_g
unit_2 = unitary_group.rvs(4)
unit_2
eig_vals2, eig_vect2 = np.linalg.eig(unit_2)
eig_vals2 = np.angle(eig_vals2)
e = []
for k in eig_vals2:
if k < 0:
v = (k + 2*np.pi)/(2*np.pi)
else:
v = (k)/(2*np.pi)
e.append(v)
eig_vals2 = np.array(e)
print("Eigenstates :", eig_vect2)
print("Eigenvalues :", eig_vals2)
bases2 , basis_indices2 = [], []
for _ in range(4):
sample = unitary_group.rvs(4)
basis = []
for k in sample:
basis.append(np.array(k, dtype=complex))
# print("2 qubit basis :", basis2)
ind = np.random.choice(range(4))
# print(ind)
bases2.append(basis)
basis_indices2.append(ind)
# print("Basis set :",bases2)
print("Basis indices :",basis_indices2)
costs_2qubit_b, errors_2qubit_b, max_overlaps_2qubit_b = get_results(eig_vals2,
eig_vect2, bases2, basis_indices2,
unit_2, "original", 4)
generate_plots(2, costs_2qubit_b, errors_2qubit_b,
max_overlaps_2qubit_b, "Original")
costs_2qubit_c, errors_2qubit_c, max_overlaps_2qubit_c = get_results(
eig_vals2, eig_vect2, bases2, basis_indices2, unit_2, "modified", 4)
generate_plots(2, costs_2qubit_c, errors_2qubit_c,
max_overlaps_2qubit_c, "Modified")
unit_3 = unitary_group.rvs(8)
unit_3
eig_vals3, eig_vect3 = np.linalg.eig(unit_3)
eig_vals3 = np.angle(eig_vals3)
e = []
for k in eig_vals3:
if k < 0:
v = (k + 2*np.pi)/(2*np.pi)
else:
v = (k)/(2*np.pi)
e.append(v)
eig_vals3 = np.array(e)
print("Eigenstates :", eig_vect3)
print("Eigenvalues :", eig_vals3)
bases3 , basis_indices3 = [], []
for _ in range(4):
sample = unitary_group.rvs(8)
basis = []
for k in sample:
basis.append(np.array(k, dtype=complex))
# print("3 qubit basis :", basis3)
ind = np.random.choice(range(8))
# print(ind)
bases3.append(basis)
basis_indices3.append(ind)
# print("Basis set :",bases3)
print("Basis indices :",basis_indices3)
costs_3qubit_b, errors_3qubit_b, max_overlaps_3qubit_b = get_results(
eig_vals3, eig_vect3,bases3, basis_indices3, unit_3, "original", 4)
generate_plots(3, costs_3qubit_b, errors_3qubit_b,
max_overlaps_3qubit_b, "Original")
costs_3qubit_c, errors_3qubit_c, max_overlaps_3qubit_c = get_results(
eig_vals3, eig_vect3, bases3, basis_indices3, unit_3, "modified", 4)
generate_plots(3, costs_3qubit_c, errors_3qubit_c,
max_overlaps_3qubit_c, "Modified")
unit_4 = unitary_group.rvs(16)
# unit_4
eig_vals4, eig_vect4 = np.linalg.eig(unit_4)
eig_vals4 = np.angle(eig_vals4)
e = []
for k in eig_vals4:
if k < 0:
v = (k + 2*np.pi)/(2*np.pi)
else:
v = (k)/(2*np.pi)
e.append(v)
eig_vals4 = np.array(e)
print("Eigenstates :", eig_vect4)
print("Eigenvalues :", eig_vals4)
bases4 , basis_indices4 = [], []
for _ in range(4):
sample = unitary_group.rvs(16)
basis = []
for k in sample:
basis.append(np.array(k, dtype=complex))
ind = np.random.choice(range(16))
bases4.append(basis)
basis_indices4.append(ind)
print("Basis indices :",basis_indices4)
costs_4qubit_b, errors_eig_4qubit_b, max_overlaps_4qubit_b = get_results(
eig_vals4, eig_vect4, bases4, basis_indices4, unit_4, 'original', 4)
generate_plots(4, costs_4qubit_b,
errors_eig_4qubit_b, max_overlaps_4qubit_b, "Original")
costs_4qubit_c, errors_eig_4qubit_c, max_overlaps_4qubit_c = get_results(
eig_vals4, eig_vect4, bases4, basis_indices4, unit_4, 'modified', 4)
generate_plots(4, costs_4qubit_c,
errors_eig_4qubit_c, max_overlaps_4qubit_c, "Modified")
|
https://github.com/TRSasasusu/qiskit-quantum-zoo
|
TRSasasusu
|
import unittest
import numpy as np
from sympy.physics.quantum.qubit import matrix_to_qubit
from qiskit import QuantumCircuit, Aer, transpile
from qqz.elementary import (
adder,
adder_modN,
ctrl_multi_modN,
ax_modN,
)
def run_qc_and_get_ket_vector(qc):
backend = Aer.get_backend('aer_simulator_statevector')
qc = transpile(qc, backend)
qc.save_statevector()
job = backend.run(qc)
statevector = job.result().get_statevector(qc)
return matrix_to_qubit(np.array(statevector)[:, np.newaxis])
class TestElementary(unittest.TestCase):
def test_adder(self):
qc = QuantumCircuit(2 + (2 + 1) + 2)
qc.x([0, 1])
qc.x(2)
qc.append(adder(2), range(2 + (2 + 1) + 2))
ket_vector = run_qc_and_get_ket_vector(qc)
self.assertEqual(str(ket_vector), '1.0*|0010011>')
def test_adder_modN(self):
qc = QuantumCircuit(2 + (2 + 1) + 2 + 2 + 1)
qc.x([0, 1])
qc.x(2)
qc.append(adder_modN(3), range(2 + (2 + 1) + 2 + 2 + 1))
ket_vector = run_qc_and_get_ket_vector(qc)
self.assertEqual(str(ket_vector), '1.0*|0000000111>')
def test_ctrl_multi_modN(self):
qc = QuantumCircuit(9 * 2 - 1)
qc.h(0)
qc.x(2)
qc.append(ctrl_multi_modN(a=2, N=3), range(9 * 2 - 1))
ket_vector = run_qc_and_get_ket_vector(qc)
self.assertEqual(str(ket_vector), '0.707106781186547*|00000000000001101> + 0.707106781186548*|00000000000010100>')
def test_ax_modN(self):
qc = QuantumCircuit(10 * 2 - 2)
qc.h([0, 1])
qc.append(ax_modN(a=2, N=3), range(10 * 2 - 2))
ket_vector = run_qc_and_get_ket_vector(qc)
self.assertEqual(str(ket_vector), '0.5*|000000000000000100> + 0.5*|000000000000000110> + 0.5*|000000000000001001> + 0.5*|000000000000001011>')
if __name__ == '__main__':
unittest.main()
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the CX Direction pass"""
import unittest
from math import pi
import ddt
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, pulse
from qiskit.circuit import Parameter, Gate
from qiskit.circuit.library import (
CXGate,
CZGate,
ECRGate,
RXXGate,
RYYGate,
RZXGate,
RZZGate,
SwapGate,
)
from qiskit.compiler import transpile
from qiskit.transpiler import TranspilerError, CouplingMap, Target
from qiskit.transpiler.passes import GateDirection
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestGateDirection(QiskitTestCase):
"""Tests the GateDirection pass."""
def test_no_cnots(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_direction_error(self):
"""The mapping cannot be fixed by direction mapper
qr0:---------
qr1:---(+)---
|
qr2:----.----
CouplingMap map: [2] <- [0] -> [1]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = GateDirection(coupling)
with self.assertRaises(TranspilerError):
pass_.run(dag)
def test_direction_correct(self):
"""The CX is in the right direction
qr0:---(+)---
|
qr1:----.----
CouplingMap map: [0] -> [1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_direction_flip(self):
"""Flip a CX
qr0:----.----
|
qr1:---(+)---
CouplingMap map: [0] -> [1]
qr0:-[H]-(+)-[H]--
|
qr1:-[H]--.--[H]--
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[1])
expected.cx(qr[0], qr[1])
expected.h(qr[0])
expected.h(qr[1])
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_ecr_flip(self):
"""Flip a ECR gate.
┌──────┐
q_0: ┤1 ├
│ ECR │
q_1: ┤0 ├
└──────┘
CouplingMap map: [0, 1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.ecr(qr[1], qr[0])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
# ┌─────────┐ ┌──────┐┌───┐
# qr_0: ┤ Ry(π/2) ├─┤0 ├┤ H ├
# ├─────────┴┐│ Ecr │├───┤
# qr_1: ┤ Ry(-π/2) ├┤1 ├┤ H ├
# └──────────┘└──────┘└───┘
expected = QuantumCircuit(qr)
expected.ry(pi / 2, qr[0])
expected.ry(-pi / 2, qr[1])
expected.ecr(qr[0], qr[1])
expected.h(qr[0])
expected.h(qr[1])
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_flip_with_measure(self):
"""
qr0: -(+)-[m]-
| |
qr1: --.---|--
|
cr0: ------.--
CouplingMap map: [0] -> [1]
qr0: -[H]--.--[H]-[m]-
| |
qr1: -[H]-(+)-[H]--|--
|
cr0: --------------.--
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[0])
circuit.measure(qr[0], cr[0])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.h(qr[0])
expected.h(qr[1])
expected.cx(qr[0], qr[1])
expected.h(qr[0])
expected.h(qr[1])
expected.measure(qr[0], cr[0])
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_preserves_conditions(self):
"""Verify GateDirection preserves conditional on CX gates.
┌───┐ ┌───┐
q_0: |0>───■────┤ X ├───■──┤ X ├
┌─┴─┐ └─┬─┘ ┌─┴─┐└─┬─┘
q_1: |0>─┤ X ├────■───┤ X ├──■──
└─┬─┘ │ └───┘
┌──┴──┐┌──┴──┐
c_0: 0 ╡ = 0 ╞╡ = 0 ╞══════════
└─────┘└─────┘
"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[1]).c_if(cr, 0)
circuit.cx(qr[1], qr[0]).c_if(cr, 0)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
# ┌───┐ ┌───┐ ┌───┐ ┌───┐
# q_0: ───■───────────┤ H ├────■───────────┤ H ├───■──┤ H ├──■──┤ H ├
# ┌─┴─┐ ┌───┐ └─╥─┘ ┌─┴─┐ ┌───┐ └─╥─┘ ┌─┴─┐├───┤┌─┴─┐├───┤
# q_1: ─┤ X ├──┤ H ├────╫────┤ X ├──┤ H ├────╫───┤ X ├┤ H ├┤ X ├┤ H ├
# └─╥─┘ └─╥─┘ ║ └─╥─┘ └─╥─┘ ║ └───┘└───┘└───┘└───┘
# ┌──╨──┐┌──╨──┐┌──╨──┐┌──╨──┐┌──╨──┐┌──╨──┐
# c: 1/╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞════════════════════
# └─────┘└─────┘└─────┘└─────┘└─────┘└─────┘
expected = QuantumCircuit(qr, cr)
expected.cx(qr[0], qr[1]).c_if(cr, 0)
# Order of H gates is important because DAG comparison will consider
# different conditional order on a creg to be a different circuit.
# See https://github.com/Qiskit/qiskit-terra/issues/3164
expected.h(qr[1]).c_if(cr, 0)
expected.h(qr[0]).c_if(cr, 0)
expected.cx(qr[0], qr[1]).c_if(cr, 0)
expected.h(qr[1]).c_if(cr, 0)
expected.h(qr[0]).c_if(cr, 0)
expected.cx(qr[0], qr[1])
expected.h(qr[1])
expected.h(qr[0])
expected.cx(qr[0], qr[1])
expected.h(qr[1])
expected.h(qr[0])
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_regression_gh_8387(self):
"""Regression test for flipping of CZ gate"""
qc = QuantumCircuit(3)
qc.cz(1, 0)
qc.barrier()
qc.cz(2, 0)
coupling_map = CouplingMap([[0, 1], [1, 2]])
_ = transpile(
qc,
basis_gates=["cz", "cx", "u3", "u2", "u1"],
coupling_map=coupling_map,
optimization_level=2,
)
@ddt.data(CXGate(), CZGate(), ECRGate())
def test_target_static(self, gate):
"""Test that static 2q gates are swapped correctly both if available and not available."""
circuit = QuantumCircuit(2)
circuit.append(gate, [0, 1], [])
matching = Target(num_qubits=2)
matching.add_instruction(gate, {(0, 1): None})
self.assertEqual(GateDirection(None, target=matching)(circuit), circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(gate, {(1, 0): None})
self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit)
@ddt.data(CZGate(), RZXGate(pi / 3), RXXGate(pi / 3), RYYGate(pi / 3), RZZGate(pi / 3))
def test_target_trivial(self, gate):
"""Test that trivial 2q gates are swapped correctly both if available and not available."""
circuit = QuantumCircuit(2)
circuit.append(gate, [0, 1], [])
matching = Target(num_qubits=2)
matching.add_instruction(gate, {(0, 1): None})
self.assertEqual(GateDirection(None, target=matching)(circuit), circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(gate, {(1, 0): None})
self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit)
@ddt.data(CZGate(), SwapGate(), RXXGate(pi / 3), RYYGate(pi / 3), RZZGate(pi / 3))
def test_symmetric_gates(self, gate):
"""Test symmetric gates on single direction coupling map."""
circuit = QuantumCircuit(2)
circuit.append(gate, [1, 0], [])
expected = QuantumCircuit(2)
expected.append(gate, [0, 1], [])
coupling = CouplingMap.from_line(2, bidirectional=False)
pass_ = GateDirection(coupling)
self.assertEqual(pass_(circuit), expected)
def test_target_parameter_any(self):
"""Test that a parametrised 2q gate is replaced correctly both if available and not
available."""
circuit = QuantumCircuit(2)
circuit.rzx(1.5, 0, 1)
matching = Target(num_qubits=2)
matching.add_instruction(RZXGate(Parameter("a")), {(0, 1): None})
self.assertEqual(GateDirection(None, target=matching)(circuit), circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(RZXGate(Parameter("a")), {(1, 0): None})
self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit)
def test_target_parameter_exact(self):
"""Test that a parametrised 2q gate is detected correctly both if available and not
available."""
circuit = QuantumCircuit(2)
circuit.rzx(1.5, 0, 1)
matching = Target(num_qubits=2)
matching.add_instruction(RZXGate(1.5), {(0, 1): None})
self.assertEqual(GateDirection(None, target=matching)(circuit), circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(RZXGate(1.5), {(1, 0): None})
self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit)
def test_target_parameter_mismatch(self):
"""Test that the pass raises if a gate is not supported due to a parameter mismatch."""
circuit = QuantumCircuit(2)
circuit.rzx(1.5, 0, 1)
matching = Target(num_qubits=2)
matching.add_instruction(RZXGate(2.5), {(0, 1): None})
pass_ = GateDirection(None, target=matching)
with self.assertRaises(TranspilerError):
pass_(circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(RZXGate(2.5), {(1, 0): None})
pass_ = GateDirection(None, target=swapped)
with self.assertRaises(TranspilerError):
pass_(circuit)
def test_coupling_map_control_flow(self):
"""Test that gates are replaced within nested control-flow blocks."""
circuit = QuantumCircuit(4, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((1, 2)):
circuit.cx(1, 0)
circuit.cx(0, 1)
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.ecr(3, 2)
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.rzx(2.3, 2, 1)
expected = QuantumCircuit(4, 1)
expected.h(0)
expected.measure(0, 0)
with expected.for_loop((1, 2)):
expected.h([0, 1])
expected.cx(0, 1)
expected.h([0, 1])
expected.cx(0, 1)
with expected.if_test((circuit.clbits[0], True)) as else_:
expected.ry(pi / 2, 2)
expected.ry(-pi / 2, 3)
expected.ecr(2, 3)
expected.h([2, 3])
with else_:
with expected.while_loop((circuit.clbits[0], True)):
expected.h([1, 2])
expected.rzx(2.3, 1, 2)
expected.h([1, 2])
coupling = CouplingMap.from_line(4, bidirectional=False)
pass_ = GateDirection(coupling)
self.assertEqual(pass_(circuit), expected)
def test_target_control_flow(self):
"""Test that gates are replaced within nested control-flow blocks."""
circuit = QuantumCircuit(4, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((1, 2)):
circuit.cx(1, 0)
circuit.cx(0, 1)
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.ecr(3, 2)
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.rzx(2.3, 2, 1)
expected = QuantumCircuit(4, 1)
expected.h(0)
expected.measure(0, 0)
with expected.for_loop((1, 2)):
expected.h([0, 1])
expected.cx(0, 1)
expected.h([0, 1])
expected.cx(0, 1)
with expected.if_test((circuit.clbits[0], True)) as else_:
expected.ry(pi / 2, 2)
expected.ry(-pi / 2, 3)
expected.ecr(2, 3)
expected.h([2, 3])
with else_:
with expected.while_loop((circuit.clbits[0], True)):
expected.h([1, 2])
expected.rzx(2.3, 1, 2)
expected.h([1, 2])
target = Target(num_qubits=4)
target.add_instruction(CXGate(), {(0, 1): None})
target.add_instruction(ECRGate(), {(2, 3): None})
target.add_instruction(RZXGate(Parameter("a")), {(1, 2): None})
pass_ = GateDirection(None, target)
self.assertEqual(pass_(circuit), expected)
def test_target_cannot_flip_message(self):
"""A suitable error message should be emitted if the gate would be supported if it were
flipped."""
gate = Gate("my_2q_gate", 2, [])
target = Target(num_qubits=2)
target.add_instruction(gate, properties={(0, 1): None})
circuit = QuantumCircuit(2)
circuit.append(gate, (1, 0))
pass_ = GateDirection(None, target)
with self.assertRaisesRegex(TranspilerError, "'my_2q_gate' would be supported.*"):
pass_(circuit)
def test_target_cannot_flip_message_calibrated(self):
"""A suitable error message should be emitted if the gate would be supported if it were
flipped."""
target = Target(num_qubits=2)
target.add_instruction(CXGate(), properties={(0, 1): None})
gate = Gate("my_2q_gate", 2, [])
circuit = QuantumCircuit(2)
circuit.append(gate, (1, 0))
circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock())
pass_ = GateDirection(None, target)
with self.assertRaisesRegex(TranspilerError, "'my_2q_gate' would be supported.*"):
pass_(circuit)
def test_target_unknown_gate_message(self):
"""A suitable error message should be emitted if the gate isn't valid in either direction on
the target."""
gate = Gate("my_2q_gate", 2, [])
target = Target(num_qubits=2)
target.add_instruction(CXGate(), properties={(0, 1): None})
circuit = QuantumCircuit(2)
circuit.append(gate, (0, 1))
pass_ = GateDirection(None, target)
with self.assertRaisesRegex(TranspilerError, "'my_2q_gate'.*not supported on qubits .*"):
pass_(circuit)
def test_allows_calibrated_gates_coupling_map(self):
"""Test that the gate direction pass allows a gate that's got a calibration to pass through
without error."""
cm = CouplingMap([(1, 0)])
gate = Gate("my_2q_gate", 2, [])
circuit = QuantumCircuit(2)
circuit.append(gate, (0, 1))
circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock())
pass_ = GateDirection(cm)
self.assertEqual(pass_(circuit), circuit)
def test_allows_calibrated_gates_target(self):
"""Test that the gate direction pass allows a gate that's got a calibration to pass through
without error."""
target = Target(num_qubits=2)
target.add_instruction(CXGate(), properties={(0, 1): None})
gate = Gate("my_2q_gate", 2, [])
circuit = QuantumCircuit(2)
circuit.append(gate, (0, 1))
circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock())
pass_ = GateDirection(None, target)
self.assertEqual(pass_(circuit), circuit)
if __name__ == "__main__":
unittest.main()
|
https://github.com/snow0369/qiskit_tutorial_2021_summerschool
|
snow0369
|
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.test.mock import FakeRome
from qiskit.providers.aer import AerProvider
from qiskit.quantum_info import hellinger_fidelity
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.cx(0,1)
qc.barrier()
qc.measure(qr, cr)
qc.draw('mpl')
num_shots = 4096
fake_rome = FakeRome()
job_fake_rome = fake_rome.run(qc, shots=4096)
result_fake_rome = job_fake_rome.result()
counts_fake_rome = result_fake_rome.get_counts()
print(counts_fake_rome)
pr_m = np.zeros(4, dtype=float)
for b, v in counts_fake_rome.items():
pr_m[int(b, base=2)] = v/num_shots
print(pr_m)
pr_m_p = np.zeros((4,4), dtype=float)
qr_mit = QuantumRegister(2)
cr_mit = ClassicalRegister(2)
# state prep = 00
qc_00 = QuantumCircuit(qr_mit, cr_mit)
qc_00.barrier()
qc_00.measure(qr_mit, cr_mit)
counts_00 = fake_rome.run(qc_00, shots=num_shots)\
.result().get_counts()
pr_m_p[0][0] = counts_00['00']/num_shots if '00' in counts_00 else 0.0
pr_m_p[1][0] = counts_00['01']/num_shots if '01' in counts_00 else 0.0
pr_m_p[2][0] = counts_00['10']/num_shots if '10' in counts_00 else 0.0
pr_m_p[3][0] = counts_00['11']/num_shots if '11' in counts_00 else 0.0
# state prep = 01
qc_01 = QuantumCircuit(qr_mit, cr_mit)
qc_01.x(0)
qc_01.barrier()
qc_01.measure(qr_mit, cr_mit)
counts_01 = fake_rome.run(qc_01, shots=num_shots)\
.result().get_counts()
pr_m_p[0][1] = counts_01['00']/num_shots if '00' in counts_01 else 0.0
pr_m_p[1][1] = counts_01['01']/num_shots if '01' in counts_01 else 0.0
pr_m_p[2][1] = counts_01['10']/num_shots if '10' in counts_01 else 0.0
pr_m_p[3][1] = counts_01['11']/num_shots if '11' in counts_01 else 0.0
# state prep = 10
qc_10 = QuantumCircuit(qr_mit, cr_mit)
qc_10.x(1)
qc_10.barrier()
qc_10.measure(qr_mit, cr_mit)
counts_10 = fake_rome.run(qc_10, shots=num_shots)\
.result().get_counts()
pr_m_p[0][2] = counts_10['00']/num_shots if '00' in counts_10 else 0.0
pr_m_p[1][2] = counts_10['01']/num_shots if '01' in counts_10 else 0.0
pr_m_p[2][2] = counts_10['10']/num_shots if '10' in counts_10 else 0.0
pr_m_p[3][2] = counts_10['11']/num_shots if '11' in counts_10 else 0.0
# state prep = 11
qc_11 = QuantumCircuit(qr_mit, cr_mit)
qc_11.x(0)
qc_11.x(1)
qc_11.barrier()
qc_11.measure(qr_mit, cr_mit)
counts_11 = fake_rome.run(qc_11, shots=num_shots)\
.result().get_counts()
pr_m_p[0][3] = counts_11['00']/num_shots if '00' in counts_11 else 0.0
pr_m_p[1][3] = counts_11['01']/num_shots if '01' in counts_11 else 0.0
pr_m_p[2][3] = counts_11['10']/num_shots if '10' in counts_11 else 0.0
pr_m_p[3][3] = counts_11['11']/num_shots if '11' in counts_11 else 0.0
np.set_printoptions(suppress=True)
print(pr_m_p)
pr_p = np.matmul(np.linalg.inv(pr_m_p), pr_m)
print("Before mitigation: ", pr_m)
print("After mitigation: ", pr_p)
qasm_backend = AerProvider().get_backend("qasm_simulator")
counts_qasm = qasm_backend.run(qc, shots=num_shots).result().get_counts()
pr_ideal = np.zeros(4, dtype=float)
for b, v in counts_qasm.items():
pr_ideal[int(b, base=2)] = v/num_shots
print("Ideal probs: ", pr_ideal)
# convert pr_p to dict form
counts_mit = dict()
for i, v in enumerate(pr_p):
counts_mit[bin(i)[2:].rjust(2, '0')] = v * num_shots
print("Fidelity without mitigation: ", hellinger_fidelity(counts_fake_rome, counts_qasm))
print("Fidelity with mitigation: ", hellinger_fidelity(counts_mit, counts_qasm))
from qiskit.visualization import plot_histogram
plot_histogram([counts_fake_rome, counts_mit, counts_qasm],
legend=['no mit', 'mitigated', 'ideal'])
from qiskit.ignis.mitigation import CompleteMeasFitter, complete_meas_cal
meas_calibs, state_labels = complete_meas_cal(qr=qr_mit, circlabel='mcal')
for ckt in meas_calibs:
print(ckt)
job_calibs = fake_rome.run(meas_calibs, shots=num_shots)
meas_fitter = CompleteMeasFitter(job_calibs.result(), state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
meas_fitter.plot_calibration()
# Get the filter object
meas_filter = meas_fitter.filter
# Results with mitigation
mitigated_results = meas_filter.apply(result_fake_rome)
mitigated_counts = mitigated_results.get_counts(0)
print("Fidelity with mitigation: ", hellinger_fidelity(mitigated_counts, counts_qasm))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.quantumcircuitdata import CircuitInstruction
from qiskit.circuit import Measure
from qiskit.circuit.library import HGate, CXGate
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
instructions = [
CircuitInstruction(HGate(), [qr[0]], []),
CircuitInstruction(CXGate(), [qr[0], qr[1]], []),
CircuitInstruction(Measure(), [qr[0]], [cr[0]]),
CircuitInstruction(Measure(), [qr[1]], [cr[1]]),
]
circuit = QuantumCircuit.from_instructions(instructions)
circuit.draw("mpl")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_gate_map
backend = FakeVigoV2()
plot_gate_map(backend)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
all_pairs = ['00','01','10','11']
for pair in all_pairs:
# create a quantum curcuit with two qubits: Asja's and Balvis' qubits.
# both are initially set to |0>.
qreg = QuantumRegister(2) # quantum register with 2 qubits
creg = ClassicalRegister(2) # classical register with 2 bits
mycircuit = QuantumCircuit(qreg,creg) # quantum circuit with quantum and classical registers
# apply h-gate (Hadamard) to the first qubit.
mycircuit.h(qreg[0])
# apply cx-gate (CNOT) with parameters first-qubit and second-qubit.
mycircuit.cx(qreg[0],qreg[1])
# they are separated now.
# if a is 1, then apply z-gate to the first qubit.
if pair[0]=='1':
mycircuit.z(qreg[0])
# if b is 1, then apply x-gate (NOT) to the first qubit.
if pair[1]=='1':
mycircuit.x(qreg[0])
# Asja sends her qubit to Balvis.
# apply cx-gate (CNOT) with parameters first-qubit and second-qubit.
mycircuit.cx(qreg[0],qreg[1])
# apply h-gate (Hadamard) to the first qubit.
mycircuit.h(qreg[0])
# measure both qubits
mycircuit.measure(qreg,creg)
# compare the results with pair (a,b)
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit)
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print("(a,b) is",pair,"and",reverse_outcome,"is observed",counts[outcome],"times")
|
https://github.com/alpine-quantum-technologies/qiskit-aqt-provider-rc
|
alpine-quantum-technologies
|
# This code is part of Qiskit.
#
# (C) Copyright Alpine Quantum Technologies GmbH 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Basic example with the Qiskit AQT provider and the noisy offline simulator.
Creates a 2-qubit GHZ state.
"""
import qiskit
from qiskit import QuantumCircuit
from qiskit_aqt_provider.aqt_provider import AQTProvider
if __name__ == "__main__":
# Ways to specify an access token (in precedence order):
# - as argument to the AQTProvider initializer
# - in the AQT_TOKEN environment variable
# - if none of the above exists, default to an empty string, which restricts access
# to the default workspace only.
provider = AQTProvider("token")
# The backends() method lists all available computing backends. Printing it
# renders it as a table that shows each backend's containing workspace.
print(provider.backends())
# Retrieve a backend by providing search criteria. The search must have a single
# match. For example:
backend = provider.get_backend("offline_simulator_noise", workspace="default")
# Create a 2-qubit GHZ state
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
result = qiskit.execute(qc, backend, shots=200).result()
if result.success:
# due to the noise, also the states '01' and '10' may be populated!
print(result.get_counts())
else: # pragma: no cover
print(result.to_dict()["error"])
|
https://github.com/wrlee7609/hybrid_quantum_gap_estimation
|
wrlee7609
|
# Ignore warning message
import warnings
warnings.filterwarnings("ignore")
# Import python libraries
import math, json
import numpy as np
from numpy import pi
from numpy.fft import fft, rfft
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from matplotlib import colors
# Import Qiskit libraries
import qiskit
import qiskit_aer.noise as noise
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ, Aer, transpile, execute
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel, depolarizing_error
from qiskit.result import marginal_counts
# Load IBMQ account
provider = IBMQ.load_account()
# Set up parameters
Nc = 4 # number of spins: N (= 2, 3, 4, 5)
g = 0.4 # dimensionless Ising coupling: J/h (= 0.2, 0.4, 0.6, 0.8)
eta = 0.3 # dimensionless broadening: \eta/h (= 0.02, 0.1, 0.2, 0.3)
dw = 0.25*eta # dimensionless unit of discrete frequency: \delta\omega / h
L = 2*math.ceil(7.0/dw) # count of Fourier components: L
dt = 2*pi/L/dw # dimensionless unit of discrete time: h \delta t
M = 16 # Trotter depth cutoff: M
theta = 0.27*pi # input qubit orientation: \theta
prob = 0.005 # probability for depolarizing noise
shots = 1024 # count of measurement shots
# Define the bit string (00...0) as a reference for thr initial state
s = []
for j in range (Nc):
s.append('0')
str1 = ""
InQ = str1.join(s)
# Define discrete frequencies
frequency = [(j-L/2)*dw for j in range(L+1)]
with open('data_frequency', 'w') as f:
f.write(json.dumps(frequency))
# Define quantum circuits
def Circuit_TFIM (Nc,g,theta,M,dt,j):
# Apply y-rotation gates (with clockwise orientation) for basis change
for n in range (Nc):
qc.ry(theta, qreg[n])
# Iterate Trotter steps
for m in range (M):
# Apply a sequence of unitary gates for time evolution
for n in range (Nc):
qc.rx(-2*j*dt/M, qreg[n])
for n in range (Nc-1):
qc.rzz(-2*g*j*dt/M, qreg[n], qreg[n+1])
# Apply y-rotation gates (with counterclockwise orientation) for basis change back
for n in range (Nc):
qc.ry(-theta, qreg[n])
# Define the objective function for curve fitting of the Lorentzian function
def objective (x, a0, a1):
return a0 + a1 / (x**2 + eta**2)
# Print the start message
print("simulation type: ideal (noiseless)")
# Loop for causal (i=0) and anti-causal (i=1) processes
for i in range (2):
# Print the message
print("...running")
# Initialize array
propagator = []
# Loop for Fourier components
for j in range (L):
# Initialize a set of quantum/classical registers
qreg = QuantumRegister(Nc, 'q')
creg = ClassicalRegister(Nc, 'c')
qc = QuantumCircuit(qreg, creg)
# Apply a sequence of quantum circuits
Circuit_TFIM (Nc,g,theta,M,(-1)**i*dt,j)
# Measure qubits
qc.measure(qreg, creg)
# Perform quantum simulation on the IBMQ Aer simulator
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, simulator, shots = shots).result()
counts = result.get_counts()
# Construct a time series of propagators with each component being the probability for (00...0)
if InQ in counts:
propagator.append(dt*np.exp(-eta*j*dt)*counts[InQ]/shots)
else:
propagator.append(0)
# Print the end message for each step
print(j+1, end="\r")
# Flatten array
propagator = np.ravel(propagator)
# Find the many-body spectral function via discreate fast Fourier transform
if i == 0:
spectral_function_0r = np.real(np.fft.ifft(propagator))*L/2.0/pi
spectral_function_1r = np.append(spectral_function_0r[int(L/2):L], spectral_function_0r[0:int(L/2)+1])
else:
spectral_function_0a = np.real(np.fft.fft(propagator))/2.0/pi
spectral_function_1a = np.append(spectral_function_0a[int(L/2):L], spectral_function_0a[0:int(L/2)+1])
# Find the many-body spectral function via discreate fast Fourier transform
spectral_function_2 = [spectral_function_1r[j] + spectral_function_1a[j] for j in range(L+1)]
# Truncate the lists in the range [-\eta,\eta]
frequency_truncated = [frequency[j] for j in range(math.ceil(L/2-eta/dw),math.ceil(L/2+1+eta/dw))]
spectral_function_truncated = [spectral_function_2[j] for j in range(math.ceil(L/2-eta/dw),math.ceil(L/2+1+eta/dw))]
# Curve fitting for the Lorentzian function
popt, _ = curve_fit(objective, frequency_truncated, spectral_function_truncated)
a0, a1 = popt
# Subtract the zeto peak from the manu-body spectral function
spectral_function = [spectral_function_2[j] - a1 / (frequency[j]**2 + eta**2) for j in range(L+1)]
# Save data
with open('data_spectral_function_N%s_g%sp%s_eta%sp%s_M%s_theta%sp%s_ideal' %
(int(Nc),int(g),str(g).split(".")[-1],int(eta),str(eta).split(".")[-1],\
int(M),int(theta/pi),str(theta/pi).split(".")[-1]), 'w') as f:
f.write(json.dumps(spectral_function))
# Print the end message
print("...completed")
# Print the start message
print("simulation type: 2-qubit depolarizing noise")
# Build the custom noise model for 2-qubit depolarizing noise
noise_model = noise.NoiseModel()
error_gate = noise.depolarizing_error(prob, 2)
noise_model.add_all_qubit_quantum_error(error_gate, ['rzz'])
basis_gates = noise_model.basis_gates
# Loop for causal (i=0) and anti-causal (i=1) processes
for i in range (2):
# Print the message
print("...running")
# Initialize array
propagator = []
# Loop for Fourier components
for j in range (L):
# Initialize a set of quantum/classical registers
qreg = QuantumRegister(Nc, 'q')
creg = ClassicalRegister(Nc, 'c')
qc = QuantumCircuit(qreg, creg)
# Apply a sequence of quantum circuits
Circuit_TFIM (Nc,g,theta,M,(-1)**i*dt,j)
# Measure qubits
qc.measure(qreg, creg)
# Perform quantum simulation on the IBMQ Aer simulator
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, simulator, noise_model = noise_model, basis_gates = basis_gates, shots = shots).result()
counts = result.get_counts()
# Construct a time series of propagators with each component being the probability for (00...0)
if InQ in counts:
propagator.append(dt*np.exp(-eta*j*dt)*counts[InQ]/shots)
else:
propagator.append(0)
# Print the end message for each step
print(j+1, end="\r")
# Flatten array
propagator = np.ravel(propagator)
# Find the many-body spectral function via discreate fast Fourier transform
if i == 0:
spectral_function_0r = np.real(np.fft.ifft(propagator))*L/2.0/pi
spectral_function_1r = np.append(spectral_function_0r[int(L/2):L], spectral_function_0r[0:int(L/2)+1])
else:
spectral_function_0a = np.real(np.fft.fft(propagator))/2.0/pi
spectral_function_1a = np.append(spectral_function_0a[int(L/2):L], spectral_function_0a[0:int(L/2)+1])
# Find the many-body spectral function via discreate fast Fourier transform
spectral_function_2 = [spectral_function_1r[j] + spectral_function_1a[j] for j in range(L+1)]
# Truncate the lists in the range [-\eta,\eta]
frequency_truncated = [frequency[j] for j in range(math.ceil(L/2-eta/dw),math.ceil(L/2+1+eta/dw))]
spectral_function_truncated = [spectral_function_2[j] for j in range(math.ceil(L/2-eta/dw),math.ceil(L/2+1+eta/dw))]
# Curve fitting for the Lorentzian function
popt, _ = curve_fit(objective, frequency_truncated, spectral_function_truncated)
a0, a1 = popt
# Subtract the zeto peak from the manu-body spectral function
spectral_function = [spectral_function_2[j] - a1 / (frequency[j]**2 + eta**2) for j in range(L+1)]
# Save data
with open('data_spectral_function_N%s_g%sp%s_eta%sp%s_M%s_theta%sp%s_depolarizing' %
(int(Nc),int(g),str(g).split(".")[-1],int(eta),str(eta).split(".")[-1],\
int(M),int(theta/pi),str(theta/pi).split(".")[-1]), 'w') as f:
f.write(json.dumps(spectral_function))
# Print the end message
print("...completed")
# Print the start message
print("simulation type: device backend noise")
# Build noise model from backend calibration data
backend = provider.get_backend("ibmq_manila")
noise_model = NoiseModel.from_backend(backend)
coupling_map = backend.configuration().coupling_map
basis_gates = noise_model.basis_gates
# Loop for causal (i=0) and anti-causal (i=1) processes
for i in range (2):
# Print the message
print("...running")
# Initialize array
propagator = []
# Loop for Fourier components
for j in range (L):
# Initialize a set of quantum/classical registers
qreg = QuantumRegister(Nc, 'q')
creg = ClassicalRegister(Nc, 'c')
qc = QuantumCircuit(qreg, creg)
# Apply a sequence of quantum circuits
Circuit_TFIM (Nc,g,theta,M,(-1)**i*dt,j)
# Measure qubits
qc.measure(qreg, creg)
# Perform quantum simulation on the IBMQ Aer simulator
simulator = Aer.get_backend('qasm_simulator')
qc_trans = transpile(qc, backend, optimization_level = 1, initial_layout = [k for k in range(Nc)])
result = execute(qc_trans, simulator, noise_model = noise_model, coupling_map = coupling_map,\
basis_gates = basis_gates, shots = shots).result()
counts = result.get_counts()
# Construct a time series of propagators with each component being the probability for (00...0)
if InQ in counts:
propagator.append(dt*np.exp(-eta*j*dt)*counts[InQ]/shots)
else:
propagator.append(0)
# Print the end message for each step
print(j+1, end="\r")
# Flatten array
propagator = np.ravel(propagator)
# Find the many-body spectral function via discreate fast Fourier transform
if i == 0:
spectral_function_0r = np.real(np.fft.ifft(propagator))*L/2.0/pi
spectral_function_1r = np.append(spectral_function_0r[int(L/2):L], spectral_function_0r[0:int(L/2)+1])
else:
spectral_function_0a = np.real(np.fft.fft(propagator))/2.0/pi
spectral_function_1a = np.append(spectral_function_0a[int(L/2):L], spectral_function_0a[0:int(L/2)+1])
# Find the many-body spectral function via discreate fast Fourier transform
spectral_function_2 = [spectral_function_1r[j] + spectral_function_1a[j] for j in range(L+1)]
# Truncate the lists in the range [-\eta,\eta]
frequency_truncated = [frequency[j] for j in range(math.ceil(L/2-eta/dw),math.ceil(L/2+1+eta/dw))]
spectral_function_truncated = [spectral_function_2[j] for j in range(math.ceil(L/2-eta/dw),math.ceil(L/2+1+eta/dw))]
# Curve fitting for the Lorentzian function
popt, _ = curve_fit(objective, frequency_truncated, spectral_function_truncated)
a0, a1 = popt
# Subtract the zeto peak from the manu-body spectral function
spectral_function = [spectral_function_2[j] - a1 / (frequency[j]**2 + eta**2) for j in range(L+1)]
# Save data
with open('data_spectral_function_N%s_g%sp%s_eta%sp%s_M%s_theta%sp%s_noisemodel' %
(int(Nc),int(g),str(g).split(".")[-1],int(eta),str(eta).split(".")[-1],\
int(M),int(theta/pi),str(theta/pi).split(".")[-1]), 'w') as f:
f.write(json.dumps(spectral_function))
# Print the end message
print("...completed")
# Print the start message
print("simulation type: real device\n...running")
# Initialize a set of quantum/classical registers
qreg = QuantumRegister(Nc, 'q')
creg = ClassicalRegister(Nc*L*2, 'c')
qc = QuantumCircuit(qreg, creg)
# Loop for causal (i=0) and anti-causal (i=1) processes
for i in range (2):
# Loop for Fourier components (retarded part)
for j in range (L):
# Reset quantum registers
qc.reset(qreg)
# Apply a sequence of quantum circuits
Circuit_TFIM (Nc,g,theta,M,(-1)**i*dt,j)
# Perform mid-circuit measurement
assign_qubits = [Nc*L*i + Nc*j + k for k in range(Nc)]
qc.measure(qreg, assign_qubits)
# Perform quantum simulation on the IBMQ device
backend = provider.get_backend("ibmq_manila")
qc_trans = transpile(qc, backend, optimization_level = 1, initial_layout = [k for k in range(Nc)])
result = execute(qc_trans, backend, shots = shots).result()
# Loop for causal (i=0) and anti-causal (i=1) processes
for i in range (2):
# Initialize array
propagator = []
# Loop for Fourier components
for j in range (L):
# Obtain marginal measurement counts from mid-circuit measurement
assign_qubits = [Nc*L*i + Nc*j + k for k in range(Nc)]
counts = marginal_counts(result, indices = assign_qubits).get_counts()
# Construct a time series of propagators with each component being the probability for (00...0)
if InQ in counts:
propagator.append(dt*np.exp(-eta*j*dt)*counts[InQ]/shots)
else:
propagator.append(0)
# Print the end message for each step
print(j+1, end="\r")
# Flatten array
propagator = np.ravel(propagator)
# Find the many-body spectral function via discreate fast Fourier transform
if i == 0:
spectral_function_0r = np.real(np.fft.ifft(propagator))*L/2.0/pi
spectral_function_1r = np.append(spectral_function_0r[int(L/2):L], spectral_function_0r[0:int(L/2)+1])
else:
spectral_function_0a = np.real(np.fft.fft(propagator))/2.0/pi
spectral_function_1a = np.append(spectral_function_0a[int(L/2):L], spectral_function_0a[0:int(L/2)+1])
# Find the many-body spectral function via discreate fast Fourier transform
spectral_function_2 = [spectral_function_1r[j] + spectral_function_1a[j] for j in range(L+1)]
# Truncate the lists in the range [-\eta,\eta]
frequency_truncated = [frequency[j] for j in range(math.ceil(L/2-eta/dw),math.ceil(L/2+1+eta/dw))]
spectral_function_truncated = [spectral_function_2[j] for j in range(math.ceil(L/2-eta/dw),math.ceil(L/2+1+eta/dw))]
# Curve fitting for the Lorentzian function
popt, _ = curve_fit(objective, frequency_truncated, spectral_function_truncated)
a0, a1 = popt
# Subtract the zeto peak from the manu-body spectral function
spectral_function = [spectral_function_2[j] - a1 / (frequency[j]**2 + eta**2) for j in range(L+1)]
# Save data
with open('data_spectral_function_N%s_g%sp%s_eta%sp%s_M%s_theta%sp%s_realdevice' %
(int(Nc),int(g),str(g).split(".")[-1],int(eta),str(eta).split(".")[-1],\
int(M),int(theta/pi),str(theta/pi).split(".")[-1]), 'w') as f:
f.write(json.dumps(spectral_function))
# Print the end message
print("...completed")
# Load data for frequency
with open('data_frequency' , 'r') as f:
frequency = json.loads(f.read())
# Load data for spectral function
with open('data_spectral_function_N%s_g%sp%s_eta%sp%s_M%s_theta%sp%s_ideal' %
(int(Nc),int(g),str(g).split(".")[-1],int(eta),str(eta).split(".")[-1],\
int(M),int(theta/pi),str(theta/pi).split(".")[-1]), 'r') as f:
spectral_function_ideal = json.loads(f.read())
with open('data_spectral_function_N%s_g%sp%s_eta%sp%s_M%s_theta%sp%s_depolarizing' %
(int(Nc),int(g),str(g).split(".")[-1],int(eta),str(eta).split(".")[-1],\
int(M),int(theta/pi),str(theta/pi).split(".")[-1]), 'r') as f:
spectral_function_depolarizing = json.loads(f.read())
with open('data_spectral_function_N%s_g%sp%s_eta%sp%s_M%s_theta%sp%s_noisemodel' %
(int(Nc),int(g),str(g).split(".")[-1],int(eta),str(eta).split(".")[-1],\
int(M),int(theta/pi),str(theta/pi).split(".")[-1]), 'r') as f:
spectral_function_noisemodel = json.loads(f.read())
with open('data_spectral_function_N%s_g%sp%s_eta%sp%s_M%s_theta%sp%s_realdevice' %
(int(Nc),int(g),str(g).split(".")[-1],int(eta),str(eta).split(".")[-1],\
int(M),int(theta/pi),str(theta/pi).split(".")[-1]), 'r') as f:
spectral_function_realdevice = json.loads(f.read())
# Plot simulation data
plt.plot(frequency, spectral_function_ideal, label = "ideal", color = 'red', ls = '-')
plt.plot(frequency, spectral_function_depolarizing, label = "2-qubit depolarizing noise", color = 'green', ls = ':')
plt.plot(frequency, spectral_function_noisemodel, label = "device backend noise", color = 'blue', ls = '--')
plt.plot(frequency, spectral_function_realdevice, label = "real device", color = 'purple', ls = '-.')
plt.xlim([0, 4])
plt.xlabel("$\omega$/h")
plt.ylabel("$h\cdot\mathcal{A}(\omega)$")
plt.legend()
plt.savefig('Fig_spectral_function_N%s_g%sp%s_eta%sp%s_M%s_theta%sp%s.pdf' %
(int(Nc),int(g),str(g).split(".")[-1],int(eta),str(eta).split(".")[-1],\
int(M),int(theta/pi),str(theta/pi).split(".")[-1]))
|
https://github.com/DaisukeIto-ynu/KosakaQ_client
|
DaisukeIto-ynu
|
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 24 09:39:52 2022
@author: Daisuke Ito
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import differential_evolution
from qiskit import QuantumCircuit
import itertools
import requests
import json
import sys
sys.path.append("..")
from kosakaq_job import KosakaQExperimentJob
class randomized_benchmarking:
def __init__(self, backend, length_vector = [1, 10, 20, 50, 75, 100, 125, 150, 175, 200], repetition =30, shots = 4096, seed = None, interleaved = ""):
self.backend = backend
self.length_vector = length_vector
self.rep = repetition
self.shots = shots
self.seed = seed
self.interleaved = interleaved
if not (interleaved == ""):
if interleaved == "X":
self.interleaved_gate = 1
elif interleaved == "Y":
self.interleaved_gate = 2
elif interleaved == "Z":
self.interleaved_gate = 3
else:
raise
self.gate_sequence = []
self.circuits = []
self.result_data = None
self.ops = None
self.Cliford_trans = \
np.array([[ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.,
11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21.,
22., 23.],
[ 1., 0., 3., 2., 6., 7., 4., 5., 11., 10., 9.,
8., 13., 12., 18., 19., 22., 23., 14., 15., 21., 20.,
16., 17.],
[ 2., 3., 0., 1., 7., 6., 5., 4., 10., 11., 8.,
9., 20., 21., 15., 14., 23., 22., 19., 18., 12., 13.,
17., 16.],
[ 3., 2., 1., 0., 5., 4., 7., 6., 9., 8., 11.,
10., 21., 20., 19., 18., 17., 16., 15., 14., 13., 12.,
23., 22.],
[ 4., 7., 5., 6., 11., 8., 9., 10., 2., 3., 1.,
0., 22., 17., 21., 12., 14., 18., 13., 20., 23., 16.,
15., 19.],
[ 5., 6., 4., 7., 10., 9., 8., 11., 1., 0., 2.,
3., 23., 16., 12., 21., 19., 15., 20., 13., 22., 17.,
18., 14.],
[ 6., 5., 7., 4., 8., 11., 10., 9., 3., 2., 0.,
1., 16., 23., 20., 13., 18., 14., 12., 21., 17., 22.,
19., 15.],
[ 7., 4., 6., 5., 9., 10., 11., 8., 0., 1., 3.,
2., 17., 22., 13., 20., 15., 19., 21., 12., 16., 23.,
14., 18.],
[ 8., 9., 11., 10., 1., 3., 2., 0., 7., 4., 5.,
6., 19., 14., 22., 16., 20., 12., 23., 17., 15., 18.,
13., 21.],
[ 9., 8., 10., 11., 2., 0., 1., 3., 6., 5., 4.,
7., 14., 19., 23., 17., 13., 21., 22., 16., 18., 15.,
20., 12.],
[ 10., 11., 9., 8., 3., 1., 0., 2., 4., 7., 6.,
5., 18., 15., 17., 23., 12., 20., 16., 22., 14., 19.,
21., 13.],
[ 11., 10., 8., 9., 0., 2., 3., 1., 5., 6., 7.,
4., 15., 18., 16., 22., 21., 13., 17., 23., 19., 14.,
12., 20.],
[ 12., 13., 21., 20., 18., 19., 14., 15., 22., 17., 23.,
16., 1., 0., 4., 5., 8., 10., 6., 7., 2., 3.,
11., 9.],
[ 13., 12., 20., 21., 14., 15., 18., 19., 16., 23., 17.,
22., 0., 1., 6., 7., 11., 9., 4., 5., 3., 2.,
8., 10.],
[ 14., 19., 15., 18., 22., 16., 23., 17., 20., 21., 12.,
13., 8., 9., 2., 0., 6., 4., 1., 3., 10., 11.,
7., 5.],
[ 15., 18., 14., 19., 17., 23., 16., 22., 12., 13., 20.,
21., 10., 11., 0., 2., 5., 7., 3., 1., 8., 9.,
4., 6.],
[ 16., 23., 22., 17., 12., 21., 20., 13., 19., 14., 15.,
18., 5., 6., 8., 11., 3., 0., 10., 9., 7., 4.,
1., 2.],
[ 17., 22., 23., 16., 21., 12., 13., 20., 14., 19., 18.,
15., 4., 7., 9., 10., 0., 3., 11., 8., 6., 5.,
2., 1.],
[ 18., 15., 19., 14., 16., 22., 17., 23., 21., 20., 13.,
12., 11., 10., 3., 1., 4., 6., 0., 2., 9., 8.,
5., 7.],
[ 19., 14., 18., 15., 23., 17., 22., 16., 13., 12., 21.,
20., 9., 8., 1., 3., 7., 5., 2., 0., 11., 10.,
6., 4.],
[ 20., 21., 13., 12., 19., 18., 15., 14., 17., 22., 16.,
23., 3., 2., 7., 6., 10., 8., 5., 4., 0., 1.,
9., 11.],
[ 21., 20., 12., 13., 15., 14., 19., 18., 23., 16., 22.,
17., 2., 3., 5., 4., 9., 11., 7., 6., 1., 0.,
10., 8.],
[ 22., 17., 16., 23., 13., 20., 21., 12., 15., 18., 19.,
14., 7., 4., 11., 8., 2., 1., 9., 10., 5., 6.,
0., 3.],
[ 23., 16., 17., 22., 20., 13., 12., 21., 18., 15., 14.,
19., 6., 5., 10., 9., 1., 2., 8., 11., 4., 7.,
3., 0.]])
def make_sequence(self):
self.gate_sequence = []
for i in range(self.rep):
self.gate_sequence.append([])
for gate_num in self.length_vector:
if self.seed is not None:
np.random.seed(self.seed)
gate_sequence_fwd = np.random.randint(0,23,gate_num).tolist()
else:
gate_sequence_fwd = np.random.randint(0,23,gate_num).tolist()
if self.interleaved:
temp = [[x,self.interleaved_gate] for x in gate_sequence_fwd]
gate_sequence_fwd = list(itertools.chain.from_iterable(temp))
n_gate = 0
for m in gate_sequence_fwd:
n_gate = int(self.Cliford_trans[m,n_gate])
self.Cliford_last = n_gate
self.Cliford_last_dag = np.where(self.Cliford_trans[:,self.Cliford_last] == 0)[0][0]
self.gate_sequence[i].append(gate_sequence_fwd+[self.Cliford_last_dag.item()])
self._make_circuit()
def run(self):
access_token = self.backend.provider.access_token
data = {
"length_vector":self.length_vector,
"gate_sequence":self.gate_sequence,
"rep":self.rep,
"shots":self.shots,
"seed":self.seed,
"interleaved":self.interleaved
}
data = json.dumps(data)
kosakaq_json ={
'experiment': 'experiment',
'data': data,
'access_token': access_token,
'repetitions': 1,
'backend': self.backend.name,
}
header = {
"Authorization": "token " + access_token,
}
res = requests.post("http://192.168.11.85/job/", data=kosakaq_json, headers=header)
response = res.json()
res.raise_for_status()
self.job = KosakaQExperimentJob(self.backend, response['id'], access_token=self.backend.provider.access_token, qobj=data)
def result(self):
access_token = self.backend.provider.access_token
# get result
header = {
"Authorization": "Token " + access_token
}
result = requests.get(
self.backend.url + ('/job/'),
headers=header,
params={"jobid": self.job._job_id}
).json()
if result["qobjlist"][0][0]["result"] is None:
data = []
else:
data = [d.split() for d in result["qobjlist"][0][0]["result"].split("\n")]
data.pop(-1)
length = len(self.length_vector)
rep = len(data)//length
rem = len(data)%length
if (result['joblist'][0]['jobstatus'] == "ERROR") or (result['joblist'][0]['jobstatus'] == "QUEUED"):
raise
if not (rep == self.rep) and (result['joblist'][0]['jobstatus'] == "RUNNING"):
print("This job is running.")
result_data = []
for i in range(rep):
result_data.append([data[j] for j in range(i*length,(i+1)*length)])
result_data.append([data[j] for j in range(rep*length,rep*length+rem)])
self.result_data = result_data
# fitting
if rep>0:
# data
time = self.length_vector
self.sum_data = []
self.ave_data = []
print(length)
print(rep)
print(result_data)
for i in range(length):
sum_rep = 0
for j in range(rep):
sum_rep += int(result_data[j][i][0])
self.sum_data.append(sum_rep/self.shots)
self.ave_data.append(sum_rep/(self.shots*rep))
# fitting func
def exp_curve(parameter):
a, b, p = parameter
return a * (p**(time)) + b
def fit_func(parameter):
ycal = exp_curve(parameter)
residual = ycal - ave_data
return sum(abs(residual))
# optimize
ave_data = self.ave_data
bound = [(0,1),(0,10),(0.001,50)]
opts = differential_evolution(fit_func, bounds = bound)
self.opt = opts.x
print(f'a = {self.opt[0]}')
print(f'b = {self.opt[1]}')
print(f'p = {self.opt[2]}')
if self.interleaved == "":
print(f'F = {(self.opt[2]+1)/2}')
else:
print("interleavedの場合、フィデリティの計算には、interleavedではない時のデータが必要")
def plot(self):
time = np.linspace(0.01, self.length_vector[-1], 1000)
def exp_curve(parameter):
a, b, p = parameter
return a * (p**(time)) + b
plt.figure(dpi=1000)
plt.plot(time, exp_curve(self.opt), color = 'blue', label='fitting')
for i in range(len(self.result_data)):
for j in range(len(self.result_data[i])):
if i == 0 and j ==0:
pass
else:
plt.plot(self.length_vector[j], int(self.result_data[i][j][0])/self.shots, marker='.', ls='', color = 'gray')
plt.plot(self.length_vector[0], int(self.result_data[0][0][0])/self.shots, marker='.', ls='', color = 'gray', label='data')
plt.plot(self.length_vector, self.ave_data, marker='x', color = 'orange', ls='--', label='average')
plt.legend()
plt.title('randomized benchmarking')
plt.ylabel('Ground State Population')
plt.xlabel('Clifford Length')
plt.ylim(-0.1,1.1)
plt.show()
def set_job(self, job: KosakaQExperimentJob):
self.job = job
self.backend = job.backend()
data = json.loads(job.qobj["data"])
self.length_vector = data["length_vector"]
self.rep = data["rep"]
self.shots = data["shots"]
self.seed = data["seed"]
if not (data["interleaved"] == ""):
if data["interleaved"] == "X":
self.interleaved_gate = 1
elif data["interleaved"] == "Y":
self.interleaved_gate = 2
elif data["interleaved"] == "Z":
self.interleaved_gate = 3
else:
raise
self.gate_sequence = []
self.circuits = []
self.result_data = None
self.ops = None
def _make_circuit(self):
self.circuits = []
for rep, i in zip(self.gate_sequence,range(self.rep)):
self.circuits.append([])
for gates in rep:
qc = QuantumCircuit(1,1)
for gate in gates:
if gate == 0:
qc.i(0)
elif gate == 1:
qc.x(0)
elif gate == 2:
qc.y(0)
elif gate == 3:
qc.z(0)
elif gate == 4:
qc.h(0)
qc.s(0)
qc.h(0)
qc.s(0)
qc.z(0)
elif gate == 5:
qc.h(0)
qc.s(0)
qc.h(0)
qc.s(0)
elif gate == 6:
qc.h(0)
qc.s(0)
qc.h(0)
qc.s(0)
qc.y(0)
elif gate == 7:
qc.h(0)
qc.s(0)
qc.h(0)
qc.s(0)
qc.x(0)
elif gate == 8:
qc.h(0)
qc.s(0)
qc.z(0)
elif gate == 9:
qc.h(0)
qc.s(0)
elif gate == 10:
qc.h(0)
qc.s(0)
qc.x(0)
elif gate == 11:
qc.h(0)
qc.s(0)
qc.y(0)
elif gate == 12:
qc.s(0)
qc.h(0)
qc.s(0)
qc.x(0)
elif gate == 13:
qc.s(0)
qc.h(0)
qc.s(0)
elif gate == 14:
qc.h(0)
qc.z(0)
elif gate == 15:
qc.h(0)
qc.x(0)
elif gate == 16:
qc.sx(0)
qc.h(0)
qc.z(0)
qc.sxdg(0)
elif gate == 17:
qc.sx(0)
qc.h(0)
qc.x(0)
qc.sxdg(0)
elif gate == 18:
qc.h(0)
qc.z(0)
qc.x(0)
elif gate == 19:
qc.h(0)
qc.x(0)
qc.x(0)
elif gate == 20:
qc.sx(0)
qc.y(0)
elif gate == 21:
qc.sxdg(0)
qc.y(0)
elif gate == 22:
qc.s(0)
qc.x(0)
elif gate == 23:
qc.sxdg(0)
qc.h(0)
qc.z(0)
qc.sxdg(0)
qc.barrier(0)
qc.measure(0,0)
self.circuits[i].append(qc)
|
https://github.com/samuraigab/Quantum-Basic-Algorithms
|
samuraigab
|
# !pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org Ipython
# pip install -U notebook-as-pdf
from IPython.display import display, Latex
from IPython.display import Image
from qiskit import *
from qiskit.visualization import *
from qiskit.quantum_info import Statevector
import numpy as np
import warnings
# warnings.filterwarnings("ignore", category=DepriciationWarning)
warnings.filterwarnings("ignore", category=UserWarning)
qc = QuantumCircuit(3)
qc.ry (np.pi/4, 0) # optional, we want to transfer state 1 in this example
save = Statevector.from_instruction(qc)
qc.draw('mpl')
simulator = Aer.get_backend('statevector_simulator')
result = execute(qc, backend= simulator, shots = 100000).result().get_statevector()
print(f'Amplitudes alpha e beta são: [{np.round(np.cos(np.pi/8)**2,5)} {np.round(np.sin(np.pi/8)**2,5)}]')
plot_bloch_multivector(result)
alice = QuantumRegister(2, 'a')
bob = QuantumRegister(1,'b')
cr_alice = ClassicalRegister(2, 'ca')
cr_bob = ClassicalRegister(1,'cb')
qc = QuantumCircuit(alice,bob,cr_alice, cr_bob)
qc.ry(np.pi/4, alice[0]) # optional, we want to transfer state 1 in this example
qc.barrier()
qc.draw('mpl')
qc.h(alice[1])
qc.cx(alice[1],bob[0])
qc.barrier()
qc.draw('mpl')
qc.cx(alice[0],alice[1])
qc.h(alice[0])
qc.barrier()
qc.draw('mpl')
qc.measure(alice, cr_alice)
qc.barrier()
qc.draw('mpl')
qc.cx(alice[1], bob[0])
qc.cz(alice[0], bob[0])
# qc.measure(bob, cr_bob)
qc.draw('mpl')
simulator = Aer.get_backend('statevector_simulator')
result = execute(qc, backend= simulator, shots = 10000).result().get_statevector()
# plot_histogram(result)
states = [format(i,'0'+str(n)+'b')[::-1] for i in range(2**n)]
print(states)
res = [round(i.real, 5) for i in result]
array_to_latex(result)
n = 3
states = [format(i,'0'+str(n)+'b')[::-1] for i in range(2**n)]
medida = [(j,i) for i,j in zip(res,states) if i > 0]
print(f'\n\nAlice mediu {medida[0][0][:2]} o estado que está com Bob é [{medida[0][1]} {medida[1][1]}]\n\n')
alice = QuantumRegister(2, 'a')
bob = QuantumRegister(1,'b')
cr_alice = ClassicalRegister(2, 'ca')
cr_bob = ClassicalRegister(1,'cb')
qc = QuantumCircuit(alice,bob,cr_alice, cr_bob)
qc.ry(np.pi/4, alice[0]) # optional, we want to transfer state 1 in this example
qc.barrier()
save1 = Statevector.from_instruction(qc)
qc.h(alice[1])
qc.cx(alice[1],bob[0])
qc.barrier()
qc.cx(alice[0],alice[1])
qc.h(alice[0])
qc.barrier()
# qc.measure(alice, cr_alice)
qc.barrier()
qc.cx(alice[1], bob[0])
qc.cz(alice[0], bob[0])
save2 = Statevector.from_instruction(qc)
qc.measure(bob, cr_bob)
qc.draw('mpl')
plot_bloch_multivector(save1)
plot_bloch_multivector(save2)
alice = QuantumRegister(2, 'a')
bob = QuantumRegister(1,'b')
cr_alice = ClassicalRegister(2, 'ca')
cr_bob = ClassicalRegister(1,'cb')
qc = QuantumCircuit(alice,bob,cr_alice, cr_bob)
qc.ry(np.pi/4, alice[0]) # optional, we want to transfer state 1 in this example
qc.barrier()
qc.h(alice[1])
qc.cx(alice[1],bob[0])
qc.barrier()
qc.cx(alice[0],alice[1])
qc.h(alice[0])
qc.barrier()
qc.measure(alice, cr_alice)
qc.barrier()
qc.cx(alice[1], bob[0])
qc.cz(alice[0], bob[0])
qc.measure(bob, cr_bob)
qc.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
shots = 100000
result = execute(qc, backend=simulator, shots=shots).result().get_counts()
from qiskit.visualization import plot_histogram
plot_histogram(result)
prob0 = 0
prob1 = 0
for i in result.keys():
if i[0] == '0':
prob0+= result[i]
if i[0] == '1':
prob1+= result[i]
print(prob0/shots,prob1/shots)
print(np.round(np.cos(np.pi/8)**2,5), np.round(np.sin(np.pi/8)**2,5))
np.cos(np.pi/8)**2
simulator = Aer.get_backend('statevector_simulator')
result = execute(qc, backend= simulator, shots = 10000).result().get_statevector()
# plot_histogram(result)
array_to_latex(result, prefix= '\\vert \psi \\rangle = ')
|
https://github.com/usamisaori/quantum-expressibility-entangling-capability
|
usamisaori
|
import sys
sys.path.append('../')
from circuits import sampleCircuitA, sampleCircuitB1, sampleCircuitB2,\
sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE,\
sampleCircuitF
from entanglement import Ent
import warnings
warnings.filterwarnings('ignore')
labels = [
'Circuit A', 'Circuit B1', 'Circuit B2', 'Circuit B3',
'Circuit C', 'Circuit D', 'Circuit E', 'Circuit F'
]
samplers = [
sampleCircuitA,
sampleCircuitB1,
sampleCircuitB2,
sampleCircuitB3,
sampleCircuitC,
sampleCircuitD,
sampleCircuitE,
sampleCircuitF
]
q = 4
for layer in range(1, 4):
print(f'qubtis: {q}')
print('-' * 25)
for (label, sampler) in zip(labels, samplers):
expr = Ent(sampler, layer=layer, epoch=3000)
print(f'{label}(layer={layer}): {expr}')
print()
|
https://github.com/khaledalam/QuantumComputingAndPrimesAndOthers
|
khaledalam
|
# Author: Khaled Alam(khaledalam.net@gmail.com)
'''
Guess binary string (secret) of length N in 1 shot only using quantum computing circuit!
~ by using clasical computers we need at least N shots to guess string (secret) of length N
~ by using quantum computer we need 1 shot to guess string (secret) of ANY length ( cool isn't it! ^^ )
'''
secret = '01000001' # `01000001` = `A`
from qiskit import *
n = len(secret)
qCircuit = QuantumCircuit(n+1, n) # n+1 qubits and n classical bits
qCircuit.x(n)
qCircuit.barrier()
qCircuit.h(range(n+1))
qCircuit.barrier()
for ii, OZ in enumerate(reversed(secret)):
if OZ == '1':
qCircuit.cx(ii, n)
qCircuit.barrier()
qCircuit.h(range(n+1))
qCircuit.barrier()
qCircuit.measure(range(n), range(n))
%matplotlib inline
qCircuit.draw(output='mpl')
# run on simulator
simulator = Aer.get_backend('qasm_simulator')
result = execute(qCircuit, backend=simulator, shots=1).result() # only 1 shot
from qiskit.visualization import plot_histogram
plot_histogram(
result.get_counts(qCircuit)
)
|
https://github.com/ShabaniLab/q-camp
|
ShabaniLab
|
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from numpy.random import randint
import numpy as np
print("Imports Successful")
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
qc.barrier()
# Alice now sends the qubit to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
# Alice now sends the qubit to Bob
# but Eve intercepts and tries to read it
qc.measure(0, 0)
qc.barrier()
# Eve then passes this on to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
np.random.seed(seed=0)
n = 100
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
print(alice_bits)
np.random.seed(seed=0)
n = 100
## Step 1
#Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
print(alice_bases)
def encode_message(bits, bases):
message = []
for i in range(n):
qc = QuantumCircuit(1,1)
if bases[i] == 0: # Prepare qubit in Z-basis
if bits[i] == 0:
pass
else:
qc.x(0)
else: # Prepare qubit in X-basis
if bits[i] == 0:
qc.h(0)
else:
qc.x(0)
qc.h(0)
qc.barrier()
message.append(qc)
return message
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
print('bit = %i' % alice_bits[0])
print('basis = %i' % alice_bases[0])
message[0].draw()
print('bit = %i' % alice_bits[4])
print('basis = %i' % alice_bases[4])
message[4].draw()
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
print(bob_bases)
def measure_message(message, bases):
backend = Aer.get_backend('aer_simulator')
measurements = []
for q in range(n):
if bases[q] == 0: # measuring in Z-basis
message[q].measure(0,0)
if bases[q] == 1: # measuring in X-basis
message[q].h(0)
message[q].measure(0,0)
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(message[q], shots=1, memory=True)
result = aer_sim.run(qobj).result()
measured_bit = int(result.get_memory()[0])
measurements.append(measured_bit)
return measurements
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
message[0].draw()
message[6].draw()
print(bob_results)
def remove_garbage(a_bases, b_bases, bits):
good_bits = []
for q in range(n):
if a_bases[q] == b_bases[q]:
# If both used the same basis, add
# this to the list of 'good' bits
good_bits.append(bits[q])
return good_bits
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
print(alice_key)
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
print(bob_key)
def sample_bits(bits, selection):
sample = []
for i in selection:
# use np.mod to make sure the
# bit we sample is always in
# the list range
i = np.mod(i, len(bits))
# pop(i) removes the element of the
# list at index 'i'
sample.append(bits.pop(i))
return sample
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
## Step 5
sample_size = 15
bit_selection = randint(n, size=sample_size)
bob_sample = sample_bits(bob_key, bit_selection)
print(" bob_sample = " + str(bob_sample))
alice_sample = sample_bits(alice_key, bit_selection)
print("alice_sample = "+ str(alice_sample))
bob_sample == alice_sample
print(bob_key)
print(alice_key)
print("key length = %i" % len(alice_key))
np.random.seed(seed=3)
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
print(alice_bits)
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
print(alice_bases)
message[0].draw()
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
print(intercepted_message)
message[0].draw()
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
message[0].draw()
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
## Step 5
sample_size = 15
bit_selection = randint(n, size=sample_size)
bob_sample = sample_bits(bob_key, bit_selection)
print(" bob_sample = " + str(bob_sample))
alice_sample = sample_bits(alice_key, bit_selection)
print("alice_sample = "+ str(alice_sample))
bob_sample == alice_sample
n = 100
# Step 1
alice_bits = randint(2, size=n)
alice_bases = randint(2, size=n)
# Step 2
message = encode_message(alice_bits, alice_bases)
# Interception!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
# Step 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
# Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
# Step 5
sample_size = 15 # Change this to something lower and see if
# Eve can intercept the message without Alice
# and Bob finding out
bit_selection = randint(n, size=sample_size)
bob_sample = sample_bits(bob_key, bit_selection)
alice_sample = sample_bits(alice_key, bit_selection)
if bob_sample != alice_sample:
print("Eve's interference was detected.")
else:
print("Eve went undetected!")
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.draw('mpl')
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
r"""
Channel event manager for pulse schedules.
This module provides a `ChannelEvents` class that manages a series of instructions for a
pulse channel. Channel-wise filtering of the pulse program makes
the arrangement of channels easier in the core drawer function.
The `ChannelEvents` class is expected to be called by other programs (not by end-users).
The `ChannelEvents` class instance is created with the class method ``load_program``:
.. code-block:: python
event = ChannelEvents.load_program(sched, DriveChannel(0))
The `ChannelEvents` is created for a specific pulse channel and loosely assorts pulse
instructions within the channel with different visualization purposes.
Phase and frequency related instructions are loosely grouped as frame changes.
The instantaneous value of those operands are combined and provided as ``PhaseFreqTuple``.
Instructions that have finite duration are grouped as waveforms.
The grouped instructions are returned as an iterator by the corresponding method call:
.. code-block:: python
for t0, frame, instruction in event.get_waveforms():
...
for t0, frame_change, instructions in event.get_frame_changes():
...
The class method ``get_waveforms`` returns the iterator of waveform type instructions with
the ``PhaseFreqTuple`` (frame) at the time when instruction is issued.
This is because a pulse envelope of ``Waveform`` may be modulated with a
phase factor $exp(-i \omega t - \phi)$ with frequency $\omega$ and phase $\phi$ and
appear on the canvas. Thus, it is better to tell users in which phase and frequency
the pulse envelope is modulated from a viewpoint of program debugging.
On the other hand, the class method ``get_frame_changes`` returns a ``PhaseFreqTuple`` that
represents a total amount of change at that time because it is convenient to know
the operand value itself when we debug a program.
Because frame change type instructions are usually zero duration, multiple instructions
can be issued at the same time and those operand values should be appropriately
combined. In Qiskit Pulse we have set and shift type instructions for the frame control,
the set type instruction will be converted into the relevant shift amount for visualization.
Note that these instructions are not interchangeable and the order should be kept.
For example:
.. code-block:: python
sched1 = Schedule()
sched1 = sched1.insert(0, ShiftPhase(-1.57, DriveChannel(0))
sched1 = sched1.insert(0, SetPhase(3.14, DriveChannel(0))
sched2 = Schedule()
sched2 = sched2.insert(0, SetPhase(3.14, DriveChannel(0))
sched2 = sched2.insert(0, ShiftPhase(-1.57, DriveChannel(0))
In this example, ``sched1`` and ``sched2`` will have different frames.
On the drawer canvas, the total frame change amount of +3.14 should be shown for ``sched1``,
while ``sched2`` is +1.57. Since the `SetPhase` and the `ShiftPhase` instruction behave
differently, we cannot simply sum up the operand values in visualization output.
It should be also noted that zero duration instructions issued at the same time will be
overlapped on the canvas. Thus it is convenient to plot a total frame change amount rather
than plotting each operand value bound to the instruction.
"""
from __future__ import annotations
from collections import defaultdict
from collections.abc import Iterator
from qiskit import pulse, circuit
from qiskit.visualization.pulse_v2.types import PhaseFreqTuple, PulseInstruction
class ChannelEvents:
"""Channel event manager."""
_waveform_group = (
pulse.instructions.Play,
pulse.instructions.Delay,
pulse.instructions.Acquire,
)
_frame_group = (
pulse.instructions.SetFrequency,
pulse.instructions.ShiftFrequency,
pulse.instructions.SetPhase,
pulse.instructions.ShiftPhase,
)
def __init__(
self,
waveforms: dict[int, pulse.Instruction],
frames: dict[int, list[pulse.Instruction]],
channel: pulse.channels.Channel,
):
"""Create new event manager.
Args:
waveforms: List of waveforms shown in this channel.
frames: List of frame change type instructions shown in this channel.
channel: Channel object associated with this manager.
"""
self._waveforms = waveforms
self._frames = frames
self.channel = channel
# initial frame
self._init_phase = 0.0
self._init_frequency = 0.0
# time resolution
self._dt = 0.0
@classmethod
def load_program(cls, program: pulse.Schedule, channel: pulse.channels.Channel):
"""Load a pulse program represented by ``Schedule``.
Args:
program: Target ``Schedule`` to visualize.
channel: The channel managed by this instance.
Returns:
ChannelEvents: The channel event manager for the specified channel.
"""
waveforms = {}
frames = defaultdict(list)
# parse instructions
for t0, inst in program.filter(channels=[channel]).instructions:
if isinstance(inst, cls._waveform_group):
if inst.duration == 0:
# special case, duration of delay can be zero
continue
waveforms[t0] = inst
elif isinstance(inst, cls._frame_group):
frames[t0].append(inst)
return ChannelEvents(waveforms, frames, channel)
def set_config(self, dt: float, init_frequency: float, init_phase: float):
"""Setup system status.
Args:
dt: Time resolution in sec.
init_frequency: Modulation frequency in Hz.
init_phase: Initial phase in rad.
"""
self._dt = dt or 1.0
self._init_frequency = init_frequency or 0.0
self._init_phase = init_phase or 0.0
def get_waveforms(self) -> Iterator[PulseInstruction]:
"""Return waveform type instructions with frame."""
sorted_frame_changes = sorted(self._frames.items(), key=lambda x: x[0], reverse=True)
sorted_waveforms = sorted(self._waveforms.items(), key=lambda x: x[0])
# bind phase and frequency with instruction
phase = self._init_phase
frequency = self._init_frequency
for t0, inst in sorted_waveforms:
is_opaque = False
while len(sorted_frame_changes) > 0 and sorted_frame_changes[-1][0] <= t0:
_, frame_changes = sorted_frame_changes.pop()
phase, frequency = ChannelEvents._calculate_current_frame(
frame_changes=frame_changes, phase=phase, frequency=frequency
)
# Convert parameter expression into float
if isinstance(phase, circuit.ParameterExpression):
phase = float(phase.bind({param: 0 for param in phase.parameters}))
if isinstance(frequency, circuit.ParameterExpression):
frequency = float(frequency.bind({param: 0 for param in frequency.parameters}))
frame = PhaseFreqTuple(phase, frequency)
# Check if pulse has unbound parameters
if isinstance(inst, pulse.Play):
is_opaque = inst.pulse.is_parameterized()
yield PulseInstruction(t0, self._dt, frame, inst, is_opaque)
def get_frame_changes(self) -> Iterator[PulseInstruction]:
"""Return frame change type instructions with total frame change amount."""
# TODO parse parametrised FCs correctly
sorted_frame_changes = sorted(self._frames.items(), key=lambda x: x[0])
phase = self._init_phase
frequency = self._init_frequency
for t0, frame_changes in sorted_frame_changes:
is_opaque = False
pre_phase = phase
pre_frequency = frequency
phase, frequency = ChannelEvents._calculate_current_frame(
frame_changes=frame_changes, phase=phase, frequency=frequency
)
# keep parameter expression to check either phase or frequency is parameterized
frame = PhaseFreqTuple(phase - pre_phase, frequency - pre_frequency)
# remove parameter expressions to find if next frame is parameterized
if isinstance(phase, circuit.ParameterExpression):
phase = float(phase.bind({param: 0 for param in phase.parameters}))
is_opaque = True
if isinstance(frequency, circuit.ParameterExpression):
frequency = float(frequency.bind({param: 0 for param in frequency.parameters}))
is_opaque = True
yield PulseInstruction(t0, self._dt, frame, frame_changes, is_opaque)
@classmethod
def _calculate_current_frame(
cls, frame_changes: list[pulse.instructions.Instruction], phase: float, frequency: float
) -> tuple[float, float]:
"""Calculate the current frame from the previous frame.
If parameter is unbound phase or frequency accumulation with this instruction is skipped.
Args:
frame_changes: List of frame change instructions at a specific time.
phase: Phase of previous frame.
frequency: Frequency of previous frame.
Returns:
Phase and frequency of new frame.
"""
for frame_change in frame_changes:
if isinstance(frame_change, pulse.instructions.SetFrequency):
frequency = frame_change.frequency
elif isinstance(frame_change, pulse.instructions.ShiftFrequency):
frequency += frame_change.frequency
elif isinstance(frame_change, pulse.instructions.SetPhase):
phase = frame_change.phase
elif isinstance(frame_change, pulse.instructions.ShiftPhase):
phase += frame_change.phase
return phase, frequency
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Exception for errors raised by Qiskit Aer noise module.
"""
from qiskit import QiskitError
class NoiseError(QiskitError):
"""Class for errors raised in qiskit_aer.noise package."""
def __init__(self, *message):
"""Set the error message."""
super().__init__(*message)
self.message = ' '.join(message)
def __str__(self):
"""Return the message."""
return repr(self.message)
|
https://github.com/Qiskit/feedback
|
Qiskit
|
class BaseEstimatorGradient(ABC):
def __init__(
self,
estimator: BaseEstimator,
options: Options | None = None,
):
...
def run(
self,
circuits: Sequence[QuantumCircuit],
observables: Sequence[BaseOperator | PauliSumOp],
parameter_values: Sequence[Sequence[float]],
parameters: Sequence[Sequence[Parameter] | None] | None = None,
**options,
) -> AlgorithmJob:
...
@dataclass(frozen=True)
class EstimatorGradientResult:
"""Result of EstimatorGradient."""
gradients: list[np.ndarray]
"""The gradients of the expectation values."""
metadata: list[dict[str, Any]]
"""Additional information about the job."""
options: Options
"""Primitive runtime options for the execution of the job."""
from qiskit.algorithms.gradients import ParamShiftEstimatorGradient
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Estimator
from qiskit.quantum_info import SparsePauliOp
qc = RealAmplitudes(num_qubits=2, reps=1)
op = SparsePauliOp.from_list([("ZI", 1)])
qc.decompose().draw('mpl')
# How to use the Estimator
estimator = Estimator()
values = [1, 2, 3, 4]
# run a job
job = estimator.run([qc], [op], [values])
# get results
result = job.result().values
result
# How to use the ParamShiftEstimatorGradient
param_shift_grad = ParamShiftEstimatorGradient(estimator)
# run a job
job = param_shift_grad.run([qc], [op], [values])
# get results
result = job.result().gradients
result
estimator = Estimator()
# Instantiate a grdient class
param_shift_grad = ParamShiftEstimatorGradient(estimator)
values1 = [1, 2, 3, 4]
values2 = [5, 6, 7, 8]
# run a job
job = param_shift_grad.run([qc]*2, [op]*2, [values1, values2])
# get results
result = job.result().gradients
result
# EstimatorGradient
param_shift_grad = ParamShiftEstimatorGradient(estimator)
param = [p for p in qc.parameters]
# run a job
# param = list of parameters in the quantum circuit
job = param_shift_grad.run([qc]*2, [op]*2, [values, values], [param, param[:2]])
# get results
result = job.result()
result.gradients
# metadata in EstimatorGradientResult stores which parameters' graidents were caluclated
print("result.metadata")
print(result.metadata[0])
print(result.metadata[1])
|
https://github.com/INFINIT27/Grover-s-Algorithm
|
INFINIT27
|
from qiskit import QuantumCircuit
from qiskit_aer import *
from qiskit.visualization import plot_histogram
import math
import random
# val - number to be converted
# length - the number of bits for the binary value
def toBinary(val, length):
binary = '' # declare an empty string
loop = val
if val == 0:
binary = '0'
else:
while loop > 0:
temp = loop % 2 # calculate the bit value
loop = loop // 2
binary += str(temp) # add the bit value to the bit string
# If the binary value is shorter than the number of bits
# passed, append 0's in front of the binary number equal
# to the difference between the binary length and the total length .
while len(binary) < length:
binary += '0'
binary = binary[::-1] # reverse the string
return binary
# Only converts the value to binary, doesn't add extra 0's in front
# to match the number of required qubits.
def toBinary_only(val):
binary = '' # declare an empty string
loop = val
while loop > 0:
temp = loop % 2 # calculate the bit value
loop = loop // 2
binary += str(temp) # add the bit value to the bit string
binary = binary[::-1] # reverse the string
return binary
choice_list = []
# Define the length of the array, can be any length
array_length = 16
for i in range(array_length):
choice_list.append(random.randint(0, 50))
print("Array/Database =",choice_list)
binary_length = toBinary_only(array_length)
qubits_needed = len(binary_length)
# Define a search index (less then array_length) of the list/array/database
search_index = 15
search_val = choice_list[search_index]
print("Search Value =",search_val)
print("Search Index =",search_index)
def oracle(circuit, n, val):
binary_val = toBinary(val, n)
binary_val = binary_val[::-1]
# If the input value contains a qubit 0, apply an x gate to it
# to switch it to a 1 to affect the axillary bit. 1100
for i in range(len(binary_val)):
if binary_val[i] == '0':
circuit.x(i)
############ Implement the multi-control conditional gate ################
circuit.ccx(0, 1, n) # Apply the toffoli gate to the first helper qubit.
for i in range(2, n):
circuit.ccx(i, i+(n-2), i+(n-1)) # Apply a toffoli gate from the second to the last (auxillary) gate.
for i in range(n-2, 1, -1):
circuit.ccx(i, i+(n-2), i+(n-1)) # Apply the reverse gates from the second helper qubit to the last helper qubit.
circuit.ccx(0, 1, n) # Apply the toffoli gate to the first helper qubit.
##########################################################################
# Repeat the same step to revert the qubit change from '1' to '0'.
for i in range(len(binary_val)):
if binary_val[i] == '0':
circuit.x(i)
return circuit
# The diffuser takes in a circuit that applies the appropriate gates.
def diffuser(circuit, n):
# Apply the hadamard gate to the "n" address bits.
for qubit in range(n):
circuit.h(qubit)
# Apply the flip gate to the "n" address bits.
for qubit in range(n):
circuit.x(qubit)
# Apply the multi-control conditional gate to the circuit to change the auxillary bit.
########################################
circuit.ccx(0, 1, n)
for i in range(2, n):
circuit.ccx(i, i+(n-2), i+(n-1))
for i in range(n-2, 1, -1):
circuit.ccx(i, i+(n-2), i+(n-1))
circuit.ccx(0, 1, n)
########################################
# Reverse the flip gate applied earlier.
for qubit in range(n):
circuit.x(qubit)
# Reverse the hadamard gate applied earlier.
for qubit in range(n):
circuit.h(qubit)
return circuit
def ispower2(number):
log_val = math.log(number, 2);
pow_val = math.pow(2, round(log_val));
return pow_val == number
# First "n" qubits will be allocated to the address qubits.
if ispower2(array_length):
address_bit = qubits_needed - 1
else:
address_bit = qubits_needed
helper_bits = address_bit - 2 # next "n-2" qubits will be used as helper qubits for the multi-control conditional gate.
auxillary_bit = 1 # Last qubit will be reserved to the auxillary qubit.
qubits = address_bit + helper_bits + auxillary_bit # Find the total number of qubits needed to implement the circuit.
# Define the test value for the cirucit
test_value = search_index
qc = QuantumCircuit(qubits, address_bit)
# Initialise the address qubits and place them into a superposition.
for i in range(address_bit):
qc.h(i)
# Place the auxillary qubit into the |-> state.
qc.x(qubits-1)
qc.h(qubits-1)
# Define the number of needed iterations for the search to occurr.
# The optimal value is equal to the square root of the number of values in the array/database.
iterations = int(address_bit**(1/2))+1 # The int() value rounds down the number of iterations, thus we add 1 to the number of iterations.
# Apply the number of Oracle-Diffusor pair equal to the number of iterations.
for i in range(iterations):
qc.barrier()
oracle(qc, address_bit, test_value)
qc.barrier()
diffuser(qc, address_bit)
qc.barrier()
# Measure the address qubits.
for i in range(address_bit):
qc.measure(i, i)
qc.draw('mpl')
# Construct an ideal simulator
simulator = AerSimulator()
results = simulator.run(qc).result()
counts = results.get_counts()
print(counts)
display(plot_histogram(counts))
largest_val = 0
value = ''
for entry in counts:
if counts[entry] > largest_val:
largest_val = counts[entry]
value = entry
print(value)
def toInteger(val: str):
num = 0
val = val[::-1] # take the reverse of the string of integers 100 - 001
for i in range(len(val)):
if val[i] == '0':
continue
else:
num += 2**i
return num
print("The estimated index from the simulator is:",toInteger(value))
|
https://github.com/MAI-cyber/QIT
|
MAI-cyber
|
from qiskit import QuantumCircuit, execute, Aer, BasicAer
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import Statevector, state_fidelity
import numpy as np
pi = np.pi
from qiskit.visualization import plot_state_qsphere, plot_histogram, plot_bloch_multivector
# For n qubit system
n = 4
N = 2**n
w = np.exp(2*pi*(1j)/N)
# Initiliaing the qft matrix and assigning it values
qft = np.zeros((N,N),dtype = 'complex_')
for i in range(N):
for j in range(N):
qft[i][j] = pow(w,(i*j))/n
print(qft)
# Initializing the input state
in_state = np.zeros(N,dtype = 'complex_')
# State |0010> in vector form has third element non zero
in_state[2] = 1j /pow(2, 0.5)
# State |0011> in vector form has fourth element non zero
in_state[3] = 1 /pow(2, 0.5)
#print(in_state)
# Output state
out_state = np.matmul(qft, in_state)
# Making a state_vector
matrix_output = Statevector(out_state, dims=(2, 2, 2, 2))
print(out_state)
# Checking if output state is normalized
norm = pow(np.matmul(out_state.conjugate(), out_state), 0.5)
print("Norm = ", norm)
n=4
qftn=QuantumCircuit(n,n,name='QFT')
for i in range(n-1,-1,-1):
# Puttign each qubit in unifrom superposition
qftn.h(i)
# Adding the relevent rotation gate
p=0
for j in range(i):
p+=1
qftn.cp(pi/(2**(p)),i-j-1,i)
qftn.barrier()
# Swapping the output qubits
for i in range(int(n/2)):
qftn.swap(i,n-1-i)
qftn.draw('mpl')
# Perparing the inout state for the quntum circuit
sv1 = Statevector.from_label('0011')
sv2 = Statevector.from_label('0010')
sv = (sv1 + 1j* sv2)/pow(2,0.5)
# Representing the input state on the block sphere
plot_bloch_multivector(sv)
# Evolovinf the state and representing the output state on the block sphere
circuit_output = sv.evolve(qftn)
plot_bloch_multivector(circuit_output)
# Verifying that the circuit and matrix give the same results
#print(matrix_output)
#print(circuit_output)
fidelity = state_fidelity(matrix_output, circuit_output)
print("Fidelity =", fidelity)
# The QFT inverse circuit
n=4
iqftn=QuantumCircuit(n,n,name='IQFT')
for i in range(int(n/2)):
iqftn.swap(i,n-1-i)
iqftn.barrier()
for i in range(n):
p=i+1
for j in range(i):
p-=1
iqftn.cp(-pi/(2**(p)),j,i)
iqftn.h(i)
iqftn.barrier()
iqftn.draw('mpl')
|
https://github.com/AasthaShayla/Qiskit-Teleportation
|
AasthaShayla
|
from qiskit import *
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
circuit = QuantumCircuit(3,3)
%matplotlib inline
circuit.x(0)
circuit.barrier()
circuit.h(1)
circuit.cx(1,2)
circuit.barrier()
circuit.cx(0,1)
circuit.h(0)
circuit.barrier()
circuit.measure([0, 1], [0, 1])
circuit.barrier()
circuit.cx(1, 2)
circuit.cz(0, 2)
circuit.measure([2], [2])
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=simulator, shots=1024).result()
from qiskit.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
print(circuit.qasm())
statevector_simulator = Aer.get_backend('statevector_simulator')
result=execute(circuit,statevector_simulator).result()
statevector_results=result.get_statevector(circuit)
plot_bloch_multivector(statevector_results)
plot_state_qsphere(statevector_results)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeManilaV2
from qiskit import transpile
from qiskit.tools.visualization import plot_histogram
# Get a fake backend from the fake provider
backend = FakeManilaV2()
# Create a simple circuit
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(0,2)
circuit.measure_all()
circuit.draw('mpl')
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(circuit, backend)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated fake backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
from qiskit.transpiler.coupling import CouplingMap
from mirror_gates.pass_managers import Mirage, QiskitLevel3
from transpile_benchy.metrics.gate_counts import (
DepthMetric,
TotalMetric,
TotalSwaps,
)
from qiskit.transpiler import PassManager
import numpy as np
from mirror_gates.logging import transpile_benchy_logger
from mirror_gates.sqiswap_decomposer import SiSwapDecomposePass
from qiskit.transpiler.passmanager import PassManager
from qiskit import Aer, transpile
from qiskit.quantum_info import state_fidelity
from qiskit_aer import AerSimulator
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (
NoiseModel,
QuantumError,
ReadoutError,
pauli_error,
depolarizing_error,
thermal_relaxation_error,
RelaxationNoisePass,
)
from qiskit.circuit import Delay
from qiskit.transpiler.passes import PadDelay, ASAPSchedule
from qiskit import QuantumCircuit
from transpile_benchy.metrics.gate_counts import (
DepthMetric,
TotalMetric,
TotalSwaps,
)
from qiskit.circuit.library import iSwapGate
from qiskit.transpiler import CouplingMap
from mirror_gates.pass_managers import Mirage, QiskitLevel3
from mirror_gates.utilities import SubsMetric
from mirror_gates.logging import transpile_benchy_logger
N = 8
coupling_map = CouplingMap.from_line(8)
from transpile_benchy.library import CircuitLibrary
library = CircuitLibrary.from_txt("../../circuits/small_circuits.txt")
# new metric for simulating fidelity
from transpile_benchy.metrics.abc_metrics import MetricInterface
from qiskit.transpiler.basepasses import AnalysisPass
from mirror_gates.noisy_fidelity import get_noisy_fidelity
from qiskit.converters import dag_to_circuit
from mirror_gates.utilities import DoNothing
# TODO: we could move gate times and T1,T2 to be parameters
# currently, are just hardcoded at the top of the file
class FidelityAnalysis(AnalysisPass):
def __init__(self, coupling_map, sqrt_iswap_basis):
super().__init__()
self.coupling_map = coupling_map
self.sqrt_iswap_basis = sqrt_iswap_basis
def run(self, dag):
qc = dag_to_circuit(dag)
fid, duration, _, expected_fid = get_noisy_fidelity(
qc, self.coupling_map, sqrt_iswap_basis=self.sqrt_iswap_basis
)
self.property_set["noisy_fidelity"] = fid
self.property_set["scheduled_duration"] = duration
self.property_set["expected_fidelity"] = expected_fid
return dag
class FidelityMetric(MetricInterface):
"""Calculate the noisy simulated fidelity."""
def __init__(self, coupling_map):
"""Initialize the metric."""
super().__init__(name="noisy_fidelity", pretty_name="Noisy Fidelity")
self.use_geometric_mean = True
self.coupling_map = coupling_map
def _construct_pass(self, basis_gate):
"""Return the pass associated with this metric."""
sqrt_iswap_basis = basis_gate == iSwapGate().power(1 / 2)
return FidelityAnalysis(self.coupling_map, sqrt_iswap_basis)
class DurationMetric(MetricInterface):
"""Calculate the noisy simulated fidelity."""
def __init__(self):
"""Initialize the metric."""
super().__init__(name="scheduled_duration", pretty_name="Circuit Duration (ns)")
self.use_geometric_mean = True
def _construct_pass(self):
"""Return the pass associated with this metric."""
return DoNothing()
class ExpectedFidelityMetric(MetricInterface):
"""Calculate the noisy simulated fidelity."""
def __init__(self):
"""Initialize the metric."""
super().__init__(name="expected_fidelity", pretty_name="Expected Fidelity")
self.use_geometric_mean = True
def _construct_pass(self):
"""Return the pass associated with this metric."""
return DoNothing()
# XXX set consolidate to False
# this is allowed only because my pass manager will preserve consolidation
# see post_stage, I call fastconsolidate manually
# NOTE: use TotalSwaps to verify baselines have > 0 swaps
# otherwise, there is no room for improvement.
# we can include these if we want to show our methods will still work
# but somewhat trivial since we just append VF2Layout
metrics = [
DepthMetric(consolidate=False),
TotalMetric(consolidate=False),
TotalSwaps(consolidate=False),
SubsMetric(),
FidelityMetric(coupling_map),
DurationMetric(),
ExpectedFidelityMetric(),
]
transpilers = [
# QiskitLevel3(coupling_map, cx_basis=True),
# Mirage(
# coupling_map,
# logger=transpile_benchy_logger,
# cx_basis=True,
# ),
QiskitLevel3(coupling_map, cx_basis=False),
Mirage(
coupling_map,
logger=transpile_benchy_logger,
cx_basis=False,
),
]
from transpile_benchy.benchmark import Benchmark
benchmark = Benchmark(
transpilers=transpilers,
circuit_library=library,
metrics=metrics,
logger=transpile_benchy_logger,
num_runs=1,
)
benchmark.run()
print(benchmark)
benchmark.summary_statistics(transpilers[0], transpilers[1])
from transpile_benchy.render import plot_benchmark
plot_benchmark(
benchmark,
save=1,
legend_show=1,
filename="twolocal",
color_override=[0, 3],
)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.translators import from_docplex_mp
# Make a Docplex model
from docplex.mp.model import Model
mdl = Model("docplex model")
x = mdl.binary_var("x")
y = mdl.integer_var(lb=-1, ub=5, name="y")
mdl.minimize(x + 2 * y)
mdl.add_constraint(x - y == 3)
mdl.add_constraint((x + y) * (x - y) <= 1)
print(mdl.export_as_lp_string())
# load from a Docplex model
mod = from_docplex_mp(mdl)
print(type(mod))
print()
print(mod.prettyprint())
# make an empty problem
mod = QuadraticProgram("my problem")
print(mod.prettyprint())
# Add variables
mod.binary_var(name="x")
mod.integer_var(name="y", lowerbound=-1, upperbound=5)
mod.continuous_var(name="z", lowerbound=-1, upperbound=5)
print(mod.prettyprint())
# Add objective function using dictionaries
mod.minimize(constant=3, linear={"x": 1}, quadratic={("x", "y"): 2, ("z", "z"): -1})
print(mod.prettyprint())
# Add objective function using lists/arrays
mod.minimize(constant=3, linear=[1, 0, 0], quadratic=[[0, 1, 0], [1, 0, 0], [0, 0, -1]])
print(mod.prettyprint())
print("constant:\t\t\t", mod.objective.constant)
print("linear dict:\t\t\t", mod.objective.linear.to_dict())
print("linear array:\t\t\t", mod.objective.linear.to_array())
print("linear array as sparse matrix:\n", mod.objective.linear.coefficients, "\n")
print("quadratic dict w/ index:\t", mod.objective.quadratic.to_dict())
print("quadratic dict w/ name:\t\t", mod.objective.quadratic.to_dict(use_name=True))
print(
"symmetric quadratic dict w/ name:\t",
mod.objective.quadratic.to_dict(use_name=True, symmetric=True),
)
print("quadratic matrix:\n", mod.objective.quadratic.to_array(), "\n")
print("symmetric quadratic matrix:\n", mod.objective.quadratic.to_array(symmetric=True), "\n")
print("quadratic matrix as sparse matrix:\n", mod.objective.quadratic.coefficients)
# Add linear constraints
mod.linear_constraint(linear={"x": 1, "y": 2}, sense="==", rhs=3, name="lin_eq")
mod.linear_constraint(linear={"x": 1, "y": 2}, sense="<=", rhs=3, name="lin_leq")
mod.linear_constraint(linear={"x": 1, "y": 2}, sense=">=", rhs=3, name="lin_geq")
print(mod.prettyprint())
# Add quadratic constraints
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense="==",
rhs=1,
name="quad_eq",
)
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense="<=",
rhs=1,
name="quad_leq",
)
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense=">=",
rhs=1,
name="quad_geq",
)
print(mod.prettyprint())
lin_geq = mod.get_linear_constraint("lin_geq")
print("lin_geq:", lin_geq.linear.to_dict(use_name=True), lin_geq.sense, lin_geq.rhs)
quad_geq = mod.get_quadratic_constraint("quad_geq")
print(
"quad_geq:",
quad_geq.linear.to_dict(use_name=True),
quad_geq.quadratic.to_dict(use_name=True),
quad_geq.sense,
lin_geq.rhs,
)
# Remove constraints
mod.remove_linear_constraint("lin_eq")
mod.remove_quadratic_constraint("quad_leq")
print(mod.prettyprint())
sub = mod.substitute_variables(constants={"x": 0}, variables={"y": ("z", -1)})
print(sub.prettyprint())
sub = mod.substitute_variables(constants={"x": -1})
print(sub.status)
from qiskit_optimization import QiskitOptimizationError
try:
sub = mod.substitute_variables(constants={"x": -1}, variables={"y": ("x", 1)})
except QiskitOptimizationError as e:
print("Error: {}".format(e))
mod = QuadraticProgram()
mod.binary_var(name="e")
mod.binary_var(name="f")
mod.continuous_var(name="g")
mod.minimize(linear=[1, 2, 3])
print(mod.export_as_lp_string())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_qsphere(state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
pw_approximation._build()
qc = QuantumCircuit(pw_approximation.num_qubits)
qc.h(list(range(num_state_qubits)))
qc.append(pw_approximation.to_instruction(), qc.qubits)
qc.draw(output='mpl')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.