repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
from qiskit.optimization import QuadraticProgram
from docplex.mp.advmodel import AdvModel
from docplex.mp.model_reader import ModelReader
from qiskit.optimization.algorithms import MinimumEigenOptimizer
from dwave.plugins.qiskit import DWaveMinimumEigensolver
from dwave.system import DWaveCliqueSampler, LeapHybridSampler
import numpy as np
model = ModelReader.read(filename='QPLIB_DATA/QPLIB_3834.lp',model_name = "Test_QPLIB_Small", model_class=AdvModel)
qp = QuadraticProgram()
qp.from_docplex(model)
dwave_solver_hybrid = DWaveMinimumEigensolver(sampler = LeapHybridSampler())
optimizer = MinimumEigenOptimizer(dwave_solver_hybrid)
result = optimizer.solve(qp) # Problem ID : 46e887a7-d787-4307-8443-c6d7c6b454a4
result
|
https://github.com/googlercolin/Qiskit-Course
|
googlercolin
|
import numpy as np
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
from torchsummary import summary
import qiskit
from qiskit import transpile, assemble, IBMQ
from qiskit.visualization import *
from qiskit.providers.aer import AerSimulator
from qiskit.test.mock import FakeBelem
provider = IBMQ.load_account()
class QuantumCircuit:
"""
This class provides a simple interface for interaction
with the quantum circuit
"""
def __init__(self, n_qubits, backend, shots):
# --- Circuit definition ---
self._circuit = qiskit.QuantumCircuit(n_qubits)
all_qubits = [i for i in range(n_qubits)]
self.theta = qiskit.circuit.Parameter('theta')
self._circuit.h(all_qubits)
self._circuit.barrier()
self._circuit.ry(self.theta, all_qubits)
self._circuit.measure_all()
# ---------------------------
self.backend = backend
self.shots = shots
def run(self, thetas):
t_qc = transpile(self._circuit,
self.backend)
qobj = assemble(t_qc,
shots=self.shots,
parameter_binds = [{self.theta: theta} for theta in thetas])
job = self.backend.run(qobj)
result = job.result().get_counts()
# print(f"Result is {result}")
counts = np.array(list(result.values()))
states = np.array(list(result.keys())).astype(float)
# Compute probabilities for each state
probabilities = counts / self.shots
# Get state expectation
expectation = np.sum(states * probabilities)
return np.array([expectation])
# Using a noisy simulator
noisy_backend = FakeBelem()
simulator = AerSimulator.from_backend(noisy_backend)
# simulator = qiskit.Aer.get_backend('aer_simulator')
circuit = QuantumCircuit(1, simulator, 100)
print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0]))
circuit._circuit.draw('mpl')
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
expectation_z = ctx.quantum_circuit.run(input[0].tolist())
result = torch.tensor([expectation_z])
ctx.save_for_backward(input, result)
return result
@staticmethod
def backward(ctx, grad_output):
""" Backward pass computation """
input, expectation_z = ctx.saved_tensors
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.shift
shift_left = input_list - np.ones(input_list.shape) * ctx.shift
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients.append(gradient)
gradients = np.array([gradients]).T
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class Hybrid(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, shift):
super(Hybrid, self).__init__()
self.quantum_circuit = QuantumCircuit(2, backend, shots) # initialize 2 qubit VQC
self.shift = shift
def forward(self, input):
return HybridFunction.apply(input, self.quantum_circuit, self.shift)
# Concentrating on the first 100 samples
n_samples = 100
X_train = datasets.MNIST(root='./data', train=True, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
# Leaving 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]
X_train.targets = X_train.targets[idx]
train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True)
n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
n_samples = 50
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)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 5x5 square convolution
self.conv1 = nn.Conv2d(1, 6, kernel_size=5)
# 6 input channels, 16 output channels, 5x5 square convolution
self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(256, 64) # fc stands for fully connected layer
self.fc2 = nn.Linear(64, 2) # output 1 to be run on 2 qubit VQC
# self.hybrid = Hybrid(qiskit.Aer.get_backend('aer_simulator'), 100, np.pi / 2)
self.hybrid = [Hybrid(qiskit.Aer.get_backend('aer_simulator'), 100, np.pi / 2) for i in range(2)]
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
# Here is where the matrixes/channels are flattened into one long vector
x = torch.flatten(x, start_dim=1)
# x = x.view(1, -1) # make it the same shape as output
x = F.relu(self.fc1(x)) # ReLu is applied to fc1(x) where fc1 is channel which it takes an input of 256 and outputs a vector of a size of 64.
x = self.fc2(x) # Final step where input is a size of 64 and output is a size of 10.
x = torch.chunk(x, 2, dim=1)
# x = self.hybrid(x)
x = tuple([hybr(x_) for hybr, x_ in zip(self.hybrid, x)])
return torch.cat(x, -1)
# class Net(nn.Module):
# def __init__(self):
# super(Net, self).__init__()
# self.conv1 = nn.Conv2d(1, 6, kernel_size=5)
# self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
# self.dropout = nn.Dropout2d()
# self.fc1 = nn.Linear(256, 64)
# self.fc2 = nn.Linear(64, 1)
# self.hybrid = Hybrid(qiskit.Aer.get_backend('aer_simulator'), 100, np.pi / 2)
# def forward(self, x):
# x = F.relu(self.conv1(x))
# x = F.max_pool2d(x, 2)
# x = F.relu(self.conv2(x))
# x = F.max_pool2d(x, 2)
# x = self.dropout(x)
# x = x.view(1, -1)
# x = F.relu(self.fc1(x))
# x = self.fc2(x)
# x = self.hybrid(x)
# return torch.cat((x, 1 - x), -1)
model = Net()
summary(model, (1, 28, 28), device='cpu')
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad() # clears old gradients from the last step (otherwise you’d just accumulate the gradients from all loss.backward() calls).
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward() # computes the derivative of the loss w.r.t. the parameters (or anything requiring gradients) using backpropagation.
# Optimize the weights
optimizer.step() # causes the optimizer to take a step based on the gradients of the parameters.
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Negative Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
model.eval()
with torch.no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(data[0].numpy().squeeze(), cmap='gray')
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title('Predicted {}'.format(pred.item()))
count += 1
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Example showing how to use Qiskit-Terra at level 0 (novice).
This example shows the most basic way to user Terra. It builds some circuits
and runs them on both the BasicAer (local Qiskit provider) or IBMQ (remote IBMQ provider).
To control the compile parameters we have provided a transpile function which can be used
as a level 1 user.
"""
# Import the Qiskit modules
from qiskit import QuantumCircuit
from qiskit import execute, BasicAer
# making first circuit: bell state
qc1 = QuantumCircuit(2, 2)
qc1.h(0)
qc1.cx(0, 1)
qc1.measure([0, 1], [0, 1])
# making another circuit: superpositions
qc2 = QuantumCircuit(2, 2)
qc2.h([0, 1])
qc2.measure([0, 1], [0, 1])
# setting up the backend
print("(BasicAER Backends)")
print(BasicAer.backends())
# running the job
job_sim = execute([qc1, qc2], BasicAer.get_backend("qasm_simulator"))
sim_result = job_sim.result()
# Show the results
print(sim_result.get_counts(qc1))
print(sim_result.get_counts(qc2))
|
https://github.com/CQCL/pytket-qiskit
|
CQCL
|
# Copyright 2019 Cambridge Quantum Computing
#
# 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
#
# https://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.
"""Methods to allow conversion between Qiskit and pytket circuit classes
"""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Instruction, Measure
from qiskit.extensions.standard import *
from pytket._circuit import Circuit, Op, OpType
from pytket._routing import PhysicalCircuit
from sympy import pi
_known_qiskit_gate = {
IdGate : OpType.noop,
XGate : OpType.X,
YGate : OpType.Y,
ZGate : OpType.Z,
SGate : OpType.S,
SdgGate : OpType.Sdg,
TGate : OpType.T,
TdgGate : OpType.Tdg,
HGate : OpType.H,
RXGate : OpType.Rx,
RYGate : OpType.Ry,
RZGate : OpType.Rz,
U1Gate : OpType.U1,
U2Gate : OpType.U2,
U3Gate : OpType.U3,
CnotGate : OpType.CX,
CyGate : OpType.CY,
CzGate : OpType.CZ,
CHGate : OpType.CH,
SwapGate : OpType.SWAP,
ToffoliGate : OpType.CCX,
FredkinGate : OpType.CSWAP,
CrzGate : OpType.CRz,
Cu1Gate : OpType.CU1,
Cu3Gate : OpType.CU3,
Measure : OpType.Measure
}
_known_qiskit_gate_rev = {v : k for k, v in _known_qiskit_gate.items()}
def qiskit_to_tk(qcirc: QuantumCircuit) -> Circuit :
"""Convert a :py:class:`qiskit.QuantumCircuit` to a :py:class:`Circuit`.
:param qcirc: A circuit to be converted
:type qcirc: QuantumCircuit
:return: The converted circuit
:rtype: Circuit
"""
tkc = Circuit()
qregmap = {}
for reg in qcirc.qregs :
tk_reg = tkc.add_q_register(reg.name, len(reg))
qregmap.update({reg : tk_reg})
cregmap = {}
for reg in qcirc.cregs :
tk_reg = tkc.add_c_register(reg.name, len(reg))
cregmap.update({reg : tk_reg})
for i, qargs, cargs in qcirc.data :
if i.control is not None :
raise NotImplementedError("Cannot convert conditional gates from Qiskit to tket")
optype = _known_qiskit_gate[type(i)]
qubits = [qregmap[r][ind] for r, ind in qargs]
bits = [cregmap[r][ind] for r, ind in cargs]
if optype == OpType.Measure :
tkc.add_measure(*qubits, *bits)
continue
params = [p/pi for p in i.params]
tkc.add_gate(optype, params, qubits, [])
return tkc
def tk_to_qiskit(tkcirc: Circuit) -> QuantumCircuit :
"""Convert back
:param tkcirc: A circuit to be converted
:type tkcirc: Circuit
:return: The converted circuit
:rtype: QuantumCircuit
"""
tkc = tkcirc
if isinstance(tkcirc, PhysicalCircuit) :
tkc = tkcirc._get_circuit()
qcirc = QuantumCircuit()
qregmap = {}
for _, reg in tkc.q_regs.items() :
if reg.size() == 0 :
continue
name = reg.name
if len(name) == 0 :
name = None
qis_reg = QuantumRegister(reg.size(), name)
qregmap.update({reg : qis_reg})
qcirc.add_register(qis_reg)
cregmap = {}
for _, reg in tkc.c_regs.items() :
if reg.size() == 0 :
continue
name = reg.name
if len(name) == 0 :
name = None
qis_reg = ClassicalRegister(reg.size(), name)
cregmap.update({reg : qis_reg})
qcirc.add_register(qis_reg)
tempregmap = {}
for command in tkc :
op = command.op
qubits = command.qubits
qargs = [qregmap[q.reg][q.index] for q in qubits]
if len(command.controls) != 0 :
raise NotImplementedError("Cannot convert conditional gates from tket to Qiskit")
if op.get_type() == OpType.Measure :
bits = [_convert_bit(b, cregmap, qcirc, tempregmap) for b in command.bits]
qcirc.measure(*qargs, *bits)
continue
params = [p * pi for p in op.get_params()]
try :
gatetype = _known_qiskit_gate_rev[op.get_type()]
except KeyError as error :
raise NotImplementedError("Cannot convert tket Op to Qiskit gate: " + op.get_name()) from error
g = gatetype(*params)
qcirc.append(g, qargs=qargs)
return qcirc
def _convert_bit(bit, cregmap, qcirc, tempregmap) :
index = bit.index
if bit.temp :
if bit not in tempregmap :
new_reg = ClassicalRegister(1, "temp"+str(index))
qcirc.add_register(new_reg)
tempregmap.update({bit : new_reg})
return new_reg[0]
return tempregmap[bit][0]
return cregmap[bit.reg][index]
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
from qiskit import *
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua
from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector
from qiskit.quantum_info import Statevector
from qiskit.extensions import *
provider = IBMQ.load_account()
from qiskit.quantum_info import random_unitary
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
from math import pi, sqrt
from scipy.special import rel_entr
from random import seed
from random import random
import cmath
import os
from qiskit.circuit import Parameter
#Possible Bin
bins_list=[];
for i in range(76):
bins_list.append((i)/75)
#Center of the Bean
bins_x=[]
for i in range(75):
bins_x.append(bins_list[1]+bins_list[i])
def P_harr(l,u,N):
return (1-l)**(N-1)-(1-u)**(N-1)
#Harr historgram
P_harr_hist=[]
for i in range(75):
P_harr_hist.append(P_harr(bins_list[i],bins_list[i+1],16))
#Imaginary
j=(-1)**(1/2)
backend = Aer.get_backend('qasm_simulator')
nshot=1000
nparam=2000
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr, cr)
theta=[];
for y in range(80):
theta.append(2*pi*random())
qc=circuit9(qc,qr,theta,3,1)
qc.measure(qr[:],cr[:])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0000' in count and '1' in count:
ratio=count['0000']/nshot
elif '0000' in count and '1' not in count:
ratio=count['0000']/nshot
else:
ratio=0
fidelity.append(ratio)
weights = np.ones_like(fidelity)/float(len(fidelity))
plt.hist(fidelity, bins=bins_list, weights=weights, range=[0, 1], label='Circuit 1')
plt.plot(bins_x, P_harr_hist, label='Harr')
plt.legend(loc='upper right')
plt.show()
# example of calculating the kl divergence (relative entropy) with scipy
P_1_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]
kl_pq = rel_entr(P_1_hist, P_harr_hist)
print('KL(P || Q): %.3f nats' % sum(kl_pq))
list_of_circuit = [circuit1,circuit2,circuit3,circuit4,circuit5,circuit6,circuit7,circuit8,circuit9,circuit10,circuit11,circuit12,circuit13,circuit14,circuit15,circuit16,circuit17,circuit18,circuit19]
backend = Aer.get_backend('qasm_simulator')
arr = []
for kk in range(19):
arr.append([])
for lo in [1,2,3,4,5]:
nshot=1000
nparam=2000
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr, cr)
theta=[];
for y in range(500):
theta.append(2*pi*random())
qc=list_of_circuit[kk](qc,qr,theta,lo,1)
qc.measure(qr[:],cr[:])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0000' in count and '1' in count:
ratio=count['0000']/nshot
elif '0000' in count and '1' not in count:
ratio=count['0000']/nshot
else:
ratio=0
fidelity.append(ratio)
weights = np.ones_like(fidelity)/float(len(fidelity))
# example of calculating the kl divergence (relative entropy) with scipy
P_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]
kl_pq = rel_entr(P_hist, P_harr_hist)
arr[kk].append(sum(kl_pq))
print(kk,'cir',lo,'lay')
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("express_nshot1000_nparam2000.txt",express)
express
import pandas as pd
import matplotlib.pyplot as plt
#loading dataset
x = [i+1 for i in range(19)]
y = [i[0] for i in arr]
plt.plot(x, y, 'o', color='red', label='L=1');
x = [i+1 for i in range(19)]
y = [i[1] for i in arr]
plt.plot(x, y, 'o', color='blue', label='L=2');
x = [i+1 for i in range(19)]
y = [i[2] for i in arr]
plt.plot(x, y, 'o', color='black', label='L=3');
x = [i+1 for i in range(19)]
y = [i[3] for i in arr]
plt.plot(x, y, 'o', color='green', label='L=4');
x = [i+1 for i in range(19)]
y = [i[3] for i in arr]
plt.plot(x, y, 'o', color='purple', label='L=5');
plt.legend(loc='upper right')
plt.yscale('log',base=10)
plt.xlabel('Circuit ID')
plt.ylabel('Expressibility')
# Create names on the x axis
plt.xticks([i+1 for i in range(19)])
plt.show()
x = [str(i+1) for i in range(19)]
x_ticks_labels = ['9','1','2','16','3','18','10','12','15','17','4','11','7','8','19','5','13','14','6']
xarr = np.array(x)
ind = np.where(xarr.reshape(xarr.size, 1) == np.array(x_ticks_labels))[1]
fig, ax = plt.subplots(1,1)
y = [i[0] for i in arr]
ax.scatter(ind,y, marker="o", color='red', label='L=1')
y = [i[1] for i in arr]
ax.scatter(ind,y, marker="o", color='blue', label='L=2')
y = [i[2] for i in arr]
ax.scatter(ind,y, marker="o", color='black', label='L=3')
y = [i[3] for i in arr]
ax.scatter(ind,y, marker="o", color='green', label='L=4')
y = [i[4] for i in arr]
ax.scatter(ind,y, marker="o", color='purple', label='L=5')
ax.set_yscale('log',base=10)
ax.set_xlabel('Circuit ID')
ax.set_ylabel('Expressibility')
ax.legend(loc='upper right')
ax.set_xticks(range(len(x_ticks_labels)))
ax.set_xticklabels(x_ticks_labels)
plt.show()
fig
from matplotlib import pyplot as plt
fig.savefig('express_nshot1000_nparam2000.png')
list_of_circuit = [circuit1,circuit2,circuit3,circuit4,circuit5,circuit6,circuit7,circuit8,circuit9,circuit10,circuit11,circuit12,circuit13,circuit14,circuit15,circuit16,circuit17,circuit18,circuit19]
backend = Aer.get_backend('qasm_simulator')
arr = []
for kk in range(19):
arr.append([])
for lo in [1,2,3,4,5]:
nshot=10000
nparam=1000
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr, cr)
theta=[];
for y in range(500):
theta.append(2*pi*random())
qc=list_of_circuit[kk](qc,qr,theta,lo,1)
qc.measure(qr[:],cr[:])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0000' in count and '1' in count:
ratio=count['0000']/nshot
elif '0000' in count and '1' not in count:
ratio=count['0000']/nshot
else:
ratio=0
fidelity.append(ratio)
weights = np.ones_like(fidelity)/float(len(fidelity))
# example of calculating the kl divergence (relative entropy) with scipy
P_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]
kl_pq = rel_entr(P_hist, P_harr_hist)
arr[kk].append(sum(kl_pq))
print(kk,'cir',lo,'lay')
express
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("express_nshot10000_nparam1000.txt",express)
x = [str(i+1) for i in range(19)]
x_ticks_labels = ['9','1','2','16','3','18','10','12','15','17','4','11','7','8','19','5','13','14','6']
xarr = np.array(x)
ind = np.where(xarr.reshape(xarr.size, 1) == np.array(x_ticks_labels))[1]
fig, ax = plt.subplots(1,1)
y = [i[0] for i in arr]
ax.scatter(ind,y, marker="o", color='red', label='L=1')
y = [i[1] for i in arr]
ax.scatter(ind,y, marker="o", color='blue', label='L=2')
y = [i[2] for i in arr]
ax.scatter(ind,y, marker="o", color='black', label='L=3')
y = [i[3] for i in arr]
ax.scatter(ind,y, marker="o", color='green', label='L=4')
y = [i[4] for i in arr]
ax.scatter(ind,y, marker="o", color='purple', label='L=5')
ax.set_yscale('log',base=10)
ax.set_xlabel('Circuit ID')
ax.set_ylabel('Expressibility')
ax.legend(loc='upper right')
ax.set_xticks(range(len(x_ticks_labels)))
ax.set_xticklabels(x_ticks_labels)
plt.show()
from matplotlib import pyplot as plt
fig.savefig('express_nshot10000_nparam1000.png')
def circuit1(qc,qr,theta,L,repeat):
#circuit 1
#theta is list of the parameters
#theta length is 8L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit2(qc,qr,theta,L,repeat):
#circuit 2
#theta is list of the parameters
#theta length is 8L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.cx(qr[3],qr[2])
qc.cx(qr[2],qr[1])
qc.cx(qr[1],qr[0])
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.cx(qr[1],qr[0])
qc.cx(qr[2],qr[1])
qc.cx(qr[3],qr[2])
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit3(qc,qr,theta,L,repeat):
#circuit 3
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit4(qc,qr,theta,L,repeat):
#circuit 4
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit5(qc,qr,theta,L,repeat):
#circuit 5
#theta is list of the parameters
#theta length is (28)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crz(theta[count],qr[3-j],qr[3-i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crz(theta[count],qr[j],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit6(qc,qr,theta,L,repeat):
#circuit 6
#theta is list of the parameters
#theta length is (28)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crx(theta[count],qr[3-j],qr[3-i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crx(theta[count],qr[j],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit7(qc,qr,theta,L,repeat):
#circuit 7
#theta is list of the parameters
#theta length is (19)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[2],qr[1])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit8(qc,qr,theta,L,repeat):
#circuit 8
#theta is list of the parameters
#theta length is (19)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[2],qr[1])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit9(qc,qr,theta,L,repeat):
#circuit 9
#theta is list of the parameters
#theta length is (4)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.h(qr[i])
qc.cz(qr[3],qr[2])
qc.cz(qr[2],qr[1])
qc.cz(qr[1],qr[0])
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
qc.cz(qr[1],qr[0])
qc.cz(qr[2],qr[1])
qc.cz(qr[3],qr[2])
for i in range(4):
qc.h(qr[i])
return qc
def circuit10(qc,qr,theta,L,repeat):
#circuit 10
#theta is list of the parameters
#theta length is (4)L+4
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
for l in range(L):
qc.cz(qr[3],qr[2])
qc.cz(qr[2],qr[1])
qc.cz(qr[1],qr[0])
qc.cz(qr[3],qr[0])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.cz(qr[3],qr[0])
qc.cz(qr[1],qr[0])
qc.cz(qr[2],qr[1])
qc.cz(qr[3],qr[2])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit11(qc,qr,theta,L,repeat):
#circuit 11
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.cx(qr[1],qr[0])
qc.cx(qr[3],qr[2])
qc.ry(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.rz(theta[count],qr[2])
count=count+1
qc.cx(qr[2],qr[1])
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.cx(qr[2],qr[1])
qc.rz(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.ry(theta[count],qr[1])
count=count+1
qc.cx(qr[3],qr[2])
qc.cx(qr[1],qr[0])
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit12(qc,qr,theta,L,repeat):
#circuit 12
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.cz(qr[1],qr[0])
qc.cz(qr[3],qr[2])
qc.ry(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.rz(theta[count],qr[2])
count=count+1
qc.cz(qr[2],qr[1])
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.cz(qr[2],qr[1])
qc.rz(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.ry(theta[count],qr[1])
count=count+1
qc.cz(qr[3],qr[2])
qc.cz(qr[1],qr[0])
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit13(qc,qr,theta,L,repeat):
#circuit 13
#theta is list of the parameters
#theta length is (16)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[1])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[2],qr[1])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[0],qr[3])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[0],qr[1])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[3],qr[0])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit14(qc,qr,theta,L,repeat):
#circuit 14
#theta is list of the parameters
#theta length is (16)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[1])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[2],qr[1])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[0],qr[3])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[0],qr[1])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[3],qr[0])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit15(qc,qr,theta,L,repeat):
#circuit 15
#theta is list of the parameters
#theta length is (8)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.cx(qr[3],qr[0])
qc.cx(qr[2],qr[3])
qc.cx(qr[1],qr[2])
qc.cx(qr[0],qr[1])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.cx(qr[3],qr[2])
qc.cx(qr[0],qr[3])
qc.cx(qr[1],qr[0])
qc.cx(qr[2],qr[1])
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.cx(qr[2],qr[1])
qc.cx(qr[1],qr[0])
qc.cx(qr[0],qr[3])
qc.cx(qr[3],qr[2])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.cx(qr[0],qr[1])
qc.cx(qr[1],qr[2])
qc.cx(qr[2],qr[3])
qc.cx(qr[3],qr[0])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit16(qc,qr,theta,L,repeat):
#circuit 16
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[2],qr[1])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit17(qc,qr,theta,L,repeat):
#circuit 17
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[2],qr[1])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit18(qc,qr,theta,L,repeat):
#circuit 18
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[0],qr[1])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[3],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit19(qc,qr,theta,L,repeat):
#circuit 1
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[0],qr[1])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[3],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
|
https://github.com/lynnlangit/learning-quantum
|
lynnlangit
|
#@title 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
#
# https://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.
!pip install tensorflow==2.4.1
!pip install tensorflow-quantum
# Update package resources to account for version changes.
import importlib, pkg_resources
importlib.reload(pkg_resources)
import tensorflow as tf
import tensorflow_quantum as tfq
import cirq
import sympy
import numpy as np
import seaborn as sns
import collections
# visualization tools
%matplotlib inline
import matplotlib.pyplot as plt
from cirq.contrib.svg import SVGCircuit
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# Rescale the images from [0,255] to the [0.0,1.0] range.
x_train, x_test = x_train[..., np.newaxis]/255.0, x_test[..., np.newaxis]/255.0
print("Number of original training examples:", len(x_train))
print("Number of original test examples:", len(x_test))
def filter_36(x, y):
keep = (y == 3) | (y == 6)
x, y = x[keep], y[keep]
y = y == 3
return x,y
x_train, y_train = filter_36(x_train, y_train)
x_test, y_test = filter_36(x_test, y_test)
print("Number of filtered training examples:", len(x_train))
print("Number of filtered test examples:", len(x_test))
print(y_train[0])
plt.imshow(x_train[0, :, :, 0])
plt.colorbar()
x_train_small = tf.image.resize(x_train, (4,4)).numpy()
x_test_small = tf.image.resize(x_test, (4,4)).numpy()
print(y_train[0])
plt.imshow(x_train_small[0,:,:,0], vmin=0, vmax=1)
plt.colorbar()
def remove_contradicting(xs, ys):
mapping = collections.defaultdict(set)
orig_x = {}
# Determine the set of labels for each unique image:
for x,y in zip(xs,ys):
orig_x[tuple(x.flatten())] = x
mapping[tuple(x.flatten())].add(y)
new_x = []
new_y = []
for flatten_x in mapping:
x = orig_x[flatten_x]
labels = mapping[flatten_x]
if len(labels) == 1:
new_x.append(x)
new_y.append(next(iter(labels)))
else:
# Throw out images that match more than one label.
pass
num_uniq_3 = sum(1 for value in mapping.values() if len(value) == 1 and True in value)
num_uniq_6 = sum(1 for value in mapping.values() if len(value) == 1 and False in value)
num_uniq_both = sum(1 for value in mapping.values() if len(value) == 2)
print("Number of unique images:", len(mapping.values()))
print("Number of unique 3s: ", num_uniq_3)
print("Number of unique 6s: ", num_uniq_6)
print("Number of unique contradicting labels (both 3 and 6): ", num_uniq_both)
print()
print("Initial number of images: ", len(xs))
print("Remaining non-contradicting unique images: ", len(new_x))
return np.array(new_x), np.array(new_y)
x_train_nocon, y_train_nocon = remove_contradicting(x_train_small, y_train)
THRESHOLD = 0.5
x_train_bin = np.array(x_train_nocon > THRESHOLD, dtype=np.float32)
x_test_bin = np.array(x_test_small > THRESHOLD, dtype=np.float32)
_ = remove_contradicting(x_train_bin, y_train_nocon)
def convert_to_circuit(image):
"""Encode truncated classical image into quantum datapoint."""
values = np.ndarray.flatten(image)
qubits = cirq.GridQubit.rect(4, 4)
circuit = cirq.Circuit()
for i, value in enumerate(values):
if value:
circuit.append(cirq.X(qubits[i]))
return circuit
x_train_circ = [convert_to_circuit(x) for x in x_train_bin]
x_test_circ = [convert_to_circuit(x) for x in x_test_bin]
SVGCircuit(x_train_circ[0])
bin_img = x_train_bin[0,:,:,0]
indices = np.array(np.where(bin_img)).T
indices
x_train_tfcirc = tfq.convert_to_tensor(x_train_circ)
x_test_tfcirc = tfq.convert_to_tensor(x_test_circ)
class CircuitLayerBuilder():
def __init__(self, data_qubits, readout):
self.data_qubits = data_qubits
self.readout = readout
def add_layer(self, circuit, gate, prefix):
for i, qubit in enumerate(self.data_qubits):
symbol = sympy.Symbol(prefix + '-' + str(i))
circuit.append(gate(qubit, self.readout)**symbol)
demo_builder = CircuitLayerBuilder(data_qubits = cirq.GridQubit.rect(4,1),
readout=cirq.GridQubit(-1,-1))
circuit = cirq.Circuit()
demo_builder.add_layer(circuit, gate = cirq.XX, prefix='xx')
SVGCircuit(circuit)
def create_quantum_model():
"""Create a QNN model circuit and readout operation to go along with it."""
data_qubits = cirq.GridQubit.rect(4, 4) # a 4x4 grid.
readout = cirq.GridQubit(-1, -1) # a single qubit at [-1,-1]
circuit = cirq.Circuit()
# Prepare the readout qubit.
circuit.append(cirq.X(readout))
circuit.append(cirq.H(readout))
builder = CircuitLayerBuilder(
data_qubits = data_qubits,
readout=readout)
# Then add layers (experiment by adding more).
builder.add_layer(circuit, cirq.XX, "xx1")
builder.add_layer(circuit, cirq.ZZ, "zz1")
# Finally, prepare the readout qubit.
circuit.append(cirq.H(readout))
return circuit, cirq.Z(readout)
model_circuit, model_readout = create_quantum_model()
# Build the Keras model.
model = tf.keras.Sequential([
# The input is the data-circuit, encoded as a tf.string
tf.keras.layers.Input(shape=(), dtype=tf.string),
# The PQC layer returns the expected value of the readout gate, range [-1,1].
tfq.layers.PQC(model_circuit, model_readout),
])
y_train_hinge = 2.0*y_train_nocon-1.0
y_test_hinge = 2.0*y_test-1.0
def hinge_accuracy(y_true, y_pred):
y_true = tf.squeeze(y_true) > 0.0
y_pred = tf.squeeze(y_pred) > 0.0
result = tf.cast(y_true == y_pred, tf.float32)
return tf.reduce_mean(result)
model.compile(
loss=tf.keras.losses.Hinge(),
optimizer=tf.keras.optimizers.Adam(),
metrics=[hinge_accuracy])
print(model.summary())
EPOCHS = 3
BATCH_SIZE = 32
NUM_EXAMPLES = len(x_train_tfcirc)
x_train_tfcirc_sub = x_train_tfcirc[:NUM_EXAMPLES]
y_train_hinge_sub = y_train_hinge[:NUM_EXAMPLES]
qnn_history = model.fit(
x_train_tfcirc_sub, y_train_hinge_sub,
batch_size=32,
epochs=EPOCHS,
verbose=1,
validation_data=(x_test_tfcirc, y_test_hinge))
qnn_results = model.evaluate(x_test_tfcirc, y_test)
def create_classical_model():
# A simple model based off LeNet from https://keras.io/examples/mnist_cnn/
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(32, [3, 3], activation='relu', input_shape=(28,28,1)))
model.add(tf.keras.layers.Conv2D(64, [3, 3], activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))
model.add(tf.keras.layers.Dropout(0.25))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(1))
return model
model = create_classical_model()
model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
optimizer=tf.keras.optimizers.Adam(),
metrics=['accuracy'])
model.summary()
model.fit(x_train,
y_train,
batch_size=128,
epochs=1,
verbose=1,
validation_data=(x_test, y_test))
cnn_results = model.evaluate(x_test, y_test)
def create_fair_classical_model():
# A simple model based off LeNet from https://keras.io/examples/mnist_cnn/
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(4,4,1)))
model.add(tf.keras.layers.Dense(2, activation='relu'))
model.add(tf.keras.layers.Dense(1))
return model
model = create_fair_classical_model()
model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
optimizer=tf.keras.optimizers.Adam(),
metrics=['accuracy'])
model.summary()
model.fit(x_train_bin,
y_train_nocon,
batch_size=128,
epochs=20,
verbose=2,
validation_data=(x_test_bin, y_test))
fair_nn_results = model.evaluate(x_test_bin, y_test)
qnn_accuracy = qnn_results[1]
cnn_accuracy = cnn_results[1]
fair_nn_accuracy = fair_nn_results[1]
sns.barplot(["Quantum", "Classical, full", "Classical, fair"],
[qnn_accuracy, cnn_accuracy, fair_nn_accuracy])
|
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/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
from qiskit.tools.visualization import plot_histogram
q0 = QuantumRegister(1); q1 = QuantumRegister(1)
c0 = ClassicalRegister(1); c1 = ClassicalRegister(1)
qc = QuantumCircuit(q0,q1,c0,c1)
qc.h(q0); qc.cx(q0,q1) # emaranhamento compartilhado entre Alice e Bob
qc.barrier()
qc.x(q0); qc.sdg(q0); qc.h(q0); qc.measure(q0,c0) # Medida de Alice
qc.barrier()
qc.z(q1).c_if(c0, 1) # acao de Bob condicionada no cbit enviado por Alice
qc.barrier()
qc.sdg(q1); qc.h(q1); qc.measure(q1,c1) # passa da base circular pra computacional
qc.draw(output='mpl')
jobS = execute(qc, backend = simulator, shots = nshots)
plot_histogram(jobS.result().get_counts(qc))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
YEAST = "----------------------------------MM----------------------------"
PROTOZOAN = "--MM---------------M------------MMMM---------------M------------"
BACTERIAL = "---M---------------M------------MMMM---------------M------------"
import sys
import numpy as np
import math
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import execute
def encode_bitstring(bitstring, qr, cr, inverse=False):
"""
create a circuit for constructing the quantum superposition of the bitstring
"""
n = math.ceil(math.log2(len(bitstring))) + 1 #number of qubits
assert n > 2, "the length of bitstring must be at least 2"
qc = QuantumCircuit(qr, cr)
#the probability amplitude of the desired state
desired_vector = np.array([ 0.0 for i in range(2**n) ]) #initialize to zero
amplitude = np.sqrt(1.0/2**(n-1))
for i, b in enumerate(bitstring):
pos = i * 2
if b == "1" or b == "M":
pos += 1
desired_vector[pos] = amplitude
if not inverse:
qc.initialize(desired_vector, [ qr[i] for i in range(n) ] )
qc.barrier(qr)
else:
qc.initialize(desired_vector, [ qr[i] for i in range(n) ] ).inverse() #invert the circuit
for i in range(n):
qc.measure(qr[i], cr[i])
print()
return qc
n = math.ceil(math.log2(len(YEAST))) + 1 #number of qubits
qr = QuantumRegister(n)
cr = ClassicalRegister(n)
qc_yeast = encode_bitstring(YEAST, qr, cr)
qc_protozoan = encode_bitstring(PROTOZOAN, qr, cr)
qc_bacterial = encode_bitstring(BACTERIAL, qr, cr)
circs = {"YEAST": qc_yeast, "PROTOZOAN": qc_protozoan, "BACTERIAL": qc_bacterial}
inverse_qc_yeast = encode_bitstring(YEAST, qr, cr, inverse=True)
inverse_qc_protozoan = encode_bitstring(PROTOZOAN, qr, cr, inverse=True)
inverse_qc_bacterial = encode_bitstring(BACTERIAL, qr, cr, inverse=True)
inverse_circs = {"YEAST": inverse_qc_yeast, "PROTOZOAN": inverse_qc_protozoan, "BACTERIAL": inverse_qc_bacterial}
from qiskit import IBMQ, BasicAer
key = "PROTOZOAN" #the name of the code used as key to find similar ones
# use local simulator
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
combined_circs = {}
count = {}
most_similar, most_similar_score = "", -1.0
for other_key in inverse_circs:
if other_key == key:
continue
combined_circs[other_key] = circs[key] + inverse_circs[other_key] #combined circuits to look for similar codes
job = execute(combined_circs[other_key], backend=backend,shots=shots)
st = job.result().get_counts(combined_circs[other_key])
if "0"*n in st:
sim_score = st["0"*n]/shots
else:
sim_score = 0.0
print("Similarity score of",key,"and",other_key,"is",sim_score)
if most_similar_score < sim_score:
most_similar, most_similar_score = other_key, sim_score
print("[ANSWER]", key,"is most similar to", most_similar)
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
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.i(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)
from qiskit import QuantumCircuit, IBMQ, execute
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram
IBMQ.save_account('your_token')
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
qcomp = provider.get_backend('ibmq_manila')
job = execute(qc, backend = qcomp, shots = 1000)
job_monitor(job)
result = job.result()
counts = result.get_counts(qc)
print("Total counts for qubit states are:", counts)
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit import Parameter
from qiskit import QuantumCircuit
theta = Parameter('$\\theta$')
chsh_circuits_no_meas = QuantumCircuit(2)
chsh_circuits_no_meas.h(0)
chsh_circuits_no_meas.cx(0, 1)
chsh_circuits_no_meas.ry(theta, 0)
chsh_circuits_no_meas.draw('mpl')
import numpy as np
number_of_phases = 21
phases = np.linspace(0, 2*np.pi, number_of_phases)
# Phases need to be expressed as list of lists in order to work
individual_phases = [[ph] for ph in phases]
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit_ibm_runtime import Estimator, Session
from qiskit.quantum_info import SparsePauliOp
ZZ = SparsePauliOp.from_list([("ZZ", 1)])
ZX = SparsePauliOp.from_list([("ZX", 1)])
XZ = SparsePauliOp.from_list([("XZ", 1)])
XX = SparsePauliOp.from_list([("XX", 1)])
ops = [ZZ, ZX, XZ, XX]
chsh_est_sim = []
# Simulator
with Session(service=service, backend=backend):
estimator = Estimator()
for op in ops:
job = estimator.run(
circuits=[chsh_circuits_no_meas]*len(individual_phases),
observables=[op]*len(individual_phases),
parameter_values=individual_phases)
est_result = job.result()
chsh_est_sim.append(est_result)
# <CHSH1> = <AB> - <Ab> + <aB> + <ab>
chsh1_est_sim = chsh_est_sim[0].values - chsh_est_sim[1].values + chsh_est_sim[2].values + chsh_est_sim[3].values
# <CHSH2> = <AB> + <Ab> - <aB> + <ab>
chsh2_est_sim = chsh_est_sim[0].values + chsh_est_sim[1].values - chsh_est_sim[2].values + chsh_est_sim[3].values
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
fig, ax = plt.subplots(figsize=(10, 6))
# results from a simulator
ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Simulation')
ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Simulation')
# classical bound +-2
ax.axhline(y=2, color='r', linestyle='--')
ax.axhline(y=-2, color='r', linestyle='--')
# quantum bound, +-2√2
ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.')
ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.')
# set x tick labels to the unit of pi
ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5))
# set title, labels, and legend
plt.title('Violation of CHSH Inequality')
plt.xlabel('Theta')
plt.ylabel('CHSH witness')
plt.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Alap Qiskit könyvtárak
from qiskit import QuantumCircuit, transpile
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# IBM Quantum account betöltése
service = QiskitRuntimeService(channel="ibm_quantum")
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute
from qiskit.circuit import ControlledGate
# Tegyük fel, hogy n a qubitek száma
n = 3
# Hozzunk létre egy kvantum regisztert n qubittal a függvényhez és 1 qubittal a CNOT céljához
qr = QuantumRegister(n + 1)
# Hozzunk létre egy klasszikus regisztert a méréshez
cr = ClassicalRegister(n + 1)
circuit = QuantumCircuit(qr, cr)
# Az f függvény implementálása: Bitenkénti NOT művelet minden egyes első n qubit esetén (csak próbaként)
for qubit in range(n):
circuit.x(qr[qubit])
# Alkalmazzunk CNOT-t az n-edik qubit vezérlésével és az (n+1)-edik qubit célpontjával
circuit.cnot(qr[n-1], qr[n])
# Mérjük meg a qubiteket
circuit.measure(qr, cr)
print(circuit)
# szimuláció
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=1024)
result = job.result()
counts = result.get_counts(circuit)
print(counts)
|
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/DRA-chaos/Quantum-Classical-Hyrid-Neural-Network-for-binary-image-classification-using-PyTorch-Qiskit-pipeline
|
DRA-chaos
|
!pip install qiskit
# check if CUDA is available
import torch
train_on_gpu = torch.cuda.is_available()
if not train_on_gpu:
print('CUDA is not available. Training on CPU ...')
else:
print('CUDA is available! Training on GPU ...')
import numpy as np
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
from qiskit.visualization import *
import numpy as np
import torch
from torch.autograd import Function
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute
from qiskit.circuit import Parameter
from qiskit import Aer
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 QuantumCircuit:
"""
This class provides a simple interface for interaction
with the quantum circuit
"""
def __init__(self, n_qubits, backend, shots):
# --- Circuit definition ---
self._circuit = qiskit.QuantumCircuit(n_qubits)
all_qubits = [i for i in range(n_qubits)]
self.theta = qiskit.circuit.Parameter('theta')
self._circuit.h(all_qubits)
self._circuit.barrier()
self._circuit.ry(self.theta, all_qubits)
self._circuit.measure_all()
# ---------------------------
self.backend = backend
self.shots = shots
def run(self, thetas):
t_qc = transpile(self._circuit,
self.backend)
qobj = assemble(t_qc,
shots=self.shots,
parameter_binds = [{self.theta: theta} for theta in thetas])
job = self.backend.run(qobj)
result = job.result().get_counts()
counts = np.array(list(result.values()))
states = np.array(list(result.keys())).astype(float)
# Compute probabilities for each state
probabilities = counts / self.shots
# Get state expectation
expectation = np.sum(states * probabilities)
return np.array([expectation])
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
expectation_z = ctx.quantum_circuit.run(input[0].tolist())
result = torch.tensor([expectation_z])
ctx.save_for_backward(input, result)
return result
@staticmethod
def backward(ctx, grad_output):
""" Backward pass computation """
input, expectation_z = ctx.saved_tensors
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.shift
shift_left = input_list - np.ones(input_list.shape) * ctx.shift
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients.append(gradient)
gradients = np.array([gradients]).T
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class Hybrid(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, shift):
super(Hybrid, self).__init__()
self.quantum_circuit = QuantumCircuit(1, backend, shots)
self.shift = shift
def forward(self, input):
return HybridFunction.apply(input, self.quantum_circuit, self.shift)
import torchvision
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors
cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform)
len(cifar_trainset)
from torch.utils.data import DataLoader, random_split
#cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform)
labels = cifar_trainset.targets # get the labels for the data
labels = np.array(labels)
idx1 = np.where(labels == 0) # filter on aeroplanes
idx2 = np.where(labels == 1) # filter on automobiles
# Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set)
n=100
# concatenate the data indices
idx = np.concatenate((idx1[0][0:n],idx2[0][0:n]))
# create the filtered dataset for our training set
cifar_trainset.targets = labels[idx]
cifar_trainset.data = cifar_trainset.data[idx]
cifar_trainset, valid = random_split(cifar_trainset,[150,50])
train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True)
valid_loader = torch.utils.data.DataLoader(valid, batch_size=1, shuffle=True)
@torch.no_grad()
def get_all_preds(model, test_loader):
all_preds = torch.tensor([])
for batch in test_loader:
images, labels = batch
preds = model(images)
all_preds = torch.cat(
(all_preds, preds)
,dim=0
)
return all_preds
import numpy as np
import matplotlib.pyplot as plt
n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 2))
while n_samples_show > 0:
images, targets = data_iter.__next__()
images=images.squeeze()
axes[n_samples_show - 1].imshow(images[0].numpy(), cmap='gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
import torchvision
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors
cifar_testset = datasets.CIFAR10(root='./data1', train=False, download=True, transform=transform)
labels = cifar_testset.targets # get the labels for the data
labels = np.array(labels)
idx1 = np.where(labels == 0) # filter on aeroplanes
idx2 = np.where(labels == 1) # filter on automobiles
# Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set)
n=100
# concatenate the data indices
idx = np.concatenate((idx1[0][0:n],idx2[0][0:n]))
# create the filtered dataset for our training set
cifar_testset.targets = labels[idx]
cifar_testset.data = cifar_testset.data[idx]
test_loader = torch.utils.data.DataLoader(cifar_testset, batch_size=1, shuffle=False)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(500, 500)
self.fc2 = nn.Linear(500, 1)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(1, -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x)
return torch.cat((x, 1 - x), -1)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 30
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 40
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 50
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
###This is CPU run not GPU
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 30
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(20, 500)
self.fc2 = nn.Linear(500, 1)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.max_pool2d(x, 2) #Added layer
x = F.relu(self.conv2(x))
x = self.dropout(x) #Added layer
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(1, -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x)
return torch.cat((x, 1 - x), -1)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 5
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 30
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 40
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(20, 500)
self.fc2 = nn.Linear(500, 1)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = self.dropout(x)
x = F.max_pool2d(x, 2)
x = torch.flatten(x, 1) #Added layer
x = self.dropout(x)
x = x.view(1, -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x)
return torch.cat((x, 1 - x), -1)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = self.dropout(x)
x = F.max_pool2d(x, 2)
x = torch.flatten(x, 1) #Added layer
x = self.dropout(x)
x = x.view(1, -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x)
return torch.cat((x, 1 - x), -1)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 5
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 30
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 40
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(500, 500)
self.fc2 = nn.Linear(500, 1)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
#x = self.dropout(x) omitting this layer
x = x.view(1, -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x)
return torch.cat((x, 1 - x), -1)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 30
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 40
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 50
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.0005)
loss_func = nn.NLLLoss()
epochs = 30
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.0005)
loss_func = nn.CrossEntropyLoss()
epochs = 30
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
valid_loss_min = np.Inf # track change in validation loss
optimizer = optim.Adam(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 30
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch+1, loss_list[epoch], loss_list_V[-1]))
if (validation_loss)<=(valid_loss_min):
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
validation_loss))
torch.save(model.state_dict(), 'model_cifar.pt')
valid_loss_min = validation_loss
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from __future__ import annotations
import numpy as np
import networkx as nx
num_nodes = 4
w = np.array([[0., 1., 1., 0.],
[1., 0., 1., 1.],
[1., 1., 0., 1.],
[0., 1., 1., 0.]])
G = nx.from_numpy_array(w)
layout = nx.random_layout(G, seed=10)
colors = ['r', 'g', 'b', 'y']
nx.draw(G, layout, node_color=colors)
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels);
def objective_value(x: np.ndarray, w: np.ndarray) -> float:
"""Compute the value of a cut.
Args:
x: Binary string as numpy array.
w: Adjacency matrix.
Returns:
Value of the cut.
"""
X = np.outer(x, (1 - x))
w_01 = np.where(w != 0, 1, 0)
return np.sum(w_01 * X)
def bitfield(n: int, L: int) -> list[int]:
result = np.binary_repr(n, L)
return [int(digit) for digit in result] # [2:] to chop off the "0b" part
# use the brute-force way to generate the oracle
L = num_nodes
max = 2**L
sol = np.inf
for i in range(max):
cur = bitfield(i, L)
how_many_nonzero = np.count_nonzero(cur)
if how_many_nonzero * 2 != L: # not balanced
continue
cur_v = objective_value(np.array(cur), w)
if cur_v < sol:
sol = cur_v
print(f'Objective value computed by the brute-force method is {sol}')
from qiskit.quantum_info import Pauli, SparsePauliOp
def get_operator(weight_matrix: np.ndarray) -> tuple[SparsePauliOp, float]:
r"""Generate Hamiltonian for the graph partitioning
Notes:
Goals:
1 Separate the vertices into two set of the same size.
2 Make sure the number of edges between the two set is minimized.
Hamiltonian:
H = H_A + H_B
H_A = sum\_{(i,j)\in E}{(1-ZiZj)/2}
H_B = (sum_{i}{Zi})^2 = sum_{i}{Zi^2}+sum_{i!=j}{ZiZj}
H_A is for achieving goal 2 and H_B is for achieving goal 1.
Args:
weight_matrix: Adjacency matrix.
Returns:
Operator for the Hamiltonian
A constant shift for the obj function.
"""
num_nodes = len(weight_matrix)
pauli_list = []
coeffs = []
shift = 0
for i in range(num_nodes):
for j in range(i):
if weight_matrix[i, j] != 0:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append(Pauli((z_p, x_p)))
coeffs.append(-0.5)
shift += 0.5
for i in range(num_nodes):
for j in range(num_nodes):
if i != j:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append(Pauli((z_p, x_p)))
coeffs.append(1.0)
else:
shift += 1
return SparsePauliOp(pauli_list, coeffs=coeffs), shift
qubit_op, offset = get_operator(w)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.primitives import Sampler
from qiskit.quantum_info import Pauli, Statevector
from qiskit.result import QuasiDistribution
from qiskit.utils import algorithm_globals
sampler = Sampler()
def sample_most_likely(state_vector: QuasiDistribution | Statevector) -> np.ndarray:
"""Compute the most likely binary string from state vector.
Args:
state_vector: State vector or quasi-distribution.
Returns:
Binary string as an array of ints.
"""
if isinstance(state_vector, QuasiDistribution):
values = list(state_vector.values())
else:
values = state_vector
n = int(np.log2(len(values)))
k = np.argmax(np.abs(values))
x = bitfield(k, n)
x.reverse()
return np.asarray(x)
algorithm_globals.random_seed = 10598
optimizer = COBYLA()
qaoa = QAOA(sampler, optimizer, reps=2)
result = qaoa.compute_minimum_eigenvalue(qubit_op)
x = sample_most_likely(result.eigenstate)
print(x)
print(f'Objective value computed by QAOA is {objective_value(x, w)}')
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.quantum_info import Operator
npme = NumPyMinimumEigensolver()
result = npme.compute_minimum_eigenvalue(Operator(qubit_op))
x = sample_most_likely(result.eigenstate)
print(x)
print(f'Objective value computed by the NumPyMinimumEigensolver is {objective_value(x, w)}')
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
from qiskit.circuit.library import TwoLocal
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 10598
optimizer = COBYLA()
ansatz = TwoLocal(qubit_op.num_qubits, "ry", "cz", reps=2, entanglement="linear")
sampling_vqe = SamplingVQE(sampler, ansatz, optimizer)
result = sampling_vqe.compute_minimum_eigenvalue(qubit_op)
x = sample_most_likely(result.eigenstate)
print(x)
print(f"Objective value computed by VQE is {objective_value(x, w)}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_jakarta')
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
def bernstein_vazirani(s):
ls = len(s)
qc = QuantumCircuit(ls+1,ls)
qc.h(range(ls))
qc.x(ls)
qc.h(ls)
qc.barrier();
for ii, yesno in enumerate(reversed(s)): # the black box
if yesno == '1':
qc.cx(ii, ls);
qc.barrier();
qc.h(range(ls));
qc.barrier();
qc.measure(range(ls),range(ls))
return qc
s = '011' # secretnumber
qc = bernstein_vazirani(s)
qc.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 1).result()
counts = result.get_counts()
print(counts)
jobE = execute(qc, backend = device, shots = nshots)
job_monitor(jobE)
jobS = execute(qc, backend = simulator, shots = nshots)
plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)],
bar_labels = False, legend = ['sim', 'exp'])
|
https://github.com/qiskit-community/qgss-2023
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import SparsePauliOp
def heisenberg_hamiltonian(
length: int, jx: float = 1.0, jy: float = 0.0, jz: float = 0.0
) -> SparsePauliOp:
terms = []
for i in range(length - 1):
if jx:
terms.append(("XX", [i, i + 1], jx))
if jy:
terms.append(("YY", [i, i + 1], jy))
if jz:
terms.append(("ZZ", [i, i + 1], jz))
return SparsePauliOp.from_sparse_list(terms, num_qubits=length)
def state_prep_circuit(num_qubits: int, layers: int = 1) -> QuantumCircuit:
qubits = QuantumRegister(num_qubits, name="q")
circuit = QuantumCircuit(qubits)
circuit.h(qubits)
for _ in range(layers):
for i in range(0, num_qubits - 1, 2):
circuit.cx(qubits[i], qubits[i + 1])
circuit.ry(0.1, qubits)
for i in range(1, num_qubits - 1, 2):
circuit.cx(qubits[i], qubits[i + 1])
circuit.ry(0.1, qubits)
return circuit
length = 5
hamiltonian = heisenberg_hamiltonian(length, 1.0, 1.0)
circuit = state_prep_circuit(length, layers=2)
print(hamiltonian)
circuit.draw("mpl")
from qiskit_aer.primitives import Estimator
estimator = Estimator(approximation=True)
job = estimator.run(circuit, hamiltonian, shots=None)
result = job.result()
exact_value = result.values[0]
print(f"Exact energy: {exact_value}")
from qiskit_ibm_runtime import QiskitRuntimeService
hub = "ibm-q-internal"
group = "deployed"
project = "default"
service = QiskitRuntimeService(instance=f"{hub}/{group}/{project}")
from qiskit_ibm_runtime import Estimator, Options, Session
from qiskit.transpiler import CouplingMap
backend = service.get_backend("simulator_statevector")
# set simulation options
simulator = {
"basis_gates": ["id", "rz", "sx", "cx", "reset"],
"coupling_map": list(CouplingMap.from_line(length + 1)),
}
shots = 10000
import math
options = Options(
simulator=simulator,
resilience_level=0,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
from qiskit_aer.noise import NoiseModel, ReadoutError
noise_model = NoiseModel()
##### your code here #####
# add modest readout error on all qubits
p0given1 = 0.05
p1given0 = 0.02
readout_error = ReadoutError(
[
[1 - p1given0, p1given0],
[p0given1, 1 - p0given1],
]
)
noise_model.add_all_qubit_readout_error(readout_error)
# add really bad readout error on qubit 0
p0given1 = 0.5
p1given0 = 0.2
readout_error = ReadoutError(
[
[1 - p1given0, p1given0],
[p0given1, 1 - p0given1],
]
)
noise_model.add_readout_error(readout_error, [0])
print(noise_model)
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex1
grade_lab5_ex1(noise_model)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=0,
transpilation=dict(initial_layout=list(range(length))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=0,
transpilation=dict(initial_layout=list(range(1, length + 1))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
transpilation=dict(initial_layout=list(range(1, length + 1))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
new_shots: int
##### your code here #####
new_shots = 20000
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex2
grade_lab5_ex2(new_shots)
from qiskit_aer.noise import depolarizing_error
noise_model = NoiseModel()
##### your code here #####
noise_model.add_all_qubit_quantum_error(depolarizing_error(0.01, 2), ["cx"])
print(noise_model)
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex3
grade_lab5_ex3(noise_model)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=2,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
from qiskit_aer.noise import depolarizing_error, amplitude_damping_error
noise_model = NoiseModel()
##### your code here #####
noise_model.add_all_qubit_quantum_error(amplitude_damping_error(0.01).tensor(amplitude_damping_error(0.05)), ["cx"])
print(noise_model)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=2,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.circuit.library import UCCSD
ansatz = UCCSD()
ansatz.num_spin_orbitals = 10
from qiskit_nature.second_q.circuit.library import UCCSD
ansatz = UCCSD()
ansatz.num_spatial_orbitals = 5
from qiskit_nature.circuit.library import UCC, UVCC
ucc = UCC(qubit_converter=None, num_particles=None, num_spin_orbitals=None, excitations=None)
uvcc = UVCC(qubit_converter=None, num_modals=None, excitations=None)
from qiskit_nature.second_q.circuit.library import UCC, UVCC
ucc = UCC(num_spatial_orbitals=None, num_particles=None, excitations=None, qubit_converter=None)
uvcc = UVCC(num_modals=None, excitations=None, qubit_converter=None)
from qiskit_nature.circuit.library import HartreeFock, VSCF
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import DirectMapper, JordanWignerMapper
hf = HartreeFock(
num_spin_orbitals=4, num_particles=(1, 1), qubit_converter=QubitConverter(JordanWignerMapper())
)
vscf = VSCF(num_modals=[2, 2])
from qiskit_nature.second_q.circuit.library import HartreeFock, VSCF
from qiskit_nature.second_q.mappers import DirectMapper, JordanWignerMapper, QubitConverter
hf = HartreeFock()
hf.num_spatial_orbitals = 2
hf.num_particles = (1, 1)
hf.qubit_converter = QubitConverter(JordanWignerMapper())
vscf = VSCF()
vscf.num_modals = [2, 2]
from qiskit.providers.basicaer import BasicAer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms.ground_state_solvers import VQEUCCFactory
quantum_instance = QuantumInstance(BasicAer.get_backend("statevector_simulator"))
vqe_factory = VQEUCCFactory(quantum_instance=quantum_instance)
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.circuit.library import UCCSD
from qiskit_nature.second_q.algorithms.ground_state_solvers import VQEUCCFactory
estimator = Estimator()
ansatz = UCCSD()
optimizer = SLSQP()
vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer)
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver, VQEUCCFactory
from qiskit_nature.algorithms.excited_states_solvers import QEOM
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
vqe_factory = VQEUCCFactory()
converter = QubitConverter(JordanWignerMapper())
ground_state_solver = GroundStateEigensolver(converter, vqe_factory)
qeom = QEOM(ground_state_solver)
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.circuit.library import UCCSD
from qiskit_nature.second_q.algorithms.ground_state_solvers import (
GroundStateEigensolver,
VQEUCCFactory,
)
from qiskit_nature.second_q.algorithms.excited_states_solvers import QEOM
from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter
estimator = Estimator()
ansatz = UCCSD()
optimizer = SLSQP()
vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer)
converter = QubitConverter(JordanWignerMapper())
ground_state_solver = GroundStateEigensolver(converter, vqe_factory)
qeom = QEOM(ground_state_solver, estimator)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
#%matplotlib inline
from qiskit import *
from qiskit.tools.monitor import *
from qiskit.providers.ibmq import least_busy
import numpy as np
#Function to create the circuits for the CHSH game
def CHSH_circuit(x,y,a0=0,a1=np.pi/2,b0=np.pi/4,b1=-np.pi/4):
#x: bit received by Alice
#y: bit received by Bob
#a0: measure angle used by Alice when she receives 0
#a1: measure angle used by Alice when she receives 1
#b0: measure angle used by Bob when he receives 0
#b1: measure angle used by Bob when he receives 1
circ = QuantumCircuit(2,2)
# First, we create a Bell pair
circ.h(0)
circ.cx(0,1)
# Now, we apply rotations for Alice and Bob depending on the bits they have received
if(x==0):
circ.ry(a0,0)
else:
circ.ry(a1,0)
if(y==0):
circ.ry(b0,1)
else:
circ.ry(b1,1)
# We measure
circ.measure(range(2),range(2)) # Medimos
return circ
def winning_probability(backend, shots = 8192, a0=0,a1=np.pi/2,b0=np.pi/4,b1=-np.pi/4):
total = 0
circuits = [CHSH_circuit(0,0,a0,a1,b0,b1), CHSH_circuit(0,1,a0,a1,b0,b1), CHSH_circuit(1,0,a0,a1,b0,b1), CHSH_circuit(1,1,a0,a1,b0,b1)] # We 'pack' four different circuits for execution
job = execute(circuits, backend=backend, shots = shots)
# For the first three circuits, the winning condition is that Alice's and Bob's outputs are equal
for qc in circuits[0:3]:
counts = job.result().get_counts(qc)
if('00' in counts):
total += counts['00']
if('11' in counts):
total += counts['11']
# For the fourth circuit, Alice's and Bob's outputs must be different for them to win
counts = job.result().get_counts(circuits[3])
if('01' in counts):
total += counts['01']
if('10' in counts):
total += counts['10']
return total/(4*shots)
# Backend definition
backend = Aer.get_backend('qasm_simulator')
# Execution
print(winning_probability(backend))
# Load the account
provider = IBMQ.load_account()
# We execute on the least busy device (among the actual quantum computers)
backend = least_busy(provider.backends(operational = True, simulator=False, status_msg='active',
filters=lambda x: x.configuration().n_qubits > 1))
print("We are executing on...",backend)
print(winning_probability(backend))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.barrier()
circuit.h(0)
circuit = RemoveBarriers()(circuit)
circuit.draw('mpl')
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#
# OUR SOLUTION
#
# initial case
# We assume that the probability of getting head is 1 at the beginning,
# because Asja will start with one euro.
prob_head = 1
prob_tail = 0
#
# first coin-flip
#
# if the last result was head
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
# if the last result was tail
# we know that prob_tail is 0 at the beginning
# but we still keep these two lines to have the same code for each iteration
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
# update the probabilities at the end of coin toss
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
#
# second coin-flip
#
# we do the same calculations
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
#
# third coin-flip
#
# we do the same calculations
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
# print prob_head and prob_tail
print("the probability of getting head",prob_head)
print("the probability of getting tail",prob_tail)
#
# your solution is here
#
|
https://github.com/renatawong/quantum-protein-structure-prediction
|
renatawong
|
'''
(C) Renata Wong (CGU-CoIC, NCTS-NTU) 2023.
This is a simplified validation code for amino acid sequences of length 3 only.
Note: the full algorithm requires a number of qubits that is not achievable on present
day devices. This simplification is the largest possible on a quantum simulator
and requires the following resources:
Number of qubits: 25
Number of gates per iteration: 15 H + 67 X + 24 CX + 724 CCX + 2 CZ = 832
Number of iterations: 4
Runtime: about 2 minutes
Description of the algorithm:
The algorithm is based on Grover's amplitude amplification routine.
In this routine, Algorithm 1 through Algorithm 4 are executed a certain number
of times, which is determined by the formula pi/4 * sqrt(N/M) where N is the
total number of possible conformations (for sequence of 3 qubits, this is 8)
and M is the number of solutions (here we are looking for a single solution only).
In each iteration of amplitude amplification, the conformation (solution) is marked
and then that conformation's quantum amplitude is amplified. Upon measurement we
are guaranteed to obtain the solution with a high probability of 0.9993.
See the reference paper for the calculation of this theoretical probability.
Algorithm 1: generates the conformational space by calculating the coordinates
of each conformation based on the values of w.
As this is a 2D model, we need to consider 4 neighbouring amino acids:
west (w=11), east (w=01), north (w=00), adn south (w=10).
In this simplified version of the algorithm, we arbitrarily choose
the conformation w1w2=1100. Hence, this conformation corresponds to the
one shown in Fig. 8 of the reference paper.
Algorithm 2: calculates the energy values for each conformation and stores them
in qubit e. By design, only 1 conformation will have e = 1.
This conformation is: w=1100.
Algorithm 3: uncomputing coordinate values for all conformations
Algorithm 4: Grover's algorithm executed once on vectors w and e
the single solution 1100 has theoretical probability of 0.9993
Measurement: measure the vector |w> which encodes all directional transitions
for a given conformation
Reference: R. Wong and W-L Chang, Fast quantum algorithm for protein structure prediction in
hydrophobic-hydrophilic model, Journal of Parallel and Distributed Computing 164: 178-190
doi: 10.1016/j.jpdc.2022.03.011
'''
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import numpy as np
import math
from qiskit.tools.visualization import plot_histogram
# Attention: the following code is for sequences of length 3 bit only
length = 3
'''
This algorithm uses two's complement to represent the Cartesian coordinates
of amino acids, i.e.,
0 = 000, 1 = 001, 2 = 010, 3 = 011, -1 = 111, -2 = 110, -3 = 101
(-4 = 100, not needed)
For the purpose of this simplified validation we don't need the fixed
coordinates of the first amino acid which are all 0
Using two's complement allows us to design a single subcircuit for both
addition and subtraction.
'''
# quantum register holding the x coordinates for x1, x2 etc. (x0 = 000 omitted)
x = QuantumRegister(length*2, 'x')
# quantum register holding the y coordinates for y1, y2 etc. (y0 = 000 omitted)
y = QuantumRegister(length*2, 'y')
# quantum register holding the controls w0, w1, etc.
w = QuantumRegister(2*(length-1), 'w')
# register holding the binary 1 (3 qubits)
a = QuantumRegister(length,'a')
# register holding the two's complement of 1 (3 qubits) not needed,
# can be replaced by a with the first 2 qubits negated.
# register holding the carry bit for ripple-carry adder
c = QuantumRegister(1,'c')
# quantum register that holds the energy value for each conformation: if first and
# last amino acid are located diagonally # from each other, e = 1, otherwise e = 0.
# There are 4 conformations for which e = 1.
e = QuantumRegister(1, 'e')
# additional qubit for grover's algorithm
g = QuantumRegister(1, 'g')
# classical register
out = ClassicalRegister(4,'out')
# quantum circuit consisting of all quantum and classical registers
qc = QuantumCircuit(x,y,w,a,c,e,g,out)
# ancilla qubits, at most three needed for the ccrca function
anc = QuantumRegister(3,'anc')
qc.add_register(anc)
# encoding binary 1
qc.x(a[length-1])
# encoding the two's complement of 1
#qc.x(t[0:length])
# setting the state into superposition
qc.h(w[0:(length-1)*2])
# Grvoer qubit must be in its own superposition
qc.h(g[0])
'''
Subcircuit for the controlled-controlled ripple-carry adder for 3 bits
(the sum is stored by overwriting the values of x)
'''
sw = QuantumRegister(2,'sw') # control qubits
sa = QuantumRegister(3,'sa') # ancilla qubits
ss = QuantumRegister(1,'ss') # carry
sx = QuantumRegister(length,'sx') # summand x
sy = QuantumRegister(length,'sy') # summand y
sc = QuantumCircuit(sw,sa,ss,sx,sy,name='ccrca')
sc.ccx(sw[0],sw[1],sa[0])
sc.ccx(sa[0],sy[2],sx[2])
sc.ccx(sa[0],sy[2],ss[0])
sc.ccx(sa[0],ss[0],sa[1])
sc.ccx(sa[1],sx[2],sa[2])
sc.ccx(sa[1],sa[2],sy[2])
# uncompute
sc.ccx(sa[1],sx[2],sa[2])
sc.ccx(sa[0],ss[0],sa[1])
sc.ccx(sa[0],sy[1],sx[1])
sc.ccx(sa[0],sy[1],sy[2])
sc.ccx(sa[0],sy[2],sa[1])
sc.ccx(sa[1],sx[1],sa[2])
sc.ccx(sa[1],sa[2],sy[1])
# uncompute
sc.ccx(sa[1],sx[1],sa[2])
sc.ccx(sa[0],sy[2],sa[1])
sc.ccx(sa[0],sy[0],sx[0])
sc.ccx(sa[0],sy[0],sy[1])
sc.ccx(sa[0],sy[1],sa[1])
sc.ccx(sa[1],sx[0],sa[2])
sc.ccx(sa[1],sa[2],sy[0])
# uncompute
sc.ccx(sa[1],sx[0],sa[2])
sc.ccx(sa[0],sy[1],sa[1])
sc.ccx(sa[0],sy[1],sa[1])
sc.ccx(sa[1],sx[0],sa[2])
sc.ccx(sa[1],sa[2],sy[0])
# uncompute
sc.ccx(sa[1],sx[0],sa[2])
sc.ccx(sa[0],sy[1],sa[1])
# continue
sc.ccx(sa[0],sy[0],sy[1])
sc.ccx(sa[0],sy[1],sx[0])
sc.ccx(sa[0],sy[2],sa[1])
sc.ccx(sa[1],sx[1],sa[2])
sc.ccx(sa[1],sa[2],sy[1])
# uncompute
sc.ccx(sa[1],sx[1],sa[2])
sc.ccx(sa[0],sy[2],sa[1])
# continue
sc.ccx(sa[0],sy[1],sy[2])
sc.ccx(sa[0],sy[2],sx[1])
sc.ccx(sa[0],ss[0],sa[1])
sc.ccx(sa[1],sx[2],sa[2])
sc.ccx(sa[1],sa[2],sy[2])
# uncompute
sc.ccx(sa[1],sx[2],sa[2])
sc.ccx(sa[0],ss[0],sa[1])
# continue
sc.ccx(sa[0],sy[2],ss[0])
sc.ccx(sa[0],ss[0],sx[2])
sc.ccx(sw[0],sw[1],sa[0])
subinst = sc.to_instruction()
'''
Main body of the algorithm: Grover iteration
'''
num_solutions = 1 # (by design since we only want to find conformation w = 1100)
# Number of iterations
num_iter = int(math.ceil(np.pi*(np.sqrt(2**(2*(length-1)/num_solutions)))/4))
for j in range(num_iter):
# global variable used in Algorithm 1 to navigate among the values of vector w
b = 0
arglist = []
'''
Algorithm 1: Generating conformational space
'''
for d in range (2, length+1):
for q in range (length):
if d == 3:
qc.cx(x[q],x[length+q])
qc.cx(y[q],y[length+q])
# calculating the western neighbour of site d-1 (w=11)
arglist.append(w[b])
arglist.append(w[b+1])
for i in range(3):
arglist.append(anc[i])
arglist.append(c[0])
#range [0,1,2] for d=2, range [3,4,5] for d=3
for i in range((d-2)*length,(d-2)*length+3):
arglist.append(x[i])
qc.x(a[0])
qc.x(a[1])
for i in range(length):
arglist.append(a[i])
qc.append(subinst,arglist)
qc.x(a[0])
qc.x(a[1])
# calculating the eastern neighbour of site d-1 (w=01)
for i in range(len(arglist)-1,-1,-1):
arglist.pop(i)
qc.x(w[b])
arglist.append(w[b])
arglist.append(w[b+1])
for i in range(3):
arglist.append(anc[i])
arglist.append(c[0])
for i in range((d-2)*length,(d-2)*length+3):
arglist.append(x[i])
for i in range(length):
arglist.append(a[i])
qc.append(subinst,arglist)
# calculating the northern neighbour of site d-1 (w=00)
for i in range(len(arglist)-1,-1,-1):
arglist.pop(i)
qc.x(w[b+1])
arglist.append(w[b])
arglist.append(w[b+1])
for i in range(3):
arglist.append(anc[i])
arglist.append(c[0])
for i in range((d-2)*length,(d-2)*length+3):
arglist.append(y[i])
for i in range(length):
arglist.append(a[i])
qc.append(subinst,arglist)
# calculating the southern neighbour of site d-1 (w=10)
for i in range(len(arglist)-1,-1,-1):
arglist.pop(i)
qc.x(w[b])
arglist.append(w[b])
arglist.append(w[b+1])
for i in range(3):
arglist.append(anc[i])
arglist.append(c[0])
for i in range((d-2)*length,(d-2)*length+3):
arglist.append(y[i])
qc.x(a[0])
qc.x(a[1])
for i in range(length):
arglist.append(a[i])
qc.append(subinst,arglist)
qc.x(w[b+1])
for i in range(len(arglist)-1,-1,-1):
arglist.pop(i)
qc.x(a[0])
qc.x(a[1])
b = b+2
'''
Algorithm 2: Finding the conformation |w>=|1100> among the 16 possible conformations.
For this conformation, the energy value will be e = 1, while e = 0 for all other conf.
Conformation 1100 has the following coordinates: |x2>=111, |x3>=111, |y2>=000, |y3>=001.
As this conformation is uniquely identified by the values of the y coordinates and the coordinate x3,
the energy value depends on all these values.
We only check the first and the third bits of each y coordinate and the first bit of x3 (5 values)
The 6 bits of the y vector are indexed as y0y1y2 y3y4y5
'''
qc.x(y[0])
qc.x(y[2])
qc.x(y[3])
qc.ccx(x[3],y[0],anc[0])
qc.ccx(anc[0],y[2],anc[1])
qc.ccx(anc[1],y[3],anc[2])
qc.ccx(anc[2],y[5],e[0])
qc.cz(e[0],g[0])
# resetting all qubits, including the energy qubit
qc.ccx(anc[2],y[5],e[0])
qc.ccx(anc[1],y[3],anc[2])
qc.ccx(anc[0],y[2],anc[1])
qc.ccx(x[3],y[0],anc[0])
qc.x(y[0])
qc.x(y[2])
qc.x(y[3])
'''
Algorithm 3: Uncomputing of coordinates by running Algorithm 1 in reverse
'''
b = 2
for d in range (length,1,-1):
# uncalculating the western neighbour of site d-1 (w=11)
arglist.append(w[b])
arglist.append(w[b+1])
for i in range(3):
arglist.append(anc[i])
arglist.append(c[0])
#range [0,1,2] for d=2, range [3,4,5] for d=3
for i in range((d-2)*length,(d-2)*length+3):
arglist.append(x[i])
qc.x(a[0])
qc.x(a[1])
for i in range(length):
arglist.append(a[i])
qc.append(subinst.inverse(),arglist)
qc.x(a[0])
qc.x(a[1])
# calculating the eastern neighbour of site d-1 (w=01)
for i in range(len(arglist)-1,-1,-1):
arglist.pop(i)
qc.x(w[b])
arglist.append(w[b])
arglist.append(w[b+1])
for i in range(3):
arglist.append(anc[i])
arglist.append(c[0])
for i in range((d-2)*length,(d-2)*length+3):
arglist.append(x[i])
for i in range(length):
arglist.append(a[i])
qc.append(subinst.inverse(),arglist)
# calculating the northern neighbour of site d-1 (w=00)
for i in range(len(arglist)-1,-1,-1):
arglist.pop(i)
qc.x(w[b+1])
arglist.append(w[b])
arglist.append(w[b+1])
for i in range(3):
arglist.append(anc[i])
arglist.append(c[0])
for i in range((d-2)*length,(d-2)*length+3):
arglist.append(y[i])
for i in range(length):
arglist.append(a[i])
qc.append(subinst.inverse(),arglist)
# calculating the southern neighbour of site d-1 (w=10)
for i in range(len(arglist)-1,-1,-1):
arglist.pop(i)
qc.x(w[b])
arglist.append(w[b])
arglist.append(w[b+1])
for i in range(3):
arglist.append(anc[i])
arglist.append(c[0])
for i in range((d-2)*length,(d-2)*length+3):
arglist.append(y[i])
qc.x(a[0])
qc.x(a[1])
for i in range(length):
arglist.append(a[i])
qc.append(subinst.inverse(),arglist)
qc.x(w[b+1])
qc.x(a[0])
qc.x(a[1])
for i in range(len(arglist)-1,-1,-1):
arglist.pop(i)
b = b-2
for q in range (length-1, -1,-1):
if d == 3:
qc.cx(x[q],x[length+q])
qc.cx(y[q],y[length+q])
'''
Algorithm 4: Finding the conformation with e = 1 among 16. This can be done with
Grover's diffusion operator, which has to be executed
pi/4 * sqrt(N/M) where N = 16 (all conformations) and M = 1 (solutions).
This is equal to 3.4. Thus executing the search algorithm 4 times is optimal
for finding the solution with a high probability.
'''
for i in range(4):
qc.h(w[i])
qc.x(w[i])
qc.h(g[0])
qc.x(g[0])
qc.ccx(w[0],w[1],anc[0])
qc.ccx(anc[0],w[2],anc[1])
qc.ccx(anc[1],w[3],anc[2])
qc.cz(anc[2],g[0])
qc.ccx(anc[1],w[3],anc[2])
qc.ccx(anc[0],w[2],anc[1])
qc.ccx(w[0],w[1],anc[0])
qc.x(g[0])
qc.h(g[0])
for i in range(4):
qc.x(w[i])
qc.h(w[i])
'''
MEASUREMENT
'''
coord = []
for i in range(2*(length-1)):
coord.append(w[i])
# Reversing coordinates due to Qiskit's little endian notation
coord.reverse()
# Measurement
qc.measure(coord,out)
# Output in the form of vector |w>, which encodes the directional transitions for
# each conformation
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc,backend = simulator, shots = 1024).result()
counts = result.get_counts()
plot_histogram(counts)
'''Print out the quantum circuit'''
qc.draw('mpl')
|
https://github.com/sebasmos/QuantumVE
|
sebasmos
|
import os
MODEL_METADATA = "SVM"
model_name = "efficientnet_b3_embeddings_finetuning"
EXPERIMENT_NAME = "efficientnet_b3_embeddings_"#"efficientnet_v2_m"#"convnext_base"#"efficientnet_b3"#"mobileNet"
results_path = f"{model_name}/{MODEL_METADATA}"
os.makedirs(results_path, exist_ok = True)
train_path = f"{model_name}/train"
val_path = f"{model_name}/val"
os.makedirs(train_path, exist_ok = True)
os.makedirs(val_path, exist_ok=True)
import sys
sys.path.insert(0,'../')
# from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from torch.utils.data import random_split
from torch.utils.data import Subset, DataLoader, random_split
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import confusion_matrix, classification_report
import pandas as pd
import argparse
import argparse
import datetime
import json
import numpy as np
import os
import time
from pathlib import Path
import torch
import torch.backends.cudnn as cudnn
from torch.utils.tensorboard import SummaryWriter
# import models_vit
import sys
import os
import torch
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# import models_mae
import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}')
from sklearn.metrics import confusion_matrix, classification_report
import seaborn as sns
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
from itertools import cycle
import numpy as np
from sklearn.metrics import precision_score, recall_score, f1_score
import torch.optim as optim
import torch.nn as nn
import torch
import PIL
import pandas as pd
import torch
import numpy as np
import pandas as pd
from tqdm import tqdm
import os
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score
from sklearn.metrics import precision_score, recall_score, f1_score, fbeta_score
import numpy as np
from torchvision import datasets, transforms
from timm.data import create_transform
# from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
IMAGENET_DEFAULT_MEAN = np.array([0.485, 0.456, 0.406])
IMAGENET_DEFAULT_STD = np.array([0.229, 0.224, 0.225])
def show_image(image, title=''):
# image is [H, W, 3]
assert image.shape[2] == 3
plt.imshow(torch.clip((image * IMAGENET_DEFAULT_STD + IMAGENET_DEFAULT_MEAN) * 255, 0, 255).int())
plt.title(title, fontsize=16)
plt.axis('off')
return
def plot_multiclass_roc_curve(all_labels, all_predictions, results_path="."):
# Step 1: Label Binarization
label_binarizer = LabelBinarizer()
y_onehot = label_binarizer.fit_transform(all_labels)
all_predictions_hot = label_binarizer.transform(all_predictions)
# Step 2: Calculate ROC curves
fpr = dict()
tpr = dict()
roc_auc = dict()
unique_classes = range(y_onehot.shape[1])
for i in unique_classes:
fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# Step 3: Plot ROC curves
fig, ax = plt.subplots(figsize=(8, 8))
# Micro-average ROC curve
fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel())
roc_auc_micro = auc(fpr_micro, tpr_micro)
plt.plot(
fpr_micro,
tpr_micro,
label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})",
color="deeppink",
linestyle=":",
linewidth=4,
)
# Macro-average ROC curve
all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes]))
mean_tpr = np.zeros_like(all_fpr)
for i in unique_classes:
mean_tpr += np.interp(all_fpr, fpr[i], tpr[i])
mean_tpr /= len(unique_classes)
fpr_macro = all_fpr
tpr_macro = mean_tpr
roc_auc_macro = auc(fpr_macro, tpr_macro)
plt.plot(
fpr_macro,
tpr_macro,
label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})",
color="navy",
linestyle=":",
linewidth=4,
)
# Individual class ROC curves with unique colors
colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes)))
for class_id, color in zip(unique_classes, colors):
plt.plot(
fpr[class_id],
tpr[class_id],
color=color,
label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})",
linewidth=2,
)
plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference
plt.axis("equal")
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass")
plt.legend()
plt.savefig(f'{results_path}/roc_curve.png')
plt.show()
def build_dataset(is_train, args):
transform = build_transform(is_train, args)
root = os.path.join(args.data_path, 'train' if is_train else 'val')
dataset = datasets.ImageFolder(root, transform=transform)
print(dataset)
return dataset
def build_transform(is_train, args):
mean = IMAGENET_DEFAULT_MEAN
std = IMAGENET_DEFAULT_STD
# train transform
if is_train:
# this should always dispatch to transforms_imagenet_train
transform = create_transform(
input_size=args.input_size,
is_training=True,
color_jitter=args.color_jitter,
auto_augment=args.aa,
interpolation='bicubic',
re_prob=args.reprob,
re_mode=args.remode,
re_count=args.recount,
mean=mean,
std=std,
)
return transform
# eval transform
t = []
if args.input_size <= 224:
crop_pct = 224 / 256
else:
crop_pct = 1.0
size = int(args.input_size / crop_pct)
t.append(
transforms.Resize(size, interpolation=PIL.Image.BICUBIC), # to maintain same ratio w.r.t. 224 images
)
t.append(transforms.CenterCrop(args.input_size))
t.append(transforms.ToTensor())
t.append(transforms.Normalize(mean, std))
return transforms.Compose(t)
# Set the seed for PyTorch
torch.manual_seed(42)
from sklearn.svm import SVC
# Read embeddings CSV files
train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv')
val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv')
print(f"Reading embeddings from: ", train_path)
# Prepare data for training
X_train = train_embeddings.iloc[:, :-1].values # Features
y_train = train_embeddings.iloc[:, -1].values # Labels
X_val = val_embeddings.iloc[:, :-1].values # Features
y_val = val_embeddings.iloc[:, -1].values # Labels
# Use los mejores parámetros encontrados
best_params = {'C': 4, 'gamma': 'scale', 'kernel': 'rbf'}#{'C': 10, 'gamma': 'scale', 'kernel': 'rbf'}
# Inicializa el clasificador SVM con los mejores parámetros
svm_classifier = SVC(**best_params, random_state=42)
svm_classifier.fit(X_train, y_train)
# Predict on validation data
y_pred = svm_classifier.predict(X_val)
# Calculate accuracy
accuracy = accuracy_score(y_val, y_pred)
# Calculate precision
precision = precision_score(y_val, y_pred, average='weighted')
# Calculate recall
recall = recall_score(y_val, y_pred, average='weighted')
# Calculate F1 score
f1 = f1_score(y_val, y_pred, average='weighted')
# Calculate F0.75 score
fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted')
print("Validation Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)
print("F1 Score:", f1)
print("F0.75 Score:", fbeta_75)
X_train.shape
unique_classes = np.unique(np.concatenate(((y_pred, y_val))))
confusion_mat = confusion_matrix(y_pred, y_val, labels=unique_classes)
conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes)
# Plot the confusion matrix using seaborn
plt.figure(figsize=(5, 4))
ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True)
# Set labels and ticks
ax.set_xlabel('Predicted Labels')
ax.set_ylabel('True Labels')
# Set x and y ticks using the unique classes
ax.set_xticks(range(len(unique_classes)))
ax.set_yticks(range(len(unique_classes)))
# Set x and y ticks at the center of the cells
ax.set_xticks([i + 0.5 for i in range(len(unique_classes))])
ax.set_yticks([i + 0.5 for i in range(len(unique_classes))])
plt.show()
plot_multiclass_roc_curve(y_pred, y_val, results_path)
report = classification_report(y_val,y_pred, target_names=unique_classes,output_dict=True)# Mostrar el informe de
df = pd.DataFrame(report).transpose()
df.to_csv(os.path.join(results_path, f"confusion_matrix_{MODEL_METADATA}.csv"))
print(df)
# Calculate precision, recall, and specificity (micro-averaged)
precision = precision_score(y_val, y_pred, average='micro')
recall = recall_score(y_val, y_pred, average='micro')
# Calculate true negatives, false positives, and specificity (micro-averaged)
tn = np.sum((y_val != 1) & (y_pred != 1))
fp = np.sum((y_val != 1) & (y_pred == 1))
specificity = tn / (tn + fp)
# Calculate F1 score (weighted average)
f1 = f1_score(y_val, y_pred, average='weighted')
fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted')
evaluation_metrics = {
"Accuracy": accuracy,
"F1 Score": f1,
"F0.75 Score": fbeta_75,
"Precision": precision,
"Recall": recall,
"Specificity": specificity
}
print("Evaluation Metrics:")
# for metric, value in evaluation_metrics.items():
# print(f"{metric}: {value}")
# Create a DataFrame from the dictionary
df = pd.DataFrame(evaluation_metrics, index=[0])
# # Save the DataFrame to a CSV file
df.to_csv(f'{results_path}/evaluation_metrics_for_table_{MODEL_METADATA}.csv', index=False)
df
from sklearn.svm import SVC
# Read embeddings CSV files
train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv')
val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv')
print(f"Reading embeddings from: ", train_path)
# Prepare data for training
X_train = train_embeddings.iloc[:, :-1].values # Features
y_train = train_embeddings.iloc[:, -1].values # Labels
X_val = val_embeddings.iloc[:, :-1].values # Features
y_val = val_embeddings.iloc[:, -1].values # Labels
start = 0.1
end = 100.0
step = 0.1
# Initialize variables to track best F0.75 score and its corresponding C value
best_fbeta_75 = -1
best_c_val = None
for c_val in np.arange(start, end + step, step):
# Use los mejores parámetros encontrados
best_params = {'C': c_val, 'gamma': 'scale', 'kernel': 'rbf'}#{'C': 10, 'gamma': 'scale', 'kernel': 'rbf'}
# Inicializa el clasificador SVM con los mejores parámetros
svm_classifier = SVC(**best_params, random_state=42)
svm_classifier.fit(X_train, y_train)
# Predict on validation data
y_pred = svm_classifier.predict(X_val)
# Calculate accuracy
accuracy = accuracy_score(y_val, y_pred)
# Calculate precision
precision = precision_score(y_val, y_pred, average='weighted')
# Calculate recall
recall = recall_score(y_val, y_pred, average='weighted')
# Calculate F1 score
f1 = f1_score(y_val, y_pred, average='weighted')
# Calculate F0.75 score
fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted')
# Update best F0.75 score and corresponding C value if a higher score is found
if fbeta_75 > best_fbeta_75:
best_fbeta_75 = fbeta_75
best_c_val = c_val
print(f"value of c: {c_val} ".center(60,"-"))
print("Validation Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)
print("F1 Score:", f1)
print("F0.75 Score:", fbeta_75)
# Print the parameter C that obtains the highest F0.75 score
print("Best C value:", best_c_val)
print("Best F0.75 Score:", best_fbeta_75)
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
# Define el rango de parámetros que deseas buscar
param_grid = {
'C': [0.1,1,10,100],
'gamma': [0.1, 0.01, 0.001, 0.0001],
'kernel': ['rbf']
}
# Crea un clasificador SVM
svm_classifier = SVC(random_state=42)
# Crea un objeto GridSearchCV
grid_search = GridSearchCV(estimator=svm_classifier, param_grid=param_grid, cv=10, scoring='accuracy')
# Ajusta el modelo GridSearchCV a los datos de entrenamiento
grid_search.fit(X_train, y_train)
# Obtiene los mejores parámetros y el mejor puntaje
best_params = grid_search.best_params_
best_score = grid_search.best_score_
print("Mejores parámetros:", best_params)
print("Mejor puntaje:", best_score)
# Usa el mejor estimador encontrado por GridSearchCV
best_svm_classifier = grid_search.best_estimator_
# Predice sobre los datos de validación usando el mejor modelo
y_pred = best_svm_classifier.predict(X_val)
# Calcula las métricas de evaluación
accuracy = accuracy_score(y_val, y_pred)
precision = precision_score(y_val, y_pred, average='weighted')
recall = recall_score(y_val, y_pred, average='weighted')
f1 = f1_score(y_val, y_pred, average='weighted')
fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted')
print("Exactitud de la validación:", accuracy)
print("Precisión:", precision)
print("Recall:", recall)
print("Puntuación F1:", f1)
print("Puntuación F0.75:", fbeta_75)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
gate_counts = []
non_local_gate_counts = []
levels = [str(x) for x in range(4)]
for level in range(4):
circ = transpile(ghz, backend, optimization_level=level)
depths.append(circ.depth())
gate_counts.append(sum(circ.count_ops().values()))
non_local_gate_counts.append(circ.num_nonlocal_gates())
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.bar(levels, depths, label='Depth')
ax1.set_xlabel("Optimization Level")
ax1.set_ylabel("Depth")
ax1.set_title("Output Circuit Depth")
ax2.bar(levels, gate_counts, label='Number of Circuit Operations')
ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates')
ax2.set_xlabel("Optimization Level")
ax2.set_ylabel("Number of gates")
ax2.legend()
ax2.set_title("Number of output circuit gates")
fig.tight_layout()
plt.show()
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### removed cx gate ###
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### removed h gate ###
return qc
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
from qiskit.primitives import Estimator
estimator = Estimator()
import numpy as np
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SLSQP
from qiskit.circuit.library import TwoLocal
from qiskit.utils import algorithm_globals
# we will iterate over these different optimizers
optimizers = [COBYLA(maxiter=80), L_BFGS_B(maxiter=60), SLSQP(maxiter=60)]
converge_counts = np.empty([len(optimizers)], dtype=object)
converge_vals = np.empty([len(optimizers)], dtype=object)
for i, optimizer in enumerate(optimizers):
print("\rOptimizer: {} ".format(type(optimizer).__name__), end="")
algorithm_globals.random_seed = 50
ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
vqe = VQE(estimator, ansatz, optimizer, callback=store_intermediate_result)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
converge_counts[i] = np.asarray(counts)
converge_vals[i] = np.asarray(values)
print("\rOptimization complete ");
import pylab
pylab.rcParams["figure.figsize"] = (12, 8)
for i, optimizer in enumerate(optimizers):
pylab.plot(converge_counts[i], converge_vals[i], label=type(optimizer).__name__)
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Energy convergence for various optimizers")
pylab.legend(loc="upper right");
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.opflow import PauliSumOp
numpy_solver = NumPyMinimumEigensolver()
result = numpy_solver.compute_minimum_eigenvalue(operator=PauliSumOp(H2_op))
ref_value = result.eigenvalue.real
print(f"Reference value: {ref_value:.5f}")
pylab.rcParams["figure.figsize"] = (12, 8)
for i, optimizer in enumerate(optimizers):
pylab.plot(
converge_counts[i],
abs(ref_value - converge_vals[i]),
label=type(optimizer).__name__,
)
pylab.xlabel("Eval count")
pylab.ylabel("Energy difference from solution reference value")
pylab.title("Energy convergence for various optimizers")
pylab.yscale("log")
pylab.legend(loc="upper right");
from qiskit.algorithms.gradients import FiniteDiffEstimatorGradient
estimator = Estimator()
gradient = FiniteDiffEstimatorGradient(estimator, epsilon=0.01)
algorithm_globals.random_seed = 50
ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
optimizer = SLSQP(maxiter=100)
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
vqe = VQE(
estimator, ansatz, optimizer, callback=store_intermediate_result, gradient=gradient
)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(f"Value using Gradient: {result.eigenvalue.real:.5f}")
pylab.rcParams["figure.figsize"] = (12, 8)
pylab.plot(counts, values, label=type(optimizer).__name__)
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Energy convergence using Gradient")
pylab.legend(loc="upper right");
print(result)
cost_function_evals = result.cost_function_evals
initial_pt = result.optimal_point
estimator1 = Estimator()
gradient1 = FiniteDiffEstimatorGradient(estimator, epsilon=0.01)
ansatz1 = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
optimizer1 = SLSQP(maxiter=1000)
vqe1 = VQE(
estimator1, ansatz1, optimizer1, gradient=gradient1, initial_point=initial_pt
)
result1 = vqe1.compute_minimum_eigenvalue(operator=H2_op)
print(result1)
cost_function_evals1 = result1.cost_function_evals
print()
print(
f"cost_function_evals is {cost_function_evals1} with initial point versus {cost_function_evals} without it."
)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 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.
r"""
===================
Overview of Sampler
===================
Sampler class calculates probabilities or quasi-probabilities of bitstrings from quantum circuits.
A sampler is initialized with an empty parameter set. The sampler is used to
create a :class:`~qiskit.providers.JobV1`, via the :meth:`qiskit.primitives.Sampler.run()`
method. This method is called with the following parameters
* quantum circuits (:math:`\psi_i(\theta)`): list of (parameterized) quantum circuits.
(a list of :class:`~qiskit.circuit.QuantumCircuit` objects)
* parameter values (:math:`\theta_k`): list of sets of parameter values
to be bound to the parameters of the quantum circuits.
(list of list of float)
The method returns a :class:`~qiskit.providers.JobV1` object, calling
:meth:`qiskit.providers.JobV1.result()` yields a :class:`~qiskit.primitives.SamplerResult`
object, which contains probabilities or quasi-probabilities of bitstrings,
plus optional metadata like error bars in the samples.
Here is an example of how sampler is used.
.. code-block:: python
from qiskit.primitives import Sampler
from qiskit import QuantumCircuit
from qiskit.circuit.library import RealAmplitudes
# a Bell circuit
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()
# two parameterized circuits
pqc = RealAmplitudes(num_qubits=2, reps=2)
pqc.measure_all()
pqc2 = RealAmplitudes(num_qubits=2, reps=3)
pqc2.measure_all()
theta1 = [0, 1, 1, 2, 3, 5]
theta2 = [0, 1, 2, 3, 4, 5, 6, 7]
# initialization of the sampler
sampler = Sampler()
# Sampler runs a job on the Bell circuit
job = sampler.run(circuits=[bell], parameter_values=[[]], parameters=[[]])
job_result = job.result()
print([q.binary_probabilities() for q in job_result.quasi_dists])
# Sampler runs a job on the parameterized circuits
job2 = sampler.run(
circuits=[pqc, pqc2],
parameter_values=[theta1, theta2],
parameters=[pqc.parameters, pqc2.parameters])
job_result = job2.result()
print([q.binary_probabilities() for q in job_result.quasi_dists])
"""
from __future__ import annotations
from abc import abstractmethod
from collections.abc import Sequence
from copy import copy
from typing import Generic, TypeVar
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.parametertable import ParameterView
from qiskit.providers import JobV1 as Job
from .base_primitive import BasePrimitive
T = TypeVar("T", bound=Job)
class BaseSampler(BasePrimitive, Generic[T]):
"""Sampler base class
Base class of Sampler that calculates quasi-probabilities of bitstrings from quantum circuits.
"""
__hash__ = None
def __init__(
self,
*,
options: dict | None = None,
):
"""
Args:
options: Default options.
"""
self._circuits = []
self._parameters = []
super().__init__(options)
def run(
self,
circuits: QuantumCircuit | Sequence[QuantumCircuit],
parameter_values: Sequence[float] | Sequence[Sequence[float]] | None = None,
**run_options,
) -> T:
"""Run the job of the sampling of bitstrings.
Args:
circuits: One of more circuit objects.
parameter_values: Parameters to be bound to the circuit.
run_options: Backend runtime options used for circuit execution.
Returns:
The job object of the result of the sampler. The i-th result corresponds to
``circuits[i]`` evaluated with parameters bound as ``parameter_values[i]``.
Raises:
ValueError: Invalid arguments are given.
"""
# Singular validation
circuits = self._validate_circuits(circuits)
parameter_values = self._validate_parameter_values(
parameter_values,
default=[()] * len(circuits),
)
# Cross-validation
self._cross_validate_circuits_parameter_values(circuits, parameter_values)
# Options
run_opts = copy(self.options)
run_opts.update_options(**run_options)
return self._run(
circuits,
parameter_values,
**run_opts.__dict__,
)
@abstractmethod
def _run(
self,
circuits: tuple[QuantumCircuit, ...],
parameter_values: tuple[tuple[float, ...], ...],
**run_options,
) -> T:
raise NotImplementedError("The subclass of BaseSampler must implment `_run` method.")
# TODO: validate measurement gates are present
@classmethod
def _validate_circuits(
cls,
circuits: Sequence[QuantumCircuit] | QuantumCircuit,
) -> tuple[QuantumCircuit, ...]:
circuits = super()._validate_circuits(circuits)
for i, circuit in enumerate(circuits):
if circuit.num_clbits == 0:
raise ValueError(
f"The {i}-th circuit does not have any classical bit. "
"Sampler requires classical bits, plus measurements "
"on the desired qubits."
)
return circuits
@property
def circuits(self) -> tuple[QuantumCircuit, ...]:
"""Quantum circuits to be sampled.
Returns:
The quantum circuits to be sampled.
"""
return tuple(self._circuits)
@property
def parameters(self) -> tuple[ParameterView, ...]:
"""Parameters of quantum circuits.
Returns:
List of the parameters in each quantum circuit.
"""
return tuple(self._parameters)
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
# Do the necessary import for our program
#!pip install qiskit-aqua
from qiskit import BasicAer
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle
from qiskit.tools.visualization import plot_histogram
log_expr = '((A & B) | (C & D)) & ~(A & D)'
algorithm = Grover(LogicalExpressionOracle(log_expr))
# Run the algorithm on a simulator, printing the most frequently occurring result
backend = BasicAer.get_backend('qasm_simulator')
result = algorithm.run(backend)
print(result['top_measurement'])
plot_histogram(result['measurement'])
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
import scipy as sci
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
M_simulator = Aer.backends(name='qasm_simulator')[0]
N = 3
s = np.zeros(N)
for i in range(N):
s[i] = m.floor(2*np.random.rand())
inputs = np.zeros(2**N)
outputs = []
for o in range(2**N):
inputs[o] = o
outputs.append(o)
f = np.zeros(2**N)
for j in range(2**N):
out = outputs[int(m.floor(len(outputs)*np.random.rand()))]
f[j] = out
f[int(oq.From_Binary(oq.Oplus(oq.Binary(j, 2**N),s)))] = out
outputs.remove(out)
print(' s: ', s)
print(' ')
print(' inputs: ', inputs)
print('outputs: ', f)
q = QuantumRegister(2, name='q')
anc=QuantumRegister(2, name='anc')
S_qc=QuantumCircuit(q,anc,name='qc')
S_qc.h(q[0])
S_qc.h(q[1])
print('___________Initial state_______________')
oq.Wavefunction(S_qc, sustem=[2,2])
S_qc,s,f = oq.Blackbox_g_S(2, S_qc, q, anc)
print('\ns = ', s)
print('\n__________________After g__________')
oq.Wavefunction(S_qc, systems=[2,2,1], show_systems=[True,True,False])
S_qc.h(q[0])
S_qc.h(q[1])
print('\n___________Afeter H^2_______________')
oq.Wavefunction(S_qc, systems=[2,2,1], show_systems=[True,True,False]);
q = QuantumRegister(3, name='q')
c = ClassicalRegister(3,name='c')
anc=QuantumRegister(3, name='anc')
S_qc=QuantumCircuit(q,anc,c, name='qc')
for i in range(3):
S_qc.h(q[i])
S_qc, s, f = oq.Blackbox_g_S(3, S_qc, q, anc)
for i in range(3):
S_qc.h(q[i])
S_qc.measure(q,c)
run_quantum = True
while(run_quantum):
M = oq.Measurement(S_qc, shots = 20, return_M = True, print_M = False)
if len(list(M.keys())) >= 4:
run_quantum = False
print('Measurement Results: ', M)
Equations = []
for i in range(len(list(M.keys()))):
if list(M.keys())[i] != '000':
Equations.append([int(list(M.keys())[i][0]), int(list(M.keys())[i][1]), int(list(M.keys())[i][2])])
s_primes = oq.Simons_Solver(Equations,3)
print('\ncandidate: ', s_primes)
print('\n hidden: ', s)
q = QuantumRegister(3, name='q')
c = ClassicalRegister(3,name='c')
anc=QuantumRegister(3, name='anc')
S_qc=QuantumCircuit(q,anc,c, name='qc')
for i in range(3):
S_qc.h(q[i])
S_qc, s, f = oq.Blackbox_g_S(3, S_qc, q, anc)
for i in range(3):
S_qc.h(q[i])
S_qc.measure(q,c)
run_quantum = True
Equations = []
Results = []
quantum_runs = 0
while(run_quantum):
quantum_runs += 1
M = oq.Measurement(S_qc, shots = 20, return_M = True, print_M = False)
new_result = True
for r in range(len(Results)):
if list(M.keys())[0] == Results[r]:
new_result = False
break
if new_result:
Results.append(list(M.keys())[0])
Equations.append([int(list(M.keys())[0][0]), int(list(M.keys())[0][1]), int(list(M.keys())[0][2])])
s_primes = oq.Simons_Solver(Equations, 3)
if len(s_primes) == 1:
run_quantum = False
print('\n candidate: ', s_primes)
print('\n hidden: ', s)
print('\nunique measurements: ', Results)
print('\n quantum runs: ', quantum_runs)
Q = 4
q = QuantumRegister(Q, name='q')
c = ClassicalRegister(Q,name='c')
anc=QuantumRegister(Q, name='anc')
S_qc=QuantumCircuit(q,anc,c, name='qc')
S_qc, s = oq.Simons_Quantum(Q, S_qc, q, c, anc)
sp, r, qr = oq.Simons_Classical(Q, S_qc)
print('\n candidate: ', sp)
print('\n hidden: ', s)
print('\nunique measurements: ', r)
print('\n quantum runs: ', qr)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
import qiskit
qc = qiskit.QuantumCircuit(4, 2)
qc.h([0, 2]); qc.cx([0], [1]); qc.cx([2], [3]) # preparacao e distribuicao de emaranhamento
qc.barrier() # base de Bell -> base computacional
qc.cx([1], [2]); qc.h([1])
qc.barrier() # feedback baseado na info classica
qc.x([1, 2]); qc.cx([2], [3]); qc.cz([1], [3]); qc.x([1, 2])
qc.barrier() # para verificacao da funcionalidade do cq (tem que sair Psi-=11)
qc.cx([0], [3]); qc.h([0]); qc.measure([0, 3], [0, 1])
qc.draw(output = 'mpl')
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
simulator = qiskit.Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_bogota')
from qiskit.tools.monitor import job_monitor
from qiskit.tools.visualization import plot_histogram
job = qiskit.execute(qc, backend = simulator, shots = nshots)
plot_histogram(job.result().get_counts(qc))
job = qiskit.execute(qc, backend = device, shots = nshots)
job_monitor(job)
plot_histogram(job.result().get_counts(qc))
#from qiskit.circuit.Instruction import c_if
from qiskit import *
q0 = QuantumRegister(1); q1 = QuantumRegister(1); q2 = QuantumRegister(1); q3 = QuantumRegister(1)
c0 = ClassicalRegister(1); c1 = ClassicalRegister(1); c2 = ClassicalRegister(1); c3 = ClassicalRegister(1)
qc = qiskit.QuantumCircuit(q0, q1, q2, q3, c0, c1, c2, c3)
qc.h(q0); qc.h(q2); qc.cx(q0, q1); qc.cx(q2, q3) # preparacao e distribuicao de emaranhamento
qc.barrier() # base de Bell -> base computacional
qc.cx(q1, q2); qc.h(q1); qc.measure(q1, c0); qc.measure(q2, c1)
qc.barrier() # feedback baseado na info classica
qc.x(q3).c_if(c1, 0); qc.z(q3).c_if(c0, 0)
qc.barrier() # para verificacao da funcionalidade do cq
qc.measure(q0, c2); qc.measure(q3, c3)
qc.draw(output = 'mpl')
job = qiskit.execute(qc, backend = simulator, shots = nshots)
plot_histogram(job.result().get_counts(qc))
# parece que não podemos executar no chip real a c_if
job = qiskit.execute(qc, backend = device, shots = nshots)
job_monitor(job)
plot_histogram(job.result().get_counts(qc))
import math
def E_Phi(p, q):
return 2*math.sqrt(p*(1-p)*q*(1-q))/(p*q+(1-p)*(1-q))
def E_Psi(p, q):
return 2*math.sqrt(p*(1-p)*q*(1-q))/(p*(1-q)+(1-p)*q)
import numpy as np
from matplotlib import pyplot as plt
import matplotlib
matplotlib.rcParams.update({'font.size':12})
plt.figure(figsize = (6,4), dpi = 100)
p = np.zeros(101)
Eq0 = np.zeros(101); Eq001 = np.zeros(101); Eq005 = np.zeros(101); Eq025 = np.zeros(101); Eq05 = np.zeros(101)
Eq0 = np.zeros(101); Eq099 = np.zeros(101); Eq095 = np.zeros(101); Eq075 = np.zeros(101)
for j in range(0, 101):
p[j] = j*0.01
if p[j] != 0 and p[j] != 1:
q = 0.0; Eq0[j] = E_Phi(p[j], q); q = 0.01; Eq001[j] = E_Phi(p[j], q)
q = 0.05; Eq005[j] = E_Phi(p[j], q); q = 0.25; Eq025[j] = E_Phi(p[j],q)
q = 0.5; Eq05[j] = E_Phi(p[j],q); q = 0.75; Eq075[j] = E_Phi(p[j],q)
q = 0.95; Eq095[j] = E_Phi(p[j],q); q = 0.99; Eq099[j] = E_Phi(p[j],q)
plt.plot(p, Eq0); plt.plot(p, Eq001); plt.plot(p, Eq005); plt.plot(p, Eq025); plt.plot(p, Eq05)
plt.plot(p, Eq075); plt.plot(p, Eq095); plt.plot(p, Eq099)
plt.xlabel('p'); plt.ylabel(r'$E(\rho_{AD})$')
plt.legend(('q=0','q=0.01','q=0.05','q=0.25','q=0.5','q=0.75','q=0.95','q=0.99'),
bbox_to_anchor=(1.05, 1.0), loc='upper left')
plt.title(r'$|\Phi_{\pm}\rangle$')
plt.show()
matplotlib.rcParams.update({'font.size':12})
plt.figure(figsize = (6,4), dpi = 100)
p = np.zeros(101)
Eq0 = np.zeros(101); Eq001 = np.zeros(101); Eq005 = np.zeros(101); Eq025 = np.zeros(101); Eq05 = np.zeros(101)
Eq0 = np.zeros(101); Eq099 = np.zeros(101); Eq095 = np.zeros(101); Eq075 = np.zeros(101)
for j in range(0, 101):
p[j] = j*0.01
if p[j] != 0 and p[j] != 1:
q = 0.0; Eq0[j] = E_Psi(p[j], q); q = 0.01; Eq001[j] = E_Psi(p[j], q)
q = 0.05; Eq005[j] = E_Psi(p[j], q); q = 0.25; Eq025[j] = E_Psi(p[j],q)
q = 0.5; Eq05[j] = E_Psi(p[j],q); q = 0.75; Eq075[j] = E_Psi(p[j],q)
q = 0.95; Eq095[j] = E_Psi(p[j],q); q = 0.99; Eq099[j] = E_Psi(p[j],q)
plt.plot(p, Eq0); plt.plot(p, Eq001); plt.plot(p, Eq005); plt.plot(p, Eq025); plt.plot(p, Eq05)
plt.plot(p, Eq075); plt.plot(p, Eq095); plt.plot(p, Eq099)
plt.xlabel('p'); plt.ylabel(r'$E(\rho_{AD})$')
plt.legend(('q=0','q=0.01','q=0.05','q=0.25','q=0.5','q=0.75','q=0.95','q=0.99'),
bbox_to_anchor=(1.05, 1.0), loc='upper left')
plt.title(r'$|\Psi_{\pm}\rangle$')
plt.show()
E_Phi(p,q), E_Psi(p,q)
p,q = symbols('p q'); factor(diff(E_Phi(p,q),p)), factor(diff(E_Psi(p,q),p))
E_Phi(1-q,q), E_Psi(q,q) # nos 2 casos, E=1
import numpy as np
from matplotlib import pyplot as plt
q = np.arange(0.001, 1.0, 0.001); PmaxE = 2*(1-q)*q; plt.plot(q, 1-PmaxE, label = r'$1-Pr(\max E)$');
pred = 1 + q*np.log2(q) + (1-q)*np.log2(1-q); plt.plot(q, pred, label = r'$P_{vn}(\rho_{A})$')
plt.legend(); plt.xlabel(r'$q$'); plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from __future__ import annotations
import numpy as np
import networkx as nx
num_nodes = 4
w = np.array([[0., 1., 1., 0.],
[1., 0., 1., 1.],
[1., 1., 0., 1.],
[0., 1., 1., 0.]])
G = nx.from_numpy_array(w)
layout = nx.random_layout(G, seed=10)
colors = ['r', 'g', 'b', 'y']
nx.draw(G, layout, node_color=colors)
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels);
def objective_value(x: np.ndarray, w: np.ndarray) -> float:
"""Compute the value of a cut.
Args:
x: Binary string as numpy array.
w: Adjacency matrix.
Returns:
Value of the cut.
"""
X = np.outer(x, (1 - x))
w_01 = np.where(w != 0, 1, 0)
return np.sum(w_01 * X)
def bitfield(n: int, L: int) -> list[int]:
result = np.binary_repr(n, L)
return [int(digit) for digit in result] # [2:] to chop off the "0b" part
# use the brute-force way to generate the oracle
L = num_nodes
max = 2**L
sol = np.inf
for i in range(max):
cur = bitfield(i, L)
how_many_nonzero = np.count_nonzero(cur)
if how_many_nonzero * 2 != L: # not balanced
continue
cur_v = objective_value(np.array(cur), w)
if cur_v < sol:
sol = cur_v
print(f'Objective value computed by the brute-force method is {sol}')
from qiskit.quantum_info import Pauli, SparsePauliOp
def get_operator(weight_matrix: np.ndarray) -> tuple[SparsePauliOp, float]:
r"""Generate Hamiltonian for the graph partitioning
Notes:
Goals:
1 Separate the vertices into two set of the same size.
2 Make sure the number of edges between the two set is minimized.
Hamiltonian:
H = H_A + H_B
H_A = sum\_{(i,j)\in E}{(1-ZiZj)/2}
H_B = (sum_{i}{Zi})^2 = sum_{i}{Zi^2}+sum_{i!=j}{ZiZj}
H_A is for achieving goal 2 and H_B is for achieving goal 1.
Args:
weight_matrix: Adjacency matrix.
Returns:
Operator for the Hamiltonian
A constant shift for the obj function.
"""
num_nodes = len(weight_matrix)
pauli_list = []
coeffs = []
shift = 0
for i in range(num_nodes):
for j in range(i):
if weight_matrix[i, j] != 0:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append(Pauli((z_p, x_p)))
coeffs.append(-0.5)
shift += 0.5
for i in range(num_nodes):
for j in range(num_nodes):
if i != j:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append(Pauli((z_p, x_p)))
coeffs.append(1.0)
else:
shift += 1
return SparsePauliOp(pauli_list, coeffs=coeffs), shift
qubit_op, offset = get_operator(w)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.primitives import Sampler
from qiskit.quantum_info import Pauli, Statevector
from qiskit.result import QuasiDistribution
from qiskit.utils import algorithm_globals
sampler = Sampler()
def sample_most_likely(state_vector: QuasiDistribution | Statevector) -> np.ndarray:
"""Compute the most likely binary string from state vector.
Args:
state_vector: State vector or quasi-distribution.
Returns:
Binary string as an array of ints.
"""
if isinstance(state_vector, QuasiDistribution):
values = list(state_vector.values())
else:
values = state_vector
n = int(np.log2(len(values)))
k = np.argmax(np.abs(values))
x = bitfield(k, n)
x.reverse()
return np.asarray(x)
algorithm_globals.random_seed = 10598
optimizer = COBYLA()
qaoa = QAOA(sampler, optimizer, reps=2)
result = qaoa.compute_minimum_eigenvalue(qubit_op)
x = sample_most_likely(result.eigenstate)
print(x)
print(f'Objective value computed by QAOA is {objective_value(x, w)}')
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.quantum_info import Operator
npme = NumPyMinimumEigensolver()
result = npme.compute_minimum_eigenvalue(Operator(qubit_op))
x = sample_most_likely(result.eigenstate)
print(x)
print(f'Objective value computed by the NumPyMinimumEigensolver is {objective_value(x, w)}')
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
from qiskit.circuit.library import TwoLocal
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 10598
optimizer = COBYLA()
ansatz = TwoLocal(qubit_op.num_qubits, "ry", "cz", reps=2, entanglement="linear")
sampling_vqe = SamplingVQE(sampler, ansatz, optimizer)
result = sampling_vqe.compute_minimum_eigenvalue(qubit_op)
x = sample_most_likely(result.eigenstate)
print(x)
print(f"Objective value computed by VQE is {objective_value(x, w)}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
import numpy as np
from qiskit import *
from qiskit.tools.jupyter import *
%matplotlib inline
IBMQ.load_account()
provider = IBMQ.get_provider(group='open')
provider.backends(simulator=False)
backend = provider.get_backend('ibmqx4')
backend.configuration().basis_gates
qr = QuantumRegister(2, 'q')
cr = ClassicalRegister(1, 'c')
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.x(qr[1])
qc.cu1(np.pi/4, qr[0], qr[1])
qc.h(qr[0])
qc.measure(qr[0], cr[0])
qc.draw(output='mpl')
qr = QuantumRegister(2, 'q')
cr = ClassicalRegister(1, 'c')
qc_basis = QuantumCircuit(qr, cr)
# Hadamard in U2 format
qc_basis.u2(0, np.pi, qr[0])
# X gate in U3 format
qc_basis.u3(np.pi, 0, np.pi, qr[1])
# Decomposition for controlled-U1 with lambda=pi/4
qc_basis.u1(np.pi/8, qr[0])
qc_basis.cx(qr[0], qr[1])
qc_basis.u1(-np.pi/8, qr[1])
qc_basis.cx(qr[0], qr[1])
qc_basis.u1(np.pi/8, qr[1])
# Hadamard in U2 format
qc_basis.u2(0, np.pi, qr[0])
qc_basis.measure(qr[0], cr[0])
qc_basis.draw(output='mpl')
print(qc.depth(), ',', qc_basis.depth())
qr = QuantumRegister(3, 'q')
qc = QuantumCircuit(qr)
qc.ccx(qr[0], qr[1], qr[2])
qc.draw(output='mpl')
qr = QuantumRegister(3, 'q')
qc_basis = QuantumCircuit(qr)
qc_basis.u2(0,np.pi, qr[2])
qc_basis.cx(qr[1], qr[2])
qc_basis.u1(-np.pi/4, qr[2])
qc_basis.cx(qr[0], qr[2])
qc_basis.u1(np.pi/4, qr[2])
qc_basis.cx(qr[1], qr[2])
qc_basis.u1(np.pi/4, qr[1])
qc_basis.u1(-np.pi/4, qr[2])
qc_basis.cx(qr[0], qr[2])
qc_basis.cx(qr[0], qr[1])
qc_basis.u1(np.pi/4, qr[2])
qc_basis.u1(np.pi/4, qr[0])
qc_basis.u1(-np.pi/4, qr[1])
qc_basis.u2(0,np.pi, qr[2])
qc_basis.cx(qr[0], qr[1])
qc_basis.draw(output='mpl')
qr = QuantumRegister(5, 'q')
cr = ClassicalRegister(5, 'c')
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.cx(qr[0], qr[4])
qc.cx(qr[4], qr[3])
qc.cx(qr[3], qr[1])
qc.cx(qr[1], qr[2])
qc.draw(output='mpl')
backend = provider.get_backend('ibmqx4')
from qiskit.visualization.gate_map import plot_gate_map
plot_gate_map(backend, plot_directed=True)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=unused-import
"""
A convenient way to track reusable subschedules by name and qubit.
This can be used for scheduling circuits with custom definitions, for instance::
inst_map = InstructionScheduleMap()
inst_map.add('new_inst', 0, qubit_0_new_inst_schedule)
sched = schedule(quantum_circuit, backend, inst_map)
An instance of this class is instantiated by Pulse-enabled backends and populated with defaults
(if available)::
inst_map = backend.defaults().instruction_schedule_map
"""
from __future__ import annotations
import functools
import warnings
from collections import defaultdict
from collections.abc import Iterable, Callable
from qiskit import circuit
from qiskit.circuit.parameterexpression import ParameterExpression
from qiskit.pulse.calibration_entries import (
CalibrationEntry,
ScheduleDef,
CallableDef,
# for backward compatibility
PulseQobjDef,
CalibrationPublisher,
)
from qiskit.pulse.exceptions import PulseError
from qiskit.pulse.schedule import Schedule, ScheduleBlock
class InstructionScheduleMap:
"""Mapping from :py:class:`~qiskit.circuit.QuantumCircuit`
:py:class:`qiskit.circuit.Instruction` names and qubits to
:py:class:`~qiskit.pulse.Schedule` s. In particular, the mapping is formatted as type::
Dict[str, Dict[Tuple[int], Schedule]]
where the first key is the name of a circuit instruction (e.g. ``'u1'``, ``'measure'``), the
second key is a tuple of qubit indices, and the final value is a Schedule implementing the
requested instruction.
These can usually be seen as gate calibrations.
"""
def __init__(self):
"""Initialize a circuit instruction to schedule mapper instance."""
# The processed and reformatted circuit instruction definitions
# Do not use lambda function for nested defaultdict, i.e. lambda: defaultdict(CalibrationEntry).
# This crashes qiskit parallel. Note that parallel framework passes args as
# pickled object, however lambda function cannot be pickled.
self._map: dict[str | circuit.instruction.Instruction, dict[tuple, CalibrationEntry]] = (
defaultdict(functools.partial(defaultdict, CalibrationEntry))
)
# A backwards mapping from qubit to supported instructions
self._qubit_instructions: dict[tuple[int, ...], set] = defaultdict(set)
def has_custom_gate(self) -> bool:
"""Return ``True`` if the map has user provided instruction."""
for qubit_inst in self._map.values():
for entry in qubit_inst.values():
if entry.user_provided:
return True
return False
@property
def instructions(self) -> list[str]:
"""Return all instructions which have definitions.
By default, these are typically the basis gates along with other instructions such as
measure and reset.
Returns:
The names of all the circuit instructions which have Schedule definitions in this.
"""
return list(self._map.keys())
def qubits_with_instruction(
self, instruction: str | circuit.instruction.Instruction
) -> list[int | tuple[int, ...]]:
"""Return a list of the qubits for which the given instruction is defined. Single qubit
instructions return a flat list, and multiqubit instructions return a list of ordered
tuples.
Args:
instruction: The name of the circuit instruction.
Returns:
Qubit indices which have the given instruction defined. This is a list of tuples if the
instruction has an arity greater than 1, or a flat list of ints otherwise.
Raises:
PulseError: If the instruction is not found.
"""
instruction = _get_instruction_string(instruction)
if instruction not in self._map:
return []
return [
qubits[0] if len(qubits) == 1 else qubits
for qubits in sorted(self._map[instruction].keys())
]
def qubit_instructions(self, qubits: int | Iterable[int]) -> list[str]:
"""Return a list of the instruction names that are defined by the backend for the given
qubit or qubits.
Args:
qubits: A qubit index, or a list or tuple of indices.
Returns:
All the instructions which are defined on the qubits.
For 1 qubit, all the 1Q instructions defined. For multiple qubits, all the instructions
which apply to that whole set of qubits (e.g. ``qubits=[0, 1]`` may return ``['cx']``).
"""
if _to_tuple(qubits) in self._qubit_instructions:
return list(self._qubit_instructions[_to_tuple(qubits)])
return []
def has(
self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int]
) -> bool:
"""Is the instruction defined for the given qubits?
Args:
instruction: The instruction for which to look.
qubits: The specific qubits for the instruction.
Returns:
True iff the instruction is defined.
"""
instruction = _get_instruction_string(instruction)
return instruction in self._map and _to_tuple(qubits) in self._map[instruction]
def assert_has(
self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int]
) -> None:
"""Error if the given instruction is not defined.
Args:
instruction: The instruction for which to look.
qubits: The specific qubits for the instruction.
Raises:
PulseError: If the instruction is not defined on the qubits.
"""
instruction = _get_instruction_string(instruction)
if not self.has(instruction, _to_tuple(qubits)):
if instruction in self._map:
raise PulseError(
"Operation '{inst}' exists, but is only defined for qubits "
"{qubits}.".format(
inst=instruction, qubits=self.qubits_with_instruction(instruction)
)
)
raise PulseError(f"Operation '{instruction}' is not defined for this system.")
def get(
self,
instruction: str | circuit.instruction.Instruction,
qubits: int | Iterable[int],
*params: complex | ParameterExpression,
**kwparams: complex | ParameterExpression,
) -> Schedule | ScheduleBlock:
"""Return the defined :py:class:`~qiskit.pulse.Schedule` or
:py:class:`~qiskit.pulse.ScheduleBlock` for the given instruction on the given qubits.
If all keys are not specified this method returns schedule with unbound parameters.
Args:
instruction: Name of the instruction or the instruction itself.
qubits: The qubits for the instruction.
*params: Command parameters for generating the output schedule.
**kwparams: Keyworded command parameters for generating the schedule.
Returns:
The Schedule defined for the input.
"""
return self._get_calibration_entry(instruction, qubits).get_schedule(*params, **kwparams)
def _get_calibration_entry(
self,
instruction: str | circuit.instruction.Instruction,
qubits: int | Iterable[int],
) -> CalibrationEntry:
"""Return the :class:`.CalibrationEntry` without generating schedule.
When calibration entry is un-parsed Pulse Qobj, this returns calibration
without parsing it. :meth:`CalibrationEntry.get_schedule` method
must be manually called with assigned parameters to get corresponding pulse schedule.
This method is expected be directly used internally by the V2 backend converter
for faster loading of the backend calibrations.
Args:
instruction: Name of the instruction or the instruction itself.
qubits: The qubits for the instruction.
Returns:
The calibration entry.
"""
instruction = _get_instruction_string(instruction)
self.assert_has(instruction, qubits)
return self._map[instruction][_to_tuple(qubits)]
def add(
self,
instruction: str | circuit.instruction.Instruction,
qubits: int | Iterable[int],
schedule: Schedule | ScheduleBlock | Callable[..., Schedule | ScheduleBlock],
arguments: list[str] | None = None,
) -> None:
"""Add a new known instruction for the given qubits and its mapping to a pulse schedule.
Args:
instruction: The name of the instruction to add.
qubits: The qubits which the instruction applies to.
schedule: The Schedule that implements the given instruction.
arguments: List of parameter names to create a parameter-bound schedule from the
associated gate instruction. If :py:meth:`get` is called with arguments rather
than keyword arguments, this parameter list is used to map the input arguments to
parameter objects stored in the target schedule.
Raises:
PulseError: If the qubits are provided as an empty iterable.
"""
instruction = _get_instruction_string(instruction)
# validation of target qubit
qubits = _to_tuple(qubits)
if not qubits:
raise PulseError(f"Cannot add definition {instruction} with no target qubits.")
# generate signature
if isinstance(schedule, (Schedule, ScheduleBlock)):
entry: CalibrationEntry = ScheduleDef(arguments)
elif callable(schedule):
if arguments:
warnings.warn(
"Arguments are overruled by the callback function signature. "
"Input `arguments` are ignored.",
UserWarning,
)
entry = CallableDef()
else:
raise PulseError(
"Supplied schedule must be one of the Schedule, ScheduleBlock or a "
"callable that outputs a schedule."
)
entry.define(schedule, user_provided=True)
self._add(instruction, qubits, entry)
def _add(
self,
instruction_name: str,
qubits: tuple[int, ...],
entry: CalibrationEntry,
):
"""A method to resister calibration entry.
.. note::
This is internal fast-path function, and caller must ensure
the entry is properly formatted. This function may be used by other programs
that load backend calibrations to create Qiskit representation of it.
Args:
instruction_name: Name of instruction.
qubits: List of qubits that this calibration is applied.
entry: Calibration entry to register.
:meta public:
"""
self._map[instruction_name][qubits] = entry
self._qubit_instructions[qubits].add(instruction_name)
def remove(
self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int]
) -> None:
"""Remove the given instruction from the listing of instructions defined in self.
Args:
instruction: The name of the instruction to add.
qubits: The qubits which the instruction applies to.
"""
instruction = _get_instruction_string(instruction)
qubits = _to_tuple(qubits)
self.assert_has(instruction, qubits)
del self._map[instruction][qubits]
if not self._map[instruction]:
del self._map[instruction]
self._qubit_instructions[qubits].remove(instruction)
if not self._qubit_instructions[qubits]:
del self._qubit_instructions[qubits]
def pop(
self,
instruction: str | circuit.instruction.Instruction,
qubits: int | Iterable[int],
*params: complex | ParameterExpression,
**kwparams: complex | ParameterExpression,
) -> Schedule | ScheduleBlock:
"""Remove and return the defined schedule for the given instruction on the given
qubits.
Args:
instruction: Name of the instruction.
qubits: The qubits for the instruction.
*params: Command parameters for generating the output schedule.
**kwparams: Keyworded command parameters for generating the schedule.
Returns:
The Schedule defined for the input.
"""
instruction = _get_instruction_string(instruction)
schedule = self.get(instruction, qubits, *params, **kwparams)
self.remove(instruction, qubits)
return schedule
def get_parameters(
self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int]
) -> tuple[str, ...]:
"""Return the list of parameters taken by the given instruction on the given qubits.
Args:
instruction: Name of the instruction.
qubits: The qubits for the instruction.
Returns:
The names of the parameters required by the instruction.
"""
instruction = _get_instruction_string(instruction)
self.assert_has(instruction, qubits)
signature = self._map[instruction][_to_tuple(qubits)].get_signature()
return tuple(signature.parameters.keys())
def __str__(self):
single_q_insts = "1Q instructions:\n"
multi_q_insts = "Multi qubit instructions:\n"
for qubits, insts in self._qubit_instructions.items():
if len(qubits) == 1:
single_q_insts += f" q{qubits[0]}: {insts}\n"
else:
multi_q_insts += f" {qubits}: {insts}\n"
instructions = single_q_insts + multi_q_insts
return f"<{self.__class__.__name__}({instructions})>"
def __eq__(self, other):
if not isinstance(other, InstructionScheduleMap):
return False
for inst in self.instructions:
for qinds in self.qubits_with_instruction(inst):
try:
if self._map[inst][_to_tuple(qinds)] != other._map[inst][_to_tuple(qinds)]:
return False
except KeyError:
return False
return True
def _to_tuple(values: int | Iterable[int]) -> tuple[int, ...]:
"""Return the input as a tuple.
Args:
values: An integer, or iterable of integers.
Returns:
The input values as a sorted tuple.
"""
try:
return tuple(values)
except TypeError:
return (values,)
def _get_instruction_string(inst: str | circuit.instruction.Instruction) -> str:
if isinstance(inst, str):
return inst
else:
try:
return inst.name
except AttributeError as ex:
raise PulseError(
'Input "inst" has no attribute "name". This should be a circuit "Instruction".'
) from ex
|
https://github.com/qctrl/python-qiskit
|
qctrl
|
# General
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
# Q-CTRL Open Controls
from qctrlopencontrols import new_quadratic_sequence, new_ramsey_sequence
# Q-CTRL Qiskit Adapter
from qctrlqiskit import convert_dds_to_qiskit_quantum_circuit
# Q-CTRL Visualizer
from qctrlvisualizer import plot_sequences
# Qiskit
##To define a backend (simulated or real), transpile and assemble a circuit
from qiskit import BasicAer
from qiskit.compiler import transpile, assemble
##To plot the outcome
from qiskit.tools.visualization import plot_histogram
## To handle account information,find a suitable device and monitor a job
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
## Quadratic sequence, total duration: 20us
quadratic_sequence = new_quadratic_sequence(
duration=20e-6,
inner_offset_count=2,
outer_offset_count=2,
pre_post_rotation=True,
name="Quadratic sequence",
)
# Ramsey sequence, total duration: 20us
ramsey_sequence = new_ramsey_sequence(
duration=20e-6, pre_post_rotation=True, name="Ramsey sequence"
)
print(quadratic_sequence)
print(ramsey_sequence)
## Prepare the Qiskit related parameters
"""
target_qubits : list
A list of integers specifying the target qubits within the set of qubit registers
"""
target_qubits = [0]
"""
gate_time : float
Time delay (in seconds) introduced by identity gate
"""
gate_time = 0.4e-6
"""
add_measurement : bool
Indicates if the circuit requires a measurement step.
Required for 'qasm_simulator' and real device backends
"""
add_measurement = True
"""
circuit_name : str
An optional string as a name to the circuit
"""
circuit_name = "quadratic-sequence-circuit"
## convert the quadratic sequence to QuantumCircuit
quadratic_quantum_circuit = convert_dds_to_qiskit_quantum_circuit(
dynamic_decoupling_sequence=quadratic_sequence,
target_qubits=target_qubits,
gate_time=gate_time,
add_measurement=add_measurement,
circuit_name=circuit_name,
)
## convert the ramsey sequence to QuantumCircuit
circuit_name = "ramsey-sequence-circuit"
ramsey_quantum_circuit = convert_dds_to_qiskit_quantum_circuit(
dynamic_decoupling_sequence=ramsey_sequence,
target_qubits=target_qubits,
gate_time=gate_time,
add_measurement=add_measurement,
circuit_name=circuit_name,
)
formatted_plot_data = quadratic_sequence.export()
figure = plt.figure()
plt.suptitle("Quadratic Sequence")
plot_sequences(figure, formatted_plot_data)
formatted_plot_data = ramsey_sequence.export()
figure = plt.figure()
plt.suptitle("Ramsey Sequence")
plot_sequences(figure, formatted_plot_data)
##Drawing the Quadratic Circuit
quadratic_quantum_circuit.draw()
ramsey_quantum_circuit.draw()
print(ramsey_quantum_circuit.count_ops()["id"])
## Prepares the simulator backend
"""
backend : str
One of 'unitary_simulator', 'statevector_simulator' or 'qasm_simulator';
defaults to 'qasm_simulator'
"""
backend = "qasm_simulator"
backend_simulator = BasicAer.get_backend(backend)
"""
number_of_shots : int
Number of repeats the experiment has to be carried out;
defaults to 1
"""
number_of_shots = 1024
## Run the quadratic sequence circuit, Get the result (counts of state |1> and |0>), plot the histogram
# Transpile and assemble the circuits so that the identity gates are preserved
transpiled_quadratic_circuit = transpile(
quadratic_quantum_circuit, backend=backend_simulator, optimization_level=0
)
assembled_quadratic_circuit = assemble(
transpiled_quadratic_circuit, shots=number_of_shots
)
# run the circuit
job = backend_simulator.run(assembled_quadratic_circuit)
result = job.result()
counts = result.get_counts(quadratic_quantum_circuit)
plot_histogram(counts)
## Run the ramsey sequence circuit, Get the result (counts of state |1> and |0>), plot the histogram
# Transpile and assemble the circuits so that the identity gates are preserved
transpiled_ramsey_circuit = transpile(
ramsey_quantum_circuit, backend=backend_simulator, optimization_level=0
)
assembled_ramsey_circuit = assemble(transpiled_ramsey_circuit, shots=number_of_shots)
job = backend_simulator.run(assembled_ramsey_circuit)
result = job.result()
counts = result.get_counts(ramsey_quantum_circuit)
plot_histogram(counts)
# NBVAL_SKIP
"""
account_token : str
Token to enable IBM Q device access
"""
account_token = "insert-your-ibmq-token-here"
IBMQ.enable_account(account_token)
provider = IBMQ.get_provider(hub="ibm-q", group="open")
backends = provider.backends()
backends = [backend for backend in backends if backend.name() != "ibmq_qasm_simulator"]
backend = least_busy(backends)
print("Least busy device is {}".format(backend.name()))
# NBVAL_SKIP
job = backend.run(assembled_quadratic_circuit)
job_monitor(job)
result = job.result()
counts = result.get_counts(quadratic_quantum_circuit)
plot_histogram(counts)
# NBVAL_SKIP
job = backend.run(assembled_ramsey_circuit)
job_monitor(job)
result = job.result()
counts = result.get_counts(ramsey_quantum_circuit)
plot_histogram(counts)
# NBVAL_SKIP
IBMQ.disable_account()
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import QuantumCircuit
from qiskit import QuantumRegister, QuantumCircuit
c = QuantumRegister(1, 'control')
t = QuantumRegister(2, 'target')
cu = QuantumCircuit(c, t, name="Controlled 13^x mod 35")
# Your code goes here
# easy (non-optimal) solution:
cu.ccx(c, t[0], t[1])
cu.cx(c, t[0])
# end solution
cu.draw()
c = QuantumRegister(1, 'control')
t = QuantumRegister(2, 'target')
cu2 = QuantumCircuit(c, t)
# Your code here
# Non-optimal solution:
cu2 = cu.compose(cu)
# end solution
cu2.draw()
c = QuantumRegister(1, 'control')
t = QuantumRegister(2, 'target')
cu4 = QuantumCircuit(c, t)
# Your code here
# VERY bad solution (to be removed):
cu4 = cu2.compose(cu2)
# end solution
cu4.draw()
cqr = QuantumRegister(3, 'control')
tqr = QuantumRegister(2, 'target')
cux = QuantumCircuit(cqr, tqr)
solutions = [cu, cu2, cu4]
for i in range(3):
cux = cux.compose(solutions[i], [cqr[i], tqr[0], tqr[1]])
cux.draw()
# To be removed before the challenge
from qiskit.circuit.library import QFT
from qiskit import transpile
import numpy as np
cqr = QuantumRegister(3, 'control')
tqr = QuantumRegister(2, 'target')
cux2 = QuantumCircuit(cqr, tqr)
cux2.append(QFT(2, do_swaps=False), [3, 4])
cux2.cz(0, 3)
cux2.cp(np.pi/2, 0, 4)
cux2.cz(1, 4)
cux2.append(QFT(2, inverse=True, do_swaps=False), [3, 4])
display(cux2.draw())
t_cux2 = transpile(cux2, basis_gates=['u','cx'], optimization_level=3)
display(t_cux2.draw())
t_cux2.count_ops()['cx']
from qiskit.circuit.library import QFT
from qiskit import ClassicalRegister
cr = ClassicalRegister(3)
shor_circuit = QuantumCircuit(cqr, tqr, cr)
shor_circuit.h(cqr)
shor_circuit.compose(cux2, inplace=True)
shor_circuit.append(QFT(3, inverse=True, do_swaps=True), cqr)
shor_circuit.measure(cqr, cr)
shor_circuit.draw()
from qiskit.test.mock import FakeAthens
from qiskit import assemble
from qiskit.visualization import plot_histogram
# we can do some more transpiling to squeeze out extra performance, but this isn't necessary
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import HoareOptimizer
athens = FakeAthens()
tqc = transpile(shor_circuit, athens, optimization_level=3)
pm = PassManager(HoareOptimizer())
tqc = pm.run(tqc)
counts = athens.run(assemble(tqc)).result().get_counts()
plot_histogram(counts)
|
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.
"""Tests for pass cancelling 2 consecutive CNOTs on the same qubits."""
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Clbit, Qubit
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import CXCancellation
from qiskit.test import QiskitTestCase
class TestCXCancellation(QiskitTestCase):
"""Test the CXCancellation pass."""
def test_pass_cx_cancellation(self):
"""Test the cx cancellation pass.
It should cancel consecutive cx pairs on same qubits.
"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[0])
self.assertEqual(out_circuit, expected)
def test_pass_cx_cancellation_intermixed_ops(self):
"""Cancellation shouldn't be affected by the order of ops on different qubits."""
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[1])
self.assertEqual(out_circuit, expected)
def test_pass_cx_cancellation_chained_cx(self):
"""Include a test were not all operations can be cancelled."""
# ┌───┐
# q0_0: ┤ H ├──■─────────■───────
# ├───┤┌─┴─┐ ┌─┴─┐
# q0_1: ┤ H ├┤ X ├──■──┤ X ├─────
# └───┘└───┘┌─┴─┐└───┘
# q0_2: ──────────┤ X ├──■────■──
# └───┘┌─┴─┐┌─┴─┐
# q0_3: ───────────────┤ X ├┤ X ├
# └───┘└───┘
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[2], qr[3])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
# ┌───┐
# q0_0: ┤ H ├──■─────────■──
# ├───┤┌─┴─┐ ┌─┴─┐
# q0_1: ┤ H ├┤ X ├──■──┤ X ├
# └───┘└───┘┌─┴─┐└───┘
# q0_2: ──────────┤ X ├─────
# └───┘
# q0_3: ────────────────────
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[1])
expected.cx(qr[0], qr[1])
expected.cx(qr[1], qr[2])
expected.cx(qr[0], qr[1])
self.assertEqual(out_circuit, expected)
def test_swapped_cx(self):
"""Test that CX isn't cancelled if there are intermediary ops."""
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0])
circuit.swap(qr[1], qr[2])
circuit.cx(qr[1], qr[0])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
self.assertEqual(out_circuit, circuit)
def test_inverted_cx(self):
"""Test that CX order dependence is respected."""
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
self.assertEqual(out_circuit, circuit)
def test_if_else(self):
"""Test that the pass recurses in a simple if-else."""
pass_ = CXCancellation()
inner_test = QuantumCircuit(4, 1)
inner_test.cx(0, 1)
inner_test.cx(0, 1)
inner_test.cx(2, 3)
inner_expected = QuantumCircuit(4, 1)
inner_expected.cx(2, 3)
test = QuantumCircuit(4, 1)
test.h(0)
test.measure(0, 0)
test.if_else((0, True), inner_test.copy(), inner_test.copy(), range(4), [0])
expected = QuantumCircuit(4, 1)
expected.h(0)
expected.measure(0, 0)
expected.if_else((0, True), inner_expected, inner_expected, range(4), [0])
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that collection recurses into nested control flow."""
pass_ = CXCancellation()
qubits = [Qubit() for _ in [None] * 4]
clbit = Clbit()
inner_test = QuantumCircuit(qubits, [clbit])
inner_test.cx(0, 1)
inner_test.cx(0, 1)
inner_test.cx(2, 3)
inner_expected = QuantumCircuit(qubits, [clbit])
inner_expected.cx(2, 3)
true_body = QuantumCircuit(qubits, [clbit])
true_body.while_loop((clbit, True), inner_test.copy(), [0, 1, 2, 3], [0])
test = QuantumCircuit(qubits, [clbit])
test.for_loop(range(2), None, inner_test.copy(), [0, 1, 2, 3], [0])
test.if_else((clbit, True), true_body, None, [0, 1, 2, 3], [0])
expected_if_body = QuantumCircuit(qubits, [clbit])
expected_if_body.while_loop((clbit, True), inner_expected, [0, 1, 2, 3], [0])
expected = QuantumCircuit(qubits, [clbit])
expected.for_loop(range(2), None, inner_expected, [0, 1, 2, 3], [0])
expected.if_else((clbit, True), expected_if_body, None, [0, 1, 2, 3], [0])
self.assertEqual(pass_(test), expected)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
import qiskit
from qiskit import *
import math
import numpy as np
def qc_ezz(t):
qc = QuantumCircuit(2, name = 'e^(-itZZ)')
qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1)
return qc
def qc_exx(t):
qc = QuantumCircuit(2, name = 'e^(-itXX)')
qc.h([0,1]); qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1); qc.h([0,1])
return qc
def qc_eyy(t):
qc = QuantumCircuit(2, name = 'e^(-itYY)')
qc.sdg([0,1]); qc.h([0,1]); qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1); qc.h([0,1]); qc.s([0,1])
return qc
def qc_Bj(t):
qc = QuantumCircuit(3, name = 'B_j')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
return qc
qc_Bj_ = qc_Bj(math.pi/2); qc_Bj_.draw(output='mpl')
qc_Bj_.decompose().draw(output='mpl')
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
#provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_jakarta')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.tools.monitor import backend_overview, backend_monitor
from qiskit.providers.aer import noise
from qiskit.providers.aer.noise import NoiseModel
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
noise_model = NoiseModel.from_backend(device)
basis_gates = noise_model.basis_gates
coupling_map = device.configuration().coupling_map
ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]);
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
for j in range(0, 10): # Trotter stepsm_info.
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_ = qc_Bj(t/(j+1))
for k in range(0, j+1):
qc.append(qc_Bj_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
qstf_exp = StateTomographyFitter(job_exp.result(), qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('No. passos=', j+1, ',F_sim=', F_sim, ',F_exp=', F_exp)
inha visto essa reprovação mas não me dei por conta que n# for error mitigation
qr = QuantumRegister(7)
qubit_list = [5,3,1] # the qubits on which we shall apply error mitigation
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr)
job_cal = execute(meas_calibs, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
meas_fitter = CompleteMeasFitter(job_cal.result(), state_labels)
ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
for j in range(0, 10): # Trotter steps
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_ = qc_Bj(t/(j+1))
for k in range(0, j+1):
qc.append(qc_Bj_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('No. passos=', j+1, ',F_sim=', F_sim, ',F_exp=', F_exp)
def qc_Bj_zz(t, th, ph):
qc = QuantumCircuit(3, name = 'B_j_zz')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.rz(2*th, [1,2])
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.rz(-2*th, [1,2])
qc.rz(2*ph, [0,1])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
qc.rz(-2*ph, [0,1])
return qc
qc_Bj_zz_ = qc_Bj_zz(math.pi, math.pi/3, math.pi/4); qc_Bj_zz_.draw(output='mpl')
ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
j = 6; print('N. of Trotter steps = ', j+1)
th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0]
ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0]
for m in range(0, dim_th):
for n in range(0, dim_ph):
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_zz_ = qc_Bj_zz(t/(j+1), th[m], ph[n])
for k in range(0, j+1):
qc.append(qc_Bj_zz_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp)
def qc_Bj_zx(t, th, ph):
qc = QuantumCircuit(3, name = 'B_j_zz')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.rx(2*th, [1,2])
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.rx(-2*th, [1,2])
qc.rz(2*ph, [0,1])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
qc.rz(-2*ph, [0,1])
return qc
qc_Bj_zx_ = qc_Bj_zx(math.pi, math.pi/3, math.pi/4); qc_Bj_zx_.draw(output='mpl')
inha visto essa reprovação mas não me dei por conta que nket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
j = 6; print('N. of Trotter steps = ', j+1)
th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0]
ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0]
for m in range(0, dim_th):
for n in range(0, dim_ph):
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_zx_ = qc_Bj_zx(t/(j+1), th[m], ph[n])
for k in range(0, j+1):
qc.append(qc_Bj_zx_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp)
def qc_Bj_yx(t, th, ph):
qc = QuantumCircuit(3, name = 'B_j_zz')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.rx(2*th, [1,2])
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.rx(-2*th, [1,2])
qc.barrier()
qc.ry(2*ph, [0,1])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
qc.ry(-2*ph, [0,1])
return qc
qc_Bj_yx_ = qc_Bj_yx(math.pi, math.pi/3, math.pi/4); qc_Bj_yx_.draw(output='mpl')
https://arxiv.org/abs/2204.07816ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
j = 6; print('N. of Trotter steps = ', j+1)
th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0]
ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0]
for m in range(0, dim_th):
for n in range(0, dim_ph):
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_yx_ = qc_Bj_yx(t/(j+1), th[m], ph[n])
for k in range(0, j+1):
qc.append(qc_Bj_yx_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation0.34
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp)
noise_model = NoiseModel.from_backend(device)
basis_gates = noise_model.basis_gates
coupling_map = device.configuration().coupling_map
basis_gates
print(coupling_map)
|
https://github.com/erinaldi/bmn2-qiskit
|
erinaldi
|
# Here's where the number of qubits are set. The Hamiltonian will be have a size of (N-2)x(N-2)
qubits = 8
N = (2**qubits)+2
print(f"The Hamiltonian will be a {N-2}x{N-2} matrix")
#lattice lower bound
a = -6
#lattice upper bound
b = 6
# Import necessary libraries
import numpy as np
import matplotlib.pyplot as plt
# Define x grid and step size
x = np.linspace(a,b,N)
h = x[1]-x[0]
print(f"Discretized grid with {N} sites and step size {h:.4f}")
plt.plot(x,np.zeros(x.shape),'o', label="Grid points")
plt.legend(loc='upper right');
print(f"The extremal points will not be considered. That is why we have a {N-2}x{N-2} Hamiltonian but {N} points.")
# Define potential energy function. Change this to change the potential.
def Vpot(x):
return (1/2)*x**2
# Create Kinetic Energy Matrix
T = np.zeros((N-2)**2).reshape(N-2,N-2)
for i in range(N-2):
for j in range(N-2):
if i==j:
T[i,j]= -2
elif np.abs(i-j)==1:
T[i,j]=1
else:
T[i,j]=0
# Create Potential Energy Matrix
V = np.zeros((N-2)**2).reshape(N-2,N-2)
for i in range(N-2):
for j in range(N-2):
if i==j:
V[i,j]= Vpot(x[i+1])
else:
V[i,j]=0
# Create Hamiltonian: a big matrix 😂
H = -T/(2*h**2) + V
Tp = np.zeros((N-2,N-2)) # create a kinetic matrix full of zeros
T_id = np.diag_indices(Tp.shape[0]) # select the indices on the diagonal
T_idp = (T_id[0][:-1],(T_id[1][:-1]+1)) # select the indices above the diagonal y-x=1
T_idm = (T_id[0][:-1]+1,T_id[1][:-1]) # select the indices below the diagonal x-y=1
# fill the 3 "diagonals" with entries for the discretized derivative
Tp[T_id] = -2.0
Tp[T_idp] = Tp[T_idm] = 1.0
# check it is the same as the matrix created with for loops
assert(np.allclose(T,Tp))
Tp.shape
Vp = np.zeros((N-2,N-2))
V_id = np.diag_indices(Vp.shape[0])
Vp[V_id] = Vpot(x[1:-1])
assert(np.allclose(V,Vp))
Vp.shape
# this has 2 more sites
x.shape
# Create Hamiltonian: a big matrix 😂
Hp = -Tp/(2*h**2) + Vp
assert(np.allclose(H,Hp))
plt.imshow(H, cmap='jet')
plt.colorbar();
# Find eigenvalues and eigenvectors, then sort them in ascending order
val, vec = np.linalg.eig(H)
z = np.argsort(val)
z = z[0:4]
energies = val[z]
print("Finite Difference Energies for the first 4 states: ", energies)
# Compare finite difference calculation to theoretical calculation
nVec = np.linspace(0, len(energies) - 1, len(energies))
En = nVec + 0.5
print("Theoretical Energies: ", En)
percentError = ((En - energies) / (energies)) * 100
print("Percent Error: ", percentError)
# potential energy
# get the ground state
gs_vec = vec[:,z[0]]
# sandwich the potential energy
gs_vec.T.dot(Vp.dot(gs_vec))
En[0]/2
# Plot wavefunctions for first 4 lowest states
plt.figure(figsize=(12,10))
scalingFactor=1.5
for i in range(len(z)):
y = []
y = np.append(y,vec[:,z[i]])
y = np.append(y,0)
y = np.insert(y,0,0)
plt.plot(x,scalingFactor*y+energies[i],lw=3, label="{} ".format(i))
plt.xlabel('x', size=14)
plt.ylabel(r'$\Psi$(x)',size=14,color='tab:red')
plt.legend(title="nth Quantum State")
plt.title('normalized wavefunctions for a harmonic oscillator using finite difference method',size=14)
# function to compute the ground state energy as a function of R and L
def gs_energy(R, L, potential=Vpot):
# add boundary points
# Define x grid and step size
x = np.linspace(-R, R, L)
h = x[1] - x[0]
# print(R,L,h)
# add boundary
x = np.append(x, x[-1] + h)
x = np.insert(x, 0, x[0] - h)
# kinetic
Tp = np.zeros((L, L)) # create a kinetic matrix full of zeros
T_id = np.diag_indices(Tp.shape[0]) # select the indices on the diagonal
T_idp = (
T_id[0][:-1],
(T_id[1][:-1] + 1),
) # select the indices above the diagonal y-x=1
T_idm = (
T_id[0][:-1] + 1,
T_id[1][:-1],
) # select the indices below the diagonal x-y=1
# fill the 3 "diagonals" with entries for the discretized derivative
Tp[T_id] = -2.0
Tp[T_idp] = Tp[T_idm] = 1.0
# Potential
Vp = np.zeros((L, L))
V_id = np.diag_indices(Vp.shape[0])
Vp[V_id] = potential(x[1:-1])
# Hamiltonian
Hp = -Tp / (2 * h**2) + Vp
# Ground state
val, vec = np.linalg.eig(Hp)
z = np.argsort(val)
# print(val[z[0]])
delta_energy = np.fabs(val[z[0]] - 0.5)
# get the ground state
gs_vec = vec[:, z[0]]
# sandwich the potential energy
potential_energy = gs_vec.T.dot(Vp.dot(gs_vec))
return np.array([h, R, L, delta_energy, potential_energy], dtype=np.float64)
gs_energy(11,1050)
from tqdm.notebook import tqdm
df = list()
# for r in tqdm([0.5,1.,1.5,2.,2.5,3.,3.5,4.,5.,7.,9.,11.], desc='R'):
# for l in tqdm([50,150,250,350,450,550,650,850,1050], desc='L'):
for r in tqdm([4.,5.,7.,9.,11.], desc='R'):
for l in tqdm([450,550,650,850,1050], desc='L'):
df.append(gs_energy(r,l))
df = np.asarray(df)
import pandas as pd
df = pd.DataFrame(df, columns=["A","R","L","D","P"], dtype=np.float64)
df.head()
import seaborn as sns
g = sns.relplot(data=df, x="L", y="D", hue="R", palette='tab20', kind='line', height=4, aspect=2)
g.set_axis_labels(r"$\Lambda$", r"$\Delta E_0$")
g.set(yscale='log', xscale='log')
g = sns.relplot(data=df, x="A", y="P", hue="L", palette='tab20', kind='line', height=4, aspect=2)
g.set_axis_labels(r"$a_{dig}$", r"$V_p$")
g.set(yscale='log', xscale='log')
a_dig = 0.7
def ir_cutoff(a_dig):
return 1_000 * a_dig
def uv_cutoff(a_dig):
return int(1 + 2 * ir_cutoff(a_dig) / a_dig)
R = ir_cutoff(a_dig)
L = uv_cutoff(a_dig)
print(f"Choosing a_dig={a_dig} with R={R} and L={L}")
# Define potential energy function. Change this to change the potential.
# M^2 = 1
def Vpot_quartic(x):
return (1/2)*x**2 + (1/4)*x**4
# M^2 = -1
def Vpot_quartic_neg(x):
return -(1/2)*x**2 + (1/4)*x**4
gs_energy(R,L,potential=Vpot_quartic)
gs_energy(R,L,potential=Vpot_quartic_neg)
# T = 0.1
T = 0.1
beta = 1.0/T
print(f"Temperature = {T} \n (beta={beta})")
# Example: correction to the 0.5 ground state energy of the harmonic oscillator at zero temperature
np.fabs(0.5 - 0.5*1./np.tanh(beta/2))
def harmonic_energy(beta):
return 0.5*1./np.tanh(beta/2)
# Example: harmonic oscillator potential energy at finite temperature
v_beta = np.sum([np.exp(-beta*val[i])*(vec[:,i].T.dot(Vp.dot(vec[:,i]))) for i in z])
# normalize using the partition function
z_beta = np.sum(np.exp(-beta*val))
v_beta /= z_beta
print(f"Potential energy at beta={beta} : {v_beta}")
# result "in the continuum": it is slightly higher than 0.25 because of thermal fluctuations
harmonic_energy(beta)/2
# function to compute the average potential energy at finite temperature as a function of R and L
def pot_energy(beta, R, L, potential=Vpot):
# add boundary points
# Define x grid and step size
x = np.linspace(-R, R, L)
h = x[1] - x[0]
# print(R,L,h)
# add boundary
x = np.append(x, x[-1] + h)
x = np.insert(x, 0, x[0] - h)
# kinetic
Tp = np.zeros((L, L)) # create a kinetic matrix full of zeros
T_id = np.diag_indices(Tp.shape[0]) # select the indices on the diagonal
T_idp = (
T_id[0][:-1],
(T_id[1][:-1] + 1),
) # select the indices above the diagonal y-x=1
T_idm = (
T_id[0][:-1] + 1,
T_id[1][:-1],
) # select the indices below the diagonal x-y=1
# fill the 3 "diagonals" with entries for the discretized derivative
Tp[T_id] = -2.0
Tp[T_idp] = Tp[T_idm] = 1.0
# Potential
Vp = np.zeros((L, L))
V_id = np.diag_indices(Vp.shape[0])
Vp[V_id] = potential(x[1:-1])
# Hamiltonian
Hp = -Tp / (2 * h**2) + Vp
# Spectrum: use eigh because eig will not return all eigenvalues correctly (contains nan)
val, vec = np.linalg.eigh(Hp)
ei = np.argsort(val)
# partition function
z_beta = np.sum(np.exp(-beta * val))
# potential energy
v_beta = np.sum(
[
np.exp(-beta * val[i]) * (vec[:, i].T.dot(Vp.dot(vec[:, i]))) / z_beta
for i in ei[::-1]
]
)
return np.array([h, R, L, z_beta, v_beta], dtype=np.float64)
pot_energy(1/T, a, N, potential=Vpot)
a_dig = 0.3
R = ir_cutoff(a_dig)
L = uv_cutoff(a_dig)
T = 0.1
beta = 1/T
print(f"Quadratic potential: {pot_energy(beta, R, L, potential=Vpot)}")
print(f"Quartic msq=1 potential: {pot_energy(beta, R, L, potential=Vpot_quartic)}")
print(f"Quartic msq=-1 potential: {pot_energy(beta, R, L, potential=Vpot_quartic_neg)}")
a_dig = 0.5
R = ir_cutoff(a_dig)
L = uv_cutoff(a_dig)
T = 0.1
beta = 1/T
print(f"Quadratic potential: {pot_energy(beta, R, L, potential=Vpot)}")
print(f"Quartic msq=1 potential: {pot_energy(beta, R, L, potential=Vpot_quartic)}")
print(f"Quartic msq=-1 potential: {pot_energy(beta, R, L, potential=Vpot_quartic_neg)}")
a_dig = 0.7
R = ir_cutoff(a_dig)
L = uv_cutoff(a_dig)
T = 0.1
beta = 1/T
print(f"Quadratic potential: {pot_energy(beta, R, L, potential=Vpot)}")
print(f"Quartic msq=1 potential: {pot_energy(beta, R, L, potential=Vpot_quartic)}")
print(f"Quartic msq=-1 potential: {pot_energy(beta, R, L, potential=Vpot_quartic_neg)}")
import warnings
import time
from qiskit.opflow import MatrixOp
start_time = time.time()
warnings.filterwarnings("ignore")
qubitOp = MatrixOp(primitive=H)
print("Size of Hamiltonian:", np.shape(H))
print(qubitOp)
end_time = time.time()
runtime = end_time-start_time
print('Program runtime: ',runtime)
from qiskit.circuit.library import EfficientSU2
var_form = EfficientSU2(qubitOp.num_qubits, su2_gates=['ry'], entanglement="full", reps=3)
display(var_form.draw(output='mpl',fold=100))
from qiskit.algorithms import NumPyEigensolver
# exactly diagonalize the system using numpy routines
solver = NumPyEigensolver(k=4)
exact_solution = solver.compute_eigenvalues(qubitOp)
print("Exact Result of qubit hamiltonian:", np.real(exact_solution.eigenvalues))
print("Exact Result of discrete hamiltonian:", energies[0:4])
from qiskit import Aer # change this to Aer for C++ compiled code and the option to run on the GPU
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import SLSQP
from qiskit.utils import algorithm_globals, QuantumInstance
warnings.filterwarnings("ignore")
rngseed = 0
algorithm_globals.random_seed = rngseed
if HAS_GPU:
# with GPU
backend = Aer.get_backend("statevector_simulator", method="statevector_gpu")
else:
# without GPU
backend = Aer.get_backend("statevector_simulator", max_parallel_threads=1, max_parallel_experiments=0)
q_instance = QuantumInstance(
backend, seed_transpiler=rngseed, seed_simulator=rngseed
)
optimizer = SLSQP(maxiter=600)
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
# Run the VQE
vqe = VQE(
ansatz=var_form,
optimizer=optimizer,
quantum_instance=q_instance,
callback=store_intermediate_result,
)
ret = vqe.compute_minimum_eigenvalue(qubitOp)
vqe_result = np.real(ret.eigenvalue)
print("VQE Result:", vqe_result)
# Plot convergence plot
plt.figure(figsize=(12,10))
plt.plot(counts, values, label="SLSQP")
plt.xlabel('Eval count')
plt.ylabel('Energy')
plt.title('Energy convergence')
plt.legend(loc='upper right')
ffrom qiskit.algorithms.optimizers import SPSA
from qiskit.utils import algorithm_globals, QuantumInstance
rngseed = 0
algorithm_globals.random_seed = rngseed
if HAS_GPU:
backendQasm = Aer.get_backend('qasm_simulator', method="statevector_gpu")
else:
backendQasm = Aer.get_backend('qasm_simulator', method="statevector")
q_instance = QuantumInstance(backend=backendQasm, shots=1024, seed_transpiler=rngseed, seed_simulator=rngseed)
optimizer = SPSA(maxiter=600)
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
# Run the VQE
vqe = VQE(
ansatz=var_form,
optimizer=optimizer,
quantum_instance=q_instance,
callback=store_intermediate_result,
)
ret = vqe.compute_minimum_eigenvalue(qubitOp)
vqe_result = np.real(ret.eigenvalue)
print("VQE Result:", vqe_result)
# Plot convergence plot
plt.figure(figsize=(12,10))
plt.plot(counts, values, label="SPSA")
plt.xlabel('Eval count')
plt.ylabel('Energy')
plt.title('Energy convergence for various optimizers')
plt.legend(loc='upper right')
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import GaussianForcesDriver
# if you ran Gaussian elsewhere and already have the output file
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
# if you want to run the Gaussian job from Qiskit
# driver = GaussianForcesDriver(
# ['#p B3LYP/6-31g Freq=(Anharm) Int=Ultrafine SCF=VeryTight',
# '',
# 'CO2 geometry optimization B3LYP/6-31g',
# '',
# '0 1',
# 'C -0.848629 2.067624 0.160992',
# 'O 0.098816 2.655801 -0.159738',
# 'O -1.796073 1.479446 0.481721',
# '',
# ''
from qiskit_nature.second_q.problems import HarmonicBasis
basis = HarmonicBasis([2, 2, 2, 2])
from qiskit_nature.second_q.problems import VibrationalStructureProblem
from qiskit_nature.second_q.mappers import DirectMapper
vibrational_problem = driver.run(basis=basis)
vibrational_problem.hamiltonian.truncation_order = 2
main_op, aux_ops = vibrational_problem.second_q_ops()
print(main_op)
qubit_mapper = DirectMapper()
qubit_op = qubit_mapper.map(main_op)
print(qubit_op)
basis = HarmonicBasis([3, 3, 3, 3])
vibrational_problem = driver.run(basis=basis)
vibrational_problem.hamiltonian.truncation_order = 2
main_op, aux_ops = vibrational_problem.second_q_ops()
qubit_mapper = DirectMapper()
qubit_op = qubit_mapper.map(main_op)
print(qubit_op)
# for simplicity, we will use the smaller basis again
vibrational_problem = driver.run(basis=HarmonicBasis([2, 2, 2, 2]))
vibrational_problem.hamiltonian.truncation_order = 2
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
solver = GroundStateEigensolver(
qubit_mapper,
NumPyMinimumEigensolver(filter_criterion=vibrational_problem.get_default_filter_criterion()),
)
result = solver.solve(vibrational_problem)
print(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Unit-testing Transpiler Service"""
import numpy as np
import pytest
from qiskit import QuantumCircuit, qasm2, qasm3
from qiskit.circuit.library import IQP, EfficientSU2, QuantumVolume
from qiskit.circuit.random import random_circuit
from qiskit.compiler import transpile
from qiskit.quantum_info import SparsePauliOp, random_hermitian
from qiskit_transpiler_service.transpiler_service import TranspilerService
from qiskit_transpiler_service.wrappers import _get_circuit_from_result
@pytest.mark.parametrize(
"optimization_level", [1, 2, 3], ids=["opt_level_1", "opt_level_2", "opt_level_3"]
)
@pytest.mark.parametrize("ai", ["false", "true"], ids=["no_ai", "ai"])
@pytest.mark.parametrize(
"qiskit_transpile_options",
[None, {"seed_transpiler": 0}],
ids=["no opt", "one option"],
)
def test_rand_circ_backend_routing(optimization_level, ai, qiskit_transpile_options):
backend_name = "ibm_brisbane"
random_circ = random_circuit(5, depth=3, seed=42)
cloud_transpiler_service = TranspilerService(
backend_name=backend_name,
ai=ai,
optimization_level=optimization_level,
qiskit_transpile_options=qiskit_transpile_options,
)
transpiled_circuit = cloud_transpiler_service.run(random_circ)
assert isinstance(transpiled_circuit, QuantumCircuit)
@pytest.mark.parametrize(
"optimization_level", [1, 2, 3], ids=["opt_level_1", "opt_level_2", "opt_level_3"]
)
@pytest.mark.parametrize("ai", ["false", "true"], ids=["no_ai", "ai"])
@pytest.mark.parametrize(
"qiskit_transpile_options",
[None, {"seed_transpiler": 0}],
ids=["no opt", "one option"],
)
def test_qv_backend_routing(optimization_level, ai, qiskit_transpile_options):
backend_name = "ibm_brisbane"
qv_circ = QuantumVolume(27, depth=3, seed=42).decompose(reps=3)
cloud_transpiler_service = TranspilerService(
backend_name=backend_name,
ai=ai,
optimization_level=optimization_level,
qiskit_transpile_options=qiskit_transpile_options,
)
transpiled_circuit = cloud_transpiler_service.run(qv_circ)
assert isinstance(transpiled_circuit, QuantumCircuit)
@pytest.mark.parametrize(
"coupling_map",
[
[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]],
[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]],
],
)
@pytest.mark.parametrize("optimization_level", [1, 2, 3])
@pytest.mark.parametrize("ai", ["false", "true"], ids=["no_ai", "ai"])
@pytest.mark.parametrize("qiskit_transpile_options", [None, {"seed_transpiler": 0}])
def test_rand_circ_cmap_routing(
coupling_map, optimization_level, ai, qiskit_transpile_options
):
random_circ = random_circuit(5, depth=3, seed=42).decompose(reps=3)
cloud_transpiler_service = TranspilerService(
coupling_map=coupling_map,
ai=ai,
optimization_level=optimization_level,
qiskit_transpile_options=qiskit_transpile_options,
)
transpiled_circuit = cloud_transpiler_service.run(random_circ)
assert isinstance(transpiled_circuit, QuantumCircuit)
def test_qv_circ_several_circuits_routing():
qv_circ = QuantumVolume(5, depth=3, seed=42).decompose(reps=3)
cloud_transpiler_service = TranspilerService(
backend_name="ibm_brisbane",
ai="true",
optimization_level=1,
)
transpiled_circuit = cloud_transpiler_service.run([qv_circ] * 2)
for circ in transpiled_circuit:
assert isinstance(circ, QuantumCircuit)
transpiled_circuit = cloud_transpiler_service.run([qasm2.dumps(qv_circ)] * 2)
for circ in transpiled_circuit:
assert isinstance(circ, QuantumCircuit)
transpiled_circuit = cloud_transpiler_service.run([qasm2.dumps(qv_circ), qv_circ])
for circ in transpiled_circuit:
assert isinstance(circ, QuantumCircuit)
def test_qv_circ_wrong_input_routing():
qv_circ = QuantumVolume(5, depth=3, seed=42).decompose(reps=3)
cloud_transpiler_service = TranspilerService(
backend_name="ibm_brisbane",
ai="true",
optimization_level=1,
)
circ_dict = {"a": qv_circ}
with pytest.raises(TypeError):
cloud_transpiler_service.run(circ_dict)
@pytest.mark.parametrize("ai", ["false", "true"], ids=["no_ai", "ai"])
def test_transpile_layout_reconstruction(ai):
n_qubits = 27
mat = np.real(random_hermitian(n_qubits, seed=1234))
circuit = IQP(mat)
observable = SparsePauliOp("Z" * n_qubits)
cloud_transpiler_service = TranspilerService(
backend_name="ibm_brisbane",
ai=ai,
optimization_level=1,
)
transpiled_circuit = cloud_transpiler_service.run(circuit)
# This fails if initial layout is not correct
try:
observable.apply_layout(transpiled_circuit.layout)
except Exception:
pytest.fail(
"This should not fail. Probably something wrong with the reconstructed layout."
)
def test_transpile_non_valid_backend():
circuit = EfficientSU2(100, entanglement="circular", reps=1).decompose()
non_valid_backend_name = "ibm_torin"
transpiler_service = TranspilerService(
backend_name=non_valid_backend_name,
ai="false",
optimization_level=3,
)
try:
transpiler_service.run(circuit)
pytest.fail("Error expected")
except Exception as e:
assert (
str(e)
== f'"User doesn\'t have access to the specified backend: {non_valid_backend_name}"'
)
def test_transpile_exceed_circuit_size():
circuit = EfficientSU2(100, entanglement="circular", reps=50).decompose()
transpiler_service = TranspilerService(
backend_name="ibm_kyoto",
ai="false",
optimization_level=3,
)
try:
transpiler_service.run(circuit)
pytest.fail("Error expected")
except Exception as e:
assert str(e) == "'Circuit has more gates than the allowed maximum of 5000.'"
def test_transpile_malformed_body():
circuit = EfficientSU2(100, entanglement="circular", reps=1).decompose()
transpiler_service = TranspilerService(
backend_name="ibm_kyoto",
ai="false",
optimization_level=3,
qiskit_transpile_options={"failing_option": 0},
)
try:
transpiler_service.run(circuit)
pytest.fail("Error expected")
except Exception as e:
assert (
str(e)
== "\"transpile() got an unexpected keyword argument 'failing_option'\""
)
def test_transpile_failing_task():
open_qasm_circuit = 'OPENQASM 2.0;\ninclude "qelib1.inc";\ngate dcx q0,q1 { cx q0,q1; cx q1,q0; }\nqreg q[3];\ncz q[0],q[2];\nsdg q[1];\ndcx q[2],q[1];\nu3(3.890139082217223,3.447697582994976,1.1583481971959322) q[0];\ncrx(2.3585459177723522) q[1],q[0];\ny q[2];'
circuit = QuantumCircuit.from_qasm_str(open_qasm_circuit)
transpiler_service = TranspilerService(
backend_name="ibm_kyoto",
ai="false",
optimization_level=3,
coupling_map=[[1, 2], [2, 1]],
qiskit_transpile_options={
"basis_gates": ["u1", "u2", "u3", "cx"],
"seed_transpiler": 0,
},
)
try:
transpiler_service.run(circuit)
pytest.fail("Error expected")
except Exception as e:
assert "The background task" in str(e)
assert "FAILED" in str(e)
def compare_layouts(plugin_circ, non_ai_circ):
assert (
plugin_circ.layout.initial_layout == non_ai_circ.layout.initial_layout
), "initial_layouts differs"
assert (
plugin_circ.layout.initial_index_layout()
== non_ai_circ.layout.initial_index_layout()
), "initial_index_layout differs"
assert (
plugin_circ.layout.input_qubit_mapping == non_ai_circ.layout.input_qubit_mapping
), "input_qubit_mapping differs"
assert (
plugin_circ.layout._input_qubit_count == non_ai_circ.layout._input_qubit_count
), "_input_qubit_count differs"
assert (
plugin_circ.layout._output_qubit_list == non_ai_circ.layout._output_qubit_list
), "_output_qubit_list differs"
# Sometimes qiskit transpilation does not add final_layout
if non_ai_circ.layout.final_layout:
assert (
plugin_circ.layout.final_layout == non_ai_circ.layout.final_layout
), "final_layout differs"
assert (
plugin_circ.layout.final_index_layout()
== non_ai_circ.layout.final_index_layout()
), "final_index_layout differs"
def get_circuit_as_in_service(circuit):
return {
"qasm": qasm3.dumps(circuit),
"layout": {
"initial": circuit.layout.initial_index_layout(),
"final": circuit.layout.final_index_layout(False),
},
}
def transpile_and_check_layout(cmap, circuit):
non_ai_circ = transpile(
circuits=circuit,
coupling_map=cmap,
optimization_level=1,
)
service_resp = get_circuit_as_in_service(non_ai_circ)
plugin_circ = _get_circuit_from_result(service_resp, circuit)
compare_layouts(plugin_circ, non_ai_circ)
def test_layout_construction_no_service(backend, cmap_backend):
for n_qubits in [5, 10, 15, 20, 27]:
circuit = random_circuit(n_qubits, 4, measure=True)
transpile_and_check_layout(cmap_backend[backend], circuit)
for n_qubits in [5, 10, 15, 20, 27]:
circuit = EfficientSU2(n_qubits, entanglement="circular", reps=1).decompose()
transpile_and_check_layout(cmap_backend[backend], circuit)
for n_qubits in [5, 10, 15, 20, 27]:
circuit = QuantumCircuit(n_qubits)
circuit.cx(0, 1)
circuit.cx(1, 2)
circuit.h(4)
transpile_and_check_layout(cmap_backend[backend], circuit)
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
from qiskit.circuit.library import QuantumVolume, EfficientSU2, TwoLocal, QFT
from qiskit import QuantumCircuit
from qiskit.circuit.library.standard_gates import iSwapGate, CXGate
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeQuitoV2
from qiskit.transpiler.coupling import CouplingMap
from qiskit.extensions import UnitaryGate
from weylchamber import canonical_gate
from mirror_gates.pass_managers import Mirage, QiskitLevel3
from transpile_benchy.metrics.gate_counts import (
DepthMetric,
TotalMetric,
TotalSwaps,
)
from transpile_benchy.metrics.timer import TimeMetric
from mirror_gates.fast_unitary import FastConsolidateBlocks
from qiskit.transpiler.passes import (
Collect2qBlocks,
Unroll3qOrMore,
ConsolidateBlocks,
)
from qiskit.transpiler import PassManager
import numpy as np
from mirror_gates.logging import transpile_benchy_logger
from transpile_benchy.interfaces.mqt_interface import MQTBench
from transpile_benchy.interfaces.qasm_interface import QASMBench
from transpile_benchy.library import CircuitLibrary
lib = CircuitLibrary.from_txt("../circuits/medium_circuits.txt")
qc = lib.get_circuit("seca_n11")
# lib = CircuitLibrary(circuit_list=["qft_n4"])
# qc = lib.get_circuit("qft_n4")
qc = qc.decompose()
qc = qc.decompose()
qc = qc.decompose()
qc.remove_final_measurements()
display(qc.draw("mpl", fold=-1))
# from qiskit.quantum_info import Operator
# from qiskit import QuantumCircuit
# import numpy as np
# from qutip import Qobj
# circ = QuantumCircuit(2)
# circ.cx(1, 0)
# circ.u(0, 0, -np.pi / 4, 0)
# circ.cx(1, 0)
# from weylchamber import c1c2c3
# print(c1c2c3(Operator(circ).data))
# Qobj(Operator(circ).data)
from mirror_gates.fast_unitary import FastConsolidateBlocks
from qiskit.transpiler.passes import (
ConsolidateBlocks,
Collect2qBlocks,
RemoveBarriers,
RemoveFinalMeasurements,
)
from mirror_gates.utilities import RemoveAllMeasurements
from qiskit.transpiler import PassManager
from qiskit.quantum_info import Operator
from weylchamber import c1c2c3
for circuit_name in lib.circuit_list:
if circuit_name == "portfolioqaoa_n16":
continue
# if circuit_name != "qpeexact_16":
# continue
print("\n")
qc = lib.get_circuit(circuit_name)
qc = qc.decompose().decompose().decompose()
qc.remove_final_measurements()
list1 = []
pm0 = PassManager()
pm0.append(RemoveBarriers())
pm0.append(RemoveAllMeasurements())
pm0.append(Collect2qBlocks())
pm0.append(ConsolidateBlocks(force_consolidate=True))
qc0 = pm0.run(qc)
for gate in qc0:
if gate.operation.name not in ["barrier"]:
# print(gate.operation)\
corrd = c1c2c3(gate.operation.to_matrix())
list1.append(corrd)
# print(corrd)
print("\n")
list2 = []
pm1 = PassManager()
pm1.append(RemoveBarriers())
pm1.append(RemoveAllMeasurements())
pm1.append(FastConsolidateBlocks())
qc1 = pm1.run(qc)
for gate in qc1:
if gate.operation.name not in ["barrier"]:
# print(gate.operation)
corrd = c1c2c3(gate.operation.to_matrix())
list2.append(corrd)
# print(corrd)
# compare the two lists
print(circuit_name)
for x, y in zip(list1, list2):
print(x, y)
print("list1 == list2: ", list1 == list2)
|
https://github.com/SimoneGasperini/qiskit-symb
|
SimoneGasperini
|
# -*- 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.
"""Utils for using with Qiskit unit tests."""
import logging
import os
import unittest
from enum import Enum
from qiskit import __path__ as qiskit_path
class Path(Enum):
"""Helper with paths commonly used during the tests."""
# Main SDK path: qiskit/
SDK = qiskit_path[0]
# test.python path: qiskit/test/python/
TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python'))
# Examples path: examples/
EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples'))
# Schemas path: qiskit/schemas
SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas'))
# VCR cassettes path: qiskit/test/cassettes/
CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes'))
# Sample QASMs path: qiskit/test/python/qasm
QASMS = os.path.normpath(os.path.join(TEST, 'qasm'))
def setup_test_logging(logger, log_level, filename):
"""Set logging to file and stdout for a logger.
Args:
logger (Logger): logger object to be updated.
log_level (str): logging level.
filename (str): name of the output file.
"""
# Set up formatter.
log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
' %(message)s'.format(logger.name))
formatter = logging.Formatter(log_fmt)
# Set up the file handler.
file_handler = logging.FileHandler(filename)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Set the logging level from the environment variable, defaulting
# to INFO if it is not a valid level.
level = logging._nameToLevel.get(log_level, logging.INFO)
logger.setLevel(level)
class _AssertNoLogsContext(unittest.case._AssertLogsContext):
"""A context manager used to implement TestCase.assertNoLogs()."""
# pylint: disable=inconsistent-return-statements
def __exit__(self, exc_type, exc_value, tb):
"""
This is a modified version of TestCase._AssertLogsContext.__exit__(...)
"""
self.logger.handlers = self.old_handlers
self.logger.propagate = self.old_propagate
self.logger.setLevel(self.old_level)
if exc_type is not None:
# let unexpected exceptions pass through
return False
if self.watcher.records:
msg = 'logs of level {} or higher triggered on {}:\n'.format(
logging.getLevelName(self.level), self.logger.name)
for record in self.watcher.records:
msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname,
record.lineno,
record.getMessage())
self._raiseFailure(msg)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
import sympy
from sympy import *
import numpy as np
from numpy import random
import math
import scipy
init_printing(use_unicode=True)
from matplotlib import pyplot as plt
%matplotlib inline
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum import TensorProduct as tp
from mpmath import factorial as fact
import io
import base64
#from IPython.core.display import display, HTML, clear_output
from IPython import *
from ipywidgets import interactive, interact, fixed, interact_manual, widgets
import csv
import importlib
import scipy.interpolate
from mpl_toolkits.mplot3d import Axes3D, proj3d
from itertools import product, combinations
from matplotlib.patches import FancyArrowPatch
from matplotlib import cm, colors
from sympy.functions.special.tensor_functions import KroneckerDelta
from scipy.linalg import polar, lapack
import mpmath
# constantes físicas
e = 1.60217662*10**-19 # C (carga elementar)
k = 8.9875517923*10**9 # Nm^2/C^2 (constante de Coulomb)
eps0 = 8.8541878128*10**-12 #F/m (permissividade do vácuo)
mu0 = 1.25663706212*10**-6 # N/A^2 (permeabilidade do vácuo)
h = 6.626069*10**-34 # Js (constante de Planck)
heV = h/e # em eV
hb = h/(2*math.pi) # hbar
hbeV = hb/e # em eV
c = 2.99792458*10**8 # m/s (velocidade da luz no vácuo)
G = 6.6742*10**-11 # Nm^2/kg^2 (constante gravitacional)
kB = 1.38065*10**-23 # J/K (constante de Boltzmann)
me = 9.109382*10**-31 # kg (massa do elétron)
mp = 1.6726219*10**-27 # kg (massa do próton)
mn = 1.67492749804*10**-27 # kg (massa do nêutron)
mT = 5.9722*10**24 # kg (massa da Terra)
mS = 1.98847*10**30 # kg (massa do Sol)
u = 1.660538921*10**-27 # kg (unidade de massa atômica)
dTS = 1.496*10**11 # m (distância Terra-Sol)
rT = 6.3781*10**6 # m (raio da Terra)
sSB = 5.670374419*10**-8 # W⋅m−2⋅K−4 (constante de Stefan-Boltzmann)
Ri = 10973734.848575922 # m^-1 (constante de Rydberg)
al = (k*e**2)/(hb*c) # ~1/137.035999084 (constante de estrutura fina)
a0=(hb**2)/(me*k*e**2) # ~ 0.52917710^-10 m (raio de Bohr)
ge = 2 # (fator giromagnetico do eletron)
gp = 5.58 # (fator giromagnetico do proton)
def id(n):
'''retorna a matriz identidade nxn'''
id = zeros(n,n)
for j in range(0,n):
id[j,j] = 1
return id
#id(2)
def pauli(j):
'''retorna as matrizes de Pauli'''
if j == 1:
return Matrix([[0,1],[1,0]])
elif j == 2:
return Matrix([[0,-1j],[1j,0]])
elif j == 3:
return Matrix([[1,0],[0,-1]])
#pauli(1), pauli(2), pauli(3)
def tr(A):
'''retorna o traço de uma matriz'''
d = A.shape[0]
tr = 0
for j in range(0,d):
tr += A[j,j]
return tr
#tr(pauli(1))
def comm(A,B):
'''retorna a função comutador'''
return A*B-B*A
#comm(pauli(1),pauli(2))
def acomm(A,B):
'''retorna a função anti-comutador'''
return A*B+B*A
#acomm(pauli(1),pauli(2))
def cb(n,j):
'''retorna um vetor da base padrão de C^n'''
vec = zeros(n,1)
vec[j] = 1
return vec
#cb(2,0)
def proj(psi):
'''retorna o projeto no vetor psi'''
d = psi.shape[0]
P = zeros(d,d)
for j in range(0,d):
for k in range(0,d):
P[j,k] = psi[j]*conjugate(psi[k])
return P
#proj(cb(2,0))
def bell(j,k):
if j == 0 and k == 0:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))+tp(cb(2,1),cb(2,1)))
elif j == 0 and k == 1:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))+tp(cb(2,1),cb(2,0)))
elif j == 1 and k == 0:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))-tp(cb(2,1),cb(2,0)))
elif j == 1 and k == 1:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))-tp(cb(2,1),cb(2,1)))
#bell(0,0), bell(0,1), bell(1,0), bell(1,1)
def inner_product(v,w):
d = len(v); ip = 0
for j in range(0,d):
ip += conjugate(v[j])*w[j]
return ip
#a,b,c,d = symbols("a b c d"); v = [b,a]; w = [c,d]; inner_product(v,w)
def norm(v):
d = len(v)
return sqrt(inner_product(v,v))
#v = [2,2]; norm(v)
def tp(x,y):
return tensorproduct(x,y)
A = tp(pauli(3),pauli(1)); A
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
qc = QuantumCircuit(2, 2)
sv = Statevector.from_label("10")
qc.initialize(sv, range(2))
qc.h(0)
qc.cx(0, 1)
qc.measure(range(2), range(2))
qc.draw("mpl")
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Evolution problem class."""
from __future__ import annotations
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.opflow import OperatorBase, StateFn
from qiskit.utils.deprecation import deprecate_func
from ..list_or_dict import ListOrDict
class EvolutionProblem:
"""Deprecated: Evolution problem class.
The EvolutionProblem class has been superseded by the
:class:`qiskit_algorithms.time_evolvers.TimeEvolutionProblem` class.
This class will be deprecated in a future release and subsequently
removed after that.
This class is the input to time evolution algorithms and must contain information on the total
evolution time, a quantum state to be evolved and under which Hamiltonian the state is evolved.
"""
@deprecate_func(
additional_msg=(
"Instead, use the class ``qiskit_algorithms.time_evolvers.TimeEvolutionProblem``. "
"See https://qisk.it/algo_migration for a migration guide."
),
since="0.24.0",
)
def __init__(
self,
hamiltonian: OperatorBase,
time: float,
initial_state: StateFn | QuantumCircuit | None = None,
aux_operators: ListOrDict[OperatorBase] | None = None,
truncation_threshold: float = 1e-12,
t_param: Parameter | None = None,
param_value_dict: dict[Parameter, complex] | None = None,
):
"""
Args:
hamiltonian: The Hamiltonian under which to evolve the system.
time: Total time of evolution.
initial_state: The quantum state to be evolved for methods like Trotterization.
For variational time evolutions, where the evolution happens in an ansatz,
this argument is not required.
aux_operators: Optional list of auxiliary operators to be evaluated with the
evolved ``initial_state`` and their expectation values returned.
truncation_threshold: Defines a threshold under which values can be assumed to be 0.
Used when ``aux_operators`` is provided.
t_param: Time parameter in case of a time-dependent Hamiltonian. This
free parameter must be within the ``hamiltonian``.
param_value_dict: Maps free parameters in the problem to values. Depending on the
algorithm, it might refer to e.g. a Hamiltonian or an initial state.
Raises:
ValueError: If non-positive time of evolution is provided.
"""
self.t_param = t_param
self.param_value_dict = param_value_dict
self.hamiltonian = hamiltonian
self.time = time
self.initial_state = initial_state
self.aux_operators = aux_operators
self.truncation_threshold = truncation_threshold
@property
def time(self) -> float:
"""Returns time."""
return self._time
@time.setter
def time(self, time: float) -> None:
"""
Sets time and validates it.
Raises:
ValueError: If time is not positive.
"""
if time <= 0:
raise ValueError(f"Evolution time must be > 0 but was {time}.")
self._time = time
def validate_params(self) -> None:
"""
Checks if all parameters present in the Hamiltonian are also present in the dictionary
that maps them to values.
Raises:
ValueError: If Hamiltonian parameters cannot be bound with data provided.
"""
if isinstance(self.hamiltonian, OperatorBase):
t_param_set = set()
if self.t_param is not None:
t_param_set.add(self.t_param)
hamiltonian_dict_param_set: set[Parameter] = set()
if self.param_value_dict is not None:
hamiltonian_dict_param_set = hamiltonian_dict_param_set.union(
set(self.param_value_dict.keys())
)
params_set = t_param_set.union(hamiltonian_dict_param_set)
hamiltonian_param_set = set(self.hamiltonian.parameters)
if hamiltonian_param_set != params_set:
raise ValueError(
f"Provided parameters {params_set} do not match Hamiltonian parameters "
f"{hamiltonian_param_set}."
)
|
https://github.com/VoicuTomut/Qsiris-Quantum-Odyssey-and-Qiskit
|
VoicuTomut
|
import numpy as np
import cmath
from qiskit import QuantumCircuit, transpile
from qiskit import Aer, execute
from qiskit import IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram
from project_qsiris.conversion_qo_qiskit import odyssey_to_qiskit,load_oddysey_puzzle
#Enable this line if you plan to use IBM Q Experience and run these circuit on real IBM hw (and see results in IBMQ)
#IBMQ.load_account()
#Step 1: Read the QO puzzle file (has extension .qpf).
#If you want to change the puzzle file, simply add the new path or puzzle in path= folder
path = "circuits/qiskit_to_odyssey/example_002.qpf"
puzzle = load_oddysey_puzzle(path)
#Step 2: convert your QO puzzle to a Qiskit circuit and draw the mpl
qc = odyssey_to_qiskit(puzzle, incl_initial_state = False,
use_barrier = False,
incl_all_measurements = True)
qc.draw('mpl')
#Step 3: Run your puzzle on a qiskit simulator and plot counts
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend,shots=1000)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
#Step 4: Run your puzzle on a real QPU from IBM. You can customize the execution here.
# It will take some time for the job to be executed
provider = IBMQ.get_provider('ibm-q')
ibm_QPU=provider.get_backend('ibmq_santiago')
job=execute(qc, backend=ibm_QPU, shots=100)
job_monitor(job,interval=10)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
path = "circuits/odyssey_circuits/asdasd.qpf"
res = load_oddysey_puzzle(path)
res.keys()
qc = odyssey_to_qiskit(res, incl_initial_state = False,
use_barrier = False,
incl_all_measurements = True)
qc.draw('mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend,shots=1000)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
backend = Aer.get_backend('qasm_simulator')
result = transpile(qc, backend=backend, optimization_level=3)
result.draw(output='mpl')
# This runbook is for testing how much you can approximate decimals if Qiskit is still able to rec as unitary
# It is important to have as many decimals as possible
# Otherwise we can get unitary errors (even if we can introduce the gate in the circuit) .
unit=[[ 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
[ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j],
[ 0.+0.j, 0.+0.j, 0.70710679+0.j, 0.70710679+0.j],#np.sqrt(1/2)+0.j, np.sqrt(1/2)+0.j],
[ 0.+0.j, 0.+0.j, 0.70710679+0.j, -0.70710679+0.j],]#np.sqrt(1/2)+0.j, -np.sqrt(1/2)+0.j],]#0.70710679+0.j, -0.70710679+0.j],]
qc=QuantumCircuit(2)
qc.unitary(unit,[0,1])
qc.draw()
print(qc.qasm())
|
https://github.com/Qottmann/Quantum-anomaly-detection
|
Qottmann
|
import time
import numpy as np
import qiskit
from qiskit.opflow import X,Z,I
from qiskit.opflow.state_fns import StateFn, CircuitStateFn
import matplotlib.pyplot as plt
from scipy import sparse
import scipy.sparse.linalg.eigen.arpack as arp
%matplotlib inline
# copypaste niccolo's code
def QNKron(N,op1,op2,pos):
'''
Tensor product operator (Qiskit Pauli operators)
returns tensor product of op1,op2 on sites pos,pos+1 and identity on remaining sites
N:number of sites
op1,op2: Pauli operators on neighboring sites
pos: site to insert op1
'''
temp=np.array([I]*(N))
temp[pos]=op1
if pos!=(N-1):
temp[pos+1]=op2
mat=1
for j in range(N):
mat=mat^temp[j]
return mat
def QHIsing(N,lam,p):
'''
Quantum Ising Hamiltonian (1D) with transverse field (Qiskit Pauli operators)
N:number of sites
lam: transverse field)
'''
H=-QNKron(N,Z,Z,0)-lam*QNKron(N,X,I,0)-p*QNKron(N,Z,I,0)
for i in range(1,N-1):
H=H-QNKron(N,Z,Z,i)-lam*QNKron(N,X,I,i)-p*QNKron(N,Z,I,i)
H=H-lam*QNKron(N,X,I,N-1)-p*QNKron(N,Z,I,N-1)
return H
def NKron(N,op1,op2,pos):
'''
Tensor product operator
returns tensor product of op1,op2 on sites pos,pos+1 and identity on remaining sites
N:number of sites
op1,op2: Pauli operators on neighboring sites
pos: site to insert op1
'''
ide=np.eye(2)
temp=np.array([ide]*(N),dtype=np.complex128)
temp[pos,:,:]=op1
# if pos!=(N-1):
temp[(pos+1)%N,:,:]=op2
mat=1
for j in range(N):
mat=np.kron(mat,temp[j])
return mat
def Mag(N): #magnetization operator (numpy array)
sz=np.array([[1,0],[0,-1]])
M=np.zeros((2**N,2**N))
for i in range(N):
M=M+NKron(N,sz,np.eye(2),i)
return M/N
def QMag(N): #magnetization operator (Qiskit operator)
M=QNKron(N,Z,I,0)
for i in range(1,N):
M=M+QNKron(N,Z,I,i)
return M/N
def ising_groundstate(L, J, g, p):
"""For comparison: obtain ground state energy from exact diagonalization.
Exponentially expensive in L, only works for small enough `L` <~ 20.
"""
if L >= 20:
warnings.warn("Large L: Exact diagonalization might take a long time!")
# get single site operaors
sx = sparse.csr_matrix(np.array([[0., 1.], [1., 0.]]))
sz = sparse.csr_matrix(np.array([[1., 0.], [0., -1.]]))
id = sparse.csr_matrix(np.eye(2))
sx_list = [] # sx_list[i] = kron([id, id, ..., id, sx, id, .... id])
sz_list = []
for i_site in range(L):
x_ops = [id] * L
z_ops = [id] * L
x_ops[i_site] = sx
z_ops[i_site] = sz
X = x_ops[0]
Z = z_ops[0]
for j in range(1, L):
X = sparse.kron(X, x_ops[j], 'csr')
Z = sparse.kron(Z, z_ops[j], 'csr')
sx_list.append(X)
sz_list.append(Z)
H_zz = sparse.csr_matrix((2**L, 2**L))
H_x = sparse.csr_matrix((2**L, 2**L))
for i in range(L - 1):
H_zz = H_zz + J*sz_list[i] * sz_list[(i + 1) % L]
for i in range(L):
H_x = H_x + g*sx_list[i] +p*sz_list[i]
H = - H_zz - H_x
E, V = arp.eigsh(H, k=1, which='SA', return_eigenvectors=True, ncv=20)
return V[:,0], E[0], H
def sort_vals(vals):
""" vals is (unsorted) dictionary of parameters from VQE ansatz circuit, this returns sorted values as list """
indices = np.array([_.index for _ in vals]) # unordered list of indices from the ParameterVectorElement(Theta(INDEX))
vals_sorted = np.array([vals[_] for _ in vals]) # unordered list of values (but same ordering as indices)
return vals_sorted[np.argsort(indices)]
def init_vqe(vals):
return qiskit.circuit.library.EfficientSU2(L, reps=3).assign_parameters(sort_vals(vals))
L = 6
VQE_vals = np.load(f'params_VQE_ising_N{L}.npy', allow_pickle=True).item()
lambdas = np.array([_ for _ in VQE_vals]) # list of lambda values (the items in the dictionary)
# note that Rike calls them gs
mag = QMag(L) #magnetization operator (Qiskit)
Smag=Mag(L) #magnetization operator (numpy)
# the ~ is the adjoint, but also it turns the is_measurement attribute to True
~StateFn(mag)
# state is technically a circuit, that prepares the ground state via VQE circuit
#state.draw() # uncomment to see, but is very long
Qen=np.zeros(len(lambdas)); Sen=np.zeros(len(lambdas)) #energies
Qmags=np.zeros(len(lambdas)); Smags=np.zeros(len(lambdas)) #magnetizations
for j,lambda0 in enumerate(lambdas):
print(lambda0)
H = QHIsing(L,np.float32(lambda0),1e-4) # build Hamiltonian Op
state = init_vqe(VQE_vals[lambda0])
StateFn(state)
meas_outcome = ~StateFn(mag) @ StateFn(state)
Qmags[j]=meas_outcome.eval()
e_outcome = ~StateFn(H) @ StateFn(state)
Qen[j]=e_outcome.eval()
init_state, E, ham = ising_groundstate(L, 1., np.float(lambda0),1e-4)
Sen[j]=E
Smags[j]=init_state.T.conj()@Smag@init_state #Magnetization with Numpy results
lambdas = np.array([_ for _ in VQE_vals],dtype=np.float) # list of lambda values (the items in the dictionary)
plt.figure(1,dpi=220)
plt.plot(lambdas,Sen,".--")
plt.plot(lambdas,Qen)
plt.xscale("log")
plt.ylabel("GS energy")
plt.xlabel("Mag. field")
plt.legend(["Sparse","Qiskit"])
plt.grid()
print(Sen,Qen)
plt.figure(2,dpi=220)
plt.scatter(lambdas,Smags)
plt.scatter(lambdas,Qmags)
plt.xscale('log')
plt.ylabel("Magnetization")
plt.xlabel("Mag. field")
plt.legend(["Sparse","Qiskit"])
plt.grid()
print(Smags,Qmags)
|
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
|
alejomonbar
|
%load_ext autoreload
%autoreload 2
#pip install pennyane
#improt pennylane dependnecies
import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import NesterovMomentumOptimizer
# load the csv files
import pandas as pd
# plot the historical acc and cost
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.display import clear_output
clear_output(wait=False)
import os
data_train = pd.read_csv("dataset/fair_train.csv")
X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values
data_test = pd.read_csv("dataset/classic_test.csv")
X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values
(X_train.shape, y_train.shape),(X_test.shape, y_test.shape)
n_wires = 4
dev = qml.device("default.mixed", wires=n_wires)
def block(weights, wires):
qml.CNOT(wires=[wires[0],wires[1]])
qml.RY(weights[0], wires=wires[0])
qml.RY(weights[1], wires=wires[1])
n_block_wires = 2
n_params_block = 2
n_blocks = qml.MERA.get_n_blocks(range(n_wires),n_block_wires)
n_blocks
@qml.qnode(dev)
@qml.transforms.insert(qml.AmplitudeDamping, 0.2, position="end")
def circuit(weights, x):
qml.AmplitudeEmbedding(x, wires=[0,1,2,3],normalize=True,pad_with=True)
for w in weights:
qml.MERA(range(n_wires),n_block_wires,block, n_params_block, w)
#print(w)
#print(x)
return qml.expval(qml.PauliZ(1))
def variational_classifier(weights, bias, x):
return circuit(weights, x) + bias
def square_loss(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
loss = loss + (l - p) ** 2
loss = loss / len(labels)
return loss
def accuracy(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
if abs(l - p) < 1e-5:
loss = loss + 1
loss = loss / len(labels)
return loss
def cost(weights, bias, X, Y):
#print(1)
predictions = [variational_classifier(weights, bias, x) for x in X]
return square_loss(Y, predictions)
np.random.seed(0)
num_layers = 1
weights_init = 2*np.pi * np.random.randn(num_layers,n_blocks, n_params_block, requires_grad=True)
bias_init = np.array(0.0, requires_grad=True)
print(weights_init, bias_init)
print(qml.draw(circuit,expansion_strategy='device',wire_order=[0,1,2,3])(weights_init,np.asarray(X_train[0])))
for i in weights_init:
print(i[0])
y_train = np.where(y_train < 1, -1, y_train)
y_test = np.where(y_test < 1, -1, y_test)
from sklearn.utils import shuffle
X,y = shuffle(X_train, y_train, random_state=0)
from sklearn.model_selection import train_test_split
opt = NesterovMomentumOptimizer(0.4)
batch_size = 32
num_data = len(y_train)
num_train = 0.9
# train the variational classifier
weights = weights_init
bias = bias_init
print()
cost_g = []
acc_train = []
acc_test = []
plt.show()
for it in range(50):
X_train_70, X_test_30, y_train_70, y_test_30 =train_test_split(np.asarray(X), np.asarray(y), train_size=num_train, test_size=1.0-num_train, shuffle=True)
# Update the weights by one optimizer step
batch_index = np.random.randint(0, len(X_train_70), (batch_size,))
feats_train_batch = X_train_70[batch_index]
Y_train_batch = y_train_70[batch_index]
weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch)
# Compute predictions on train and validation set
predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in X_train_70]
predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in X_test_30]
# Compute accuracy on train and validation set
acc_tra = accuracy(y_train_70, predictions_train)
acc_val = accuracy(y_test_30, predictions_val)
cost_train = cost(weights, bias,X_train, y_train)
cost_g.append(cost_train)
acc_train.append(acc_tra)
acc_test.append(acc_val)
clear_output(wait=True)
plt.plot(cost_g,label='cost')
plt.plot(acc_train,label='acc_train')
plt.plot(acc_test,label='acc_test')
plt.legend(['cost','acc_train','acc_test'])
plt.show()
print(
"Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} "
"".format(it + 1, cost_train, acc_tra, acc_val)
)
print(weights)
x_test = []
for x in X_test.tolist():
if sum(x) == 0:
x[0]=1
x_test.append( x/ np.linalg.norm(x))
x_test[0]
y_test
y_pred = [np.sign(variational_classifier(weights, bias, f)) for f in x_test]
y_test_pred = []
for i in y_pred:
if i < 0:
y_test_pred.append(-1)
else:
y_test_pred.append(1)
from sklearn.metrics import confusion_matrix, roc_curve, auc
from sklearn.preprocessing import StandardScaler
# demonstration of calculating metrics for a neural network model using sklearn
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import roc_auc_score
accuracy = accuracy_score(y_test, y_test_pred)
print('Accuracy: %f' % accuracy)
# precision tp / (tp + fp)
precision = precision_score(y_test, y_test_pred)
print('Precision: %f' % precision)
# recall: tp / (tp + fn)
recall = recall_score(y_test, y_test_pred)
print('Recall: %f' % recall)
# f1: 2 tp / (2 tp + fp + fn)
f1 = f1_score(y_test, y_test_pred)
print('F1 score: %f' % f1)
# kappa
kappa = cohen_kappa_score(y_test, y_test_pred)
print('Cohens kappa: %f' % kappa)
# ROC AUC
auc = roc_auc_score(y_test, y_test_pred)
print('ROC AUC: %f' % auc)
# confusion matrix
test_matrix = confusion_matrix(y_test, y_test_pred)
print(test_matrix)
ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g')
ax.set_title('Seaborn Confusion Matrix with labels\n\n');
ax.set_xlabel('\nPredicted Values')
ax.set_ylabel('Actual Values ');
ax.xaxis.set_ticklabels(['0','1'])
ax.yaxis.set_ticklabels(['0','1'])
## Display the visualization of the Confusion Matrix.
plt.show()
y_pred_1 = [int(i) for i in y_test_pred ]
y_pred_1 = ["{}\n".format(i) for i in y_pred_1]
with open(r'mera_1_layers_noise.csv', 'w') as fp:
fp.writelines(y_pred_1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms.optimizers import SLSQP
ansatz = TwoLocal(3, rotation_blocks=["ry", "rz"], entanglement_blocks="cz", reps=1)
optimizer = SLSQP()
ansatz.decompose().draw('mpl')
from qiskit.primitives import Sampler, Estimator
from qiskit.algorithms.state_fidelities import ComputeUncompute
estimator = Estimator()
sampler = Sampler()
fidelity = ComputeUncompute(sampler)
k = 3
betas = [33, 33, 33]
counts = []
values = []
steps = []
def callback(eval_count, params, value, meta, step):
counts.append(eval_count)
values.append(value)
steps.append(step)
from qiskit.algorithms.eigensolvers import VQD
vqd = VQD(estimator, fidelity, ansatz, optimizer, k=k, betas=betas, callback=callback)
result = vqd.compute_eigenvalues(operator = H2_op)
vqd_values = result.optimal_values
print(vqd_values)
import numpy as np
import pylab
pylab.rcParams["figure.figsize"] = (12, 8)
steps = np.asarray(steps)
counts = np.asarray(counts)
values = np.asarray(values)
for i in range(1,4):
_counts = counts[np.where(steps == i)]
_values = values[np.where(steps == i)]
pylab.plot(_counts, _values, label=f"State {i-1}")
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Energy convergence for each computed state")
pylab.legend(loc="upper right");
from qiskit.algorithms.eigensolvers import NumPyEigensolver
from qiskit.opflow import PauliSumOp
exact_solver = NumPyEigensolver(k=3)
exact_result = exact_solver.compute_eigenvalues(PauliSumOp(H2_op))
ref_values = exact_result.eigenvalues
print(f"Reference values: {ref_values}")
print(f"VQD values: {vqd_values}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/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/liyaochong/quantum-algorithm-learning-and-implementation
|
liyaochong
|
# 导入相应的运算库
import numpy as np
from qiskit import BasicAer, execute
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
desired_vector1 = [6/np.sqrt(200), 8/np.sqrt(200), 1/np.sqrt(2), 0]
desired_vector2 = [10/np.sqrt(101), -1/np.sqrt(101)]
q0 = QuantumRegister(1,'q0')
c0 = ClassicalRegister(1,'c0')
q1 = QuantumRegister(2,'q1')
c1 = ClassicalRegister(2,'c1')
q2 = QuantumRegister(1,'q2')
c2 = ClassicalRegister(1,'c2')
Circuit = QuantumCircuit()
Circuit.add_register(q0,c0)
Circuit.add_register(q1,c1)
Circuit.add_register(q2,c2)
Circuit.initialize(desired_vector1, [q1[0],q1[1]])
Circuit.initialize(desired_vector2, [q2[0]])
Circuit.h(q0[0])
Circuit.ccx(q0[0],q1[1],q2[0])
Circuit.ccx(q0[0],q2[0],q1[1])
Circuit.ccx(q0[0],q1[1],q2[0])
Circuit.h(q0[0])
Circuit.draw(output='mpl')
# 对寄存器q0进行测量
Circuit.measure(q0,c0)
# 测量次数设置为1024次
backend = BasicAer.get_backend('qasm_simulator')
job = execute(Circuit, backend,shots=1024)
job.result().get_counts(Circuit)
P_0 = 0.5-89/202*0.5
P_1 = 0.5+89/202*0.5
Times_0 = P_0*1024
Times_1 = P_1*1024
print('进行测量之后,辅助量子比特为0态的次数是',Times_0)
print('进行测量之后,辅助量子比特为1态的次数是',Times_1)
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# 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.
"""Test of NFT optimizer"""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from qiskit import BasicAer
from qiskit.circuit.library import RealAmplitudes
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.opflow import PauliSumOp
from qiskit_algorithms.optimizers import NFT
from qiskit_algorithms import VQE
class TestOptimizerNFT(QiskitAlgorithmsTestCase):
"""Test NFT optimizer using RY with VQE"""
def setUp(self):
super().setUp()
algorithm_globals.random_seed = 50
with self.assertWarns(DeprecationWarning):
self.qubit_op = PauliSumOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
def test_nft(self):
"""Test NFT optimizer by using it"""
with self.assertWarns(DeprecationWarning):
vqe = VQE(
ansatz=RealAmplitudes(),
optimizer=NFT(),
quantum_instance=QuantumInstance(
BasicAer.get_backend("statevector_simulator"),
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed,
),
)
result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op)
self.assertAlmostEqual(result.eigenvalue.real, -1.857275, places=6)
if __name__ == "__main__":
unittest.main()
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import Aer, QuantumCircuit
from qiskit.circuit.library import PhaseEstimation
qc= QuantumCircuit(3,3)
# dummy unitary circuit
unitary_circuit = QuantumCircuit(1)
unitary_circuit.h(0)
# QPE
qc.append(PhaseEstimation(2, unitary_circuit), list(range(3)))
qc.measure(list(range(3)), list(range(3)))
backend = Aer.get_backend('qasm_simulator')
result = backend.run(qc, shots = 8192).result()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
gate_counts = []
non_local_gate_counts = []
levels = [str(x) for x in range(4)]
for level in range(4):
circ = transpile(ghz, backend, optimization_level=level)
depths.append(circ.depth())
gate_counts.append(sum(circ.count_ops().values()))
non_local_gate_counts.append(circ.num_nonlocal_gates())
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.bar(levels, depths, label='Depth')
ax1.set_xlabel("Optimization Level")
ax1.set_ylabel("Depth")
ax1.set_title("Output Circuit Depth")
ax2.bar(levels, gate_counts, label='Number of Circuit Operations')
ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates')
ax2.set_xlabel("Optimization Level")
ax2.set_ylabel("Number of gates")
ax2.legend()
ax2.set_title("Number of output circuit gates")
fig.tight_layout()
plt.show()
|
https://github.com/SimoneGasperini/qiskit-symb
|
SimoneGasperini
|
"""Test controlled standard gates module"""
import numpy
from hypothesis import given, strategies, settings
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator
from qiskit.circuit.library import (
XGate, CXGate,
YGate, CYGate,
ZGate, CZGate,
HGate, CHGate,
SXGate, CSXGate,
SXdgGate,
SGate, CSGate,
SdgGate, CSdgGate,
TGate,
TdgGate,
SwapGate, CSwapGate,
iSwapGate
)
from qiskit_symb.utils import get_random_controlled
from qiskit_symb import Operator as symb_Operator
from qiskit_symb.circuit.library import (
CXGate as symb_CXGate,
CYGate as symb_CYGate,
CZGate as symb_CZGate,
CHGate as symb_CHGate,
CSXGate as symb_CSXGate,
CSXdgGate as symb_CSXdgGate,
CSGate as symb_CSGate,
CSdgGate as symb_CSdgGate,
CTGate as symb_CTGate,
CTdgGate as symb_CTdgGate,
CSwapGate as symb_CSwapGate,
CiSwapGate as symb_CiSwapGate
)
def test_cx():
"""todo"""
arr1 = CXGate().to_matrix()
arr2 = symb_CXGate().to_numpy()
assert numpy.allclose(arr1, arr2)
@settings(deadline=None, max_examples=10)
@given(seed=strategies.integers(min_value=0))
def test_mcx(seed):
"""todo"""
circuit = get_random_controlled(base_gate=XGate(), seed=seed)
arr1 = Operator(circuit).data
arr2 = symb_Operator(circuit).to_numpy()
assert numpy.allclose(arr1, arr2)
def test_cy():
"""todo"""
arr1 = CYGate().to_matrix()
arr2 = symb_CYGate().to_numpy()
assert numpy.allclose(arr1, arr2)
@settings(deadline=None, max_examples=10)
@given(seed=strategies.integers(min_value=0))
def test_mcy(seed):
"""todo"""
circuit = get_random_controlled(base_gate=YGate(), seed=seed)
arr1 = Operator(circuit).data
arr2 = symb_Operator(circuit).to_numpy()
assert numpy.allclose(arr1, arr2)
def test_cz():
"""todo"""
arr1 = CZGate().to_matrix()
arr2 = symb_CZGate().to_numpy()
assert numpy.allclose(arr1, arr2)
@settings(deadline=None, max_examples=10)
@given(seed=strategies.integers(min_value=0))
def test_mcz(seed):
"""todo"""
circuit = get_random_controlled(base_gate=ZGate(), seed=seed)
arr1 = Operator(circuit).data
arr2 = symb_Operator(circuit).to_numpy()
assert numpy.allclose(arr1, arr2)
def test_ch():
"""todo"""
arr1 = CHGate().to_matrix()
arr2 = symb_CHGate().to_numpy()
assert numpy.allclose(arr1, arr2)
@settings(deadline=None, max_examples=10)
@given(seed=strategies.integers(min_value=0))
def test_mch(seed):
"""todo"""
circuit = get_random_controlled(base_gate=HGate(), seed=seed)
arr1 = Operator(circuit).data
arr2 = symb_Operator(circuit).to_numpy()
assert numpy.allclose(arr1, arr2)
def test_csx():
"""todo"""
arr1 = CSXGate().to_matrix()
arr2 = symb_CSXGate().to_numpy()
assert numpy.allclose(arr1, arr2)
@settings(deadline=None, max_examples=10)
@given(seed=strategies.integers(min_value=0))
def test_mcsx(seed):
"""todo"""
circuit = get_random_controlled(base_gate=SXGate(), seed=seed)
arr1 = Operator(circuit).data
arr2 = symb_Operator(circuit).to_numpy()
assert numpy.allclose(arr1, arr2)
def test_csxdg():
"""todo"""
circuit = QuantumCircuit(2)
circuit.append(SXdgGate().control(), qargs=[0, 1])
arr1 = Operator(circuit).data
arr2 = symb_CSXdgGate().to_numpy()
assert numpy.allclose(arr1, arr2)
@settings(deadline=None, max_examples=10)
@given(seed=strategies.integers(min_value=0))
def test_mcsxdg(seed):
"""todo"""
circuit = get_random_controlled(base_gate=SXdgGate(), seed=seed)
arr1 = Operator(circuit).data
arr2 = symb_Operator(circuit).to_numpy()
assert numpy.allclose(arr1, arr2)
def test_cs():
"""todo"""
arr1 = CSGate().to_matrix()
arr2 = symb_CSGate().to_numpy()
assert numpy.allclose(arr1, arr2)
@settings(deadline=None, max_examples=10)
@given(seed=strategies.integers(min_value=0))
def test_mcs(seed):
"""todo"""
circuit = get_random_controlled(base_gate=SGate(), seed=seed)
arr1 = Operator(circuit).data
arr2 = symb_Operator(circuit).to_numpy()
assert numpy.allclose(arr1, arr2)
def test_csdg():
"""todo"""
arr1 = CSdgGate().to_matrix()
arr2 = symb_CSdgGate().to_numpy()
assert numpy.allclose(arr1, arr2)
@settings(deadline=None, max_examples=10)
@given(seed=strategies.integers(min_value=0))
def test_mcsdg(seed):
"""todo"""
circuit = get_random_controlled(base_gate=SdgGate(), seed=seed)
arr1 = Operator(circuit).data
arr2 = symb_Operator(circuit).to_numpy()
assert numpy.allclose(arr1, arr2)
def test_ct():
"""todo"""
circuit = QuantumCircuit(2)
circuit.append(TGate().control(), qargs=[0, 1])
arr1 = Operator(circuit).data
arr2 = symb_CTGate().to_numpy()
assert numpy.allclose(arr1, arr2)
@settings(deadline=None, max_examples=10)
@given(seed=strategies.integers(min_value=0))
def test_mct(seed):
"""todo"""
circuit = get_random_controlled(base_gate=TGate(), seed=seed)
arr1 = Operator(circuit).data
arr2 = symb_Operator(circuit).to_numpy()
assert numpy.allclose(arr1, arr2)
def test_ctdg():
"""todo"""
circuit = QuantumCircuit(2)
circuit.append(TdgGate().control(), qargs=[0, 1])
arr1 = Operator(circuit).data
arr2 = symb_CTdgGate().to_numpy()
assert numpy.allclose(arr1, arr2)
@settings(deadline=None, max_examples=10)
@given(seed=strategies.integers(min_value=0))
def test_mctdg(seed):
"""todo"""
circuit = get_random_controlled(base_gate=TdgGate(), seed=seed)
arr1 = Operator(circuit).data
arr2 = symb_Operator(circuit).to_numpy()
assert numpy.allclose(arr1, arr2)
def test_cswap():
"""todo"""
arr1 = CSwapGate().to_matrix()
arr2 = symb_CSwapGate().to_numpy()
assert numpy.allclose(arr1, arr2)
@settings(deadline=None, max_examples=10)
@given(seed=strategies.integers(min_value=0))
def test_mcswap(seed):
"""todo"""
circuit = get_random_controlled(base_gate=SwapGate(), seed=seed)
arr1 = Operator(circuit).data
arr2 = symb_Operator(circuit).to_numpy()
assert numpy.allclose(arr1, arr2)
def test_ciswap():
"""todo"""
circuit = QuantumCircuit(3)
circuit.append(iSwapGate().control(), qargs=[0, 1, 2])
arr1 = Operator(circuit).data
arr2 = symb_CiSwapGate().to_numpy()
assert numpy.allclose(arr1, arr2)
@settings(deadline=None, max_examples=10)
@given(seed=strategies.integers(min_value=0))
def test_mciswap(seed):
"""todo"""
circuit = get_random_controlled(base_gate=iSwapGate(), seed=seed)
arr1 = Operator(circuit).data
arr2 = symb_Operator(circuit).to_numpy()
assert numpy.allclose(arr1, arr2)
|
https://github.com/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/quantumofme/pavia-qiskit-tutorials
|
quantumofme
|
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
import qiskit as qk
qr0 = qk.QuantumRegister(1,name='qb') # qb for "qubit", but the name is optional
cr0 = qk.ClassicalRegister(1,name='b') # b for "bit", but the name is optional
qc0 = qk.QuantumCircuit(qr0,cr0)
qc0.draw(output='mpl') # this is to visualize the circuit. Remove the output option for a different style.
from qiskit.tools.visualization import plot_bloch_vector
import math
theta = math.pi/2 # You can try to change the parameters theta and phi
phi = math.pi/4 # to see how the vector moves on the sphere
plot_bloch_vector([math.cos(phi)*math.sin(theta),math.sin(phi)*math.sin(theta),math.cos(theta)]) # Entries of the
# input vector are
# coordinates [x,y,z]
qc0.measure(qr0[0],cr0[0])
qc0.draw(output='mpl')
backend = qk.Aer.get_backend('qasm_simulator')
job = qk.execute(qc0, backend, shots=1024)
result = job.result()
counts = result.get_counts()
print(counts)
qc1 = qk.QuantumCircuit(qr0,cr0)
qc1.x(qr0[0]) # A X gate targeting the first (and only) qubit in register qr0
qc1.measure(qr0[0],cr0[0])
qc1.draw(output='mpl')
backend = qk.Aer.get_backend('qasm_simulator')
job1 = qk.execute(qc1, backend, shots=1024)
result1 = job1.result()
counts1 = result1.get_counts()
print(counts1)
from qiskit.tools.visualization import plot_bloch_multivector
vec_backend = qk.Aer.get_backend('statevector_simulator')
result_vec0 = qk.execute(qc0, vec_backend).result()
result_vec1 = qk.execute(qc1, vec_backend).result()
psi0 = result_vec0.get_statevector()
psi1 = result_vec1.get_statevector()
plot_bloch_multivector(psi0)
plot_bloch_multivector(psi1)
qc2 = qk.QuantumCircuit(qr0,cr0)
qc2.h(qr0[0])
qc2.measure(qr0[0],cr0[0])
qc2.draw(output='mpl')
job2 = qk.execute(qc2, backend, shots=1024)
result2 = job2.result()
counts2 = result2.get_counts()
print(counts2)
qc2_bis = qk.QuantumCircuit(qr0,cr0)
qc2_bis.h(qr0[0])
result_vec2 = qk.execute(qc2_bis, vec_backend).result()
psi2 = result_vec2.get_statevector()
plot_bloch_multivector(psi2)
qc3 = qk.QuantumCircuit(qr0,cr0)
qc3.h(qr0[0])
qc3.s(qr0[0]) # Use sdg instead of s for the adjoint
qc3.measure(qr0[0],cr0[0])
qc3.draw(output='mpl')
job3 = qk.execute(qc3, backend, shots=1024)
result3 = job3.result()
counts3 = result3.get_counts()
print(counts3)
qc3_bis = qk.QuantumCircuit(qr0,cr0)
qc3_bis.h(qr0[0])
qc3_bis.s(qr0[0])
result_vec3 = qk.execute(qc3_bis, vec_backend).result()
psi3 = result_vec3.get_statevector()
plot_bloch_multivector(psi3)
qc4 = qk.QuantumCircuit(qr0,cr0)
qc4.h(qr0[0])
qc4.t(qr0[0]) # Use tdg instead of t for the adjoint
qc4.measure(qr0[0],cr0[0])
qc4.draw(output='mpl')
job4 = qk.execute(qc4, backend, shots=1024)
result4 = job4.result()
counts4 = result4.get_counts()
print(counts4)
qc4_bis = qk.QuantumCircuit(qr0,cr0)
qc4_bis.h(qr0[0])
qc4_bis.t(qr0[0])
result_vec4 = qk.execute(qc4_bis, vec_backend).result()
psi4 = result_vec4.get_statevector()
plot_bloch_multivector(psi4)
lmbd = 1.2 # Change this value to rotate the output vector on the equator of the Bloch sphere
qc5 = qk.QuantumCircuit(qr0,cr0)
qc5.h(qr0[0])
qc5.u1(lmbd, qr0[0])
qc5.draw(output='mpl')
result_vec5 = qk.execute(qc5, vec_backend).result()
psi5 = result_vec5.get_statevector()
plot_bloch_multivector(psi5)
qc6 = qk.QuantumCircuit(qr0,cr0)
qc6.u2(0,math.pi, qr0[0])
result_vec6 = qk.execute(qc6, vec_backend).result()
psi6 = result_vec6.get_statevector()
plot_bloch_multivector(psi6)
theta = 0.5
phi = math.pi/4
lmb = math.pi/8
qc7 = qk.QuantumCircuit(qr0,cr0)
qc7.u3(theta,phi, lmb, qr0[0])
result_vec7 = qk.execute(qc7, vec_backend).result()
psi7 = result_vec7.get_statevector()
plot_bloch_multivector(psi7)
qr = qk.QuantumRegister(2,name='qr') # we need a 2-qubit register now
cr = qk.ClassicalRegister(2,name='cr')
cnot_example = qk.QuantumCircuit(qr,cr)
cnot_example.x(qr[0])
cnot_example.cx(qr[0],qr[1]) # First entry is control, the second is the target
cnot_example.measure(qr[0],cr[0])
cnot_example.measure(qr[1],cr[1])
cnot_example.draw(output='mpl')
job_cnot = qk.execute(cnot_example, backend, shots=1024)
result_cnot = job_cnot.result()
counts_cnot = result_cnot.get_counts()
print(counts_cnot)
cnot_reversed = qk.QuantumCircuit(qr,cr)
cnot_reversed.x(qr[0])
# This part uses cx(qr[1],qr[0]) but is equivalent to cx(qr[0],qr[1])
cnot_reversed.h(qr[0])
cnot_reversed.h(qr[1])
cnot_reversed.cx(qr[1],qr[0])
cnot_reversed.h(qr[0])
cnot_reversed.h(qr[1])
#
cnot_reversed.measure(qr[0],cr[0])
cnot_reversed.measure(qr[1],cr[1])
cnot_reversed.draw(output='mpl')
job_cnot_rev = qk.execute(cnot_reversed, backend, shots=1024)
result_cnot_rev = job_cnot_rev.result()
counts_cnot_rev = result_cnot_rev.get_counts()
print(counts_cnot_rev)
bell_phi_p = qk.QuantumCircuit(qr,cr)
bell_phi_p.h(qr[0])
bell_phi_p.cx(qr[0],qr[1])
bell_phi_p.measure(qr[0],cr[0])
bell_phi_p.measure(qr[1],cr[1])
bell_phi_p.draw(output='mpl')
job_bell_phi_p = qk.execute(bell_phi_p, backend, shots=1024)
result_bell_phi_p = job_bell_phi_p.result()
counts_bell_phi_p = result_bell_phi_p.get_counts()
print(counts_bell_phi_p)
cz_example = qk.QuantumCircuit(qr)
cz_example.cz(qr[0],qr[1])
cz_example.draw(output='mpl')
cz_from_cnot = qk.QuantumCircuit(qr)
cz_from_cnot.h(qr[1])
cz_from_cnot.cx(qr[0],qr[1])
cz_from_cnot.h(qr[1])
cz_from_cnot.draw(output='mpl')
delta = 0.5
cphase_test = qk.QuantumCircuit(qr)
cphase_test.cu1(delta,qr[0],qr[1])
cphase_test.draw(output='mpl')
delta = 0.5
cphase_from_cnot = qk.QuantumCircuit(qr)
cphase_from_cnot.u1(delta/2,qr[1])
cphase_from_cnot.cx(qr[0],qr[1])
cphase_from_cnot.u1(-delta/2,qr[1])
cphase_from_cnot.cx(qr[0],qr[1])
cphase_from_cnot.u1(delta/2,qr[0])
cphase_from_cnot.draw(output='mpl')
swap_test = qk.QuantumCircuit(qr)
swap_test.swap(qr[0],qr[1])
swap_test.draw(output='mpl')
swap_from_cnot = qk.QuantumCircuit(qr)
swap_from_cnot.cx(qr[0],qr[1])
swap_from_cnot.cx(qr[1],qr[0])
swap_from_cnot.cx(qr[0],qr[1])
swap_from_cnot.draw(output='mpl')
qr_many = qk.QuantumRegister(5)
control_example = qk.QuantumCircuit(qr_many)
control_example.cy(qr_many[0],qr_many[1])
control_example.ch(qr_many[1],qr_many[2])
control_example.crz(0.2,qr_many[2],qr_many[3])
control_example.cu3(0.5, 0, 0, qr_many[3],qr_many[4])
control_example.draw(output='mpl')
qrthree = qk.QuantumRegister(3)
toffoli_example = qk.QuantumCircuit(qrthree)
toffoli_example.ccx(qrthree[0],qrthree[1],qrthree[2])
toffoli_example.draw(output='mpl')
toffoli_from_cnot = qk.QuantumCircuit(qrthree)
toffoli_from_cnot.h(qrthree[2])
toffoli_from_cnot.cx(qrthree[1],qrthree[2])
toffoli_from_cnot.tdg(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[2])
toffoli_from_cnot.t(qrthree[2])
toffoli_from_cnot.cx(qrthree[1],qrthree[2])
toffoli_from_cnot.tdg(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[2])
toffoli_from_cnot.tdg(qrthree[1])
toffoli_from_cnot.t(qrthree[2])
toffoli_from_cnot.h(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[1])
toffoli_from_cnot.tdg(qrthree[1])
toffoli_from_cnot.cx(qrthree[0],qrthree[1])
toffoli_from_cnot.s(qrthree[1])
toffoli_from_cnot.t(qrthree[0])
toffoli_from_cnot.draw(output='mpl')
crsingle = qk.ClassicalRegister(1)
deutsch = qk.QuantumCircuit(qr,crsingle)
deutsch.x(qr[1])
deutsch.h(qr[1])
deutsch.draw(output='mpl')
deutsch.h(qr[0])
deutsch.draw(output='mpl')
deutsch.cx(qr[0],qr[1])
deutsch.h(qr[0])
deutsch.measure(qr[0],crsingle[0])
deutsch.draw(output='mpl')
N = 4
qrQFT = qk.QuantumRegister(N,'qftr')
QFT = qk.QuantumCircuit(qrQFT)
for i in range(N):
QFT.h(qrQFT[i])
for k in range(i+1,N):
l = k-i+1
QFT.cu1(2*math.pi/(2**l),qrQFT[k],qrQFT[i])
QFT.draw(output='mpl')
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### replaced x gate ###
qc.x(1)
return qc
|
https://github.com/EusseJhoan/DeutschJosza_algorithm
|
EusseJhoan
|
from qiskit import QuantumCircuit, transpile, Aer
from qiskit.visualization import plot_histogram
import numpy as np
sim = Aer.get_backend('aer_simulator')
def U_f1(qc):
return qc
def U_f2(qc):
qc.x(1) #Compuerta X al segundo qubit
return qc
def U_f3(qc):
qc.cx(0,1) #Compuerta CNOT entre primer y segundo quibit (el primero es el que controla)
return qc
def U_f4(qc):
qc.cx(0,1) #Compuerta CNOT entre primer y segundo quibit (el primero es el que controla)
qc.x(1) #Compuerta X al segundo qubit
return qc
def Deutsch(U_f):
qc=QuantumCircuit(2,1) #Se crea un circuito cuántico con 2 bits cuánticos y 1 canal clásico
qc.x(1) #Compuerta X al segundo qubit (inicializar estado |1>)
qc.h(0) #Compuerta H al primer qubit
qc.h(1) #Compuerta H al segundo qubit
qc.barrier() #Barrera (empieza oráculo)
qc = U_f(qc) #Agregamos el oráculo
qc.barrier() #Barrera (termina oráculo)
qc.h(0) #Compuerta H al primer qubit
qc.measure(0,0) #Medimos el primer qubit y enviamos señal al canal clásico
return qc
qc=Deutsch(U_f1) # definición circuito con oráculo usando f_1(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=Deutsch(U_f2) #definición circuito con oráculo usando f_2(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas del simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=Deutsch(U_f3) #definición circuito con oráculo usando f_3(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=Deutsch(U_f4) #definición circuito con oráculo usando f_4(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
#oráculo para f(x) constante para un número n de bits en el registro
def constant(qc,n):
ran=np.random.randint(2) #selección aleatoria de 0 ó 1
if ran == 1:
qc.x(n) #si el número aleatorio es 1 se pone compuerta X en el objetivo (se induce fase global -1 al registro)
return qc
#oráculo para f(x) balanceado para un número n de bits en el registro
def balanced(qc,n):
for i in range(n):
qc.cx(i,n) #se crea una CNOT entre cada qubit del registro y el objetivo (los qubits del registro controlan)
ran=np.random.randint(2) #selección aleatoria de 0 ó 1
if ran == 1:
qc.x(n) #si el número aleatorio es 1 se pone compuerta X en el objetivo (se induce fase global -1 al registro)
return qc
def D_J(U_f,n):
qc=QuantumCircuit(n+1,n) #Se crea un circuito cuántico con n+1 quibits y n canales clásicos
qc.x(n) #Compuerta X al bit del registro
for i in range(n+1):
qc.h(i) #Compuerta H a todos los bits
qc.barrier() #Barrera (empieza oráculo)
qc = U_f(qc,n) #Agregamos el oráculo
qc.barrier() #Barrera (termina oráculo)
for i in range(n):
qc.h(i) #Compuerta H a los n bits del registro
qc.measure(i,i) #Medición los n bits del registro
return qc
qc=D_J(constant,3) #definición circuito con oráculo constante y 3 bits en registro
display(qc.draw()) #ver circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=D_J(balanced,3)
display(qc.draw())
counts = sim.run(qc).result().get_counts()
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Create circuit to test transpiler on
from qiskit import QuantumCircuit
from qiskit.circuit.library import GroverOperator, Diagonal
oracle = Diagonal([1]*7 + [-1])
qc = QuantumCircuit(3)
qc.h([0,1,2])
qc = qc.compose(GroverOperator(oracle))
# Use Statevector object to calculate the ideal output
from qiskit.quantum_info import Statevector
ideal_distribution = Statevector.from_instruction(qc).probabilities_dict()
from qiskit.visualization import plot_histogram
plot_histogram(ideal_distribution)
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = service.backend('ibm_algiers')
# Need to add measurements to the circuit
qc.measure_all()
from qiskit import transpile
circuits = []
for optimization_level in [0, 3]:
t_qc = transpile(qc,
backend,
optimization_level=optimization_level,
seed_transpiler=0)
print(f'CNOTs (optimization_level={optimization_level}): ',
t_qc.count_ops()['cx'])
circuits.append(t_qc)
from qiskit.transpiler import PassManager, InstructionDurations
from qiskit.transpiler.passes import ASAPSchedule, DynamicalDecoupling
from qiskit.circuit.library import XGate
# Get gate durations so the transpiler knows how long each operation takes
durations = InstructionDurations.from_backend(backend)
# This is the sequence we'll apply to idling qubits
dd_sequence = [XGate(), XGate()]
# Run scheduling and dynamic decoupling passes on circuit
pm = PassManager([ASAPSchedule(durations),
DynamicalDecoupling(durations, dd_sequence)]
)
circ_dd = pm.run(circuits[1])
# Add this new circuit to our list
circuits.append(circ_dd)
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
sampler = Sampler()
job = sampler.run(
circuits=circuits, # sample all three circuits
skip_transpilation=True,
shots=8000)
result = job.result()
from qiskit.visualization import plot_histogram
binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists]
plot_histogram(binary_prob+[ideal_distribution],
bar_labels=False,
legend=['optimization_level=0',
'optimization_level=3',
'optimization_level=3 + dd',
'ideal distribution'])
from qiskit.quantum_info import hellinger_fidelity
for counts in result.quasi_dists:
print(
f"{hellinger_fidelity(counts.binary_probabilities(), ideal_distribution):.3f}"
)
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/ankitkmisra/Quantum-Computing-and-Cryptography
|
ankitkmisra
|
from qiskit import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import matplotlib.pyplot as plotter
import numpy as np
from IPython.display import display, Math, Latex
%matplotlib inline
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# The '0' state
plot_bloch_vector([0,0,1])
# The '1' state
plot_bloch_vector([0,0,-1])
qc1 = QuantumCircuit(2,2) # Initializing a quantum ciruit (2 qubits, 2 classical bits)
# All initialized to '0' by default.
qc1.draw(output='mpl') # Draws the circuit diagram
qc1.x(0) # Applying X gate to the first qubit
qc1.draw(output='mpl')
qc1.x(1) # Applying X gate to the second qubit
qc1.draw(output='mpl')
# The '+' state
plot_bloch_vector([1,0,0])
# The '-' state
plot_bloch_vector([-1,0,0])
qc2 = QuantumCircuit(2,2) # A new quantum circuit with 2 qubits and 2 classical bits
qc2.h(0) # Applying the Hadamard gate on first qubit
qc2.draw(output='mpl')
qc2.cx(0,1) # Applying CX gate ('control','target')
qc2.draw(output='mpl')
qc2.measure(0,0) # Measure first qubit and store it in first classical bit
qc2.measure(1,1) # Measure second qubit and store it in second classical bit
# The code below plots a histogram of the measurement result. You can copy it for further use.
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 2000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc2)
print(counts)
plot_histogram(counts)
qc1.h(0)
qc1.cx(0, 1)
qc1.draw(output='mpl')
qc1.measure(0,0)
qc1.measure(1,1)
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend, shots = 2000).result()
counts = result.get_counts()
return counts
counts = run_circuit(qc1)
print(counts)
plot_histogram(counts)
qc3 = QuantumCircuit(3,3)
qc3.x(range(3)) # Setting the all qubits to '1'
qc3.toffoli(0,1,2) # (control,control,target)
qc3.measure(0,0)
qc3.measure(1,1)
qc3.measure(2,2)
def run_circuit(qc3):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc3, backend, shots = 2000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc3)
print(counts)
plot_histogram(counts)
# The output should be '011' as the highest (q2) is flipped because the other two qubits were set to '1'
qc4 = QuantumCircuit(2,2)
#Applying the Pauli-X gate to quantum bit 0, we turn it into 1 so that the swap outcome is observable.
qc4.x(0)
qc4.cx(0, 1)
qc4.cx(1, 0)
qc4.cx(0, 1)
qc4.draw(output='mpl')
qc4.measure(0,0)
qc4.measure(1,1)
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend, shots = 2000).result()
counts = result.get_counts()
return counts
counts = run_circuit(qc4)
print(counts)
plot_histogram(counts)
qc5 = QuantumCircuit(2,2)
#We turn quantum bit 1 into 1 so that we can observe the results of HZH on both 0 (from q0) and 1 (from q1).
qc5.x(1)
qc5.h((0, 1))
qc5.z((0, 1))
qc5.h((0, 1))
qc5.draw(output='mpl')
qc5.measure(0,0)
qc5.measure(1,1)
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend, shots = 2000).result()
counts = result.get_counts()
return counts
counts = run_circuit(qc5)
print(counts)
plot_histogram(counts)
qc6 = QuantumCircuit(3,3)
#Initializing quantum bits using gates:
#q0 is initialized to 0.
#q1 is initialized to 1.
qc6.x(1)
#q2 is initialized to the state given above.
qc6.x(2)
qc6.h(2)
qc6.t(2)
#We change q2 for the controlled swap now; we'll bring it back to the same state afterwards.
qc6.tdg(2)
qc6.h(2)
#Controlled swap.
qc6.toffoli(0, 2, 1)
qc6.toffoli(1, 2, 0)
qc6.toffoli(0, 2, 1)
#We convert q2 back to whatever it was.
qc6.h(2)
qc6.t(2)
qc6.draw(output='mpl')
qc6.measure(0, 0)
qc6.measure(1, 1)
qc6.measure(2, 2)
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend, shots = 2000).result()
counts = result.get_counts()
return counts
counts = run_circuit(qc6)
print(counts)
plot_histogram(counts)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Test majority gate """
from unittest import TestCase
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qclib.gates.majority import operate as majority
from qclib.util import get_counts
class TestMajority(TestCase):
""" Testing qclib.gate.majority """
@staticmethod
def _run_majority(bin_input):
""" Run majority gate and return counts """
# initialize quantum registers
controls = QuantumRegister(len(bin_input), 'controls')
target = QuantumRegister(1, 'target')
output = ClassicalRegister(1)
circuit = QuantumCircuit(controls, target, output)
# Pattern basis encoding
for k, bit in enumerate(bin_input):
if bit == 1:
circuit.x(controls[k])
majority(circuit, controls, target)
# measure output and verify results
# pylint: disable=maybe-no-member
circuit.measure(target, output)
counts = get_counts(circuit)
return counts
def _test_majority(self, n_qubits):
""" Testing majority """
for i in range(2 ** n_qubits):
bits = [int(j) for j in '{:0{}b}'.format(i, n_qubits)]
counts = TestMajority._run_majority(bits)
if sum(bits) >= n_qubits/2:
self.assertTrue(counts['1'] / 1024 == 1)
else:
self.assertTrue(counts['0'] / 1024 == 1)
# Keep tests separated by number of qubits to make it easier to identify errors.
def test_majority_2(self):
""" Testing 2 qubits majority """
TestMajority._test_majority(self, 2)
def test_majority_3(self):
""" Testing 3 qubits majority """
TestMajority._test_majority(self, 3)
def test_majority_4(self):
""" Testing 4 qubits majority """
TestMajority._test_majority(self, 4)
def test_majority_5(self):
""" Testing 5 qubits majority """
TestMajority._test_majority(self, 5)
|
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
|
alejomonbar
|
from sklearn.metrics import ConfusionMatrixDisplay
import numpy as np
import matplotlib.pyplot as plt
ConfusionMatrixDisplay(confusion_matrix).plot()
confusion_matrix = np.array([[4684, 346],[829, 300]])
plt.figure()
plt.imshow(confusion_matrix, cmap="Blues")
for i in range(2):
for j in range(2):
plt.text(j, i, format(confusion_matrix[i, j]),
ha="center", va="center",
color="white" if confusion_matrix[i, j] > 2500 else "black", fontsize=18)
plt.xticks([0,1], [0,1], fontsize=14)
plt.yticks([0,1], [0,1], fontsize=14)
plt.xlabel("Predicted Label", fontsize=14)
plt.ylabel("True Label", fontsize=14)
plt.colorbar()
confusion_matrix = np.array([[3690, 1070],[182, 947]])
plt.figure()
plt.imshow(confusion_matrix, cmap="Blues")
for i in range(2):
for j in range(2):
plt.text(j, i, format(confusion_matrix[i, j]),
ha="center", va="center",
color="white" if confusion_matrix[i, j] > 2500 else "black", fontsize=18)
plt.xticks([0,1], [0,1], fontsize=14)
plt.yticks([0,1], [0,1], fontsize=14)
plt.xlabel("Predicted Label", fontsize=14)
plt.ylabel("True Label", fontsize=14)
plt.colorbar()
confusion_matrix = np.array([[3835, 1195],[237, 892]])
plt.figure()
plt.imshow(confusion_matrix, cmap="Blues")
for i in range(2):
for j in range(2):
plt.text(j, i, format(confusion_matrix[i, j]),
ha="center", va="center",
color="white" if confusion_matrix[i, j] > 2500 else "black", fontsize=18)
plt.xticks([0,1], [0,1], fontsize=14)
plt.yticks([0,1], [0,1], fontsize=14)
plt.xlabel("Predicted Label", fontsize=14)
plt.ylabel("True Label", fontsize=14)
plt.colorbar()
https://arxiv.org/pdf/2010.07335.pdf
https://arxiv.org/pdf/2105.10162.pdf
https://arxiv.org/pdf/2203.01340.pdf maria
https://arxiv.org/pdf/1810.03787.pdf MERA
https://arxiv.org/pdf/1905.01426.pdf MERA 2
https://pennylane.ai/qml/demos/tutorial_tn_circuits.html
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can make the bars more transparent to better see the ones that are behind
# if they overlap.
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
from qiskit import QuantumCircuit
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)
state = Statevector(qc)
plot_state_city(state, alpha=0.6)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Core module of the timeline drawer.
This module provides the `DrawerCanvas` which is a collection of drawings.
The canvas instance is not just a container of drawing objects, as it also performs
data processing like binding abstract coordinates.
Initialization
~~~~~~~~~~~~~~
The `DataCanvas` is not exposed to users as they are implicitly initialized in the
interface function. It is noteworthy that the data canvas is agnostic to plotters.
This means once the canvas instance is initialized we can reuse this data
among multiple plotters. The canvas is initialized with a stylesheet.
```python
canvas = DrawerCanvas(stylesheet=stylesheet)
canvas.load_program(sched)
canvas.update()
```
Once all properties are set, `.update` method is called to apply changes to drawings.
Update
~~~~~~
To update the image, a user can set new values to canvas and then call the `.update` method.
```python
canvas.set_time_range(2000, 3000)
canvas.update()
```
All stored drawings are updated accordingly. The plotter API can access to
drawings with `.collections` property of the canvas instance. This returns
an iterator of drawings with the unique data key.
If a plotter provides object handler for plotted shapes, the plotter API can manage
the lookup table of the handler and the drawings by using this data key.
"""
from __future__ import annotations
import warnings
from collections.abc import Iterator
from copy import deepcopy
from functools import partial
from enum import Enum
import numpy as np
from qiskit import circuit
from qiskit.visualization.exceptions import VisualizationError
from qiskit.visualization.timeline import drawings, types
from qiskit.visualization.timeline.stylesheet import QiskitTimelineStyle
class DrawerCanvas:
"""Data container for drawings."""
def __init__(self, stylesheet: QiskitTimelineStyle):
"""Create new data container."""
# stylesheet
self.formatter = stylesheet.formatter
self.generator = stylesheet.generator
self.layout = stylesheet.layout
# drawings
self._collections: dict[str, drawings.ElementaryData] = {}
self._output_dataset: dict[str, drawings.ElementaryData] = {}
# vertical offset of bits
self.bits: list[types.Bits] = []
self.assigned_coordinates: dict[types.Bits, float] = {}
# visible controls
self.disable_bits: set[types.Bits] = set()
self.disable_types: set[str] = set()
# time
self._time_range = (0, 0)
# graph height
self.vmax = 0
self.vmin = 0
@property
def time_range(self) -> tuple[int, int]:
"""Return current time range to draw.
Calculate net duration and add side margin to edge location.
Returns:
Time window considering side margin.
"""
t0, t1 = self._time_range
duration = t1 - t0
new_t0 = t0 - duration * self.formatter["margin.left_percent"]
new_t1 = t1 + duration * self.formatter["margin.right_percent"]
return new_t0, new_t1
@time_range.setter
def time_range(self, new_range: tuple[int, int]):
"""Update time range to draw."""
self._time_range = new_range
@property
def collections(self) -> Iterator[tuple[str, drawings.ElementaryData]]:
"""Return currently active entries from drawing data collection.
The object is returned with unique name as a key of an object handler.
When the horizontal coordinate contains `AbstractCoordinate`,
the value is substituted by current time range preference.
"""
yield from self._output_dataset.items()
def add_data(self, data: drawings.ElementaryData):
"""Add drawing to collections.
If the given object already exists in the collections,
this interface replaces the old object instead of adding new entry.
Args:
data: New drawing to add.
"""
if not self.formatter["control.show_clbits"]:
data.bits = [b for b in data.bits if not isinstance(b, circuit.Clbit)]
self._collections[data.data_key] = data
# pylint: disable=cyclic-import
def load_program(self, program: circuit.QuantumCircuit):
"""Load quantum circuit and create drawing..
Args:
program: Scheduled circuit object to draw.
Raises:
VisualizationError: When circuit is not scheduled.
"""
not_gate_like = (circuit.Barrier,)
if getattr(program, "_op_start_times") is None:
# Run scheduling for backward compatibility
from qiskit import transpile
from qiskit.transpiler import InstructionDurations, TranspilerError
warnings.warn(
"Visualizing un-scheduled circuit with timeline drawer has been deprecated. "
"This circuit should be transpiled with scheduler though it consists of "
"instructions with explicit durations.",
DeprecationWarning,
)
try:
program = transpile(
program,
scheduling_method="alap",
instruction_durations=InstructionDurations(),
optimization_level=0,
)
except TranspilerError as ex:
raise VisualizationError(
f"Input circuit {program.name} is not scheduled and it contains "
"operations with unknown delays. This cannot be visualized."
) from ex
for t0, instruction in zip(program.op_start_times, program.data):
bits = list(instruction.qubits) + list(instruction.clbits)
for bit_pos, bit in enumerate(bits):
if not isinstance(instruction.operation, not_gate_like):
# Generate draw object for gates
gate_source = types.ScheduledGate(
t0=t0,
operand=instruction.operation,
duration=instruction.operation.duration,
bits=bits,
bit_position=bit_pos,
)
for gen in self.generator["gates"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(gate_source):
self.add_data(datum)
if len(bits) > 1 and bit_pos == 0:
# Generate draw object for gate-gate link
line_pos = t0 + 0.5 * instruction.operation.duration
link_source = types.GateLink(
t0=line_pos, opname=instruction.operation.name, bits=bits
)
for gen in self.generator["gate_links"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(link_source):
self.add_data(datum)
if isinstance(instruction.operation, circuit.Barrier):
# Generate draw object for barrier
barrier_source = types.Barrier(t0=t0, bits=bits, bit_position=bit_pos)
for gen in self.generator["barriers"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(barrier_source):
self.add_data(datum)
self.bits = list(program.qubits) + list(program.clbits)
for bit in self.bits:
for gen in self.generator["bits"]:
# Generate draw objects for bit
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(bit):
self.add_data(datum)
# update time range
t_end = max(program.duration, self.formatter["margin.minimum_duration"])
self.set_time_range(t_start=0, t_end=t_end)
def set_time_range(self, t_start: int, t_end: int):
"""Set time range to draw.
Args:
t_start: Left boundary of drawing in units of cycle time.
t_end: Right boundary of drawing in units of cycle time.
"""
self.time_range = (t_start, t_end)
def set_disable_bits(self, bit: types.Bits, remove: bool = True):
"""Interface method to control visibility of bits.
Specified object in the blocked list will not be shown.
Args:
bit: A qubit or classical bit object to disable.
remove: Set `True` to disable, set `False` to enable.
"""
if remove:
self.disable_bits.add(bit)
else:
self.disable_bits.discard(bit)
def set_disable_type(self, data_type: types.DataTypes, remove: bool = True):
"""Interface method to control visibility of data types.
Specified object in the blocked list will not be shown.
Args:
data_type: A drawing data type to disable.
remove: Set `True` to disable, set `False` to enable.
"""
if isinstance(data_type, Enum):
data_type_str = str(data_type.value)
else:
data_type_str = data_type
if remove:
self.disable_types.add(data_type_str)
else:
self.disable_types.discard(data_type_str)
def update(self):
"""Update all collections.
This method should be called before the canvas is passed to the plotter.
"""
self._output_dataset.clear()
self.assigned_coordinates.clear()
# update coordinate
y0 = -self.formatter["margin.top"]
for bit in self.layout["bit_arrange"](self.bits):
# remove classical bit
if isinstance(bit, circuit.Clbit) and not self.formatter["control.show_clbits"]:
continue
# remove idle bit
if not self._check_bit_visible(bit):
continue
offset = y0 - 0.5
self.assigned_coordinates[bit] = offset
y0 = offset - 0.5
self.vmax = 0
self.vmin = y0 - self.formatter["margin.bottom"]
# add data
temp_gate_links = {}
temp_data = {}
for data_key, data in self._collections.items():
# deep copy to keep original data hash
new_data = deepcopy(data)
new_data.xvals = self._bind_coordinate(data.xvals)
new_data.yvals = self._bind_coordinate(data.yvals)
if data.data_type == str(types.LineType.GATE_LINK.value):
temp_gate_links[data_key] = new_data
else:
temp_data[data_key] = new_data
# update horizontal offset of gate links
temp_data.update(self._check_link_overlap(temp_gate_links))
# push valid data
for data_key, data in temp_data.items():
if self._check_data_visible(data):
self._output_dataset[data_key] = data
def _check_data_visible(self, data: drawings.ElementaryData) -> bool:
"""A helper function to check if the data is visible.
Args:
data: Drawing object to test.
Returns:
Return `True` if the data is visible.
"""
_barriers = [str(types.LineType.BARRIER.value)]
_delays = [str(types.BoxType.DELAY.value), str(types.LabelType.DELAY.value)]
def _time_range_check(_data):
"""If data is located outside the current time range."""
t0, t1 = self.time_range
if np.max(_data.xvals) < t0 or np.min(_data.xvals) > t1:
return False
return True
def _associated_bit_check(_data):
"""If any associated bit is not shown."""
if all(bit not in self.assigned_coordinates for bit in _data.bits):
return False
return True
def _data_check(_data):
"""If data is valid."""
if _data.data_type == str(types.LineType.GATE_LINK.value):
active_bits = [bit for bit in _data.bits if bit not in self.disable_bits]
if len(active_bits) < 2:
return False
elif _data.data_type in _barriers and not self.formatter["control.show_barriers"]:
return False
elif _data.data_type in _delays and not self.formatter["control.show_delays"]:
return False
return True
checks = [_time_range_check, _associated_bit_check, _data_check]
if all(check(data) for check in checks):
return True
return False
def _check_bit_visible(self, bit: types.Bits) -> bool:
"""A helper function to check if the bit is visible.
Args:
bit: Bit object to test.
Returns:
Return `True` if the bit is visible.
"""
_gates = [str(types.BoxType.SCHED_GATE.value), str(types.SymbolType.FRAME.value)]
if bit in self.disable_bits:
return False
if self.formatter["control.show_idle"]:
return True
for data in self._collections.values():
if bit in data.bits and data.data_type in _gates:
return True
return False
def _bind_coordinate(self, vals: Iterator[types.Coordinate]) -> np.ndarray:
"""A helper function to bind actual coordinates to an `AbstractCoordinate`.
Args:
vals: Sequence of coordinate objects associated with a drawing.
Returns:
Numpy data array with substituted values.
"""
def substitute(val: types.Coordinate):
if val == types.AbstractCoordinate.LEFT:
return self.time_range[0]
if val == types.AbstractCoordinate.RIGHT:
return self.time_range[1]
if val == types.AbstractCoordinate.TOP:
return self.vmax
if val == types.AbstractCoordinate.BOTTOM:
return self.vmin
raise VisualizationError(f"Coordinate {val} is not supported.")
try:
return np.asarray(vals, dtype=float)
except TypeError:
return np.asarray(list(map(substitute, vals)), dtype=float)
def _check_link_overlap(
self, links: dict[str, drawings.GateLinkData]
) -> dict[str, drawings.GateLinkData]:
"""Helper method to check overlap of bit links.
This method dynamically shifts horizontal position of links if they are overlapped.
"""
duration = self.time_range[1] - self.time_range[0]
allowed_overlap = self.formatter["margin.link_interval_percent"] * duration
# return y coordinates
def y_coords(link: drawings.GateLinkData):
return np.array([self.assigned_coordinates.get(bit, np.nan) for bit in link.bits])
# group overlapped links
overlapped_group: list[list[str]] = []
data_keys = list(links.keys())
while len(data_keys) > 0:
ref_key = data_keys.pop()
overlaps = set()
overlaps.add(ref_key)
for key in data_keys[::-1]:
# check horizontal overlap
if np.abs(links[ref_key].xvals[0] - links[key].xvals[0]) < allowed_overlap:
# check vertical overlap
y0s = y_coords(links[ref_key])
y1s = y_coords(links[key])
v1 = np.nanmin(y0s) - np.nanmin(y1s)
v2 = np.nanmax(y0s) - np.nanmax(y1s)
v3 = np.nanmin(y0s) - np.nanmax(y1s)
v4 = np.nanmax(y0s) - np.nanmin(y1s)
if not (v1 * v2 > 0 and v3 * v4 > 0):
overlaps.add(data_keys.pop(data_keys.index(key)))
overlapped_group.append(list(overlaps))
# renew horizontal offset
new_links = {}
for overlaps in overlapped_group:
if len(overlaps) > 1:
xpos_mean = np.mean([links[key].xvals[0] for key in overlaps])
# sort link key by y position
sorted_keys = sorted(overlaps, key=lambda x: np.nanmax(y_coords(links[x])))
x0 = xpos_mean - 0.5 * allowed_overlap * (len(overlaps) - 1)
for ind, key in enumerate(sorted_keys):
data = links[key]
data.xvals = [x0 + ind * allowed_overlap]
new_links[key] = data
else:
key = overlaps[0]
new_links[key] = links[key]
return {key: new_links[key] for key in links.keys()}
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# 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.
"""Transpiler testing"""
import io
from logging import StreamHandler, getLogger
import unittest.mock
import sys
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import PassManager, TranspilerError
from qiskit.transpiler.runningpassmanager import (
DoWhileController,
ConditionalController,
FlowController,
)
from qiskit.test import QiskitTestCase
from ._dummy_passes import (
PassA_TP_NR_NP,
PassB_TP_RA_PA,
PassC_TP_RA_PA,
PassD_TP_NR_NP,
PassE_AP_NR_NP,
PassF_reduce_dag_property,
PassI_Bad_AP,
PassJ_Bad_NoReturn,
PassK_check_fixed_point_property,
PassM_AP_NR_NP,
)
class SchedulerTestCase(QiskitTestCase):
"""Asserts for the scheduler."""
def assertScheduler(self, circuit, passmanager, expected):
"""
Run `transpile(circuit, passmanager)` and check
if the passes run as expected.
Args:
circuit (QuantumCircuit): Circuit to transform via transpilation.
passmanager (PassManager): pass manager instance for the transpilation process
expected (list): List of things the passes are logging
"""
logger = "LocalLogger"
with self.assertLogs(logger, level="INFO") as cm:
out = passmanager.run(circuit)
self.assertIsInstance(out, QuantumCircuit)
self.assertEqual([record.message for record in cm.records], expected)
def assertSchedulerRaises(self, circuit, passmanager, expected, exception_type):
"""
Run `transpile(circuit, passmanager)` and check
if the passes run as expected until exception_type is raised.
Args:
circuit (QuantumCircuit): Circuit to transform via transpilation
passmanager (PassManager): pass manager instance for the transpilation process
expected (list): List of things the passes are logging
exception_type (Exception): Exception that is expected to be raised.
"""
logger = "LocalLogger"
with self.assertLogs(logger, level="INFO") as cm:
self.assertRaises(exception_type, passmanager.run, circuit)
self.assertEqual([record.message for record in cm.records], expected)
class TestPassManagerInit(SchedulerTestCase):
"""The pass manager sets things at init time."""
def test_passes(self):
"""A single chain of passes, with Requests and Preserves, at __init__ time"""
circuit = QuantumCircuit(QuantumRegister(1))
passmanager = PassManager(
passes=[
PassC_TP_RA_PA(), # Request: PassA / Preserves: PassA
PassB_TP_RA_PA(), # Request: PassA / Preserves: PassA
PassD_TP_NR_NP(argument1=[1, 2]), # Requires: {}/ Preserves: {}
PassB_TP_RA_PA(),
]
)
self.assertScheduler(
circuit,
passmanager,
[
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassD_TP_NR_NP",
"argument [1, 2]",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
],
)
class TestUseCases(SchedulerTestCase):
"""Combine passes in different ways and checks that passes are run
in the right order."""
def setUp(self):
super().setUp()
self.circuit = QuantumCircuit(QuantumRegister(1))
self.passmanager = PassManager()
def test_chain(self):
"""A single chain of passes, with Requires and Preserves."""
self.passmanager.append(PassC_TP_RA_PA()) # Requires: PassA / Preserves: PassA
self.passmanager.append(PassB_TP_RA_PA()) # Requires: PassA / Preserves: PassA
self.passmanager.append(PassD_TP_NR_NP(argument1=[1, 2])) # Requires: {}/ Preserves: {}
self.passmanager.append(PassB_TP_RA_PA())
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassD_TP_NR_NP",
"argument [1, 2]",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
],
)
def test_conditional_passes_true(self):
"""A pass set with a conditional parameter. The callable is True."""
self.passmanager.append(PassE_AP_NR_NP(True))
self.passmanager.append(
PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"]
)
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run analysis pass PassE_AP_NR_NP",
"set property as True",
"run transformation pass PassA_TP_NR_NP",
],
)
def test_conditional_passes_true_fc(self):
"""A pass set with a conditional parameter (with FlowController). The callable is True."""
self.passmanager.append(PassE_AP_NR_NP(True))
self.passmanager.append(
ConditionalController(
[PassA_TP_NR_NP()], condition=lambda property_set: property_set["property"]
)
)
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run analysis pass PassE_AP_NR_NP",
"set property as True",
"run transformation pass PassA_TP_NR_NP",
],
)
def test_conditional_passes_false(self):
"""A pass set with a conditional parameter. The callable is False."""
self.passmanager.append(PassE_AP_NR_NP(False))
self.passmanager.append(
PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"]
)
self.assertScheduler(
self.circuit,
self.passmanager,
["run analysis pass PassE_AP_NR_NP", "set property as False"],
)
def test_conditional_and_loop(self):
"""Run a conditional first, then a loop."""
self.passmanager.append(PassE_AP_NR_NP(True))
self.passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
condition=lambda property_set: property_set["property"],
)
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run analysis pass PassE_AP_NR_NP",
"set property as True",
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run analysis pass PassG_calculates_dag_property",
"set property as 5 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run analysis pass PassG_calculates_dag_property",
"set property as 4 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
"run analysis pass PassG_calculates_dag_property",
"set property as 3 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
],
)
def test_loop_and_conditional(self):
"""Run a loop first, then a conditional."""
FlowController.remove_flow_controller("condition")
FlowController.add_flow_controller("condition", ConditionalController)
self.passmanager.append(PassK_check_fixed_point_property())
self.passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
condition=lambda property_set: not property_set["property_fixed_point"],
)
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run analysis pass PassG_calculates_dag_property",
"set property as 5 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run analysis pass PassG_calculates_dag_property",
"set property as 4 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
"run analysis pass PassG_calculates_dag_property",
"set property as 3 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
],
)
def test_do_not_repeat_based_on_preservation(self):
"""When a pass is still a valid pass (because the following passes
preserved it), it should not run again."""
self.passmanager.append([PassB_TP_RA_PA(), PassA_TP_NR_NP(), PassB_TP_RA_PA()])
self.assertScheduler(
self.circuit,
self.passmanager,
["run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA"],
)
def test_do_not_repeat_based_on_idempotence(self):
"""Repetition can be optimized to a single execution when
the pass is idempotent."""
self.passmanager.append(PassA_TP_NR_NP())
self.passmanager.append([PassA_TP_NR_NP(), PassA_TP_NR_NP()])
self.passmanager.append(PassA_TP_NR_NP())
self.assertScheduler(
self.circuit, self.passmanager, ["run transformation pass PassA_TP_NR_NP"]
)
def test_non_idempotent_pass(self):
"""Two or more runs of a non-idempotent pass cannot be optimized."""
self.passmanager.append(PassF_reduce_dag_property())
self.passmanager.append([PassF_reduce_dag_property(), PassF_reduce_dag_property()])
self.passmanager.append(PassF_reduce_dag_property())
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
],
)
def test_fenced_dag(self):
"""Analysis passes are not allowed to modified the DAG."""
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.cx(qr[0], qr[1])
circ.cx(qr[0], qr[1])
circ.cx(qr[1], qr[0])
circ.cx(qr[1], qr[0])
self.passmanager.append(PassI_Bad_AP())
self.assertSchedulerRaises(
circ,
self.passmanager,
["run analysis pass PassI_Bad_AP", "cx_runs: {(4, 5, 6, 7)}"],
TranspilerError,
)
def test_analysis_pass_is_idempotent(self):
"""Analysis passes are idempotent."""
passmanager = PassManager()
passmanager.append(PassE_AP_NR_NP(argument1=1))
passmanager.append(PassE_AP_NR_NP(argument1=1))
self.assertScheduler(
self.circuit, passmanager, ["run analysis pass PassE_AP_NR_NP", "set property as 1"]
)
def test_ap_before_and_after_a_tp(self):
"""A default transformation does not preserves anything
and analysis passes need to be re-run"""
passmanager = PassManager()
passmanager.append(PassE_AP_NR_NP(argument1=1))
passmanager.append(PassA_TP_NR_NP())
passmanager.append(PassE_AP_NR_NP(argument1=1))
self.assertScheduler(
self.circuit,
passmanager,
[
"run analysis pass PassE_AP_NR_NP",
"set property as 1",
"run transformation pass PassA_TP_NR_NP",
"run analysis pass PassE_AP_NR_NP",
"set property as 1",
],
)
def test_pass_no_return(self):
"""Transformation passes that don't return a DAG raise error."""
self.passmanager.append(PassJ_Bad_NoReturn())
self.assertSchedulerRaises(
self.circuit,
self.passmanager,
["run transformation pass PassJ_Bad_NoReturn"],
TranspilerError,
)
def test_fixed_point_pass(self):
"""A pass set with a do_while parameter that checks for a fixed point."""
self.passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
)
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run analysis pass PassG_calculates_dag_property",
"set property as 5 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run analysis pass PassG_calculates_dag_property",
"set property as 4 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
"run analysis pass PassG_calculates_dag_property",
"set property as 3 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
],
)
def test_fixed_point_fc(self):
"""A fixed point scheduler with flow control."""
self.passmanager.append(
DoWhileController(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
)
)
expected = [
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run analysis pass PassG_calculates_dag_property",
"set property as 5 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run analysis pass PassG_calculates_dag_property",
"set property as 4 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
"run analysis pass PassG_calculates_dag_property",
"set property as 3 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_fixed_point_pass_max_iteration(self):
"""A pass set with a do_while parameter that checks that
the max_iteration is raised."""
self.passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
max_iteration=2,
)
self.assertSchedulerRaises(
self.circuit,
self.passmanager,
[
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
],
TranspilerError,
)
def test_fresh_initial_state(self):
"""New construction gives fresh instance."""
self.passmanager.append(PassM_AP_NR_NP(argument1=1))
self.passmanager.append(PassA_TP_NR_NP())
self.passmanager.append(PassM_AP_NR_NP(argument1=1))
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run analysis pass PassM_AP_NR_NP",
"self.argument1 = 2",
"run transformation pass PassA_TP_NR_NP",
"run analysis pass PassM_AP_NR_NP",
"self.argument1 = 2",
],
)
def test_nested_conditional_in_loop(self):
"""Run a loop with a nested conditional."""
nested_conditional = [
ConditionalController(
[PassA_TP_NR_NP()], condition=lambda property_set: property_set["property"] >= 5
)
]
self.passmanager.append(
[PassK_check_fixed_point_property()]
+ nested_conditional
+ [PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
)
expected = [
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run analysis pass PassG_calculates_dag_property",
"set property as 5 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run analysis pass PassG_calculates_dag_property",
"set property as 4 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
"run analysis pass PassG_calculates_dag_property",
"set property as 3 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
class DoXTimesController(FlowController):
"""A control-flow plugin for running a set of passes an X amount of times."""
def __init__(self, passes, options, do_x_times=0, **_):
self.do_x_times = do_x_times()
super().__init__(passes, options)
def __iter__(self):
for _ in range(self.do_x_times):
yield from self.passes
class TestControlFlowPlugin(SchedulerTestCase):
"""Testing the control flow plugin system."""
def setUp(self):
super().setUp()
self.passmanager = PassManager()
self.circuit = QuantumCircuit(QuantumRegister(1))
def test_control_flow_plugin(self):
"""Adds a control flow plugin with a single parameter and runs it."""
FlowController.add_flow_controller("do_x_times", DoXTimesController)
self.passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3)
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
],
)
def test_callable_control_flow_plugin(self):
"""Removes do_while, then adds it back. Checks max_iteration still working."""
controllers_length = len(FlowController.registered_controllers)
FlowController.remove_flow_controller("do_while")
self.assertEqual(controllers_length - 1, len(FlowController.registered_controllers))
FlowController.add_flow_controller("do_while", DoWhileController)
self.assertEqual(controllers_length, len(FlowController.registered_controllers))
self.passmanager.append(
[PassB_TP_RA_PA(), PassC_TP_RA_PA()],
do_while=lambda property_set: True,
max_iteration=2,
)
self.assertSchedulerRaises(
self.circuit,
self.passmanager,
[
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
],
TranspilerError,
)
def test_remove_nonexistent_plugin(self):
"""Tries to remove a plugin that does not exist."""
self.assertRaises(KeyError, FlowController.remove_flow_controller, "foo")
def test_bad_conditional(self):
"""Flow controller are not allowed to modify the property set."""
def bad_condition(property_set):
property_set["property"] = "forbidden write"
self.passmanager.append(PassA_TP_NR_NP(), condition=bad_condition)
self.assertRaises(TranspilerError, self.passmanager.run, self.circuit)
class TestDumpPasses(SchedulerTestCase):
"""Testing the passes method."""
def test_passes(self):
"""Dump passes in different FlowControllerLinear"""
passmanager = PassManager()
passmanager.append(PassC_TP_RA_PA())
passmanager.append(PassB_TP_RA_PA())
expected = [
{"flow_controllers": {}, "passes": [PassC_TP_RA_PA()]},
{"flow_controllers": {}, "passes": [PassB_TP_RA_PA()]},
]
self.assertEqual(expected, passmanager.passes())
def test_passes_in_linear(self):
"""Dump passes in the same FlowControllerLinear"""
passmanager = PassManager(
passes=[
PassC_TP_RA_PA(),
PassB_TP_RA_PA(),
PassD_TP_NR_NP(argument1=[1, 2]),
PassB_TP_RA_PA(),
]
)
expected = [
{
"flow_controllers": {},
"passes": [
PassC_TP_RA_PA(),
PassB_TP_RA_PA(),
PassD_TP_NR_NP(argument1=[1, 2]),
PassB_TP_RA_PA(),
],
}
]
self.assertEqual(expected, passmanager.passes())
def test_control_flow_plugin(self):
"""Dump passes in a custom flow controller."""
passmanager = PassManager()
FlowController.add_flow_controller("do_x_times", DoXTimesController)
passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3)
expected = [
{"passes": [PassB_TP_RA_PA(), PassC_TP_RA_PA()], "flow_controllers": {"do_x_times"}}
]
self.assertEqual(expected, passmanager.passes())
def test_conditional_and_loop(self):
"""Dump passes with a conditional and a loop."""
passmanager = PassManager()
passmanager.append(PassE_AP_NR_NP(True))
passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
condition=lambda property_set: property_set["property_fixed_point"],
)
expected = [
{"passes": [PassE_AP_NR_NP(True)], "flow_controllers": {}},
{
"passes": [
PassK_check_fixed_point_property(),
PassA_TP_NR_NP(),
PassF_reduce_dag_property(),
],
"flow_controllers": {"condition", "do_while"},
},
]
self.assertEqual(expected, passmanager.passes())
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestLogPasses(QiskitTestCase):
"""Testing the log_passes option."""
def setUp(self):
super().setUp()
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel("DEBUG")
self.output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.output))
self.circuit = QuantumCircuit(QuantumRegister(1))
def assertPassLog(self, passmanager, list_of_passes):
"""Runs the passmanager and checks that the elements in
passmanager.property_set['pass_log'] match list_of_passes (the names)."""
passmanager.run(self.circuit)
self.output.seek(0)
# Filter unrelated log lines
output_lines = self.output.readlines()
pass_log_lines = [x for x in output_lines if x.startswith("Pass:")]
for index, pass_name in enumerate(list_of_passes):
self.assertTrue(pass_log_lines[index].startswith("Pass: %s -" % pass_name))
def test_passes(self):
"""Dump passes in different FlowControllerLinear"""
passmanager = PassManager()
passmanager.append(PassC_TP_RA_PA())
passmanager.append(PassB_TP_RA_PA())
self.assertPassLog(passmanager, ["PassA_TP_NR_NP", "PassC_TP_RA_PA", "PassB_TP_RA_PA"])
def test_passes_in_linear(self):
"""Dump passes in the same FlowControllerLinear"""
passmanager = PassManager(
passes=[
PassC_TP_RA_PA(),
PassB_TP_RA_PA(),
PassD_TP_NR_NP(argument1=[1, 2]),
PassB_TP_RA_PA(),
]
)
self.assertPassLog(
passmanager,
[
"PassA_TP_NR_NP",
"PassC_TP_RA_PA",
"PassB_TP_RA_PA",
"PassD_TP_NR_NP",
"PassA_TP_NR_NP",
"PassB_TP_RA_PA",
],
)
def test_control_flow_plugin(self):
"""Dump passes in a custom flow controller."""
passmanager = PassManager()
FlowController.add_flow_controller("do_x_times", DoXTimesController)
passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3)
self.assertPassLog(
passmanager,
[
"PassA_TP_NR_NP",
"PassB_TP_RA_PA",
"PassC_TP_RA_PA",
"PassB_TP_RA_PA",
"PassC_TP_RA_PA",
"PassB_TP_RA_PA",
"PassC_TP_RA_PA",
],
)
def test_conditional_and_loop(self):
"""Dump passes with a conditional and a loop"""
passmanager = PassManager()
passmanager.append(PassE_AP_NR_NP(True))
passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
condition=lambda property_set: property_set["property_fixed_point"],
)
self.assertPassLog(passmanager, ["PassE_AP_NR_NP"])
class TestPassManagerReuse(SchedulerTestCase):
"""The PassManager instance should be reusable."""
def setUp(self):
super().setUp()
self.passmanager = PassManager()
self.circuit = QuantumCircuit(QuantumRegister(1))
def test_chain_twice(self):
"""Run a chain twice."""
self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_conditional_twice(self):
"""Run a conditional twice."""
self.passmanager.append(PassE_AP_NR_NP(True))
self.passmanager.append(
PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"]
)
expected = [
"run analysis pass PassE_AP_NR_NP",
"set property as True",
"run transformation pass PassA_TP_NR_NP",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_fixed_point_twice(self):
"""A fixed point scheduler, twice."""
self.passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
)
expected = [
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run analysis pass PassG_calculates_dag_property",
"set property as 5 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run analysis pass PassG_calculates_dag_property",
"set property as 4 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
"run analysis pass PassG_calculates_dag_property",
"set property as 3 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
self.assertScheduler(self.circuit, self.passmanager, expected)
class TestPassManagerChanges(SchedulerTestCase):
"""Test PassManager manipulation with changes"""
def setUp(self):
super().setUp()
self.passmanager = PassManager()
self.circuit = QuantumCircuit(QuantumRegister(1))
def test_replace0(self):
"""Test passmanager.replace(0, ...)."""
self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.replace(0, PassB_TP_RA_PA())
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_replace1(self):
"""Test passmanager.replace(1, ...)."""
self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.replace(1, PassC_TP_RA_PA())
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_remove0(self):
"""Test passmanager.remove(0)."""
self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.remove(0)
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_remove1(self):
"""Test passmanager.remove(1)."""
self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.remove(1)
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_remove_minus_1(self):
"""Test passmanager.remove(-1)."""
self.passmanager.append(PassA_TP_NR_NP())
self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.remove(-1)
expected = ["run transformation pass PassA_TP_NR_NP"]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_setitem(self):
"""Test passmanager[1] = ..."""
self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager[1] = PassC_TP_RA_PA()
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_replace_with_conditional(self):
"""Replace a pass with a conditional pass."""
self.passmanager.append(PassE_AP_NR_NP(False))
self.passmanager.append(PassB_TP_RA_PA())
self.passmanager.replace(
1, PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"]
)
expected = ["run analysis pass PassE_AP_NR_NP", "set property as False"]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_replace_error(self):
"""Replace a non-existing index."""
self.passmanager.append(PassB_TP_RA_PA())
with self.assertRaises(TranspilerError):
self.passmanager.replace(99, PassA_TP_NR_NP())
class TestPassManagerSlicing(SchedulerTestCase):
"""test PassManager slicing."""
def setUp(self):
super().setUp()
self.passmanager = PassManager()
self.circuit = QuantumCircuit(QuantumRegister(1))
def test_empty_passmanager_length(self):
"""test len(PassManager) when PassManager is empty"""
length = len(self.passmanager)
expected_length = 0
self.assertEqual(length, expected_length)
def test_passmanager_length(self):
"""test len(PassManager) when PassManager is not empty"""
self.passmanager.append(PassA_TP_NR_NP())
self.passmanager.append(PassA_TP_NR_NP())
length = len(self.passmanager)
expected_length = 2
self.assertEqual(length, expected_length)
def test_accessing_passmanager_by_index(self):
"""test accessing PassManager's passes by index"""
self.passmanager.append(PassB_TP_RA_PA())
self.passmanager.append(PassC_TP_RA_PA())
new_passmanager = self.passmanager[1]
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, new_passmanager, expected)
def test_accessing_passmanager_by_index_with_condition(self):
"""test accessing PassManager's conditioned passes by index"""
self.passmanager.append(PassF_reduce_dag_property())
self.passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
condition=lambda property_set: True,
do_while=lambda property_set: not property_set["property_fixed_point"],
)
new_passmanager = self.passmanager[1]
expected = [
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run analysis pass PassG_calculates_dag_property",
"set property as 5 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run analysis pass PassG_calculates_dag_property",
"set property as 4 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
"run analysis pass PassG_calculates_dag_property",
"set property as 3 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
]
self.assertScheduler(self.circuit, new_passmanager, expected)
def test_accessing_passmanager_by_range(self):
"""test accessing PassManager's passes by range"""
self.passmanager.append(PassC_TP_RA_PA())
self.passmanager.append(PassB_TP_RA_PA())
self.passmanager.append(PassC_TP_RA_PA())
self.passmanager.append(PassD_TP_NR_NP())
new_passmanager = self.passmanager[1:3]
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, new_passmanager, expected)
def test_accessing_passmanager_by_range_with_condition(self):
"""test accessing PassManager's passes by range with condition"""
self.passmanager.append(PassB_TP_RA_PA())
self.passmanager.append(PassE_AP_NR_NP(True))
self.passmanager.append(
PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"]
)
self.passmanager.append(PassB_TP_RA_PA())
new_passmanager = self.passmanager[1:3]
expected = [
"run analysis pass PassE_AP_NR_NP",
"set property as True",
"run transformation pass PassA_TP_NR_NP",
]
self.assertScheduler(self.circuit, new_passmanager, expected)
def test_accessing_passmanager_error(self):
"""testing accessing a pass item not in list"""
self.passmanager.append(PassB_TP_RA_PA())
with self.assertRaises(IndexError):
self.passmanager = self.passmanager[99]
class TestPassManagerConcatenation(SchedulerTestCase):
"""test PassManager concatenation by + operator."""
def setUp(self):
super().setUp()
self.passmanager1 = PassManager()
self.passmanager2 = PassManager()
self.circuit = QuantumCircuit(QuantumRegister(1))
def test_concatenating_passmanagers(self):
"""test adding two PassManagers together"""
self.passmanager1.append(PassB_TP_RA_PA())
self.passmanager2.append(PassC_TP_RA_PA())
new_passmanager = self.passmanager1 + self.passmanager2
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, new_passmanager, expected)
def test_concatenating_passmanagers_with_condition(self):
"""test adding two pass managers with condition"""
self.passmanager1.append(PassE_AP_NR_NP(True))
self.passmanager1.append(PassB_TP_RA_PA())
self.passmanager2.append(
PassC_TP_RA_PA(), condition=lambda property_set: property_set["property"]
)
self.passmanager2.append(PassB_TP_RA_PA())
new_passmanager = self.passmanager1 + self.passmanager2
expected = [
"run analysis pass PassE_AP_NR_NP",
"set property as True",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
]
self.assertScheduler(self.circuit, new_passmanager, expected)
def test_adding_pass_to_passmanager(self):
"""test adding a pass to PassManager"""
self.passmanager1.append(PassE_AP_NR_NP(argument1=1))
self.passmanager1.append(PassB_TP_RA_PA())
self.passmanager1 += PassC_TP_RA_PA()
expected = [
"run analysis pass PassE_AP_NR_NP",
"set property as 1",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager1, expected)
def test_adding_list_of_passes_to_passmanager(self):
"""test adding a list of passes to PassManager"""
self.passmanager1.append(PassE_AP_NR_NP(argument1=1))
self.passmanager1.append(PassB_TP_RA_PA())
self.passmanager1 += [PassC_TP_RA_PA(), PassB_TP_RA_PA()]
expected = [
"run analysis pass PassE_AP_NR_NP",
"set property as 1",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager1, expected)
def test_adding_list_of_passes_to_passmanager_with_condition(self):
"""test adding a list of passes to a PassManager that have conditions"""
self.passmanager1.append(PassE_AP_NR_NP(False))
self.passmanager1.append(
PassB_TP_RA_PA(), condition=lambda property_set: property_set["property"]
)
self.passmanager1 += PassC_TP_RA_PA()
expected = [
"run analysis pass PassE_AP_NR_NP",
"set property as False",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager1, expected)
def test_adding_pass_to_passmanager_error(self):
"""testing adding a non-pass item to PassManager"""
with self.assertRaises(TypeError):
self.passmanager1 += "not a pass"
def test_adding_list_to_passmanager_error(self):
"""testing adding a list having a non-pass item to PassManager"""
with self.assertRaises(TypeError):
self.passmanager1 += [PassB_TP_RA_PA(), "not a pass"]
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Kraus, SuperOp
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,
pauli_error, depolarizing_error, thermal_relaxation_error)
# Construct a 1-qubit bit-flip and phase-flip errors
p_error = 0.05
bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)])
phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)])
print(bit_flip)
print(phase_flip)
# Compose two bit-flip and phase-flip errors
bitphase_flip = bit_flip.compose(phase_flip)
print(bitphase_flip)
# Tensor product two bit-flip and phase-flip errors with
# bit-flip on qubit-0, phase-flip on qubit-1
error2 = phase_flip.tensor(bit_flip)
print(error2)
# Convert to Kraus operator
bit_flip_kraus = Kraus(bit_flip)
print(bit_flip_kraus)
# Convert to Superoperator
phase_flip_sop = SuperOp(phase_flip)
print(phase_flip_sop)
# Convert back to a quantum error
print(QuantumError(bit_flip_kraus))
# Check conversion is equivalent to original error
QuantumError(bit_flip_kraus) == bit_flip
# Measurement miss-assignement probabilities
p0given1 = 0.1
p1given0 = 0.05
ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]])
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates
error = depolarizing_error(0.05, 1)
noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3'])
# Print noise model info
print(noise_model)
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only
error = depolarizing_error(0.05, 1)
noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0])
# Print noise model info
print(noise_model)
# System Specification
n_qubits = 4
circ = QuantumCircuit(n_qubits)
# Test Circuit
circ.h(0)
for qubit in range(n_qubits - 1):
circ.cx(qubit, qubit + 1)
circ.measure_all()
print(circ)
# Ideal simulator and execution
sim_ideal = AerSimulator()
result_ideal = sim_ideal.run(circ).result()
plot_histogram(result_ideal.get_counts(0))
# Example error probabilities
p_reset = 0.03
p_meas = 0.1
p_gate1 = 0.05
# QuantumError objects
error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)])
error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)])
error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)])
error_gate2 = error_gate1.tensor(error_gate1)
# Add errors to noise model
noise_bit_flip = NoiseModel()
noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset")
noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure")
noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"])
noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"])
print(noise_bit_flip)
# Create noisy simulator backend
sim_noise = AerSimulator(noise_model=noise_bit_flip)
# Transpile circuit for noisy basis gates
circ_tnoise = transpile(circ, sim_noise)
# Run and get counts
result_bit_flip = sim_noise.run(circ_tnoise).result()
counts_bit_flip = result_bit_flip.get_counts(0)
# Plot noisy output
plot_histogram(counts_bit_flip)
# T1 and T2 values for qubits 0-3
T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
# Truncate random T2s <= T1s
T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)])
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_reset[j], "reset", [j])
noise_thermal.add_quantum_error(errors_measure[j], "measure", [j])
noise_thermal.add_quantum_error(errors_u1[j], "u1", [j])
noise_thermal.add_quantum_error(errors_u2[j], "u2", [j])
noise_thermal.add_quantum_error(errors_u3[j], "u3", [j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k])
print(noise_thermal)
# Run the noisy simulation
sim_thermal = AerSimulator(noise_model=noise_thermal)
# Transpile circuit for noisy basis gates
circ_tthermal = transpile(circ, sim_thermal)
# Run and get counts
result_thermal = sim_thermal.run(circ_tthermal).result()
counts_thermal = result_thermal.get_counts(0)
# Plot noisy output
plot_histogram(counts_thermal)
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/BankNatchapol/Quantum-Classical-Logic-Gate
|
BankNatchapol
|
import sys
import numpy as np
from matplotlib import pyplot as plt
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, visualization
from random import randint
def to_binary(N,n_bit):
Nbin = np.zeros(n_bit, dtype=bool)
for i in range(1,n_bit+1):
bit_state = (N % (2**i) != 0)
if bit_state:
N -= 2**(i-1)
Nbin[n_bit-i] = bit_state
return Nbin
def modular_multiplication(qc,a,N):
"""
applies the unitary operator that implements
modular multiplication function x -> a*x(modN)
Only works for the particular case x -> 7*x(mod15)!
"""
for i in range(0,3):
qc.x(i)
qc.cx(2,1)
qc.cx(1,2)
qc.cx(2,1)
qc.cx(1,0)
qc.cx(0,1)
qc.cx(1,0)
qc.cx(3,0)
qc.cx(0,1)
qc.cx(1,0)
def quantum_period(a, N, n_bit):
# Quantum part
print(" Searching the period for N =", N, "and a =", a)
qr = QuantumRegister(n_bit)
cr = ClassicalRegister(n_bit)
qc = QuantumCircuit(qr,cr)
simulator = Aer.get_backend('qasm_simulator')
s0 = randint(1, N-1) # Chooses random int
sbin = to_binary(s0,n_bit) # Turns to binary
print("\n Starting at \n s =", s0, "=", "{0:b}".format(s0), "(bin)")
# Quantum register is initialized with s (in binary)
for i in range(0,n_bit):
if sbin[n_bit-i-1]:
qc.x(i)
s = s0
r=-1 # makes while loop run at least 2 times
# Applies modular multiplication transformation until we come back to initial number s
while s != s0 or r <= 0:
r+=1
# sets up circuit structure
qc.measure(qr, cr)
modular_multiplication(qc,a,N)
qc.draw('mpl')
# runs circuit and processes data
job = execute(qc,simulator, shots=10)
result_counts = job.result().get_counts(qc)
result_histogram_key = list(result_counts)[0] # https://qiskit.org/documentation/stubs/qiskit.result.Result.get_counts.html#qiskit.result.Result.get_counts
s = int(result_histogram_key, 2)
print(" ", result_counts)
plt.show()
print("\n Found period r =", r)
return r
if __name__ == '__main__':
a = 7
N = 15
n_bit=5
r = quantum_period(a, N, n_bit)
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Qiskit's QuantumCircuit class for multiple registers."""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.circuit.exceptions import CircuitError
class TestCircuitMultiRegs(QiskitTestCase):
"""QuantumCircuit Qasm tests."""
def test_circuit_multi(self):
"""Test circuit multi regs declared at start."""
qreg0 = QuantumRegister(2, "q0")
creg0 = ClassicalRegister(2, "c0")
qreg1 = QuantumRegister(2, "q1")
creg1 = ClassicalRegister(2, "c1")
circ = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circ.x(qreg0[1])
circ.x(qreg1[0])
meas = QuantumCircuit(qreg0, qreg1, creg0, creg1)
meas.measure(qreg0, creg0)
meas.measure(qreg1, creg1)
qc = circ.compose(meas)
circ2 = QuantumCircuit()
circ2.add_register(qreg0)
circ2.add_register(qreg1)
circ2.add_register(creg0)
circ2.add_register(creg1)
circ2.x(qreg0[1])
circ2.x(qreg1[0])
meas2 = QuantumCircuit()
meas2.add_register(qreg0)
meas2.add_register(qreg1)
meas2.add_register(creg0)
meas2.add_register(creg1)
meas2.measure(qreg0, creg0)
meas2.measure(qreg1, creg1)
qc2 = circ2.compose(meas2)
dag_qc = circuit_to_dag(qc)
dag_qc2 = circuit_to_dag(qc2)
dag_circ2 = circuit_to_dag(circ2)
dag_circ = circuit_to_dag(circ)
self.assertEqual(dag_qc, dag_qc2)
self.assertEqual(dag_circ, dag_circ2)
def test_circuit_multi_name_collision(self):
"""Test circuit multi regs, with name collision."""
qreg0 = QuantumRegister(2, "q")
qreg1 = QuantumRegister(3, "q")
self.assertRaises(CircuitError, QuantumCircuit, qreg0, qreg1)
|
https://github.com/Varary73/Visualising-Quantum-Time-Evolution-using-Qiskit
|
Varary73
|
# !pip install qiskit
# !pip install pylatexenc
from qiskit import *
import numpy as np
from matplotlib import pyplot as plt
from qiskit.visualization import plot_histogram
from qiskit.circuit.library import QFT
import pylatexenc
#Number of qubits
n=6
#Circuit
phi=0.1 #time step
iterations=30 #iterations
#Potential
V=1.75
#Spatial Grid
N=2**n #grid points
xMin=-4
xMax=4
x = np.linspace(xMin,xMax, num=N)
#Wavefunction
mu=-2.25
psi= (1/(np.sqrt(2*np.pi)*2*0.4)*np.exp(-(0.5*(x-mu)**2)/(2*0.016)))*np.exp(-300j*x)
psi/= np.sqrt(np.sum(np.abs(psi**2)))
plt.plot(x,psi)
qubits=QuantumRegister(n+1)
splitOp=QuantumCircuit(qubits,name="splitOp")
'''potential operator'''
splitOp.ccx(3,4,0)
splitOp.cp(V*phi,0,5)
splitOp.ccx(3,4,0)
splitOp.barrier()
'''momentum operator'''
splitOp.append(QFT(n),qubits[1:])
for i in range(n):
splitOp.p(phi/2**(n-3+i), n-i)
for i in range(n):
for j in range(i+1,n):
splitOp.cx(n-j,0)
splitOp.cx(n-i,0)
splitOp.p(phi*(2**(2-i-j)),0)
splitOp.cx(n-i,0)
splitOp.cx(n-j,0)
splitOp.append(QFT(n,inverse=True),qubits[1:])
splitOp.barrier()
splitOp.draw('mpl')
q=QuantumRegister(n+1)
c=ClassicalRegister(n)
circuit=QuantumCircuit(q,c)
'''initialization'''
circuit.initialize(psi,q[1:])
circuit.barrier()
'''time steps'''
for i in range(iterations):
circuit.append(splitOp,q[:])
'''measurement'''
for i in range(1,n+1):
circuit.measure(i,i-1)
#circuit.draw('mpl')
answer = execute(circuit, backend=BasicAer.get_backend('qasm_simulator'), shots=5000).result().get_counts()
for a in range(N):
s = bin(a)[2:]
while len(s)!=6:
s='0'+s
if s not in answer.keys():
answer[s] = 0
plot_histogram(answer, figsize = [20,10])
new_psi=np.zeros(N)
count=0
for key in sorted(answer.keys()):
new_psi[count]=answer[key]
count+=1
new_psi=new_psi/np.sqrt(np.sum(psi**2))
barrier=np.zeros(N)
barrier[14:16]=20000
print(np.sum(np.abs(psi**2)))
plt.plot(x,new_psi)
plt.plot(x,barrier)
plt.show()
|
https://github.com/gatchan00/QPlex
|
gatchan00
|
%config IPCompleter.greedy=True
%matplotlib inline
from qplex_core import *
precision = 6
coefs_param = [2, -3]
beta = 7
a = wrapper_optimiza_f(precision, coefs_param, beta)
print(a)
#tú mandas la función 2*X-3*Y,
#La precisión para representar enteros es de 6 qbits por número (usamos los X e Y y le añadimos un Z)
#como restricción se manda X*y<=6
#El resultado es {0: 0, 1: 7}, que quiere decir, que X vale 0 e Y vale 7
# useful additional packages
import matplotlib.pyplot as plt
import matplotlib.axes as axes
import numpy as np
import networkx as nx
from qiskit import BasicAer
from qiskit.tools.visualization import plot_histogram
from qiskit.aqua import Operator, run_algorithm
from qiskit.aqua.input import EnergyInput
from qiskit.aqua.translators.ising import max_cut, tsp
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua.components.variational_forms import RY
from qiskit.aqua import QuantumInstance
# setup aqua logging
import logging
from qiskit.aqua import set_qiskit_aqua_logging
# set_qiskit_aqua_logging(logging.DEBUG) # choose INFO, DEBUG to see the log
from docplex.mp.model import Model
from qiskit.aqua.translators.ising import docplex
from qplex_core import *
def mainJGOS():
precision = 6
coefs_param = [2, -3 ]
coefs = coefs_param.copy()
coefs.append(0)
coefs_restr = (1, 1, 1)
beta = 7
lista_vars = ['a', 'b', 'c', 'd', 'e','f','g','h']
mdl = Model()
variables = []
for num_var in range(len(coefs)):
tmp ={i: mdl.binary_var(name=(lista_vars[num_var]+'_{0}').format(i)) for i in range(precision)}
variables.append(tmp)
#x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(precision)}
#y = {i: mdl.binary_var(name='y_{0}'.format(i)) for i in range(precision)}
#z = {i: mdl.binary_var(name='z_{0}'.format(i)) for i in range(precision)}
print(variables)
# Object function
#my_func = mdl.sum(coefs[0]*(2**i)*x[i]+coefs[1]*(2**i)*y[i]+(2**i)*coefs[2]*z[i] for i in range(precision))
#my_func = mdl.sum(coefs[j]*(2**i)*vars[j][i] for j in range(len(coefs)) for i in range(precision))
my_func = mdl.sum(coefs[j]*(2**i)*variables[j][i] for j in range(len(coefs)) for i in range(precision))
#(x[i] for i in range(precision)), (y[i] for i in range(precision)), (z[i] for i in range(precision)
#tmp = {0:{'var':x,'coef':coefs_restr[0]},
# 1:{'var':y,'coef':coefs_restr[1]},
# 2:{'var':z,'coef':coefs_restr[2]}}
mdl.maximize(my_func)
inverted_beta = dameInversoBinario(beta, precision, len(coefs))
#mdl.add_constraint(mdl.sum( tmp[v]['var'][i]*(2**i)*tmp[v]['coef'] for v in range(len(coefs)) for i in range(precision)) == beta)
#mdl.add_constraint(mdl.sum( x[0] + x[1]*(2) + x[2]*(4) + y[0] + y[1]*(2) + y[2]*(4) + z[0] + z[1]*(2) + z[2]*(4) ) == inverted_beta)
#mdl.add_constraint(mdl.sum( variables[0][0] + variables[0][1]*(2) + variables[0][2]*(4) + variables[1][0] + variables[1][1]
#*(2) + variables[1][2]*(4) + variables[2][0] + variables[2][1]*(2) + variables[2][2]*(4) ) == inverted_beta)
mdl.add_constraint(mdl.sum(variables[v][i]*2**i for v in range(len(coefs)) for i in range(precision)) == inverted_beta)
#mdl.add_constraint(mdl.sum( -x[0] - x[1]*(2) - x[2]*(4) - y[0] - y[1]*(2) - y[2]*(4) - z[0] - z[1]*(2) - z[2]*(4) ) == 6)
#mdl.add_constraint(mdl.sum( -1*tmp[v]['var'][i]*(2**i)*tmp[v]['coef'] for v in range(len(coefs)) for i in range(precision)) == -beta)
qubitOp_docplex, offset_docplex = docplex.get_qubitops(mdl)
print(qubitOp_docplex)
#algo_input = EnergyInput(qubitOp_docplex)
#print(algo_input.)
#ee = VQE(qubitOp_docplex)
#ee.run()
ee = ExactEigensolver(qubitOp_docplex, k=1)
result_ee = ee.run()
x_ee = max_cut.sample_most_likely(result_ee['eigvecs'][0])
print('solution:', max_cut.get_graph_solution(x_ee))
solucion_ee = max_cut.get_graph_solution(x_ee)
return (solucion_ee, None)
"""
algorithm_cfg = {
'name': 'ExactEigensolver',
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg
}
result = run_algorithm(params,algo_input)
"""
#x = max_cut.sample_most_likely(result['eigvecs'][0])
#print('energy:', result['energy'])
#print('max-cut objective:', result['energy'] + offset_docplex)
#print('solution:', max_cut.get_graph_solution(x))
#print('solution objective:', max_cut.max_cut_value(x, w))
seed = 10598
#change optimizer(spsa), change ry (riyc)
spsa = SPSA(max_trials=300)
ry = RY(qubitOp_docplex.num_qubits, depth=6, entanglement='linear')
vqe = VQE(qubitOp_docplex, ry, spsa, 'matrix')
backend = BasicAer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend, seed=seed, seed_transpiler=seed)
result = vqe.run(quantum_instance)
x = max_cut.sample_most_likely(result['eigvecs'][0])
print('solution:', max_cut.get_graph_solution(x))
return (solucion_ee, max_cut.get_graph_solution(x))
resultado = mainJGOS()
r_ee = resultado[0]
vars = np.array_split(r_ee, 3)
tam = len(vars)
for i in range(tam):
curr = vars[i]
curr_i = np.flip(curr)
curr_i = [ str(int(k)) for k in curr_i ]
en_binario = "".join(list(curr_i))
curr_var = int(en_binario, 2)
if i != tam-1:
print("Var %d = %d" %(i,curr_var))
|
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.
"""CircuitSampler Class"""
import logging
from functools import partial
from time import time
from typing import Any, Dict, List, Optional, Tuple, Union, cast
import numpy as np
from qiskit import QiskitError
from qiskit.circuit import Parameter, ParameterExpression, QuantumCircuit
from qiskit.opflow.converters.converter_base import ConverterBase
from qiskit.opflow.exceptions import OpflowError
from qiskit.opflow.list_ops.list_op import ListOp
from qiskit.opflow.operator_base import OperatorBase
from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn
from qiskit.opflow.state_fns.dict_state_fn import DictStateFn
from qiskit.opflow.state_fns.state_fn import StateFn
from qiskit.providers import Backend
from qiskit.utils.backend_utils import is_aer_provider, is_statevector_backend
from qiskit.utils.quantum_instance import QuantumInstance
from qiskit.utils.deprecation import deprecate_func
logger = logging.getLogger(__name__)
class CircuitSampler(ConverterBase):
"""
Deprecated: The CircuitSampler traverses an Operator and converts any CircuitStateFns into
approximations of the state function by a DictStateFn or VectorStateFn using a quantum
backend. Note that in order to approximate the value of the CircuitStateFn, it must 1) send
state function through a depolarizing channel, which will destroy all phase information and
2) replace the sampled frequencies with **square roots** of the frequency, rather than the raw
probability of sampling (which would be the equivalent of sampling the **square** of the
state function, per the Born rule.
The CircuitSampler aggressively caches transpiled circuits to handle re-parameterization of
the same circuit efficiently. If you are converting multiple different Operators,
you are better off using a different CircuitSampler for each Operator to avoid cache thrashing.
"""
@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(
self,
backend: Union[Backend, QuantumInstance],
statevector: Optional[bool] = None,
param_qobj: bool = False,
attach_results: bool = False,
caching: str = "last",
) -> None:
"""
Args:
backend: The quantum backend or QuantumInstance to use to sample the circuits.
statevector: If backend is a statevector backend, whether to replace the
CircuitStateFns with DictStateFns (from the counts) or VectorStateFns (from the
statevector). ``None`` will set this argument automatically based on the backend.
attach_results: Whether to attach the data from the backend ``Results`` object for
a given ``CircuitStateFn``` to an ``execution_results`` field added the converted
``DictStateFn`` or ``VectorStateFn``.
param_qobj: Whether to use Aer's parameterized Qobj capability to avoid re-assembling
the circuits.
caching: The caching strategy. Can be `'last'` (default) to store the last operator
that was converted, set to `'all'` to cache all processed operators.
Raises:
ValueError: Set statevector or param_qobj True when not supported by backend.
"""
super().__init__()
self._quantum_instance = (
backend if isinstance(backend, QuantumInstance) else QuantumInstance(backend=backend)
)
self._statevector = (
statevector if statevector is not None else self.quantum_instance.is_statevector
)
self._param_qobj = param_qobj
self._attach_results = attach_results
self._check_quantum_instance_and_modes_consistent()
# Object state variables
self._caching = caching
self._cached_ops: Dict[int, OperatorCache] = {}
self._last_op: Optional[OperatorBase] = None
self._reduced_op_cache = None
self._circuit_ops_cache: Dict[int, CircuitStateFn] = {}
self._transpiled_circ_cache: Optional[List[Any]] = None
self._transpiled_circ_templates: Optional[List[Any]] = None
self._transpile_before_bind = True
def _check_quantum_instance_and_modes_consistent(self) -> None:
"""Checks whether the statevector and param_qobj settings are compatible with the
backend
Raises:
ValueError: statevector or param_qobj are True when not supported by backend.
"""
if self._statevector and not is_statevector_backend(self.quantum_instance.backend):
raise ValueError(
"Statevector mode for circuit sampling requires statevector "
"backend, not {}.".format(self.quantum_instance.backend)
)
if self._param_qobj and not is_aer_provider(self.quantum_instance.backend):
raise ValueError(
"Parameterized Qobj mode requires Aer "
"backend, not {}.".format(self.quantum_instance.backend)
)
@property
def quantum_instance(self) -> QuantumInstance:
"""Returns the quantum instance.
Returns:
The QuantumInstance used by the CircuitSampler
"""
return self._quantum_instance
@quantum_instance.setter
def quantum_instance(self, quantum_instance: Union[QuantumInstance, Backend]) -> None:
"""Sets the QuantumInstance.
Raises:
ValueError: statevector or param_qobj are True when not supported by backend.
"""
if isinstance(quantum_instance, Backend):
quantum_instance = QuantumInstance(quantum_instance)
self._quantum_instance = quantum_instance
self._check_quantum_instance_and_modes_consistent()
def convert(
self,
operator: OperatorBase,
params: Optional[Dict[Parameter, Union[float, List[float], List[List[float]]]]] = None,
) -> OperatorBase:
r"""
Converts the Operator to one in which the CircuitStateFns are replaced by
DictStateFns or VectorStateFns. Extracts the CircuitStateFns out of the Operator,
caches them, calls ``sample_circuits`` below to get their converted replacements,
and replaces the CircuitStateFns in operator with the replacement StateFns.
Args:
operator: The Operator to convert
params: A dictionary mapping parameters to either single binding values or lists of
binding values.
Returns:
The converted Operator with CircuitStateFns replaced by DictStateFns or VectorStateFns.
Raises:
OpflowError: if extracted circuits are empty.
"""
# check if the operator should be cached
op_id = operator.instance_id
# op_id = id(operator)
if op_id not in self._cached_ops.keys():
# delete cache if we only want to cache one operator
if self._caching == "last":
self.clear_cache()
# convert to circuit and reduce
operator_dicts_replaced = operator.to_circuit_op()
self._reduced_op_cache = operator_dicts_replaced.reduce()
# extract circuits
self._circuit_ops_cache = {}
self._extract_circuitstatefns(self._reduced_op_cache)
if not self._circuit_ops_cache:
raise OpflowError(
"Circuits are empty. "
"Check that the operator is an instance of CircuitStateFn or its ListOp."
)
self._transpiled_circ_cache = None
self._transpile_before_bind = True
else:
# load the cached circuits
self._reduced_op_cache = self._cached_ops[op_id].reduced_op_cache
self._circuit_ops_cache = self._cached_ops[op_id].circuit_ops_cache
self._transpiled_circ_cache = self._cached_ops[op_id].transpiled_circ_cache
self._transpile_before_bind = self._cached_ops[op_id].transpile_before_bind
self._transpiled_circ_templates = self._cached_ops[op_id].transpiled_circ_templates
return_as_list = False
if params is not None and len(params.keys()) > 0:
p_0 = list(params.values())[0]
if isinstance(p_0, (list, np.ndarray)):
num_parameterizations = len(p_0)
param_bindings = [
{param: value_list[i] for param, value_list in params.items()} # type: ignore
for i in range(num_parameterizations)
]
return_as_list = True
else:
num_parameterizations = 1
param_bindings = [params]
else:
param_bindings = None
num_parameterizations = 1
# Don't pass circuits if we have in the cache, the sampling function knows to use the cache
circs = list(self._circuit_ops_cache.values()) if not self._transpiled_circ_cache else None
p_b = cast(List[Dict[Parameter, float]], param_bindings)
sampled_statefn_dicts = self.sample_circuits(circuit_sfns=circs, param_bindings=p_b)
def replace_circuits_with_dicts(operator, param_index=0):
if isinstance(operator, CircuitStateFn):
return sampled_statefn_dicts[id(operator)][param_index]
elif isinstance(operator, ListOp):
return operator.traverse(
partial(replace_circuits_with_dicts, param_index=param_index)
)
else:
return operator
# store the operator we constructed, if it isn't stored already
if op_id not in self._cached_ops.keys():
op_cache = OperatorCache()
op_cache.reduced_op_cache = self._reduced_op_cache
op_cache.circuit_ops_cache = self._circuit_ops_cache
op_cache.transpiled_circ_cache = self._transpiled_circ_cache
op_cache.transpile_before_bind = self._transpile_before_bind
op_cache.transpiled_circ_templates = self._transpiled_circ_templates
self._cached_ops[op_id] = op_cache
if return_as_list:
return ListOp(
[
replace_circuits_with_dicts(self._reduced_op_cache, param_index=i)
for i in range(num_parameterizations)
]
)
else:
return replace_circuits_with_dicts(self._reduced_op_cache, param_index=0)
def clear_cache(self) -> None:
"""Clear the cache of sampled operator expressions."""
self._cached_ops = {}
def _extract_circuitstatefns(self, operator: OperatorBase) -> None:
r"""
Recursively extract the ``CircuitStateFns`` contained in operator into the
``_circuit_ops_cache`` field.
"""
if isinstance(operator, CircuitStateFn):
self._circuit_ops_cache[id(operator)] = operator
elif isinstance(operator, ListOp):
for op in operator.oplist:
self._extract_circuitstatefns(op)
def sample_circuits(
self,
circuit_sfns: Optional[List[CircuitStateFn]] = None,
param_bindings: Optional[List[Dict[Parameter, float]]] = None,
) -> Dict[int, List[StateFn]]:
r"""
Samples the CircuitStateFns and returns a dict associating their ``id()`` values to their
replacement DictStateFn or VectorStateFn. If param_bindings is provided,
the CircuitStateFns are broken into their parameterizations, and a list of StateFns is
returned in the dict for each circuit ``id()``. Note that param_bindings is provided here
in a different format than in ``convert``, and lists of parameters within the dict is not
supported, and only binding dicts which are valid to be passed into Terra can be included
in this list.
Args:
circuit_sfns: The list of CircuitStateFns to sample.
param_bindings: The parameterizations to bind to each CircuitStateFn.
Returns:
The dictionary mapping ids of the CircuitStateFns to their replacement StateFns.
Raises:
OpflowError: if extracted circuits are empty.
"""
if not circuit_sfns and not self._transpiled_circ_cache:
raise OpflowError("CircuitStateFn is empty and there is no cache.")
if circuit_sfns:
self._transpiled_circ_templates = None
if self._statevector or circuit_sfns[0].from_operator:
circuits = [op_c.to_circuit(meas=False) for op_c in circuit_sfns]
else:
circuits = [op_c.to_circuit(meas=True) for op_c in circuit_sfns]
try:
self._transpiled_circ_cache = self.quantum_instance.transpile(
circuits, pass_manager=self.quantum_instance.unbound_pass_manager
)
except QiskitError:
logger.debug(
r"CircuitSampler failed to transpile circuits with unbound "
r"parameters. Attempting to transpile only when circuits are bound "
r"now, but this can hurt performance due to repeated transpilation."
)
self._transpile_before_bind = False
self._transpiled_circ_cache = circuits
else:
circuit_sfns = list(self._circuit_ops_cache.values())
if param_bindings is not None:
if self._param_qobj:
start_time = time()
ready_circs = self._prepare_parameterized_run_config(param_bindings)
end_time = time()
logger.debug("Parameter conversion %.5f (ms)", (end_time - start_time) * 1000)
else:
start_time = time()
ready_circs = [
circ.assign_parameters(_filter_params(circ, binding))
for circ in self._transpiled_circ_cache
for binding in param_bindings
]
end_time = time()
logger.debug("Parameter binding %.5f (ms)", (end_time - start_time) * 1000)
else:
ready_circs = self._transpiled_circ_cache
# run transpiler passes on bound circuits
if self._transpile_before_bind and self.quantum_instance.bound_pass_manager is not None:
ready_circs = self.quantum_instance.transpile(
ready_circs, pass_manager=self.quantum_instance.bound_pass_manager
)
results = self.quantum_instance.execute(
ready_circs, had_transpiled=self._transpile_before_bind
)
if param_bindings is not None and self._param_qobj:
self._clean_parameterized_run_config()
# Wipe parameterizations, if any
# self.quantum_instance._run_config.parameterizations = None
sampled_statefn_dicts = {}
for i, op_c in enumerate(circuit_sfns):
# Taking square root because we're replacing a statevector
# representation of probabilities.
reps = len(param_bindings) if param_bindings is not None else 1
c_statefns = []
for j in range(reps):
circ_index = (i * reps) + j
circ_results = results.data(circ_index)
if "expval_measurement" in circ_results:
avg = circ_results["expval_measurement"]
# Will be replaced with just avg when eval is called later
num_qubits = circuit_sfns[0].num_qubits
result_sfn = DictStateFn(
"0" * num_qubits,
coeff=avg * op_c.coeff,
is_measurement=op_c.is_measurement,
from_operator=op_c.from_operator,
)
elif self._statevector:
result_sfn = StateFn(
op_c.coeff * results.get_statevector(circ_index),
is_measurement=op_c.is_measurement,
)
else:
shots = self.quantum_instance._run_config.shots
result_sfn = DictStateFn(
{
b: (v / shots) ** 0.5 * op_c.coeff
for (b, v) in results.get_counts(circ_index).items()
},
is_measurement=op_c.is_measurement,
from_operator=op_c.from_operator,
)
if self._attach_results:
result_sfn.execution_results = circ_results
c_statefns.append(result_sfn)
sampled_statefn_dicts[id(op_c)] = c_statefns
return sampled_statefn_dicts
def _build_aer_params(
self,
circuit: QuantumCircuit,
building_param_tables: Dict[Tuple[int, int], List[float]],
input_params: Dict[Parameter, float],
) -> None:
def resolve_param(inst_param):
if not isinstance(inst_param, ParameterExpression):
return None
param_mappings = {}
for param in inst_param._parameter_symbols.keys():
if param not in input_params:
raise ValueError(f"unexpected parameter: {param}")
param_mappings[param] = input_params[param]
return float(inst_param.bind(param_mappings))
gate_index = 0
for instruction in circuit.data:
param_index = 0
for inst_param in instruction.operation.params:
val = resolve_param(inst_param)
if val is not None:
param_key = (gate_index, param_index)
if param_key in building_param_tables:
building_param_tables[param_key].append(val)
else:
building_param_tables[param_key] = [val]
param_index += 1
gate_index += 1
def _prepare_parameterized_run_config(
self, param_bindings: List[Dict[Parameter, float]]
) -> List[Any]:
self.quantum_instance._run_config.parameterizations = []
if self._transpiled_circ_templates is None or len(self._transpiled_circ_templates) != len(
self._transpiled_circ_cache
):
# temporally resolve parameters of self._transpiled_circ_cache
# They will be overridden in Aer from the next iterations
self._transpiled_circ_templates = [
circ.assign_parameters(_filter_params(circ, param_bindings[0]))
for circ in self._transpiled_circ_cache
]
for circ in self._transpiled_circ_cache:
building_param_tables: Dict[Tuple[int, int], List[float]] = {}
for param_binding in param_bindings:
self._build_aer_params(circ, building_param_tables, param_binding)
param_tables = []
for gate_and_param_indices in building_param_tables:
gate_index = gate_and_param_indices[0]
param_index = gate_and_param_indices[1]
param_tables.append(
[[gate_index, param_index], building_param_tables[(gate_index, param_index)]]
)
self.quantum_instance._run_config.parameterizations.append(param_tables)
return self._transpiled_circ_templates
def _clean_parameterized_run_config(self) -> None:
self.quantum_instance._run_config.parameterizations = []
def _filter_params(circuit, param_dict):
"""Remove all parameters from ``param_dict`` that are not in ``circuit``."""
return {param: value for param, value in param_dict.items() if param in circuit.parameters}
class OperatorCache:
"""A struct to cache an operator along with the circuits in contains."""
reduced_op_cache = None # the reduced operator
circuit_ops_cache: Optional[Dict[int, CircuitStateFn]] = None # the extracted circuits
transpiled_circ_cache = None # the transpiled circuits
transpile_before_bind = True # whether to transpile before binding parameters in the operator
transpiled_circ_templates: Optional[List[Any]] = None # transpiled circuit templates for Aer
|
https://github.com/Qottmann/Quantum-anomaly-detection
|
Qottmann
|
import time
import datetime
import numpy as np
from matplotlib import pyplot as plt
import qiskit
from qiskit import *
from qiskit.opflow import X,Z,I
from qiskit.opflow.state_fns import StateFn, CircuitStateFn
from qiskit.providers.aer import StatevectorSimulator, AerSimulator
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA
from scipy import sparse
import scipy.sparse.linalg.eigen.arpack as arp
from modules.utils import *
gz = 0
anti = 1
gx = 1e-1
L = 5
num_trash = 2
name = f"qsim_params_VQE_Ising_L{L:.0f}_anti_{anti:.0f}_single-jobs"
filename = 'data/' + name
print(filename)
# more in-depth noise models https://qiskit.org/documentation/tutorials/simulators/2_device_noise_simulation.html
#backend = qiskit.Aer.get_backend('qasm_simulator') # apparently outdated (legacy)
IBMQ.load_account() # this then automatically loads your saved account
provider = IBMQ.get_provider(hub='ibm-q-research')
from qiskit.providers.ibmq import least_busy
small_devices = provider.backends(filters=lambda x: x.configuration().n_qubits == 5
and not x.configuration().simulator)
least_busy(small_devices)
#provider.backends(simulator=False, operational=True)
backend = least_busy(small_devices)
backend
backend.status().pending_jobs
backend_sim = qiskit.providers.aer.AerSimulator.from_backend(backend)
ansatz = qiskit.circuit.library.EfficientSU2(L, reps=3)
ansatz = qiskit.transpile(ansatz, backend)
#optimizer = SLSQP(maxiter=1000)
#optimizer = COBYLA(maxiter=1000)
optimizer = SPSA(maxiter=1000)
vqe = VQE(ansatz, optimizer, quantum_instance=backend)
from qiskit.tools.monitor import job_monitor
# Number of shots to run the program (experiment);
# maximum is 8192 shots.
shots = 1024
# Maximum number of credits to spend on executions.
max_credits = 3
job_exp = execute(qc, backend, shots=shots, max_credits=max_credits)
job_monitor(job_exp)
t0 = datetime.datetime.now()
H = QHIsing(L,anti,np.float32(gx),np.float32(gz))
result = vqe.compute_minimum_eigenvalue(H, aux_operators=[QMag(L,anti)]) #ED with Qiskit VQE
print(f"elapsed time {datetime.datetime.now()-t0}")
# ED
ED_state, E, ham = ising_groundstate(L, anti, np.float32(gx), np.float32(gz))
print(f"ED energy: {E} ;; VQE energy: {result.eigenvalue}")
print(f"ED mag: {ED_state.T.conj()@Mag(L,anti)@ED_state} ;; VQE mag: {result.aux_operator_eigenvalues}")
phis = [sort_params(result.optimal_parameters)] # needs to be called phis for later
vqe2 = VQE(qiskit.circuit.library.EfficientSU2(L, reps=3), optimizer, quantum_instance=StatevectorSimulator())
t0 = datetime.datetime.now()
result2 = vqe2.compute_minimum_eigenvalue(H, aux_operators=[QMag(L,anti)]) #ED with Qiskit VQE
print(f"elapsed time {datetime.datetime.now()-t0}")
phis = []
phis.append(sort_params(result2.optimal_parameters))
state = init_vqe(phis[-1], L=L)
state = qiskit.transpile(state, backend)
meas_outcome = ~StateFn(QMag(L,anti)) @ StateFn(state)
Qmag2 = meas_outcome.eval()
e_outcome = ~StateFn(H) @ StateFn(state)
Qen2 = e_outcome.eval()
print(f"ED energy: {E} ;; VQE energy: {result.eigenvalue} ;; VQE energy from simulated: {result2.eigenvalue} ;; VQE simualted but real execution: {Qen2}")
print(f"ED mag: {ED_state.T.conj()@Mag(L,anti)@ED_state} ;; VQE mag: {result.aux_operator_eigenvalues} ;; VQE magfrom simulated: {result2.aux_operator_eigenvalues} ;; VQE simualted but real execution: {Qmag2}")
##############################################################################
### II - Training ###########################################################
##############################################################################
thetas = np.random.uniform(0, 2*np.pi, 2*L+2) # initial parameters without feature encoding
# thetas = np.random.uniform(0, 2*np.pi, (2*L+2, 2)) # initial parameters with feature encoding
# linear entangler (as in scales linearly with trash qubits)
def get_entangler_map(L, num_trash, i_permut=1):
result = []
nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy
nums_compressed = nums.copy()[:L-num_trash]
nums_trash = nums.copy()[-num_trash:]
#print(nums, nums_compressed, nums_trash)
# combine all trash qubits with themselves
for trash_q in nums_trash[:-1]:
result.append((trash_q+1,trash_q))
# combine each of the trash qubits with every n-th
repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly
for i in range(L-num_trash):
result.append((repeated[i_permut + i], nums_compressed[i]))
return result
def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"):
entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)]
circ = qiskit.circuit.library.TwoLocal(L,
parametrized_gate,
entangling_gate,
entanglement,
reps=num_trash,
insert_barriers=insert_barriers,
skip_final_rotation_layer=True
).assign_parameters(thetas[:-num_trash])
if insert_barriers: circ.barrier()
for i in range(num_trash):
circ.ry(thetas[L-i-1], L-i-1)
#circ.ry(circuit.Parameter(f'θ{i}'), L-i-1)
return circ
def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True):
qreg = QuantumRegister(L, 'q')
creg = ClassicalRegister(num_trash, 'c')
circ = QuantumCircuit(qreg, creg)
circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=True)#.assign_parameters(thetas) # difference to bind?
if measurement:
for i in range(num_trash):
circ.measure(qreg[L-i-1], creg[i])
if init_state is not None:
if vqe:
circ = init_vqe(init_state,L=L) + circ
else:
circ.initialize(init_state, qreg)
return circ
def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=1000, backend=backend):
circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe)
circ = qiskit.transpile(circ, backend)
# Execute the circuit on the qasm simulator.
job_sim = execute(circ, backend, shots=shots, seed_simulator=123, seed_transpiler=234) # fix seed to make it reproducible
return job_sim
phi = phis[0]
circ = prepare_circuit(thetas, L, num_trash, phi)
circ = qiskit.transpile(circ, backend)
# Execute the circuit on the qasm simulator.
job = execute(circ, backend, shots=shots) # fix seed to make it reproducible
from qiskit.tools.monitor import job_monitor
job_monitor(job)
jobID = job.job_id()
print('JOB ID: {}'.format(jobID))
#job_get=backend.retrieve_job(jobID)
job_get=backend.retrieve_job(jobID)
job_get
job_get.result().get_counts()
counts
def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0):
""" Optimizes circuit """
if vqe:
init_state = phis[p]
else:
J, gx, gz = p
init_state, _ = ising_groundstate(L, J, gx, gz)
if param_encoding: thetas = feature_encoding(thetas, x)
out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots).result().get_counts()
cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0)
return cost/shots
def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0):
""" Optimizes circuit """
cost = 0.
n_samples = len(ising_params)
for i, p in enumerate(ising_params):
if param_encoding:
cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i])
else:
cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding)
return cost/n_samples
def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None):
if thetas is None:
n_params = (2*L+2)*2 if param_encoding else (2*L+2)
thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding
print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)))
counts, values, accepted = [], [], []
def store_intermediate_result(eval_count, parameters, mean, std, ac):
# counts.append(eval_count)
values.append(mean)
accepted.append(ac)
# Initialize optimizer
if pick_optimizer == "cobyla":
optimizer = COBYLA(maxiter=max_iter, tol=0.0001)
if pick_optimizer == "adam" or pick_optimizer == "ADAM":
optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter)
# optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08)
if pick_optimizer == "spsa" or pick_optimizer == None:
optimizer = SPSA(maxiter=max_iter,
#blocking=True,
callback=store_intermediate_result,
#learning_rate=1e-1,
#perturbation=0.4
) # recommended from qiskit (first iteraction takes quite long)
# to reduce time figure out optimal learning rate and perturbation in advance
start_time = time.time()
ret = optimizer.optimize(
num_vars=len(thetas),
objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)),
initial_point=thetas
)
print("Time: {:.5f} sec".format(time.time()-start_time))
print(ret)
return ret[0], values, accepted
def run_inference(thetas, shots=1000, L=5):
cost = np.zeros((len(gx_vals)))
shots = 1000
for i,p in enumerate(list(zip(gxs, gzs))):
cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots)
return cost
# from the original vqe calculated state
thetas, loss, accepted = optimize([0], max_iter=100, L=5) #, pick_optimizer="adam")
plt.plot(loss)
# using the VQE parameters from simulation
thetas, loss, accepted = optimize([1], max_iter=100, L=5) #, pick_optimizer="adam")
plt.plot(loss)
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Benchmarking accuracy of qiskit to braket conversions
"""
import qiskit
from qiskit_braket_provider.providers.adapter import to_braket
from qbraid.interface import circuits_allclose
from qbraid.transpiler import transpile
from ..fixtures.qiskit.gates import get_qiskit_gates
def execute_test(conversion_function, input_circuit):
"""Execute conversion, test equality, and return 1 if it fails, 0 otherwise"""
try:
output_circuit = conversion_function(input_circuit)
if not circuits_allclose(input_circuit, output_circuit, strict_gphase=False):
return 1
except Exception: # pylint: disable=broad-exception-caught
return 1
return 0
qiskit_gates = get_qiskit_gates(seed=0)
qbraid_failed, qiskit_failed = 0, 0
for gate_name, gate in qiskit_gates.items():
if gate_name == "GlobalPhaseGate":
continue
qiskit_circuit = qiskit.QuantumCircuit(gate.num_qubits)
qiskit_circuit.compose(gate, inplace=True)
qiskit_failed += execute_test(to_braket, qiskit_circuit)
qbraid_failed += execute_test(lambda circuit: transpile(circuit, "braket"), qiskit_circuit)
total_tests = len(qiskit_gates)
qbraid_passed, qiskit_passed = total_tests - qbraid_failed, total_tests - qiskit_failed
qbraid_percentage, qiskit_percentage = round((qbraid_passed / total_tests) * 100, 2), round(
(qiskit_passed / total_tests) * 100, 2
)
print("Qiskit to Braket standard gate conversion tests\n")
print(f"qbraid: {qbraid_passed}/{total_tests} ~= {qbraid_percentage}%") # 58/58
print(f"qiskit-braket-provider: {qiskit_passed}/{total_tests} ~= {qiskit_percentage}%") # 31/58
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""`_text_circuit_drawer` draws a circuit in ascii art"""
import pathlib
import os
import tempfile
import unittest.mock
from codecs import encode
from math import pi
import numpy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.circuit import Gate, Parameter, Qubit, Clbit, Instruction
from qiskit.quantum_info.operators import SuperOp
from qiskit.quantum_info.random import random_unitary
from qiskit.test import QiskitTestCase
from qiskit.transpiler.layout import Layout, TranspileLayout
from qiskit.visualization import circuit_drawer
from qiskit.visualization.circuit import text as elements
from qiskit.visualization.circuit.circuit_visualization import _text_circuit_drawer
from qiskit.extensions import UnitaryGate, HamiltonianGate
from qiskit.extensions.quantum_initializer import UCGate
from qiskit.circuit.library import (
HGate,
U2Gate,
U3Gate,
XGate,
CZGate,
ZGate,
YGate,
U1Gate,
SwapGate,
RZZGate,
CU3Gate,
CU1Gate,
CPhaseGate,
)
from qiskit.transpiler.passes import ApplyLayout
from qiskit.utils.optionals import HAS_TWEEDLEDUM
from .visualization import path_to_diagram_reference, QiskitVisualizationTestCase
if HAS_TWEEDLEDUM:
from qiskit.circuit.classicalfunction import classical_function
from qiskit.circuit.classicalfunction.types import Int1
class TestTextDrawerElement(QiskitTestCase):
"""Draw each element"""
def assertEqualElement(self, expected, element):
"""
Asserts the top,mid,bot trio
Args:
expected (list[top,mid,bot]): What is expected.
element (DrawElement): The element to check.
"""
try:
encode("\n".join(expected), encoding="cp437")
except UnicodeEncodeError:
self.fail("_text_circuit_drawer() should only use extended ascii (aka code page 437).")
self.assertEqual(expected[0], element.top)
self.assertEqual(expected[1], element.mid)
self.assertEqual(expected[2], element.bot)
def test_measure_to(self):
"""MeasureTo element."""
element = elements.MeasureTo()
# fmt: off
expected = [" ║ ",
"═╩═",
" "]
# fmt: on
self.assertEqualElement(expected, element)
def test_measure_to_label(self):
"""MeasureTo element with cregbundle"""
element = elements.MeasureTo("1")
# fmt: off
expected = [" ║ ",
"═╩═",
" 1 "]
# fmt: on
self.assertEqualElement(expected, element)
def test_measure_from(self):
"""MeasureFrom element."""
element = elements.MeasureFrom()
# fmt: off
expected = ["┌─┐",
"┤M├",
"└╥┘"]
# fmt: on
self.assertEqualElement(expected, element)
def test_text_empty(self):
"""The empty circuit."""
expected = ""
circuit = QuantumCircuit()
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_pager(self):
"""The pager breaks the circuit when the drawing does not fit in the console."""
expected = "\n".join(
[
" ┌───┐ »",
"q_0: |0>┤ X ├──■──»",
" └─┬─┘┌─┴─┐»",
"q_1: |0>──■──┤ X ├»",
" └───┘»",
" c: 0 1/══════════»",
" »",
"« ┌─┐┌───┐ »",
"«q_0: ┤M├┤ X ├──■──»",
"« └╥┘└─┬─┘┌─┴─┐»",
"«q_1: ─╫───■──┤ X ├»",
"« ║ └───┘»",
"«c: 1/═╩═══════════»",
"« 0 »",
"« ┌─┐┌───┐ ",
"«q_0: ┤M├┤ X ├──■──",
"« └╥┘└─┬─┘┌─┴─┐",
"«q_1: ─╫───■──┤ X ├",
"« ║ └───┘",
"«c: 1/═╩═══════════",
"« 0 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
self.assertEqual(str(_text_circuit_drawer(circuit, fold=20)), expected)
def test_text_no_pager(self):
"""The pager can be disable."""
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
for _ in range(100):
circuit.h(qr[0])
amount_of_lines = str(_text_circuit_drawer(circuit, fold=-1)).count("\n")
self.assertEqual(amount_of_lines, 2)
class TestTextDrawerGatesInCircuit(QiskitTestCase):
"""Gate by gate checks in different settings."""
def test_text_measure_cregbundle(self):
"""The measure operator, using 3-bit-length registers with cregbundle=True."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├──────",
" └╥┘┌─┐ ",
"q_1: |0>─╫─┤M├───",
" ║ └╥┘┌─┐",
"q_2: |0>─╫──╫─┤M├",
" ║ ║ └╥┘",
" c: 0 3/═╩══╩══╩═",
" 0 1 2 ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_measure_cregbundle_2(self):
"""The measure operator, using 2 classical registers with cregbundle=True."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├───",
" └╥┘┌─┐",
"q_1: |0>─╫─┤M├",
" ║ └╥┘",
"cA: 0 1/═╩══╬═",
" 0 ║ ",
"cB: 0 1/════╩═",
" 0 ",
]
)
qr = QuantumRegister(2, "q")
cr_a = ClassicalRegister(1, "cA")
cr_b = ClassicalRegister(1, "cB")
circuit = QuantumCircuit(qr, cr_a, cr_b)
circuit.measure(qr[0], cr_a[0])
circuit.measure(qr[1], cr_b[0])
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_measure_1(self):
"""The measure operator, using 3-bit-length registers."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├──────",
" └╥┘┌─┐ ",
"q_1: |0>─╫─┤M├───",
" ║ └╥┘┌─┐",
"q_2: |0>─╫──╫─┤M├",
" ║ ║ └╥┘",
" c_0: 0 ═╩══╬══╬═",
" ║ ║ ",
" c_1: 0 ════╩══╬═",
" ║ ",
" c_2: 0 ═══════╩═",
" ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_measure_1_reverse_bits(self):
"""The measure operator, using 3-bit-length registers, with reverse_bits"""
expected = "\n".join(
[
" ┌─┐",
"q_2: |0>──────┤M├",
" ┌─┐└╥┘",
"q_1: |0>───┤M├─╫─",
" ┌─┐└╥┘ ║ ",
"q_0: |0>┤M├─╫──╫─",
" └╥┘ ║ ║ ",
" c: 0 3/═╩══╩══╩═",
" 0 1 2 ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_measure_2(self):
"""The measure operator, using some registers."""
expected = "\n".join(
[
" ",
"q1_0: |0>──────",
" ",
"q1_1: |0>──────",
" ┌─┐ ",
"q2_0: |0>┤M├───",
" └╥┘┌─┐",
"q2_1: |0>─╫─┤M├",
" ║ └╥┘",
" c1: 0 2/═╬══╬═",
" ║ ║ ",
" c2: 0 2/═╩══╩═",
" 0 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
qr2 = QuantumRegister(2, "q2")
cr2 = ClassicalRegister(2, "c2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.measure(qr2, cr2)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_measure_2_reverse_bits(self):
"""The measure operator, using some registers, with reverse_bits"""
expected = "\n".join(
[
" ┌─┐",
"q2_1: |0>───┤M├",
" ┌─┐└╥┘",
"q2_0: |0>┤M├─╫─",
" └╥┘ ║ ",
"q1_1: |0>─╫──╫─",
" ║ ║ ",
"q1_0: |0>─╫──╫─",
" ║ ║ ",
" c2: 0 2/═╩══╩═",
" 0 1 ",
" c1: 0 2/══════",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
qr2 = QuantumRegister(2, "q2")
cr2 = ClassicalRegister(2, "c2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.measure(qr2, cr2)
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_wire_order(self):
"""Test the wire_order option"""
expected = "\n".join(
[
" ",
"q_2: |0>────────────",
" ┌───┐ ",
"q_1: |0>┤ X ├───────",
" ├───┤ ┌───┐ ",
"q_3: |0>┤ H ├─┤ X ├─",
" ├───┤ └─╥─┘ ",
"q_0: |0>┤ H ├───╫───",
" └───┘┌──╨──┐",
" c: 0 4/═════╡ 0xa ╞",
" └─────┘",
"ca: 0 2/════════════",
" ",
]
)
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "ca")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 10)
self.assertEqual(
str(_text_circuit_drawer(circuit, wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7])), expected
)
def test_text_swap(self):
"""Swap drawing."""
expected = "\n".join(
[
" ",
"q1_0: |0>─X────",
" │ ",
"q1_1: |0>─┼──X─",
" │ │ ",
"q2_0: |0>─X──┼─",
" │ ",
"q2_1: |0>────X─",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.swap(qr1, qr2)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_swap_reverse_bits(self):
"""Swap drawing with reverse_bits."""
expected = "\n".join(
[
" ",
"q2_1: |0>────X─",
" │ ",
"q2_0: |0>─X──┼─",
" │ │ ",
"q1_1: |0>─┼──X─",
" │ ",
"q1_0: |0>─X────",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.swap(qr1, qr2)
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_reverse_bits_read_from_config(self):
"""Swap drawing with reverse_bits set in the configuration file."""
expected_forward = "\n".join(
[
" ",
"q1_0: ─X────",
" │ ",
"q1_1: ─┼──X─",
" │ │ ",
"q2_0: ─X──┼─",
" │ ",
"q2_1: ────X─",
" ",
]
)
expected_reverse = "\n".join(
[
" ",
"q2_1: ────X─",
" │ ",
"q2_0: ─X──┼─",
" │ │ ",
"q1_1: ─┼──X─",
" │ ",
"q1_0: ─X────",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.swap(qr1, qr2)
self.assertEqual(str(circuit_drawer(circuit, output="text")), expected_forward)
config_content = """
[default]
circuit_reverse_bits = true
"""
with tempfile.TemporaryDirectory() as dir_path:
file_path = pathlib.Path(dir_path) / "qiskit.conf"
with open(file_path, "w") as fptr:
fptr.write(config_content)
with unittest.mock.patch.dict(os.environ, {"QISKIT_SETTINGS": str(file_path)}):
test_reverse = str(circuit_drawer(circuit, output="text"))
self.assertEqual(test_reverse, expected_reverse)
def test_text_cswap(self):
"""CSwap drawing."""
expected = "\n".join(
[
" ",
"q_0: |0>─■──X──X─",
" │ │ │ ",
"q_1: |0>─X──■──X─",
" │ │ │ ",
"q_2: |0>─X──X──■─",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cswap(qr[0], qr[1], qr[2])
circuit.cswap(qr[1], qr[0], qr[2])
circuit.cswap(qr[2], qr[1], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cswap_reverse_bits(self):
"""CSwap drawing with reverse_bits."""
expected = "\n".join(
[
" ",
"q_2: |0>─X──X──■─",
" │ │ │ ",
"q_1: |0>─X──■──X─",
" │ │ │ ",
"q_0: |0>─■──X──X─",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cswap(qr[0], qr[1], qr[2])
circuit.cswap(qr[1], qr[0], qr[2])
circuit.cswap(qr[2], qr[1], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_cu3(self):
"""cu3 drawing."""
expected = "\n".join(
[
" ┌─────────────────┐",
"q_0: |0>─────────■─────────┤ U3(π/2,π/2,π/2) ├",
" ┌────────┴────────┐└────────┬────────┘",
"q_1: |0>┤ U3(π/2,π/2,π/2) ├─────────┼─────────",
" └─────────────────┘ │ ",
"q_2: |0>────────────────────────────■─────────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]])
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cu3_reverse_bits(self):
"""cu3 drawing with reverse_bits"""
expected = "\n".join(
[
" ",
"q_2: |0>────────────────────────────■─────────",
" ┌─────────────────┐ │ ",
"q_1: |0>┤ U3(π/2,π/2,π/2) ├─────────┼─────────",
" └────────┬────────┘┌────────┴────────┐",
"q_0: |0>─────────■─────────┤ U3(π/2,π/2,π/2) ├",
" └─────────────────┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]])
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_crz(self):
"""crz drawing."""
expected = "\n".join(
[
" ┌─────────┐",
"q_0: |0>─────■─────┤ Rz(π/2) ├",
" ┌────┴────┐└────┬────┘",
"q_1: |0>┤ Rz(π/2) ├─────┼─────",
" └─────────┘ │ ",
"q_2: |0>────────────────■─────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.crz(pi / 2, qr[0], qr[1])
circuit.crz(pi / 2, qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cry(self):
"""cry drawing."""
expected = "\n".join(
[
" ┌─────────┐",
"q_0: |0>─────■─────┤ Ry(π/2) ├",
" ┌────┴────┐└────┬────┘",
"q_1: |0>┤ Ry(π/2) ├─────┼─────",
" └─────────┘ │ ",
"q_2: |0>────────────────■─────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cry(pi / 2, qr[0], qr[1])
circuit.cry(pi / 2, qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_crx(self):
"""crx drawing."""
expected = "\n".join(
[
" ┌─────────┐",
"q_0: |0>─────■─────┤ Rx(π/2) ├",
" ┌────┴────┐└────┬────┘",
"q_1: |0>┤ Rx(π/2) ├─────┼─────",
" └─────────┘ │ ",
"q_2: |0>────────────────■─────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.crx(pi / 2, qr[0], qr[1])
circuit.crx(pi / 2, qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cx(self):
"""cx drawing."""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>──■──┤ X ├",
" ┌─┴─┐└─┬─┘",
"q_1: |0>┤ X ├──┼──",
" └───┘ │ ",
"q_2: |0>───────■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cy(self):
"""cy drawing."""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>──■──┤ Y ├",
" ┌─┴─┐└─┬─┘",
"q_1: |0>┤ Y ├──┼──",
" └───┘ │ ",
"q_2: |0>───────■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cy(qr[0], qr[1])
circuit.cy(qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cz(self):
"""cz drawing."""
expected = "\n".join(
[
" ",
"q_0: |0>─■──■─",
" │ │ ",
"q_1: |0>─■──┼─",
" │ ",
"q_2: |0>────■─",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cz(qr[0], qr[1])
circuit.cz(qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_ch(self):
"""ch drawing."""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>──■──┤ H ├",
" ┌─┴─┐└─┬─┘",
"q_1: |0>┤ H ├──┼──",
" └───┘ │ ",
"q_2: |0>───────■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.ch(qr[0], qr[1])
circuit.ch(qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_rzz(self):
"""rzz drawing. See #1957"""
expected = "\n".join(
[
" ",
"q_0: |0>─■────────────────",
" │ZZ(0) ",
"q_1: |0>─■───────■────────",
" │ZZ(π/2) ",
"q_2: |0>─────────■────────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.rzz(0, qr[0], qr[1])
circuit.rzz(pi / 2, qr[2], qr[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cu1(self):
"""cu1 drawing."""
expected = "\n".join(
[
" ",
"q_0: |0>─■─────────■────────",
" │U1(π/2) │ ",
"q_1: |0>─■─────────┼────────",
" │U1(π/2) ",
"q_2: |0>───────────■────────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]])
circuit.append(CU1Gate(pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cp(self):
"""cp drawing."""
expected = "\n".join(
[
" ",
"q_0: |0>─■────────■───────",
" │P(π/2) │ ",
"q_1: |0>─■────────┼───────",
" │P(π/2) ",
"q_2: |0>──────────■───────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]])
circuit.append(CPhaseGate(pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cu1_condition(self):
"""Test cu1 with condition"""
expected = "\n".join(
[
" ",
"q_0: ────────■────────",
" │U1(π/2) ",
"q_1: ────────■────────",
" ║ ",
"q_2: ────────╫────────",
" ┌────╨────┐ ",
"c: 3/═══╡ c_1=0x1 ╞═══",
" └─────────┘ ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected)
def test_text_rzz_condition(self):
"""Test rzz with condition"""
expected = "\n".join(
[
" ",
"q_0: ────────■────────",
" │ZZ(π/2) ",
"q_1: ────────■────────",
" ║ ",
"q_2: ────────╫────────",
" ┌────╨────┐ ",
"c: 3/═══╡ c_1=0x1 ╞═══",
" └─────────┘ ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(RZZGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected)
def test_text_cp_condition(self):
"""Test cp with condition"""
expected = "\n".join(
[
" ",
"q_0: ───────■───────",
" │P(π/2) ",
"q_1: ───────■───────",
" ║ ",
"q_2: ───────╫───────",
" ┌────╨────┐ ",
"c: 3/══╡ c_1=0x1 ╞══",
" └─────────┘ ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected)
def test_text_cu1_reverse_bits(self):
"""cu1 drawing with reverse_bits"""
expected = "\n".join(
[
" ",
"q_2: |0>───────────■────────",
" │ ",
"q_1: |0>─■─────────┼────────",
" │U1(π/2) │U1(π/2) ",
"q_0: |0>─■─────────■────────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]])
circuit.append(CU1Gate(pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_ccx(self):
"""cx drawing."""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>──■────■──┤ X ├",
" │ ┌─┴─┐└─┬─┘",
"q_1: |0>──■──┤ X ├──■──",
" ┌─┴─┐└─┬─┘ │ ",
"q_2: |0>┤ X ├──■────■──",
" └───┘ ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.ccx(qr[0], qr[1], qr[2])
circuit.ccx(qr[2], qr[0], qr[1])
circuit.ccx(qr[2], qr[1], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_reset(self):
"""Reset drawing."""
expected = "\n".join(
[
" ",
"q1_0: |0>─|0>─",
" ",
"q1_1: |0>─|0>─",
" ",
"q2_0: |0>─────",
" ",
"q2_1: |0>─|0>─",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.reset(qr1)
circuit.reset(qr2[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_single_gate(self):
"""Single Qbit gate drawing."""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>┤ H ├",
" ├───┤",
"q1_1: |0>┤ H ├",
" └───┘",
"q2_0: |0>─────",
" ┌───┐",
"q2_1: |0>┤ H ├",
" └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.h(qr1)
circuit.h(qr2[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_id(self):
"""Id drawing."""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>┤ I ├",
" ├───┤",
"q1_1: |0>┤ I ├",
" └───┘",
"q2_0: |0>─────",
" ┌───┐",
"q2_1: |0>┤ I ├",
" └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.id(qr1)
circuit.id(qr2[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_barrier(self):
"""Barrier drawing."""
expected = "\n".join(
[
" ░ ",
"q1_0: |0>─░─",
" ░ ",
"q1_1: |0>─░─",
" ░ ",
"q2_0: |0>───",
" ░ ",
"q2_1: |0>─░─",
" ░ ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.barrier(qr1)
circuit.barrier(qr2[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_no_barriers(self):
"""Drawing without plotbarriers."""
expected = "\n".join(
[
" ┌───┐ ",
"q1_0: |0>┤ H ├─────",
" ├───┤ ",
"q1_1: |0>┤ H ├─────",
" ├───┤ ",
"q2_0: |0>┤ H ├─────",
" └───┘┌───┐",
"q2_1: |0>─────┤ H ├",
" └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.h(qr1)
circuit.barrier(qr1)
circuit.barrier(qr2[1])
circuit.h(qr2)
self.assertEqual(str(_text_circuit_drawer(circuit, plot_barriers=False)), expected)
def test_text_measure_html(self):
"""The measure operator. HTML representation."""
expected = "\n".join(
[
'<pre style="word-wrap: normal;'
"white-space: pre;"
"background: #fff0;"
"line-height: 1.1;"
'font-family: "Courier New",Courier,monospace">'
" ┌─┐",
" q: |0>┤M├",
" └╥┘",
"c: 0 1/═╩═",
" 0 </pre>",
]
)
qr = QuantumRegister(1, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(_text_circuit_drawer(circuit)._repr_html_(), expected)
def test_text_repr(self):
"""The measure operator. repr."""
expected = "\n".join(
[
" ┌─┐",
" q: |0>┤M├",
" └╥┘",
"c: 0 1/═╩═",
" 0 ",
]
)
qr = QuantumRegister(1, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(_text_circuit_drawer(circuit).__repr__(), expected)
def test_text_justify_left(self):
"""Drawing with left justify"""
expected = "\n".join(
[
" ┌───┐ ",
"q1_0: |0>┤ X ├───",
" ├───┤┌─┐",
"q1_1: |0>┤ H ├┤M├",
" └───┘└╥┘",
" c1: 0 2/══════╩═",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.h(qr1[1])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_justify_right(self):
"""Drawing with right justify"""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>─────┤ X ├",
" ┌───┐└┬─┬┘",
"q1_1: |0>┤ H ├─┤M├─",
" └───┘ └╥┘ ",
" c1: 0 2/═══════╩══",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.h(qr1[1])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected)
def test_text_justify_none(self):
"""Drawing with none justify"""
expected = "\n".join(
[
" ┌───┐ ",
"q1_0: |0>┤ X ├────────",
" └───┘┌───┐┌─┐",
"q1_1: |0>─────┤ H ├┤M├",
" └───┘└╥┘",
" c1: 0 2/═══════════╩═",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.h(qr1[1])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="none")), expected)
def test_text_justify_left_barrier(self):
"""Left justify respects barriers"""
expected = "\n".join(
[
" ┌───┐ ░ ",
"q1_0: |0>┤ H ├─░──────",
" └───┘ ░ ┌───┐",
"q1_1: |0>──────░─┤ H ├",
" ░ └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
circuit = QuantumCircuit(qr1)
circuit.h(qr1[0])
circuit.barrier(qr1)
circuit.h(qr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_justify_right_barrier(self):
"""Right justify respects barriers"""
expected = "\n".join(
[
" ┌───┐ ░ ",
"q1_0: |0>┤ H ├─░──────",
" └───┘ ░ ┌───┐",
"q1_1: |0>──────░─┤ H ├",
" ░ └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
circuit = QuantumCircuit(qr1)
circuit.h(qr1[0])
circuit.barrier(qr1)
circuit.h(qr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected)
def test_text_barrier_label(self):
"""Show barrier label"""
expected = "\n".join(
[
" ┌───┐ ░ ┌───┐ End Y/X ",
"q_0: |0>┤ X ├─░─┤ Y ├────░────",
" ├───┤ ░ ├───┤ ░ ",
"q_1: |0>┤ Y ├─░─┤ X ├────░────",
" └───┘ ░ └───┘ ░ ",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.y(1)
circuit.barrier()
circuit.y(0)
circuit.x(1)
circuit.barrier(label="End Y/X")
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_overlap_cx(self):
"""Overlapping CX gates are drawn not overlapping"""
expected = "\n".join(
[
" ",
"q1_0: |0>──■───────",
" │ ",
"q1_1: |0>──┼────■──",
" │ ┌─┴─┐",
"q1_2: |0>──┼──┤ X ├",
" ┌─┴─┐└───┘",
"q1_3: |0>┤ X ├─────",
" └───┘ ",
]
)
qr1 = QuantumRegister(4, "q1")
circuit = QuantumCircuit(qr1)
circuit.cx(qr1[0], qr1[3])
circuit.cx(qr1[1], qr1[2])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_overlap_measure(self):
"""Measure is drawn not overlapping"""
expected = "\n".join(
[
" ┌─┐ ",
"q1_0: |0>┤M├─────",
" └╥┘┌───┐",
"q1_1: |0>─╫─┤ X ├",
" ║ └───┘",
" c1: 0 2/═╩══════",
" 0 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.measure(qr1[0], cr1[0])
circuit.x(qr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_overlap_swap(self):
"""Swap is drawn in 2 separate columns"""
expected = "\n".join(
[
" ",
"q1_0: |0>─X────",
" │ ",
"q1_1: |0>─┼──X─",
" │ │ ",
"q2_0: |0>─X──┼─",
" │ ",
"q2_1: |0>────X─",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.swap(qr1, qr2)
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_justify_right_measure_resize(self):
"""Measure gate can resize if necessary"""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>┤ X ├",
" └┬─┬┘",
"q1_1: |0>─┤M├─",
" └╥┘ ",
" c1: 0 2/══╩══",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected)
def test_text_box_length(self):
"""The length of boxes is independent of other boxes in the layer
https://github.com/Qiskit/qiskit-terra/issues/1882"""
expected = "\n".join(
[
" ┌───┐ ┌───┐",
"q1_0: |0>────┤ H ├────┤ H ├",
" └───┘ └───┘",
"q1_1: |0>──────────────────",
" ┌───────────┐ ",
"q1_2: |0>┤ Rz(1e-07) ├─────",
" └───────────┘ ",
]
)
qr = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.rz(0.0000001, qr[2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_spacing_2378(self):
"""Small gates in the same layer as long gates.
See https://github.com/Qiskit/qiskit-terra/issues/2378"""
expected = "\n".join(
[
" ",
"q_0: |0>──────X──────",
" │ ",
"q_1: |0>──────X──────",
" ┌───────────┐",
"q_2: |0>┤ Rz(11111) ├",
" └───────────┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.swap(qr[0], qr[1])
circuit.rz(11111, qr[2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
def test_text_synth_no_registerless(self):
"""Test synthesis's label when registerless=False.
See https://github.com/Qiskit/qiskit-terra/issues/9363"""
expected = "\n".join(
[
" ",
" a: |0>──■──",
" │ ",
" b: |0>──■──",
" │ ",
" c: |0>──o──",
" ┌─┴─┐",
"return: |0>┤ X ├",
" └───┘",
]
)
@classical_function
def grover_oracle(a: Int1, b: Int1, c: Int1) -> Int1:
return a and b and not c
circuit = grover_oracle.synth(registerless=False)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextDrawerLabels(QiskitTestCase):
"""Gates with labels."""
def test_label(self):
"""Test a gate with a label."""
# fmt: off
expected = "\n".join([" ┌───────────┐",
"q: |0>┤ an H gate ├",
" └───────────┘"])
# fmt: on
circuit = QuantumCircuit(1)
circuit.append(HGate(label="an H gate"), [0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_gate_with_label(self):
"""Test a controlled gate-with-a-label."""
expected = "\n".join(
[
" ",
"q_0: |0>──────■──────",
" ┌─────┴─────┐",
"q_1: |0>┤ an H gate ├",
" └───────────┘",
]
)
circuit = QuantumCircuit(2)
circuit.append(HGate(label="an H gate").control(1), [0, 1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_label_on_controlled_gate(self):
"""Test a controlled gate with a label (as a as a whole)."""
expected = "\n".join(
[
" a controlled H gate ",
"q_0: |0>──────────■──────────",
" ┌─┴─┐ ",
"q_1: |0>────────┤ H ├────────",
" └───┘ ",
]
)
circuit = QuantumCircuit(2)
circuit.append(HGate().control(1, label="a controlled H gate"), [0, 1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_rzz_on_wide_layer(self):
"""Test a labeled gate (RZZ) in a wide layer.
See https://github.com/Qiskit/qiskit-terra/issues/4838"""
expected = "\n".join(
[
" ",
"q_0: |0>────────────────■──────────────────────",
" │ZZ(π/2) ",
"q_1: |0>────────────────■──────────────────────",
" ┌─────────────────────────────────────┐",
"q_2: |0>┤ This is a really long long long box ├",
" └─────────────────────────────────────┘",
]
)
circuit = QuantumCircuit(3)
circuit.rzz(pi / 2, 0, 1)
circuit.x(2, label="This is a really long long long box")
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cu1_on_wide_layer(self):
"""Test a labeled gate (CU1) in a wide layer.
See https://github.com/Qiskit/qiskit-terra/issues/4838"""
expected = "\n".join(
[
" ",
"q_0: |0>────────────────■──────────────────────",
" │U1(π/2) ",
"q_1: |0>────────────────■──────────────────────",
" ┌─────────────────────────────────────┐",
"q_2: |0>┤ This is a really long long long box ├",
" └─────────────────────────────────────┘",
]
)
circuit = QuantumCircuit(3)
circuit.append(CU1Gate(pi / 2), [0, 1])
circuit.x(2, label="This is a really long long long box")
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextDrawerMultiQGates(QiskitTestCase):
"""Gates implying multiple qubits."""
def test_2Qgate(self):
"""2Q no params."""
expected = "\n".join(
[
" ┌───────┐",
"q_1: |0>┤1 ├",
" │ twoQ │",
"q_0: |0>┤0 ├",
" └───────┘",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ")
circuit.append(my_gate2, [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_2Qgate_cross_wires(self):
"""2Q no params, with cross wires"""
expected = "\n".join(
[
" ┌───────┐",
"q_1: |0>┤0 ├",
" │ twoQ │",
"q_0: |0>┤1 ├",
" └───────┘",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ")
circuit.append(my_gate2, [qr[1], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_3Qgate_cross_wires(self):
"""3Q no params, with cross wires"""
expected = "\n".join(
[
" ┌─────────┐",
"q_2: |0>┤1 ├",
" │ │",
"q_1: |0>┤0 threeQ ├",
" │ │",
"q_0: |0>┤2 ├",
" └─────────┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
my_gate3 = Gate(name="threeQ", num_qubits=3, params=[], label="threeQ")
circuit.append(my_gate3, [qr[1], qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_2Qgate_nottogether(self):
"""2Q that are not together"""
expected = "\n".join(
[
" ┌───────┐",
"q_2: |0>┤1 ├",
" │ │",
"q_1: |0>┤ twoQ ├",
" │ │",
"q_0: |0>┤0 ├",
" └───────┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ")
circuit.append(my_gate2, [qr[0], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_2Qgate_nottogether_across_4(self):
"""2Q that are 2 bits apart"""
expected = "\n".join(
[
" ┌───────┐",
"q_3: |0>┤1 ├",
" │ │",
"q_2: |0>┤ ├",
" │ twoQ │",
"q_1: |0>┤ ├",
" │ │",
"q_0: |0>┤0 ├",
" └───────┘",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ")
circuit.append(my_gate2, [qr[0], qr[3]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_unitary_nottogether_across_4(self):
"""unitary that are 2 bits apart"""
expected = "\n".join(
[
" ┌──────────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>┤ ├",
" │ Unitary │",
"q_2: |0>┤ ├",
" │ │",
"q_3: |0>┤1 ├",
" └──────────┘",
]
)
qr = QuantumRegister(4, "q")
qc = QuantumCircuit(qr)
qc.append(random_unitary(4, seed=42), [qr[0], qr[3]])
self.assertEqual(str(_text_circuit_drawer(qc)), expected)
def test_kraus(self):
"""Test Kraus.
See https://github.com/Qiskit/qiskit-terra/pull/2238#issuecomment-487630014"""
# fmt: off
expected = "\n".join([" ┌───────┐",
"q: |0>┤ kraus ├",
" └───────┘"])
# fmt: on
error = SuperOp(0.75 * numpy.eye(4) + 0.25 * numpy.diag([1, -1, -1, 1]))
qr = QuantumRegister(1, name="q")
qc = QuantumCircuit(qr)
qc.append(error, [qr[0]])
self.assertEqual(str(_text_circuit_drawer(qc)), expected)
def test_multiplexer(self):
"""Test Multiplexer.
See https://github.com/Qiskit/qiskit-terra/pull/2238#issuecomment-487630014"""
expected = "\n".join(
[
" ┌──────────────┐",
"q_0: |0>┤0 ├",
" │ Multiplexer │",
"q_1: |0>┤1 ├",
" └──────────────┘",
]
)
cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])])
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.append(cx_multiplexer, [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(qc)), expected)
def test_label_over_name_2286(self):
"""If there is a label, it should be used instead of the name
See https://github.com/Qiskit/qiskit-terra/issues/2286"""
expected = "\n".join(
[
" ┌───┐┌───────┐┌────────┐",
"q_0: |0>┤ X ├┤ alt-X ├┤0 ├",
" └───┘└───────┘│ iswap │",
"q_1: |0>──────────────┤1 ├",
" └────────┘",
]
)
qr = QuantumRegister(2, "q")
circ = QuantumCircuit(qr)
circ.append(XGate(), [qr[0]])
circ.append(XGate(label="alt-X"), [qr[0]])
circ.append(UnitaryGate(numpy.eye(4), label="iswap"), [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circ)), expected)
def test_label_turns_to_box_2286(self):
"""If there is a label, non-boxes turn into boxes
See https://github.com/Qiskit/qiskit-terra/issues/2286"""
expected = "\n".join(
[
" cz label ",
"q_0: |0>─■─────■─────",
" │ │ ",
"q_1: |0>─■─────■─────",
" ",
]
)
qr = QuantumRegister(2, "q")
circ = QuantumCircuit(qr)
circ.append(CZGate(), [qr[0], qr[1]])
circ.append(CZGate(label="cz label"), [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circ)), expected)
def test_control_gate_with_base_label_4361(self):
"""Control gate has a label and a base gate with a label
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐ my ch ┌──────┐",
"q_0: |0>┤ my h ├───■────┤ my h ├",
" └──────┘┌──┴───┐└──┬───┘",
"q_1: |0>────────┤ my h ├───■────",
" └──────┘ my ch ",
]
)
qr = QuantumRegister(2, "q")
circ = QuantumCircuit(qr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch")
circ.append(hgate, [0])
circ.append(controlh, [0, 1])
circ.append(controlh, [1, 0])
self.assertEqual(str(_text_circuit_drawer(circ)), expected)
def test_control_gate_label_with_cond_1_low(self):
"""Control gate has a label and a conditional (compression=low)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" │ ",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(str(_text_circuit_drawer(circ, vertical_compression="low")), expected)
def test_control_gate_label_with_cond_1_low_cregbundle(self):
"""Control gate has a label and a conditional (compression=low) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" │ ",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="low", cregbundle=True)), expected
)
def test_control_gate_label_with_cond_1_med(self):
"""Control gate has a label and a conditional (compression=med)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" c: 0 ═══■════",
" 0x1 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="medium")),
expected,
)
def test_control_gate_label_with_cond_1_med_cregbundle(self):
"""Control gate has a label and a conditional (compression=med) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="medium", cregbundle=True)),
expected,
)
def test_control_gate_label_with_cond_1_high(self):
"""Control gate has a label and a conditional (compression=high)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" c: 0 ═══■════",
" 0x1 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="high")), expected
)
def test_control_gate_label_with_cond_1_high_cregbundle(self):
"""Control gate has a label and a conditional (compression=high) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" ├──╨──┬┘",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="high", cregbundle=True)), expected
)
def test_control_gate_label_with_cond_2_med_space(self):
"""Control gate has a label and a conditional (on label, compression=med)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤ my h ├",
" └──┬───┘",
"q_1: |0>───■────",
" my ch ",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(str(_text_circuit_drawer(circ, vertical_compression="medium")), expected)
def test_control_gate_label_with_cond_2_med(self):
"""Control gate has a label and a conditional (on label, compression=med)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐ ",
"q_0: |0>──┤ my h ├─",
" └──┬───┘ ",
"q_1: |0>─────■─────",
" my ctrl-h ",
" ║ ",
" c: 0 ═════■═════",
" 0x1 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ctrl-h").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(
str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="medium")),
expected,
)
def test_control_gate_label_with_cond_2_med_cregbundle(self):
"""Control gate has a label and a conditional (on label, compression=med) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤ my h ├",
" └──┬───┘",
"q_1: |0>───■────",
" my ch ",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="medium", cregbundle=True)),
expected,
)
def test_control_gate_label_with_cond_2_low(self):
"""Control gate has a label and a conditional (on label, compression=low)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤ my h ├",
" └──┬───┘",
" │ ",
"q_1: |0>───■────",
" my ch ",
" ║ ",
" c: 0 ═══■════",
" 0x1 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(
str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="low")), expected
)
def test_control_gate_label_with_cond_2_low_cregbundle(self):
"""Control gate has a label and a conditional (on label, compression=low) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤ my h ├",
" └──┬───┘",
" │ ",
"q_1: |0>───■────",
" my ch ",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="low", cregbundle=True)), expected
)
class TestTextDrawerParams(QiskitTestCase):
"""Test drawing parameters."""
def test_text_no_parameters(self):
"""Test drawing with no parameters"""
expected = "\n".join(
[
" ┌───┐",
"q: |0>┤ X ├",
" └───┘",
]
)
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_parameters_mix(self):
"""cu3 drawing with parameters"""
expected = "\n".join(
[
" ",
"q_0: |0>─────────■──────────",
" ┌────────┴─────────┐",
"q_1: |0>┤ U(π/2,theta,π,0) ├",
" └──────────────────┘",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.cu(pi / 2, Parameter("theta"), pi, 0, qr[0], qr[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_bound_parameters(self):
"""Bound parameters
See: https://github.com/Qiskit/qiskit-terra/pull/3876"""
# fmt: off
expected = "\n".join([" ┌────────────┐",
"qr: |0>┤ my_u2(π,π) ├",
" └────────────┘"])
# fmt: on
my_u2_circuit = QuantumCircuit(1, name="my_u2")
phi = Parameter("phi")
lam = Parameter("lambda")
my_u2_circuit.u(3.141592653589793, phi, lam, 0)
my_u2 = my_u2_circuit.to_gate()
qr = QuantumRegister(1, name="qr")
circuit = QuantumCircuit(qr, name="circuit")
circuit.append(my_u2, [qr[0]])
circuit = circuit.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793})
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_pi_param_expr(self):
"""Text pi in circuit with parameter expression."""
expected = "\n".join(
[
" ┌─────────────────────┐",
"q: ┤ Rx((π - x)*(π - y)) ├",
" └─────────────────────┘",
]
)
x, y = Parameter("x"), Parameter("y")
circuit = QuantumCircuit(1)
circuit.rx((pi - x) * (pi - y), 0)
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_text_utf8(self):
"""Test that utf8 characters work in windows CI env."""
# fmt: off
expected = "\n".join([" ┌──────────┐",
"q: ┤ U(0,φ,λ) ├",
" └──────────┘"])
# fmt: on
phi, lam = Parameter("φ"), Parameter("λ")
circuit = QuantumCircuit(1)
circuit.u(0, phi, lam, 0)
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_text_ndarray_parameters(self):
"""Test that if params are type ndarray, params are not displayed."""
# fmt: off
expected = "\n".join([" ┌─────────┐",
"q: |0>┤ Unitary ├",
" └─────────┘"])
# fmt: on
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.unitary(numpy.array([[0, 1], [1, 0]]), 0)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_qc_parameters(self):
"""Test that if params are type QuantumCircuit, params are not displayed."""
expected = "\n".join(
[
" ┌───────┐",
"q_0: |0>┤0 ├",
" │ name │",
"q_1: |0>┤1 ├",
" └───────┘",
]
)
my_qc_param = QuantumCircuit(2)
my_qc_param.h(0)
my_qc_param.cx(0, 1)
inst = Instruction("name", 2, 0, [my_qc_param])
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.append(inst, [0, 1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextDrawerVerticalCompressionLow(QiskitTestCase):
"""Test vertical_compression='low'"""
def test_text_conditional_1(self):
"""Conditional drawing with 1-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
"q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
" ║ ║ ",
"c0: 0 ══■════╬══",
" 0x1 ║ ",
" ║ ",
"c1: 0 ═══════■══",
" 0x1 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="low")),
expected,
)
def test_text_conditional_1_bundle(self):
"""Conditional drawing with 1-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" └─╥─┘ └─╥─┘ ",
" ┌──╨──┐ ║ ",
"c0: 0 1/╡ 0x1 ╞═══╬═══",
" └─────┘ ║ ",
" ┌──╨──┐",
"c1: 0 1/═══════╡ 0x1 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="low", cregbundle=True)),
expected,
)
def test_text_conditional_reverse_bits_true(self):
"""Conditional drawing with 1-bit-length regs."""
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.x(0)
circuit.x(0)
circuit.measure(2, 1)
circuit.x(2).c_if(cr, 2)
expected = "\n".join(
[
" ┌───┐ ┌─┐ ┌───┐",
"qr_2: |0>┤ H ├─────┤M├─────┤ X ├",
" └───┘ └╥┘ └─╥─┘",
" ┌───┐ ║ ║ ",
"qr_1: |0>┤ H ├──────╫────────╫──",
" └───┘ ║ ║ ",
" ┌───┐┌───┐ ║ ┌───┐ ║ ",
"qr_0: |0>┤ H ├┤ X ├─╫─┤ X ├──╫──",
" └───┘└───┘ ║ └───┘ ║ ",
" ║ ║ ",
" cr2: 0 ═══════════╬════════╬══",
" ║ ║ ",
" ║ ║ ",
" cr_1: 0 ═══════════╩════════■══",
" ║ ",
" ║ ",
" cr_0: 0 ════════════════════o══",
" 0x2 ",
]
)
self.assertEqual(
str(
_text_circuit_drawer(
circuit, vertical_compression="low", cregbundle=False, reverse_bits=True
)
),
expected,
)
def test_text_conditional_reverse_bits_false(self):
"""Conditional drawing with 1-bit-length regs."""
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.x(0)
circuit.x(0)
circuit.measure(2, 1)
circuit.x(2).c_if(cr, 2)
expected = "\n".join(
[
" ┌───┐┌───┐┌───┐",
"qr_0: |0>┤ H ├┤ X ├┤ X ├",
" └───┘└───┘└───┘",
" ┌───┐ ",
"qr_1: |0>┤ H ├──────────",
" └───┘ ",
" ┌───┐ ┌─┐ ┌───┐",
"qr_2: |0>┤ H ├─┤M├─┤ X ├",
" └───┘ └╥┘ └─╥─┘",
" ║ ║ ",
" cr_0: 0 ═══════╬════o══",
" ║ ║ ",
" ║ ║ ",
" cr_1: 0 ═══════╩════■══",
" 0x2 ",
" ",
" cr2: 0 ═══════════════",
" ",
]
)
self.assertEqual(
str(
_text_circuit_drawer(
circuit, vertical_compression="low", cregbundle=False, reverse_bits=False
)
),
expected,
)
def test_text_justify_right(self):
"""Drawing with right justify"""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>─────┤ X ├",
" └───┘",
" ┌───┐ ┌─┐ ",
"q1_1: |0>┤ H ├─┤M├─",
" └───┘ └╥┘ ",
" ║ ",
" c1: 0 2/═══════╩══",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.h(qr1[1])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(
str(_text_circuit_drawer(circuit, justify="right", vertical_compression="low")),
expected,
)
class TestTextDrawerVerticalCompressionMedium(QiskitTestCase):
"""Test vertical_compression='medium'"""
def test_text_conditional_1(self):
"""Medium vertical compression avoids box overlap."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
"q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0: 0 ══■════╬══",
" 0x1 ║ ",
"c1: 0 ═══════■══",
" 0x1 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="medium")),
expected,
)
def test_text_conditional_1_bundle(self):
"""Medium vertical compression avoids box overlap."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" └─╥─┘ └─╥─┘ ",
" ┌──╨──┐ ║ ",
"c0: 0 1/╡ 0x1 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 1/═══════╡ 0x1 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=True)),
expected,
)
def test_text_measure_with_spaces(self):
"""Measure wire might have extra spaces
Found while reproducing
https://quantumcomputing.stackexchange.com/q/10194/1859"""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[3];
measure q[0] -> c[1];
if(c==1) x q[1];
"""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├─────",
" └╥┘┌───┐",
"q_1: |0>─╫─┤ X ├",
" ║ └─╥─┘",
" c_0: 0 ═╬═══■══",
" ║ ║ ",
" c_1: 0 ═╩═══o══",
" ║ ",
" c_2: 0 ═════o══",
" 0x1 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="medium")),
expected,
)
def test_text_measure_with_spaces_bundle(self):
"""Measure wire might have extra spaces
Found while reproducing
https://quantumcomputing.stackexchange.com/q/10194/1859"""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[3];
measure q[0] -> c[1];
if(c==1) x q[1];
"""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├───────",
" └╥┘ ┌───┐ ",
"q_1: |0>─╫──┤ X ├─",
" ║ └─╥─┘ ",
" ║ ┌──╨──┐",
" c: 0 3/═╩═╡ 0x1 ╞",
" 1 └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=True)),
expected,
)
def test_text_barrier_med_compress_1(self):
"""Medium vertical compression avoids connection break."""
circuit = QuantumCircuit(4)
circuit.cx(1, 3)
circuit.x(1)
circuit.barrier((2, 3), label="Bar 1")
expected = "\n".join(
[
" ",
"q_0: |0>────────────",
" ┌───┐ ",
"q_1: |0>──■───┤ X ├─",
" │ └───┘ ",
" │ Bar 1 ",
"q_2: |0>──┼─────░───",
" ┌─┴─┐ ░ ",
"q_3: |0>┤ X ├───░───",
" └───┘ ░ ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=False)),
expected,
)
def test_text_barrier_med_compress_2(self):
"""Medium vertical compression avoids overprint."""
circuit = QuantumCircuit(4)
circuit.barrier((0, 1, 2), label="a")
circuit.cx(1, 3)
circuit.x(1)
circuit.barrier((2, 3), label="Bar 1")
expected = "\n".join(
[
" a ",
"q_0: |0>─░─────────────",
" ░ ┌───┐ ",
"q_1: |0>─░───■───┤ X ├─",
" ░ │ └───┘ ",
" ░ │ Bar 1 ",
"q_2: |0>─░───┼─────░───",
" ░ ┌─┴─┐ ░ ",
"q_3: |0>───┤ X ├───░───",
" └───┘ ░ ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=False)),
expected,
)
def test_text_barrier_med_compress_3(self):
"""Medium vertical compression avoids conditional connection break."""
qr = QuantumRegister(1, "qr")
qc1 = ClassicalRegister(3, "cr")
qc2 = ClassicalRegister(1, "cr2")
circuit = QuantumCircuit(qr, qc1, qc2)
circuit.x(0).c_if(qc1, 3)
circuit.x(0).c_if(qc2[0], 1)
expected = "\n".join(
[
" ┌───┐┌───┐",
" qr: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"cr_0: 0 ══■════╬══",
" ║ ║ ",
"cr_2: 0 ══o════╬══",
" ║ ║ ",
" cr2: 0 ══╬════■══",
" ║ ",
"cr_1: 0 ══■═══════",
" 0x3 ",
]
)
self.assertEqual(
str(
_text_circuit_drawer(
circuit,
vertical_compression="medium",
wire_order=[0, 1, 3, 4, 2],
cregbundle=False,
)
),
expected,
)
class TestTextConditional(QiskitTestCase):
"""Gates with conditionals"""
def test_text_conditional_1_cregbundle(self):
"""Conditional drawing with 1-bit-length regs and cregbundle."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" ┌┴─╨─┴┐ └─╥─┘ ",
"c0: 0 1/╡ 0x1 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 1/═══════╡ 0x1 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_1(self):
"""Conditional drawing with 1-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
"q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0: 0 ══■════╬══",
" 0x1 ║ ",
"c1: 0 ═══════■══",
" 0x1 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_2_cregbundle(self):
"""Conditional drawing with 2-bit-length regs with cregbundle"""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[2];
creg c1[2];
if(c0==2) x q[0];
if(c1==2) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" ┌┴─╨─┴┐ └─╥─┘ ",
"c0: 0 2/╡ 0x2 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 2/═══════╡ 0x2 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_2(self):
"""Conditional drawing with 2-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[2];
creg c1[2];
if(c0==2) x q[0];
if(c1==2) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
" q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0_0: 0 ══o════╬══",
" ║ ║ ",
"c0_1: 0 ══■════╬══",
" 0x2 ║ ",
"c1_0: 0 ═══════o══",
" ║ ",
"c1_1: 0 ═══════■══",
" 0x2 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_3_cregbundle(self):
"""Conditional drawing with 3-bit-length regs with cregbundle."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[3];
creg c1[3];
if(c0==3) x q[0];
if(c1==3) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" ┌┴─╨─┴┐ └─╥─┘ ",
"c0: 0 3/╡ 0x3 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 3/═══════╡ 0x3 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_3(self):
"""Conditional drawing with 3-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[3];
creg c1[3];
if(c0==3) x q[0];
if(c1==3) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
" q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0_0: 0 ══■════╬══",
" ║ ║ ",
"c0_1: 0 ══■════╬══",
" ║ ║ ",
"c0_2: 0 ══o════╬══",
" 0x3 ║ ",
"c1_0: 0 ═══════■══",
" ║ ",
"c1_1: 0 ═══════■══",
" ║ ",
"c1_2: 0 ═══════o══",
" 0x3 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_4(self):
"""Conditional drawing with 4-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[4];
creg c1[4];
if(c0==4) x q[0];
if(c1==4) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" ┌┴─╨─┴┐ └─╥─┘ ",
"c0: 0 4/╡ 0x4 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 4/═══════╡ 0x4 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_conditional_5(self):
"""Conditional drawing with 5-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[5];
creg c1[5];
if(c0==5) x q[0];
if(c1==5) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
" q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0_0: 0 ══■════╬══",
" ║ ║ ",
"c0_1: 0 ══o════╬══",
" ║ ║ ",
"c0_2: 0 ══■════╬══",
" ║ ║ ",
"c0_3: 0 ══o════╬══",
" ║ ║ ",
"c0_4: 0 ══o════╬══",
" 0x5 ║ ",
"c1_0: 0 ═══════■══",
" ║ ",
"c1_1: 0 ═══════o══",
" ║ ",
"c1_2: 0 ═══════■══",
" ║ ",
"c1_3: 0 ═══════o══",
" ║ ",
"c1_4: 0 ═══════o══",
" 0x5 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cz_no_space_cregbundle(self):
"""Conditional CZ without space"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───■───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cz_no_space(self):
"""Conditional CZ without space"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──■──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cz_cregbundle(self):
"""Conditional CZ with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───■───",
" ║ ",
"qr_2: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cz(self):
"""Conditional CZ with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──■──",
" ║ ",
"qr_2: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cx_ct_cregbundle(self):
"""Conditional CX (control-target) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" ┌─┴─┐ ",
"qr_1: |0>─┤ X ├─",
" └─╥─┘ ",
"qr_2: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cx_ct(self):
"""Conditional CX (control-target) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" ┌─┴─┐",
"qr_1: |0>┤ X ├",
" └─╥─┘",
"qr_2: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cx_tc_cregbundle(self):
"""Conditional CX (target-control) with a wire in the middle with cregbundle."""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐ ",
"qr_0: |0>─┤ X ├─",
" └─┬─┘ ",
"qr_1: |0>───■───",
" ║ ",
"qr_2: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cx_tc(self):
"""Conditional CX (target-control) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐",
"qr_0: |0>┤ X ├",
" └─┬─┘",
"qr_1: |0>──■──",
" ║ ",
"qr_2: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cu3_ct_cregbundle(self):
"""Conditional Cu3 (control-target) with a wire in the middle with cregbundle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>─────────■─────────",
" ┌────────┴────────┐",
"qr_1: |0>┤ U3(π/2,π/2,π/2) ├",
" └────────╥────────┘",
"qr_2: |0>─────────╫─────────",
" ┌──╨──┐ ",
" cr: 0 1/══════╡ 0x1 ╞══════",
" └─────┘ ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cu3_ct(self):
"""Conditional Cu3 (control-target) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>─────────■─────────",
" ┌────────┴────────┐",
"qr_1: |0>┤ U3(π/2,π/2,π/2) ├",
" └────────╥────────┘",
"qr_2: |0>─────────╫─────────",
" ║ ",
" cr: 0 ═════════■═════════",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cu3_tc_cregbundle(self):
"""Conditional Cu3 (target-control) with a wire in the middle with cregbundle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[1], qr[0]]).c_if(cr, 1)
expected = "\n".join(
[
" ┌─────────────────┐",
"qr_0: |0>┤ U3(π/2,π/2,π/2) ├",
" └────────┬────────┘",
"qr_1: |0>─────────■─────────",
" ║ ",
"qr_2: |0>─────────╫─────────",
" ┌──╨──┐ ",
" cr: 0 1/══════╡ 0x1 ╞══════",
" └─────┘ ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cu3_tc(self):
"""Conditional Cu3 (target-control) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[1], qr[0]]).c_if(cr, 1)
expected = "\n".join(
[
" ┌─────────────────┐",
"qr_0: |0>┤ U3(π/2,π/2,π/2) ├",
" └────────┬────────┘",
"qr_1: |0>─────────■─────────",
" ║ ",
"qr_2: |0>─────────╫─────────",
" ║ ",
" cr: 0 ═════════■═════════",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_ccx_cregbundle(self):
"""Conditional CCX with a wire in the middle with cregbundle"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───■───",
" ┌─┴─┐ ",
"qr_2: |0>─┤ X ├─",
" └─╥─┘ ",
"qr_3: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_ccx(self):
"""Conditional CCX with a wire in the middle"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──■──",
" ┌─┴─┐",
"qr_2: |0>┤ X ├",
" └─╥─┘",
"qr_3: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_ccx_no_space_cregbundle(self):
"""Conditional CCX without space with cregbundle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───■───",
" ┌─┴─┐ ",
"qr_2: |0>─┤ X ├─",
" ┌┴─╨─┴┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_ccx_no_space(self):
"""Conditional CCX without space"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──■──",
" ┌─┴─┐",
"qr_2: |0>┤ X ├",
" └─╥─┘",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_h_cregbundle(self):
"""Conditional H with a wire in the middle with cregbundle"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐ ",
"qr_0: |0>─┤ H ├─",
" └─╥─┘ ",
"qr_1: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_h(self):
"""Conditional H with a wire in the middle"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐",
"qr_0: |0>┤ H ├",
" └─╥─┘",
"qr_1: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_swap_cregbundle(self):
"""Conditional SWAP with cregbundle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───X───",
" │ ",
"qr_1: |0>───X───",
" ║ ",
"qr_2: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_swap(self):
"""Conditional SWAP"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──X──",
" │ ",
"qr_1: |0>──X──",
" ║ ",
"qr_2: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cswap_cregbundle(self):
"""Conditional CSwap with cregbundle"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cswap(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───X───",
" │ ",
"qr_2: |0>───X───",
" ║ ",
"qr_3: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cswap(self):
"""Conditional CSwap"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cswap(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──X──",
" │ ",
"qr_2: |0>──X──",
" ║ ",
"qr_3: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_conditional_reset_cregbundle(self):
"""Reset drawing with cregbundle."""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.reset(qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──|0>──",
" ║ ",
"qr_1: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_conditional_reset(self):
"""Reset drawing."""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.reset(qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>─|0>─",
" ║ ",
"qr_1: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_conditional_multiplexer_cregbundle(self):
"""Test Multiplexer with cregbundle."""
cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])])
qr = QuantumRegister(3, name="qr")
cr = ClassicalRegister(1, "cr")
qc = QuantumCircuit(qr, cr)
qc.append(cx_multiplexer.c_if(cr, 1), [qr[0], qr[1]])
expected = "\n".join(
[
" ┌──────────────┐",
"qr_0: |0>┤0 ├",
" │ Multiplexer │",
"qr_1: |0>┤1 ├",
" └──────╥───────┘",
"qr_2: |0>───────╫────────",
" ┌──╨──┐ ",
" cr: 0 1/════╡ 0x1 ╞═════",
" └─────┘ ",
]
)
self.assertEqual(str(_text_circuit_drawer(qc, cregbundle=True)), expected)
def test_conditional_multiplexer(self):
"""Test Multiplexer."""
cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])])
qr = QuantumRegister(3, name="qr")
cr = ClassicalRegister(1, "cr")
qc = QuantumCircuit(qr, cr)
qc.append(cx_multiplexer.c_if(cr, 1), [qr[0], qr[1]])
expected = "\n".join(
[
" ┌──────────────┐",
"qr_0: |0>┤0 ├",
" │ Multiplexer │",
"qr_1: |0>┤1 ├",
" └──────╥───────┘",
"qr_2: |0>───────╫────────",
" ║ ",
" cr: 0 ═══════■════════",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(qc, cregbundle=False)), expected)
def test_text_conditional_measure_cregbundle(self):
"""Conditional with measure on same clbit with cregbundle"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐┌─┐ ",
"qr_0: |0>┤ H ├┤M├───────",
" └───┘└╥┘ ┌───┐ ",
"qr_1: |0>──────╫──┤ H ├─",
" ║ ┌┴─╨─┴┐",
" cr: 0 2/══════╩═╡ 0x1 ╞",
" 0 └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_measure(self):
"""Conditional with measure on same clbit"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐┌─┐ ",
"qr_0: |0>┤ H ├┤M├─────",
" └───┘└╥┘┌───┐",
"qr_1: |0>──────╫─┤ H ├",
" ║ └─╥─┘",
" cr_0: 0 ══════╩═══■══",
" ║ ",
" cr_1: 0 ══════════o══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_bit_conditional(self):
"""Test bit conditions on gates"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.h(qr[1]).c_if(cr[1], 0)
expected = "\n".join(
[
" ┌───┐ ",
"qr_0: |0>┤ H ├─────",
" └─╥─┘┌───┐",
"qr_1: |0>──╫──┤ H ├",
" ║ └─╥─┘",
" cr_0: 0 ══■════╬══",
" ║ ",
" cr_1: 0 ═══════o══",
" ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_bit_conditional_cregbundle(self):
"""Test bit conditions on gates when cregbundle=True"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.h(qr[1]).c_if(cr[1], 0)
expected = "\n".join(
[
" ┌───┐ ",
"qr_0: |0>───┤ H ├────────────────",
" └─╥─┘ ┌───┐ ",
"qr_1: |0>─────╫─────────┤ H ├────",
" ║ └─╥─┘ ",
" ┌────╨─────┐┌────╨─────┐",
" cr: 0 2/╡ cr_0=0x1 ╞╡ cr_1=0x0 ╞",
" └──────────┘└──────────┘",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=True, vertical_compression="medium")),
expected,
)
def test_text_condition_measure_bits_true(self):
"""Condition and measure on single bits cregbundle true"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(crx[1], 0)
circuit.measure(0, bits[3])
expected = "\n".join(
[
" ┌───┐ ┌─┐",
" 0: ───┤ X ├────┤M├",
" └─╥─┘ └╥┘",
" 1: ─────╫───────╫─",
" ║ ║ ",
" 0: ═════╬═══════╬═",
" ║ ║ ",
" 1: ═════╬═══════╩═",
" ║ ",
"cr: 2/═════╬═════════",
" ║ ",
" 4: ═════╬═════════",
" ┌────╨─────┐ ",
"cs: 3/╡ cs_1=0x0 ╞═══",
" └──────────┘ ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=True, initial_state=False)), expected
)
def test_text_condition_measure_bits_false(self):
"""Condition and measure on single bits cregbundle false"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(crx[1], 0)
circuit.measure(0, bits[3])
expected = "\n".join(
[
" ┌───┐┌─┐",
" 0: ┤ X ├┤M├",
" └─╥─┘└╥┘",
" 1: ──╫───╫─",
" ║ ║ ",
" 0: ══╬═══╬═",
" ║ ║ ",
" 1: ══╬═══╩═",
" ║ ",
"cr_0: ══╬═════",
" ║ ",
"cr_1: ══╬═════",
" ║ ",
" 4: ══╬═════",
" ║ ",
"cs_0: ══╬═════",
" ║ ",
"cs_1: ══o═════",
" ",
"cs_2: ════════",
" ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, initial_state=False)), expected
)
def test_text_conditional_reverse_bits_1(self):
"""Classical condition on 2q2c circuit with cregbundle=False and reverse bits"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐",
"qr_1: |0>────────┤ H ├",
" ┌───┐┌─┐└─╥─┘",
"qr_0: |0>┤ H ├┤M├──╫──",
" └───┘└╥┘ ║ ",
" cr_1: 0 ══════╬═══o══",
" ║ ║ ",
" cr_0: 0 ══════╩═══■══",
" 0x1 ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, reverse_bits=True)), expected
)
def test_text_conditional_reverse_bits_2(self):
"""Classical condition on 3q3c circuit with cergbundle=False and reverse bits"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr, 6)
circuit.h(qr[1]).c_if(cr, 1)
circuit.h(qr[2]).c_if(cr, 2)
circuit.cx(0, 1).c_if(cr, 3)
expected = "\n".join(
[
" ┌───┐ ",
"qr_2: |0>──────────┤ H ├─────",
" ┌───┐└─╥─┘┌───┐",
"qr_1: |0>─────┤ H ├──╫──┤ X ├",
" ┌───┐└─╥─┘ ║ └─┬─┘",
"qr_0: |0>┤ H ├──╫────╫────■──",
" └─╥─┘ ║ ║ ║ ",
" cr_2: 0 ══■════o════o════o══",
" ║ ║ ║ ║ ",
" cr_1: 0 ══■════o════■════■══",
" ║ ║ ║ ║ ",
" cr_0: 0 ══o════■════o════■══",
" 0x6 0x1 0x2 0x3 ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, reverse_bits=True)), expected
)
def test_text_condition_bits_reverse(self):
"""Condition and measure on single bits cregbundle true and reverse_bits true"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(bits[3], 0)
expected = "\n".join(
[
" ",
" 1: ─────",
" ┌───┐",
" 0: ┤ X ├",
" └─╥─┘",
"cs: 3/══╬══",
" ║ ",
" 4: ══╬══",
" ║ ",
"cr: 2/══╬══",
" ║ ",
" 1: ══o══",
" ",
" 0: ═════",
" ",
]
)
self.assertEqual(
str(
_text_circuit_drawer(
circuit, cregbundle=True, initial_state=False, reverse_bits=True
)
),
expected,
)
class TestTextIdleWires(QiskitTestCase):
"""The idle_wires option"""
def test_text_h(self):
"""Remove QuWires."""
# fmt: off
expected = "\n".join([" ┌───┐",
"q1_1: |0>┤ H ├",
" └───┘"])
# fmt: on
qr1 = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr1)
circuit.h(qr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_text_measure(self):
"""Remove QuWires and ClWires."""
expected = "\n".join(
[
" ┌─┐ ",
"q2_0: |0>┤M├───",
" └╥┘┌─┐",
"q2_1: |0>─╫─┤M├",
" ║ └╥┘",
" c2: 0 2/═╩══╩═",
" 0 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
qr2 = QuantumRegister(2, "q2")
cr2 = ClassicalRegister(2, "c2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.measure(qr2, cr2)
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_text_empty_circuit(self):
"""Remove everything in an empty circuit."""
expected = ""
circuit = QuantumCircuit()
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_text_barrier(self):
"""idle_wires should ignore barrier
See https://github.com/Qiskit/qiskit-terra/issues/4391"""
# fmt: off
expected = "\n".join([" ┌───┐ ░ ",
"qr_1: |0>┤ H ├─░─",
" └───┘ ░ "])
# fmt: on
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[1])
circuit.barrier(qr[1], qr[2])
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_text_barrier_delay(self):
"""idle_wires should ignore delay"""
# fmt: off
expected = "\n".join([" ┌───┐ ░ ",
"qr_1: |0>┤ H ├─░──",
" └───┘ ░ "])
# fmt: on
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[1])
circuit.barrier()
circuit.delay(100, qr[2])
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_does_not_mutate_circuit(self):
"""Using 'idle_wires=False' should not mutate the circuit. Regression test of gh-8739."""
circuit = QuantumCircuit(1)
before_qubits = circuit.num_qubits
circuit.draw(idle_wires=False)
self.assertEqual(circuit.num_qubits, before_qubits)
class TestTextNonRational(QiskitTestCase):
"""non-rational numbers are correctly represented"""
def test_text_pifrac(self):
"""u drawing with -5pi/8 fraction"""
# fmt: off
expected = "\n".join(
[" ┌──────────────┐",
"q: |0>┤ U(π,-5π/8,0) ├",
" └──────────────┘"]
)
# fmt: on
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.u(pi, -5 * pi / 8, 0, qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_complex(self):
"""Complex numbers show up in the text
See https://github.com/Qiskit/qiskit-terra/issues/3640"""
expected = "\n".join(
[
" ┌────────────────────────────────────┐",
"q_0: ┤0 ├",
" │ Initialize(0.5+0.1j,0,0,0.86023j) │",
"q_1: ┤1 ├",
" └────────────────────────────────────┘",
]
)
ket = numpy.array([0.5 + 0.1 * 1j, 0, 0, 0.8602325267042626 * 1j])
circuit = QuantumCircuit(2)
circuit.initialize(ket, [0, 1])
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_text_complex_pireal(self):
"""Complex numbers including pi show up in the text
See https://github.com/Qiskit/qiskit-terra/issues/3640"""
expected = "\n".join(
[
" ┌────────────────────────────────┐",
"q_0: |0>┤0 ├",
" │ Initialize(π/10,0,0,0.94937j) │",
"q_1: |0>┤1 ├",
" └────────────────────────────────┘",
]
)
ket = numpy.array([0.1 * numpy.pi, 0, 0, 0.9493702944526474 * 1j])
circuit = QuantumCircuit(2)
circuit.initialize(ket, [0, 1])
self.assertEqual(circuit.draw(output="text", initial_state=True).single_string(), expected)
def test_text_complex_piimaginary(self):
"""Complex numbers including pi show up in the text
See https://github.com/Qiskit/qiskit-terra/issues/3640"""
expected = "\n".join(
[
" ┌────────────────────────────────┐",
"q_0: |0>┤0 ├",
" │ Initialize(0.94937,0,0,π/10j) │",
"q_1: |0>┤1 ├",
" └────────────────────────────────┘",
]
)
ket = numpy.array([0.9493702944526474, 0, 0, 0.1 * numpy.pi * 1j])
circuit = QuantumCircuit(2)
circuit.initialize(ket, [0, 1])
self.assertEqual(circuit.draw(output="text", initial_state=True).single_string(), expected)
class TestTextInstructionWithBothWires(QiskitTestCase):
"""Composite instructions with both kind of wires
See https://github.com/Qiskit/qiskit-terra/issues/2973"""
def test_text_all_1q_1c(self):
"""Test q0-c0 in q0-c0"""
expected = "\n".join(
[
" ┌───────┐",
"qr: |0>┤0 ├",
" │ name │",
" cr: 0 ╡0 ╞",
" └───────┘",
]
)
qr1 = QuantumRegister(1, "qr")
cr1 = ClassicalRegister(1, "cr")
inst = QuantumCircuit(qr1, cr1, name="name").to_instruction()
circuit = QuantumCircuit(qr1, cr1)
circuit.append(inst, qr1[:], cr1[:])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_all_2q_2c(self):
"""Test q0-q1-c0-c1 in q0-q1-c0-c1"""
expected = "\n".join(
[
" ┌───────┐",
"qr_0: |0>┤0 ├",
" │ │",
"qr_1: |0>┤1 ├",
" │ name │",
" cr_0: 0 ╡0 ╞",
" │ │",
" cr_1: 0 ╡1 ╞",
" └───────┘",
]
)
qr2 = QuantumRegister(2, "qr")
cr2 = ClassicalRegister(2, "cr")
inst = QuantumCircuit(qr2, cr2, name="name").to_instruction()
circuit = QuantumCircuit(qr2, cr2)
circuit.append(inst, qr2[:], cr2[:])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_all_2q_2c_cregbundle(self):
"""Test q0-q1-c0-c1 in q0-q1-c0-c1. Ignore cregbundle=True"""
expected = "\n".join(
[
" ┌───────┐",
"qr_0: |0>┤0 ├",
" │ │",
"qr_1: |0>┤1 ├",
" │ name │",
" cr_0: 0 ╡0 ╞",
" │ │",
" cr_1: 0 ╡1 ╞",
" └───────┘",
]
)
qr2 = QuantumRegister(2, "qr")
cr2 = ClassicalRegister(2, "cr")
inst = QuantumCircuit(qr2, cr2, name="name").to_instruction()
circuit = QuantumCircuit(qr2, cr2)
circuit.append(inst, qr2[:], cr2[:])
with self.assertWarns(RuntimeWarning):
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_4q_2c(self):
"""Test q1-q2-q3-q4-c1-c2 in q0-q1-q2-q3-q4-q5-c0-c1-c2-c3-c4-c5"""
expected = "\n".join(
[
" ",
"q_0: |0>─────────",
" ┌───────┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤1 ├",
" │ │",
"q_3: |0>┤2 ├",
" │ │",
"q_4: |0>┤3 ├",
" │ name │",
"q_5: |0>┤ ├",
" │ │",
" c_0: 0 ╡ ╞",
" │ │",
" c_1: 0 ╡0 ╞",
" │ │",
" c_2: 0 ╡1 ╞",
" └───────┘",
" c_3: 0 ═════════",
" ",
" c_4: 0 ═════════",
" ",
" c_5: 0 ═════════",
" ",
]
)
qr4 = QuantumRegister(4)
cr4 = ClassicalRegister(2)
inst = QuantumCircuit(qr4, cr4, name="name").to_instruction()
qr6 = QuantumRegister(6, "q")
cr6 = ClassicalRegister(6, "c")
circuit = QuantumCircuit(qr6, cr6)
circuit.append(inst, qr6[1:5], cr6[1:3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_2q_1c(self):
"""Test q0-c0 in q0-q1-c0
See https://github.com/Qiskit/qiskit-terra/issues/4066"""
expected = "\n".join(
[
" ┌───────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>┤ Name ├",
" │ │",
" c: 0 ╡0 ╞",
" └───────┘",
]
)
qr = QuantumRegister(2, name="q")
cr = ClassicalRegister(1, name="c")
circuit = QuantumCircuit(qr, cr)
inst = QuantumCircuit(1, 1, name="Name").to_instruction()
circuit.append(inst, [qr[0]], [cr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_3q_3c_qlabels_inverted(self):
"""Test q3-q0-q1-c0-c1-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11
See https://github.com/Qiskit/qiskit-terra/issues/6178"""
expected = "\n".join(
[
" ┌───────┐",
"q_0: |0>┤1 ├",
" │ │",
"q_1: |0>┤2 ├",
" │ │",
"q_2: |0>┤ ├",
" │ │",
"q_3: |0>┤0 ├",
" │ Name │",
" c_0: 0 ╡0 ╞",
" │ │",
" c_1: 0 ╡1 ╞",
" │ │",
" c_2: 0 ╡ ╞",
" │ │",
"c1_0: 0 ╡2 ╞",
" └───────┘",
"c1_1: 0 ═════════",
" ",
]
)
qr = QuantumRegister(4, name="q")
cr = ClassicalRegister(3, name="c")
cr1 = ClassicalRegister(2, name="c1")
circuit = QuantumCircuit(qr, cr, cr1)
inst = QuantumCircuit(3, 3, name="Name").to_instruction()
circuit.append(inst, [qr[3], qr[0], qr[1]], [cr[0], cr[1], cr1[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_3q_3c_clabels_inverted(self):
"""Test q0-q1-q3-c_11-c0-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11
See https://github.com/Qiskit/qiskit-terra/issues/6178"""
expected = "\n".join(
[
" ┌───────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>┤1 ├",
" │ │",
"q_2: |0>┤ ├",
" │ │",
"q_3: |0>┤2 ├",
" │ │",
" c_0: 0 ╡1 Name ╞",
" │ │",
" c_1: 0 ╡ ╞",
" │ │",
" c_2: 0 ╡ ╞",
" │ │",
"c1_0: 0 ╡2 ╞",
" │ │",
"c1_1: 0 ╡0 ╞",
" └───────┘",
]
)
qr = QuantumRegister(4, name="q")
cr = ClassicalRegister(3, name="c")
cr1 = ClassicalRegister(2, name="c1")
circuit = QuantumCircuit(qr, cr, cr1)
inst = QuantumCircuit(3, 3, name="Name").to_instruction()
circuit.append(inst, [qr[0], qr[1], qr[3]], [cr1[1], cr[0], cr1[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_3q_3c_qclabels_inverted(self):
"""Test q3-q1-q2-c_11-c0-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11
See https://github.com/Qiskit/qiskit-terra/issues/6178"""
expected = "\n".join(
[
" ",
"q_0: |0>─────────",
" ┌───────┐",
"q_1: |0>┤1 ├",
" │ │",
"q_2: |0>┤2 ├",
" │ │",
"q_3: |0>┤0 ├",
" │ │",
" c_0: 0 ╡1 ╞",
" │ Name │",
" c_1: 0 ╡ ╞",
" │ │",
" c_2: 0 ╡ ╞",
" │ │",
"c1_0: 0 ╡2 ╞",
" │ │",
"c1_1: 0 ╡0 ╞",
" └───────┘",
]
)
qr = QuantumRegister(4, name="q")
cr = ClassicalRegister(3, name="c")
cr1 = ClassicalRegister(2, name="c1")
circuit = QuantumCircuit(qr, cr, cr1)
inst = QuantumCircuit(3, 3, name="Name").to_instruction()
circuit.append(inst, [qr[3], qr[1], qr[2]], [cr1[1], cr[0], cr1[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextDrawerAppendedLargeInstructions(QiskitTestCase):
"""Composite instructions with more than 10 qubits
See https://github.com/Qiskit/qiskit-terra/pull/4095"""
def test_text_11q(self):
"""Test q0-...-q10 in q0-...-q10"""
expected = "\n".join(
[
" ┌────────┐",
" q_0: |0>┤0 ├",
" │ │",
" q_1: |0>┤1 ├",
" │ │",
" q_2: |0>┤2 ├",
" │ │",
" q_3: |0>┤3 ├",
" │ │",
" q_4: |0>┤4 ├",
" │ │",
" q_5: |0>┤5 Name ├",
" │ │",
" q_6: |0>┤6 ├",
" │ │",
" q_7: |0>┤7 ├",
" │ │",
" q_8: |0>┤8 ├",
" │ │",
" q_9: |0>┤9 ├",
" │ │",
"q_10: |0>┤10 ├",
" └────────┘",
]
)
qr = QuantumRegister(11, "q")
circuit = QuantumCircuit(qr)
inst = QuantumCircuit(11, name="Name").to_instruction()
circuit.append(inst, qr)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_11q_1c(self):
"""Test q0-...-q10-c0 in q0-...-q10-c0"""
expected = "\n".join(
[
" ┌────────┐",
" q_0: |0>┤0 ├",
" │ │",
" q_1: |0>┤1 ├",
" │ │",
" q_2: |0>┤2 ├",
" │ │",
" q_3: |0>┤3 ├",
" │ │",
" q_4: |0>┤4 ├",
" │ │",
" q_5: |0>┤5 ├",
" │ Name │",
" q_6: |0>┤6 ├",
" │ │",
" q_7: |0>┤7 ├",
" │ │",
" q_8: |0>┤8 ├",
" │ │",
" q_9: |0>┤9 ├",
" │ │",
"q_10: |0>┤10 ├",
" │ │",
" c: 0 ╡0 ╞",
" └────────┘",
]
)
qr = QuantumRegister(11, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
inst = QuantumCircuit(11, 1, name="Name").to_instruction()
circuit.append(inst, qr, cr)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextControlledGate(QiskitTestCase):
"""Test controlled gates"""
def test_cch_bot(self):
"""Controlled CH (bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" │ ",
"q_1: |0>──■──",
" ┌─┴─┐",
"q_2: |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2), [qr[0], qr[1], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_mid(self):
"""Controlled CH (middle)"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └─┬─┘",
"q_2: |0>──■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2), [qr[0], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_top(self):
"""Controlled CH"""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>┤ H ├",
" └─┬─┘",
"q_1: |0>──■──",
" │ ",
"q_2: |0>──■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2), [qr[2], qr[1], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3h(self):
"""Controlled Controlled CH"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" │ ",
"q_1: |0>──■──",
" │ ",
"q_2: |0>──■──",
" ┌─┴─┐",
"q_3: |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(3), [qr[0], qr[1], qr[2], qr[3]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3h_middle(self):
"""Controlled Controlled CH (middle)"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └─┬─┘",
"q_2: |0>──■──",
" │ ",
"q_3: |0>──■──",
" ",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(3), [qr[0], qr[3], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3u2(self):
"""Controlled Controlled U2"""
expected = "\n".join(
[
" ",
"q_0: |0>───────■───────",
" ┌──────┴──────┐",
"q_1: |0>┤ U2(π,-5π/8) ├",
" └──────┬──────┘",
"q_2: |0>───────■───────",
" │ ",
"q_3: |0>───────■───────",
" ",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(U2Gate(pi, -5 * pi / 8).control(3), [qr[0], qr[3], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_edge(self):
"""Controlled composite gates (edge)
See: https://github.com/Qiskit/qiskit-terra/issues/3546"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>■ ├",
" │ ghz │",
"q_2: |0>┤1 ├",
" │ │",
"q_3: |0>┤2 ├",
" └──────┘",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1)
circuit = QuantumCircuit(4)
circuit.append(cghz, [1, 0, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_top(self):
"""Controlled composite gates (top)"""
expected = "\n".join(
[
" ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤2 ghz ├",
" │ │",
"q_3: |0>┤1 ├",
" └──────┘",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1)
circuit = QuantumCircuit(4)
circuit.append(cghz, [0, 1, 3, 2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_bot(self):
"""Controlled composite gates (bottom)"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤1 ├",
" │ │",
"q_1: |0>┤0 ghz ├",
" │ │",
"q_2: |0>┤2 ├",
" └──┬───┘",
"q_3: |0>───■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1)
circuit = QuantumCircuit(4)
circuit.append(cghz, [3, 1, 0, 2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_top_bot(self):
"""Controlled composite gates (top and bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤1 ghz ├",
" │ │",
"q_3: |0>┤2 ├",
" └──┬───┘",
"q_4: |0>───■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2)
circuit = QuantumCircuit(5)
circuit.append(ccghz, [4, 0, 1, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_all(self):
"""Controlled composite gates (top, bot, and edge)"""
expected = "\n".join(
[
" ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>■ ├",
" │ ghz │",
"q_3: |0>┤1 ├",
" │ │",
"q_4: |0>┤2 ├",
" └──┬───┘",
"q_5: |0>───■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(3)
circuit = QuantumCircuit(6)
circuit.append(ccghz, [0, 2, 5, 1, 3, 4])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_even_label(self):
"""Controlled composite gates (top and bottom) with a even label length"""
expected = "\n".join(
[
" ",
"q_0: |0>────■────",
" ┌───┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤1 cghz ├",
" │ │",
"q_3: |0>┤2 ├",
" └───┬───┘",
"q_4: |0>────■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="cghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2)
circuit = QuantumCircuit(5)
circuit.append(ccghz, [4, 0, 1, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextOpenControlledGate(QiskitTestCase):
"""Test open controlled gates"""
def test_ch_bot(self):
"""Open controlled H (bottom)"""
# fmt: off
expected = "\n".join(
[" ",
"q_0: |0>──o──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └───┘"]
)
# fmt: on
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(1, ctrl_state=0), [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cz_bot(self):
"""Open controlled Z (bottom)"""
# fmt: off
expected = "\n".join([" ",
"q_0: |0>─o─",
" │ ",
"q_1: |0>─■─",
" "])
# fmt: on
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.append(ZGate().control(1, ctrl_state=0), [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_ccz_bot(self):
"""Closed-Open controlled Z (bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>─■─",
" │ ",
"q_1: |0>─o─",
" │ ",
"q_2: |0>─■─",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(ZGate().control(2, ctrl_state="01"), [qr[0], qr[1], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cccz_conditional(self):
"""Closed-Open controlled Z (with conditional)"""
expected = "\n".join(
[
" ",
"q_0: |0>───■───",
" │ ",
"q_1: |0>───o───",
" │ ",
"q_2: |0>───■───",
" │ ",
"q_3: |0>───■───",
" ┌──╨──┐",
" c: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(
ZGate().control(3, ctrl_state="101").c_if(cr, 1), [qr[0], qr[1], qr[2], qr[3]]
)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_bot(self):
"""Controlled CH (bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>──o──",
" │ ",
"q_1: |0>──■──",
" ┌─┴─┐",
"q_2: |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2, ctrl_state="10"), [qr[0], qr[1], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_mid(self):
"""Controlled CH (middle)"""
expected = "\n".join(
[
" ",
"q_0: |0>──o──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └─┬─┘",
"q_2: |0>──■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2, ctrl_state="10"), [qr[0], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_top(self):
"""Controlled CH"""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>┤ H ├",
" └─┬─┘",
"q_1: |0>──o──",
" │ ",
"q_2: |0>──■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2, ctrl_state="10"), [qr[1], qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3h(self):
"""Controlled Controlled CH"""
expected = "\n".join(
[
" ",
"q_0: |0>──o──",
" │ ",
"q_1: |0>──o──",
" │ ",
"q_2: |0>──■──",
" ┌─┴─┐",
"q_3: |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(3, ctrl_state="100"), [qr[0], qr[1], qr[2], qr[3]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3h_middle(self):
"""Controlled Controlled CH (middle)"""
expected = "\n".join(
[
" ",
"q_0: |0>──o──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └─┬─┘",
"q_2: |0>──o──",
" │ ",
"q_3: |0>──■──",
" ",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(3, ctrl_state="010"), [qr[0], qr[3], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3u2(self):
"""Controlled Controlled U2"""
expected = "\n".join(
[
" ",
"q_0: |0>───────o───────",
" ┌──────┴──────┐",
"q_1: |0>┤ U2(π,-5π/8) ├",
" └──────┬──────┘",
"q_2: |0>───────■───────",
" │ ",
"q_3: |0>───────o───────",
" ",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(
U2Gate(pi, -5 * pi / 8).control(3, ctrl_state="100"), [qr[0], qr[3], qr[2], qr[1]]
)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_edge(self):
"""Controlled composite gates (edge)
See: https://github.com/Qiskit/qiskit-terra/issues/3546"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>o ├",
" │ ghz │",
"q_2: |0>┤1 ├",
" │ │",
"q_3: |0>┤2 ├",
" └──────┘",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1, ctrl_state="0")
circuit = QuantumCircuit(4)
circuit.append(cghz, [1, 0, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_top(self):
"""Controlled composite gates (top)"""
expected = "\n".join(
[
" ",
"q_0: |0>───o────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤2 ghz ├",
" │ │",
"q_3: |0>┤1 ├",
" └──────┘",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1, ctrl_state="0")
circuit = QuantumCircuit(4)
circuit.append(cghz, [0, 1, 3, 2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_bot(self):
"""Controlled composite gates (bottom)"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤1 ├",
" │ │",
"q_1: |0>┤0 ghz ├",
" │ │",
"q_2: |0>┤2 ├",
" └──┬───┘",
"q_3: |0>───o────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1, ctrl_state="0")
circuit = QuantumCircuit(4)
circuit.append(cghz, [3, 1, 0, 2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_top_bot(self):
"""Controlled composite gates (top and bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>───o────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤1 ghz ├",
" │ │",
"q_3: |0>┤2 ├",
" └──┬───┘",
"q_4: |0>───■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2, ctrl_state="01")
circuit = QuantumCircuit(5)
circuit.append(ccghz, [4, 0, 1, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_all(self):
"""Controlled composite gates (top, bot, and edge)"""
expected = "\n".join(
[
" ",
"q_0: |0>───o────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>o ├",
" │ ghz │",
"q_3: |0>┤1 ├",
" │ │",
"q_4: |0>┤2 ├",
" └──┬───┘",
"q_5: |0>───o────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(3, ctrl_state="000")
circuit = QuantumCircuit(6)
circuit.append(ccghz, [0, 2, 5, 1, 3, 4])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_x(self):
"""Controlled X gates.
See https://github.com/Qiskit/qiskit-terra/issues/4180"""
expected = "\n".join(
[
" ",
"qr_0: |0>──o────o────o────o────■──",
" ┌─┴─┐ │ │ │ │ ",
"qr_1: |0>┤ X ├──o────■────■────o──",
" └───┘┌─┴─┐┌─┴─┐ │ │ ",
"qr_2: |0>─────┤ X ├┤ X ├──o────o──",
" └───┘└───┘┌─┴─┐┌─┴─┐",
"qr_3: |0>───────────────┤ X ├┤ X ├",
" └───┘└─┬─┘",
"qr_4: |0>──────────────────────■──",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = XGate().control(1, ctrl_state="0")
circuit.append(control1, [0, 1])
control2 = XGate().control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2])
control2_2 = XGate().control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2])
control3 = XGate().control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3])
control3 = XGate().control(4, ctrl_state="0101")
circuit.append(control3, [0, 1, 4, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_y(self):
"""Controlled Y gates.
See https://github.com/Qiskit/qiskit-terra/issues/4180"""
expected = "\n".join(
[
" ",
"qr_0: |0>──o────o────o────o────■──",
" ┌─┴─┐ │ │ │ │ ",
"qr_1: |0>┤ Y ├──o────■────■────o──",
" └───┘┌─┴─┐┌─┴─┐ │ │ ",
"qr_2: |0>─────┤ Y ├┤ Y ├──o────o──",
" └───┘└───┘┌─┴─┐┌─┴─┐",
"qr_3: |0>───────────────┤ Y ├┤ Y ├",
" └───┘└─┬─┘",
"qr_4: |0>──────────────────────■──",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = YGate().control(1, ctrl_state="0")
circuit.append(control1, [0, 1])
control2 = YGate().control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2])
control2_2 = YGate().control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2])
control3 = YGate().control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3])
control3 = YGate().control(4, ctrl_state="0101")
circuit.append(control3, [0, 1, 4, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_z(self):
"""Controlled Z gates."""
expected = "\n".join(
[
" ",
"qr_0: |0>─o──o──o──o──■─",
" │ │ │ │ │ ",
"qr_1: |0>─■──o──■──■──o─",
" │ │ │ │ ",
"qr_2: |0>────■──■──o──o─",
" │ │ ",
"qr_3: |0>──────────■──■─",
" │ ",
"qr_4: |0>─────────────■─",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = ZGate().control(1, ctrl_state="0")
circuit.append(control1, [0, 1])
control2 = ZGate().control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2])
control2_2 = ZGate().control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2])
control3 = ZGate().control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3])
control3 = ZGate().control(4, ctrl_state="0101")
circuit.append(control3, [0, 1, 4, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_u1(self):
"""Controlled U1 gates."""
expected = "\n".join(
[
" ",
"qr_0: |0>─o─────────o─────────o─────────o─────────■────────",
" │U1(0.1) │ │ │ │ ",
"qr_1: |0>─■─────────o─────────■─────────■─────────o────────",
" │U1(0.2) │U1(0.3) │ │ ",
"qr_2: |0>───────────■─────────■─────────o─────────o────────",
" │U1(0.4) │ ",
"qr_3: |0>───────────────────────────────■─────────■────────",
" │U1(0.5) ",
"qr_4: |0>─────────────────────────────────────────■────────",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = U1Gate(0.1).control(1, ctrl_state="0")
circuit.append(control1, [0, 1])
control2 = U1Gate(0.2).control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2])
control2_2 = U1Gate(0.3).control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2])
control3 = U1Gate(0.4).control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3])
control3 = U1Gate(0.5).control(4, ctrl_state="0101")
circuit.append(control3, [0, 1, 4, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_swap(self):
"""Controlled SWAP gates."""
expected = "\n".join(
[
" ",
"qr_0: |0>─o──o──o──o─",
" │ │ │ │ ",
"qr_1: |0>─X──o──■──■─",
" │ │ │ │ ",
"qr_2: |0>─X──X──X──o─",
" │ │ │ ",
"qr_3: |0>────X──X──X─",
" │ ",
"qr_4: |0>──────────X─",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = SwapGate().control(1, ctrl_state="0")
circuit.append(control1, [0, 1, 2])
control2 = SwapGate().control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2, 3])
control2_2 = SwapGate().control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2, 3])
control3 = SwapGate().control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3, 4])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_rzz(self):
"""Controlled RZZ gates."""
expected = "\n".join(
[
" ",
"qr_0: |0>─o───────o───────o───────o──────",
" │ │ │ │ ",
"qr_1: |0>─■───────o───────■───────■──────",
" │ZZ(1) │ │ │ ",
"qr_2: |0>─■───────■───────■───────o──────",
" │ZZ(1) │ZZ(1) │ ",
"qr_3: |0>─────────■───────■───────■──────",
" │ZZ(1) ",
"qr_4: |0>─────────────────────────■──────",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = RZZGate(1).control(1, ctrl_state="0")
circuit.append(control1, [0, 1, 2])
control2 = RZZGate(1).control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2, 3])
control2_2 = RZZGate(1).control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2, 3])
control3 = RZZGate(1).control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3, 4])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_out_of_order(self):
"""Out of order CXs
See: https://github.com/Qiskit/qiskit-terra/issues/4052#issuecomment-613736911"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" │ ",
"q_1: |0>──■──",
" ┌─┴─┐",
"q_2: |0>┤ X ├",
" └─┬─┘",
"q_3: |0>──o──",
" ",
"q_4: |0>─────",
" ",
]
)
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.append(XGate().control(3, ctrl_state="101"), [qr[0], qr[3], qr[1], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextWithLayout(QiskitTestCase):
"""The with_layout option"""
def test_with_no_layout(self):
"""A circuit without layout"""
expected = "\n".join(
[
" ",
"q_0: |0>─────",
" ┌───┐",
"q_1: |0>┤ H ├",
" └───┘",
"q_2: |0>─────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_mixed_layout(self):
"""With a mixed layout."""
expected = "\n".join(
[
" ┌───┐",
" v_0 -> 0 |0>┤ H ├",
" └───┘",
"ancilla_1 -> 1 |0>─────",
" ",
"ancilla_0 -> 2 |0>─────",
" ┌───┐",
" v_1 -> 3 |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(2, "v")
ancilla = QuantumRegister(2, "ancilla")
circuit = QuantumCircuit(qr, ancilla)
circuit.h(qr)
pass_ = ApplyLayout()
pass_.property_set["layout"] = Layout({qr[0]: 0, ancilla[1]: 1, ancilla[0]: 2, qr[1]: 3})
circuit_with_layout = pass_(circuit)
self.assertEqual(str(_text_circuit_drawer(circuit_with_layout)), expected)
def test_partial_layout(self):
"""With a partial layout.
See: https://github.com/Qiskit/qiskit-terra/issues/4757"""
expected = "\n".join(
[
" ┌───┐",
"v_0 -> 0 |0>┤ H ├",
" └───┘",
" 1 |0>─────",
" ",
" 2 |0>─────",
" ┌───┐",
"v_1 -> 3 |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(2, "v")
pqr = QuantumRegister(4, "physical")
circuit = QuantumCircuit(pqr)
circuit.h(0)
circuit.h(3)
circuit._layout = TranspileLayout(
Layout({0: qr[0], 1: None, 2: None, 3: qr[1]}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
circuit._layout.initial_layout.add_register(qr)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_with_classical_regs(self):
"""Involving classical registers"""
expected = "\n".join(
[
" ",
"qr1_0 -> 0 |0>──────",
" ",
"qr1_1 -> 1 |0>──────",
" ┌─┐ ",
"qr2_0 -> 2 |0>┤M├───",
" └╥┘┌─┐",
"qr2_1 -> 3 |0>─╫─┤M├",
" ║ └╥┘",
" cr: 0 2/═╩══╩═",
" 0 1 ",
]
)
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(2, "qr2")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr1, qr2, cr)
circuit.measure(qr2[0], cr[0])
circuit.measure(qr2[1], cr[1])
pass_ = ApplyLayout()
pass_.property_set["layout"] = Layout({qr1[0]: 0, qr1[1]: 1, qr2[0]: 2, qr2[1]: 3})
circuit_with_layout = pass_(circuit)
self.assertEqual(str(_text_circuit_drawer(circuit_with_layout)), expected)
def test_with_layout_but_disable(self):
"""With parameter without_layout=False"""
expected = "\n".join(
[
" ",
"q_0: |0>──────",
" ",
"q_1: |0>──────",
" ┌─┐ ",
"q_2: |0>┤M├───",
" └╥┘┌─┐",
"q_3: |0>─╫─┤M├",
" ║ └╥┘",
"cr: 0 2/═╩══╩═",
" 0 1 ",
]
)
pqr = QuantumRegister(4, "q")
qr1 = QuantumRegister(2, "qr1")
cr = ClassicalRegister(2, "cr")
qr2 = QuantumRegister(2, "qr2")
circuit = QuantumCircuit(pqr, cr)
circuit._layout = Layout({qr1[0]: 0, qr1[1]: 1, qr2[0]: 2, qr2[1]: 3})
circuit.measure(pqr[2], cr[0])
circuit.measure(pqr[3], cr[1])
self.assertEqual(str(_text_circuit_drawer(circuit, with_layout=False)), expected)
def test_after_transpile(self):
"""After transpile, the drawing should include the layout"""
expected = "\n".join(
[
" ┌─────────┐┌─────────┐┌───┐┌─────────┐┌─┐ ",
" userqr_0 -> 0 ┤ U2(0,π) ├┤ U2(0,π) ├┤ X ├┤ U2(0,π) ├┤M├───",
" ├─────────┤├─────────┤└─┬─┘├─────────┤└╥┘┌─┐",
" userqr_1 -> 1 ┤ U2(0,π) ├┤ U2(0,π) ├──■──┤ U2(0,π) ├─╫─┤M├",
" └─────────┘└─────────┘ └─────────┘ ║ └╥┘",
" ancilla_0 -> 2 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_1 -> 3 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_2 -> 4 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_3 -> 5 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_4 -> 6 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_5 -> 7 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_6 -> 8 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_7 -> 9 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_8 -> 10 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_9 -> 11 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
"ancilla_10 -> 12 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
"ancilla_11 -> 13 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" c0_0: ═══════════════════════════════════════╩══╬═",
" ║ ",
" c0_1: ══════════════════════════════════════════╩═",
" ",
]
)
qr = QuantumRegister(2, "userqr")
cr = ClassicalRegister(2, "c0")
qc = QuantumCircuit(qr, cr)
qc.h(qr)
qc.cx(qr[0], qr[1])
qc.measure(qr, cr)
coupling_map = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
qc_result = transpile(
qc,
basis_gates=["u1", "u2", "u3", "cx", "id"],
coupling_map=coupling_map,
optimization_level=0,
seed_transpiler=0,
)
self.assertEqual(qc_result.draw(output="text", cregbundle=False).single_string(), expected)
class TestTextInitialValue(QiskitTestCase):
"""Testing the initial_state parameter"""
def setUp(self) -> None:
super().setUp()
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
self.circuit = QuantumCircuit(qr, cr)
self.circuit.measure(qr, cr)
def test_draw_initial_value_default(self):
"""Text drawer (.draw) default initial_state parameter (False)."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: ┤M├───",
" └╥┘┌─┐",
"q_1: ─╫─┤M├",
" ║ └╥┘",
"c_0: ═╩══╬═",
" ║ ",
"c_1: ════╩═",
" ",
]
)
self.assertEqual(
self.circuit.draw(output="text", cregbundle=False).single_string(), expected
)
def test_draw_initial_value_true(self):
"""Text drawer .draw(initial_state=True)."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├───",
" └╥┘┌─┐",
"q_1: |0>─╫─┤M├",
" ║ └╥┘",
" c_0: 0 ═╩══╬═",
" ║ ",
" c_1: 0 ════╩═",
" ",
]
)
self.assertEqual(
self.circuit.draw(output="text", initial_state=True, cregbundle=False).single_string(),
expected,
)
def test_initial_value_false(self):
"""Text drawer with initial_state parameter False."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: ┤M├───",
" └╥┘┌─┐",
"q_1: ─╫─┤M├",
" ║ └╥┘",
"c: 2/═╩══╩═",
" 0 1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(self.circuit, initial_state=False)), expected)
class TestTextHamiltonianGate(QiskitTestCase):
"""Testing the Hamiltonian gate drawer"""
def test_draw_hamiltonian_single(self):
"""Text Hamiltonian gate with single qubit."""
# fmt: off
expected = "\n".join([" ┌─────────────┐",
"q0: ┤ Hamiltonian ├",
" └─────────────┘"])
# fmt: on
qr = QuantumRegister(1, "q0")
circuit = QuantumCircuit(qr)
matrix = numpy.zeros((2, 2))
theta = Parameter("theta")
circuit.append(HamiltonianGate(matrix, theta), [qr[0]])
circuit = circuit.bind_parameters({theta: 1})
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_draw_hamiltonian_multi(self):
"""Text Hamiltonian gate with mutiple qubits."""
expected = "\n".join(
[
" ┌──────────────┐",
"q0_0: ┤0 ├",
" │ Hamiltonian │",
"q0_1: ┤1 ├",
" └──────────────┘",
]
)
qr = QuantumRegister(2, "q0")
circuit = QuantumCircuit(qr)
matrix = numpy.zeros((4, 4))
theta = Parameter("theta")
circuit.append(HamiltonianGate(matrix, theta), [qr[0], qr[1]])
circuit = circuit.bind_parameters({theta: 1})
self.assertEqual(circuit.draw(output="text").single_string(), expected)
class TestTextPhase(QiskitTestCase):
"""Testing the draweing a circuit with phase"""
def test_bell(self):
"""Text Bell state with phase."""
expected = "\n".join(
[
"global phase: \u03C0/2",
" ┌───┐ ",
"q_0: ┤ H ├──■──",
" └───┘┌─┴─┐",
"q_1: ─────┤ X ├",
" └───┘",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.global_phase = 3.141592653589793 / 2
circuit.h(0)
circuit.cx(0, 1)
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_empty(self):
"""Text empty circuit (two registers) with phase."""
# fmt: off
expected = "\n".join(["global phase: 3",
" ",
"q_0: ",
" ",
"q_1: ",
" "])
# fmt: on
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.global_phase = 3
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_empty_noregs(self):
"""Text empty circuit (no registers) with phase."""
expected = "\n".join(["global phase: 4.21"])
circuit = QuantumCircuit()
circuit.global_phase = 4.21
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_registerless_one_bit(self):
"""Text circuit with one-bit registers and registerless bits."""
# fmt: off
expected = "\n".join([" ",
"qrx_0: ",
" ",
"qrx_1: ",
" ",
" 2: ",
" ",
" 3: ",
" ",
" qry: ",
" ",
" 0: ",
" ",
" 1: ",
" ",
"crx: 2/",
" "])
# fmt: on
qrx = QuantumRegister(2, "qrx")
qry = QuantumRegister(1, "qry")
crx = ClassicalRegister(2, "crx")
circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx)
self.assertEqual(circuit.draw(output="text", cregbundle=True).single_string(), expected)
class TestCircuitVisualizationImplementation(QiskitVisualizationTestCase):
"""Tests utf8 and cp437 encoding."""
text_reference_utf8 = path_to_diagram_reference("circuit_text_ref_utf8.txt")
text_reference_cp437 = path_to_diagram_reference("circuit_text_ref_cp437.txt")
def sample_circuit(self):
"""Generate a sample circuit that includes the most common elements of
quantum circuits.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.y(qr[0])
circuit.z(qr[0])
circuit.barrier(qr[0])
circuit.barrier(qr[1])
circuit.barrier(qr[2])
circuit.h(qr[0])
circuit.s(qr[0])
circuit.sdg(qr[0])
circuit.t(qr[0])
circuit.tdg(qr[0])
circuit.sx(qr[0])
circuit.sxdg(qr[0])
circuit.i(qr[0])
circuit.reset(qr[0])
circuit.rx(pi, qr[0])
circuit.ry(pi, qr[0])
circuit.rz(pi, qr[0])
circuit.append(U1Gate(pi), [qr[0]])
circuit.append(U2Gate(pi, pi), [qr[0]])
circuit.append(U3Gate(pi, pi, pi), [qr[0]])
circuit.swap(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cy(qr[0], qr[1])
circuit.cz(qr[0], qr[1])
circuit.ch(qr[0], qr[1])
circuit.append(CU1Gate(pi), [qr[0], qr[1]])
circuit.append(CU3Gate(pi, pi, pi), [qr[0], qr[1]])
circuit.crz(pi, qr[0], qr[1])
circuit.cry(pi, qr[0], qr[1])
circuit.crx(pi, qr[0], qr[1])
circuit.ccx(qr[0], qr[1], qr[2])
circuit.cswap(qr[0], qr[1], qr[2])
circuit.measure(qr, cr)
return circuit
def test_text_drawer_utf8(self):
"""Test that text drawer handles utf8 encoding."""
filename = "current_textplot_utf8.txt"
qc = self.sample_circuit()
output = _text_circuit_drawer(
qc, filename=filename, fold=-1, initial_state=True, cregbundle=False, encoding="utf8"
)
try:
encode(str(output), encoding="utf8")
except UnicodeEncodeError:
self.fail("_text_circuit_drawer() should be utf8.")
self.assertFilesAreEqual(filename, self.text_reference_utf8, "utf8")
os.remove(filename)
def test_text_drawer_cp437(self):
"""Test that text drawer handles cp437 encoding."""
filename = "current_textplot_cp437.txt"
qc = self.sample_circuit()
output = _text_circuit_drawer(
qc, filename=filename, fold=-1, initial_state=True, cregbundle=False, encoding="cp437"
)
try:
encode(str(output), encoding="cp437")
except UnicodeEncodeError:
self.fail("_text_circuit_drawer() should be cp437.")
self.assertFilesAreEqual(filename, self.text_reference_cp437, "cp437")
os.remove(filename)
if __name__ == "__main__":
unittest.main()
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
from collections import OrderedDict
import time
import os
import logging, warnings
from qiskit.optimization.algorithms import CplexOptimizer
from qiskit.optimization.algorithms.optimization_algorithm import OptimizationResultStatus
from dwave.system import DWaveCliqueSampler, LeapHybridSampler
from random_lp.lp_random_gen import create_models
from utilities.helpers import create_dwave_meo
TEST_DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y") + "/DENSE/"
RES_DIR = 'RESULTS' + "/" + time.strftime("%d_%m_%Y") + "/DENSE/"
os.makedirs(RES_DIR, exist_ok=True)
TEST_DIR
logger = logging.getLogger()
logger.setLevel(logging.INFO)
warnings.filterwarnings("ignore", category=DeprecationWarning)
qps = create_models(TEST_DIR)
# init Optimizers
cplex = CplexOptimizer()
hybrid = create_dwave_meo(LeapHybridSampler())
clique = create_dwave_meo(DWaveCliqueSampler(), num_reads=4096)
dwave_auto = create_dwave_meo(num_reads=4096)
results = OrderedDict()
count_fail_hybrid, count_fail_dwave = 0, 0
for qp_name, qp in qps.items() :
print(qp_name)
print("number of qubits: ", qp.qubo.get_num_vars())
output_file_handler = logging.FileHandler(filename=RES_DIR + qp.name + ".log")
logger.addHandler(output_file_handler)
# set problem labels
for solver, label in zip([hybrid, clique, dwave_auto], ["hybrid_", "clique_", "auto_emb_"]):
solver.min_eigen_solver.sampler.set_label(label + qp_name + "_" + str(qp.complexity()))
if qp.qubo.get_num_vars() > clique.min_eigen_solver.sampler.child.largest_clique_size:
dwave = dwave_auto
else:
dwave = clique
with open(RES_DIR + qp.name + '.res', 'w') as file:
file.write(str("Start " + qp.name + "\n " + str(qp.qubo.get_num_vars()) + " qubits needed"))
file.write("\n Leap: \n")
logger.info("\n Leap: \n ")
res_classic = cplex.solve(qp)
res_hybrid = hybrid.solve(qp)
logger.info(str(res_hybrid.min_eigen_solver_result.sampleset.info))
if res_hybrid.status != OptimizationResultStatus.SUCCESS:
file.write("No solution found with DWave Hybrid Sampler Leap.")
file.write("\n CPLEX:\n")
file.write(str(res_classic))
count_fail_hybrid = count_fail_hybrid + 1
if count_fail_hybrid > 2 :
break
else:
print("Leap successful!")
count_fail_hybrid = 0
if res_hybrid.fval == res_classic.fval:
file.write("\n Leap found optimal solution\n")
else:
print("\n optimal value Leap "+str(res_hybrid.fval) + " , cplex:"+ str(res_classic.fval))
file.write("\n Leap: \n")
file.write(str(res_hybrid))
file.write("\n CPLEX:\n")
file.write(str(res_classic))
if count_fail_dwave <= 2:
file.write("\n DWave Quantum: \n")
logger.info("\n DWave Quantum: \n ")
try:
res_quantum = dwave.solve(qp)
problem_id = str(res_quantum.min_eigen_solver_result.sampleset.info['problem_id'])
logger.info("\n problem id " + problem_id)
file.write("\n problem id: " + problem_id)
if res_quantum.status != OptimizationResultStatus.SUCCESS:
print("Dwave quantum solver found no solution.")
file.write("\n No solution found with DWave Quantum Solver \n")
count_fail_dwave = count_fail_dwave + 1
if count_fail_dwave == 3:
file.write("\n Stop testing DWave Quantum Solver \n")
else:
print("Dwave Quantum successful!")
count_fail_dwave = 0
if res_quantum.fval == res_classic.fval:
file.write("\n DWave quantum solver found optimal solution\n")
else:
print("\n optimal value Dwave quantum "+str(res_quantum.fval) + " , cplex:"+ str(res_classic.fval))
file.write("\n DWave quantum solver:\n")
file.write(str(res_quantum))
file.write("\n CPLEX:\n")
file.write(str(res_classic))
except Exception as ex:
print(qp_name, " ", type(ex).__name__, " : ", ex)
file.write("\n DWave Solver produced an exception:\n")
file.write(str(ex))
logger.removeHandler(output_file_handler)
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import networkx as nx
import dwave_networkx as dnx
from dwave.system import DWaveCliqueSampler
sampler = DWaveCliqueSampler()
a = sampler.largest_clique_size
K_a = nx.complete_graph(a)
clique = dnx.maximum_clique(K_a, sampler = sampler)
for node in K_a.nodes :
if node not in clique:
print(f"Missing {node =}")
print(len(clique))
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
from builtins import format
import pytest
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
@pytest.fixture()
def ghz():
circuit = QuantumCircuit(4, 3)
circuit.name = "Qiskit Sample - 3-qubit GHZ circuit"
circuit.h(0)
circuit.cx(0, 1)
circuit.cx(1, 2)
circuit.measure([0, 1, 2], [0, 1, 2])
return circuit
@pytest.fixture()
def teleport():
q = QuantumRegister(3, name="q")
cr = ClassicalRegister(2, name="cr")
circuit = QuantumCircuit(q, cr, name="Teleport")
circuit.h(1)
circuit.cx(1, 2)
circuit.cx(0, 1)
circuit.h(0)
circuit.measure(0, 0)
circuit.measure(1, 1)
circuit.x(2).c_if(cr, int("10", 2))
circuit.z(2).c_if(cr, int("01", 2))
return circuit
@pytest.fixture()
def unroll():
circ = QuantumCircuit(3)
circ.ccx(0, 1, 2)
circ.crz(theta=0.1, control_qubit=0, target_qubit=1)
circ.id(2)
return circ.decompose()
@pytest.fixture()
def teleport_with_subroutine():
bell_circ = QuantumCircuit(2, name="CreateBellPair")
bell_circ.h(0)
bell_circ.cx(0, 1)
q = QuantumRegister(3, name="q")
cr = ClassicalRegister(2, name="cr")
circuit = QuantumCircuit(q, cr, name="Teleport")
circuit.append(bell_circ.to_instruction(), [1, 2])
circuit.cx(0, 1)
circuit.h(0)
circuit.measure(0, 0)
circuit.measure(1, 1)
circuit.x(2).c_if(cr, int("10", 2))
circuit.z(2).c_if(cr, int("01", 2))
return circuit
@pytest.fixture()
def bernstein_vazirani_with_delay():
num_qubits = 5
qq = QuantumRegister(num_qubits + 1, name="qq")
cr = ClassicalRegister(num_qubits, name="cr")
circuit = QuantumCircuit(qq, cr, name="Bernstein-Vazirani")
circuit.h(num_qubits)
circuit.z(num_qubits)
for index in range(num_qubits):
circuit.h(index)
circuit.delay(42, qq[0], "ps")
oracle = format(2, "b").zfill(num_qubits)
oracle = oracle[::-1]
for index in range(num_qubits):
if oracle[index] == "0":
circuit.id(index)
else:
circuit.cx(index, num_qubits)
circuit.delay(23, 2, "ms")
for index in range(num_qubits):
circuit.h(index)
for index in range(num_qubits):
circuit.measure(index, index)
return circuit
@pytest.fixture()
def ghz_with_delay():
qq = QuantumRegister(4, name="qq")
cr = ClassicalRegister(3, name="cr")
circuit = QuantumCircuit(qq, cr)
circuit.name = "Qiskit Sample - 3-qubit GHZ circuit"
circuit.delay(23.54, None, "us")
circuit.h(0)
circuit.delay(42, qq[0], "ps")
circuit.cx(0, 1)
circuit.delay(23, 2, "ms")
circuit.cx(1, 2)
circuit.delay(3, qq[1])
circuit.measure([0, 1, 2], [0, 1, 2])
return circuit
@pytest.fixture()
def measure_x_as_subroutine():
measure_x_circuit = QuantumCircuit(1, 1, name="measure_x")
measure_x_circuit.h(0)
measure_x_circuit.measure(0, 0)
measure_x_circuit.h(0)
measure_x_gate = measure_x_circuit.to_instruction()
qq = QuantumRegister(1, name="qq")
cr = ClassicalRegister(1, name="cr")
circuit = QuantumCircuit(qq, cr)
circuit.name = "Qiskit Sample - Measure in the X-basis as a subroutine"
circuit.append(measure_x_gate, [0], [0])
return circuit
|
https://github.com/hritiksauw199/Qiskit-textbook-solutions
|
hritiksauw199
|
import matplotlib.pyplot as plt
import numpy as np
import math
# importing Qiskit
import qiskit
from qiskit import QuantumCircuit, transpile, assemble, Aer
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit_textbook.problems import grover_problem_oracle
def diffuser(nqubits):
qc = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qc.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qc.x(qubit)
# Do multi-controlled-Z gate
qc.h(nqubits-1)
qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qc.h(nqubits-1)
# Apply transformation |11..1> -> |00..0>
for qubit in range(nqubits):
qc.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qc.h(qubit)
# We will return the diffuser as a gate
U_s = qc.to_gate()
U_s.name = "U$_s$"
return U_s
def grover_unsolved():
n=3
qc = QuantumCircuit(n)
for i in range(n):
qc.h(i)
#oracle
qc.cz(0, 2)
qc.cz(1, 2)
#diffuser #use the model of general diffuser
qc.h(range(3))
qc.x(range(3))
qc.h(2)
qc.mct([0,1],2)
qc.h(2)
qc.x(range(3))
qc.h(range(3))
return qc
grit = grover_unsolved().to_gate()
grit.label = "Grover"
cgrit = grit.control()
#This code implements the QFT on n qubits:
def qft(n):
"""Creates an n-qubit QFT circuit"""
circuit = QuantumCircuit(3)
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft_rotations(circuit, n):
"""Performs qft on the first n qubits in circuit (without swaps)"""
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(np.pi/2**(n-qubit), qubit, n)
qft_rotations(circuit, n)
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
# inversing the circuit
qft_dagger = qft(3).to_gate().inverse()
qft_dagger.label = "QFT†"
# Create QuantumCircuit
t = 3 # no. of counting qubits
n = 3 # no. of searching qubits
qc = QuantumCircuit(n+t, t) # Circuit with n+t qubits and t classical bits
# Initialize all qubits to |+>
for qubit in range(t+n):
qc.h(qubit)
# Begin controlled Grover iterations
iterations = 1
for qubit in range(t): # qubits in range of counting quibts
for i in range(iterations):
qc.append(cgrit, [qubit] + [*range(t, n+t)]) #controlled grover oracle
iterations *= 2 # iteration in power of 2
# Do inverse QFT on counting qubits
qc.append(qft_dagger, range(t))
# Measure counting qubits
qc.measure(range(t), range(t))
# Display the circuit
qc.draw()
# Execute and see results
aer_sim = Aer.get_backend('aer_simulator')
transpiled_qc = transpile(qc, aer_sim)
qobj = assemble(transpiled_qc)
job = aer_sim.run(qobj)
hist = job.result().get_counts()
plot_histogram(hist)
measured_str = max(hist, key=hist.get)
measured_int = int(measured_str,2)
print("Register Output = %i" % measured_int)
theta = (measured_int/(2**t))*math.pi*2
print("Theta = %.5f" % theta)
N = 2**n
M = N * (math.sin(theta/2)**2)
print("No. of Solutions = %.1f" % (N-M))
m = t - 1 # Upper bound: Will be less than this
err = (math.sqrt(2*M*N) + N/(2**(m+1)))*(2**(-m))
print("Error < %.2f" % err)
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.extensions import HamiltonianGate
from qiskit.circuit.library.standard_gates import CRYGate
def quantum_fourier_transform(t, vis=False):
reg = QuantumRegister(t, name='c')
circ = QuantumCircuit(reg, name='$Q.F.T.$')
for i in range(t // 2):
circ.swap(i, t - 1 - i)
for i in range(t):
circ.h(i)
for j in range(i + 1, t):
circ.cu1(np.pi / (2 ** (j - i)), i, j)
if vis:
circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\
.suptitle("Quantum Fourier Transform", fontsize=16)
return circ.to_gate()
def quantum_phase_estimation(n, t, unitary, vis=False):
reg_b = QuantumRegister(n, name='b')
reg_c = QuantumRegister(t, name='c')
circ = QuantumCircuit(reg_b, reg_c, name='$Q.P.E.$')
circ.h(range(n, n + t))
for i in range(t):
circ.append(unitary.control(1).power(2**i), [n + i] + list(range(n)))
circ.append(quantum_fourier_transform(t, vis=vis).inverse(), range(n, n + t))
if vis:
circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\
.suptitle("Quantum Phase Estimation", fontsize=16)
return circ.to_gate()
def subroutine_a(t, m, l, k, t0, vis=False):
reg_c = QuantumRegister(t, name='c')
reg_m = QuantumRegister(m, name='m')
reg_l = QuantumRegister(l, name='l')
circ = QuantumCircuit(reg_c, reg_m, reg_l, name='$Sub_A$')
vis_temp = vis
for i in range(t):
gate = subroutine_c(m, t - i, l - k, t0, vis=vis_temp)
circ.append(gate.control(2), [reg_l[k], reg_c[i]] + [reg_m[j] for j in range(m)])
vis_temp = False
if vis:
circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\
.suptitle("Subroutine A", fontsize=16)
return circ.to_gate()
def subroutine_b(t, m, l, t0, vis=False):
reg_c = QuantumRegister(t, name='c')
reg_m = QuantumRegister(m, name='m')
reg_l = QuantumRegister(l, name='l')
circ = QuantumCircuit(reg_c, reg_m, reg_l, name='$Sub_B$')
vis_temp = vis
for i in range(l):
gate = subroutine_a(t, m, l, i, t0, vis=vis_temp)
circ.append(gate, range(t + m + l))
vis_temp = False
if vis:
circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\
.suptitle("Subroutine B", fontsize=16)
return circ.to_gate()
def subroutine_c(m, u, v, t0, vis=False):
reg = QuantumRegister(m, name='m')
circ = QuantumCircuit(reg, name='$Sub_C$')
t = -t0 / (2 ** (u + v - m))
for i in range(m):
circ.rz(t / (2 ** (i + 1)), i)
if vis:
circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\
.suptitle("Subroutine C", fontsize=16)
return circ.to_gate()
def hhl_forward_ckt(n, t, m, l, A, t0, vis=False):
reg_b = QuantumRegister(n, name='b')
reg_c = QuantumRegister(t, name='c')
reg_m = QuantumRegister(m, name='m')
reg_l = QuantumRegister(l, name='l')
temp = QuantumCircuit(reg_b, name='$U$')
temp.append(HamiltonianGate(A, t0 / (2 ** t)), reg_b)
circ = QuantumCircuit(reg_b, reg_c, reg_m, reg_l, name='$Fwd$')
circ.append(quantum_phase_estimation(n, t, temp.to_gate(), vis=vis), range(n + t))
circ.h(reg_m)
circ.h(reg_l)
for i in range(m):
circ.rz(t0 / (2 ** (m - i)), reg_m[i])
circ.append(subroutine_b(t, m, l, t0, vis=vis), range(n, n + t + m + l))
if vis:
circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\
.suptitle('HHL Forward Computation', fontsize=16)
return circ.to_gate()
def hhl_circuit(A, t0, theta, size, vis=False):
n, t, m, l = size
reg_b = QuantumRegister(n, name='b')
reg_c = QuantumRegister(t, name='c')
reg_m = QuantumRegister(m, name='m')
reg_l = QuantumRegister(l, name='l')
ancil = QuantumRegister(1, name='anc')
circ = QuantumCircuit(reg_b, reg_c, reg_m, reg_l, ancil, name='$HHL$')
circ.append(hhl_forward_ckt(n, t, m, l, A, t0, vis=vis), range(sum(size)))
for i in range(l):
circ.append(CRYGate(theta).power(2**i), [reg_l[i], ancil])
circ.append(hhl_forward_ckt(n, t, m, l, A, t0).inverse(), range(sum(size)))
if vis:
circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\
.suptitle('HHL Circuit', fontsize=16)
return circ
def ad_hoc_hhl(A, t0, r):
reg_b = QuantumRegister(2)
reg_c = QuantumRegister(4)
ancil = QuantumRegister(1)
circ = QuantumCircuit(reg_b, reg_c, ancil)
circ.append(quantum_phase_estimation(2, 4, HamiltonianGate(A, t0/16)), range(6))
circ.swap(reg_c[1], reg_c[3])
for i in range(4):
circ.cry(np.pi * (2 ** (4-i-r)), reg_c[i], ancil[0])
circ.barrier()
circ.swap(reg_c[1], reg_c[3])
circ.append(quantum_phase_estimation(2, 4, HamiltonianGate(A, t0 / 16)).inverse(), range(6))
return circ
if __name__ == '__main__':
size = [3, 4, 4, 4]
theta = np.pi/12
t0 = 2 * np.pi
A = [[0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0]]
circ = hhl_circuit(A, t0, theta, size, vis=True)
plt.show()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# Copyright 2022-2023 Ohad Lev.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0,
# or in the root directory of this package("LICENSE.txt").
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
`SATInterface` class.
"""
import os
import json
from typing import List, Tuple, Union, Optional, Dict, Any
from sys import stdout
from datetime import datetime
from hashlib import sha256
from qiskit import transpile, QuantumCircuit, qpy
from qiskit.result.counts import Counts
from qiskit.visualization.circuit.text import TextDrawing
from qiskit.providers.backend import Backend
from qiskit.transpiler.passes import RemoveBarriers
from IPython import display
from matplotlib.figure import Figure
from sat_circuits_engine.util import timer_dec, timestamp, flatten_circuit
from sat_circuits_engine.util.settings import DATA_PATH, TRANSPILE_KWARGS
from sat_circuits_engine.circuit import GroverConstraintsOperator, SATCircuit
from sat_circuits_engine.constraints_parse import ParsedConstraints
from sat_circuits_engine.interface.circuit_decomposition import decompose_operator
from sat_circuits_engine.interface.counts_visualization import plot_histogram
from sat_circuits_engine.interface.translator import ConstraintsTranslator
from sat_circuits_engine.classical_processing import (
find_iterations_unknown,
calc_iterations,
ClassicalVerifier,
)
from sat_circuits_engine.interface.interactive_inputs import (
interactive_operator_inputs,
interactive_solutions_num_input,
interactive_run_input,
interactive_backend_input,
interactive_shots_input,
)
# Local globlas for visualization of charts and diagrams
IFRAME_WIDTH = "100%"
IFRAME_HEIGHT = "700"
class SATInterface:
"""
An interface for building, running and mining data from n-SAT problems quantum circuits.
There are 2 options to use this class:
(1) Using an interactive interface (intuitive but somewhat limited) - for this
just initiate a bare instance of this class: `SATInterface()`.
(2) Using the API defined by this class, that includes the following methods:
* The following descriptions are partial, for full annotations see the methods' docstrings.
- `__init__`: an instance of `SATInterface must be initiated with exactly 1 combination:
(a) (high_level_constraints_string + high_level_vars) - for constraints
in a high-level format.
(b) (num_input_qubits + constraints_string) - for constraints
in a low-level foramt.
* For formats annotations see `constriants_format.ipynb` in the main directory.
- `obtain_grover_operator`: obtains the suitable grover operator for the constraints.
- `save_display_grover_operator`: saves and displays data generated
by the `obtain_grover_operator` method.
- `obtain_overall_circuit`: obtains the suitable overall SAT circuit.
- `save_display_overall_circuit: saves and displays data generated
by the `obtain_overall_circuit` method.
- `run_overall_circuit`: executes the overall SAT circuit.
- `save_display_results`: saves and displays data generated
by the `run_overall_circuit` method.
It is very recommended to go through `demos.ipynb` that demonstrates the various optional uses
of this class, in addition to reading `constraints_format.ipynb`, which is a must for using
this package properly. Both notebooks are in ther main directory.
"""
def __init__(
self,
num_input_qubits: Optional[int] = None,
constraints_string: Optional[str] = None,
high_level_constraints_string: Optional[str] = None,
high_level_vars: Optional[Dict[str, int]] = None,
name: Optional[str] = None,
save_data: Optional[bool] = True,
) -> None:
"""
Accepts the combination of paramters:
(high_level_constraints_string + high_level_vars) or (num_input_qubits + constraints_string).
Exactly one combination is accepted.
In other cases either an iteractive user interface will be called to take user's inputs,
or an exception will be raised due to misuse of the API.
Args:
num_input_qubits (Optional[int] = None): number of input qubits.
constraints_string (Optional[str] = None): a string of constraints in a low-level format.
high_level_constraints_string (Optional[str] = None): a string of constraints in a
high-level format.
high_level_vars (Optional[Dict[str, int]] = None): a dictionary that configures
the high-level variables - keys are names and values are bits-lengths.
name (Optional[str] = None): a name for this object, if None than the
generic name "SAT" is given automatically.
save_data (Optional[bool] = True): if True, saves all data and metadata generated by this
class to a unique data folder (by using the `save_XXX` methods of this class).
Raises:
SyntaxError - if a forbidden combination of arguments has been provided.
"""
if name is None:
name = "SAT"
self.name = name
# Creating a directory for data to be saved
if save_data:
self.time_created = timestamp(datetime.now())
self.dir_path = f"{DATA_PATH}{self.time_created}_{self.name}/"
os.mkdir(self.dir_path)
print(f"Data will be saved into '{self.dir_path}'.")
# Initial metadata, more to be added by this class' `save_XXX` methods
self.metadata = {
"name": self.name,
"datetime": self.time_created,
"num_input_qubits": num_input_qubits,
"constraints_string": constraints_string,
"high_level_constraints_string": high_level_constraints_string,
"high_level_vars": high_level_vars,
}
self.update_metadata()
# Identifying user's platform, for visualization purposes
self.identify_platform()
# In the case of low-level constraints format, that is the default value
self.high_to_low_map = None
# Case A - interactive interface
if (num_input_qubits is None or constraints_string is None) and (
high_level_constraints_string is None or high_level_vars is None
):
self.interactive_interface()
# Case B - API
else:
self.high_level_constraints_string = high_level_constraints_string
self.high_level_vars = high_level_vars
# Case B.1 - high-level format constraints inputs
if num_input_qubits is None or constraints_string is None:
self.num_input_qubits = sum(self.high_level_vars.values())
self.high_to_low_map, self.constraints_string = ConstraintsTranslator(
self.high_level_constraints_string, self.high_level_vars
).translate()
# Case B.2 - low-level format constraints inputs
elif num_input_qubits is not None and constraints_string is not None:
self.num_input_qubits = num_input_qubits
self.constraints_string = constraints_string
# Misuse
else:
raise SyntaxError(
"SATInterface accepts the combination of paramters:"
"(high_level_constraints_string + high_level_vars) or "
"(num_input_qubits + constraints_string). "
"Exactly one combination is accepted, not both."
)
self.parsed_constraints = ParsedConstraints(
self.constraints_string, self.high_level_constraints_string
)
def update_metadata(self, update_metadata: Optional[Dict[str, Any]] = None) -> None:
"""
Updates the metadata file (in the unique data folder of a given `SATInterface` instance).
Args:
update_metadata (Optional[Dict[str, Any]] = None):
- If None - just dumps `self.metadata` into the metadata JSON file.
- If defined - updates the `self.metadata` attribute and then dumps it.
"""
if update_metadata is not None:
self.metadata.update(update_metadata)
with open(f"{self.dir_path}metadata.json", "w") as metadata_file:
json.dump(self.metadata, metadata_file, indent=4)
def identify_platform(self) -> None:
"""
Identifies user's platform.
Writes True to `self.jupyter` for Jupyter notebook, False for terminal.
"""
# If True then the platform is a terminal/command line/shell
if stdout.isatty():
self.jupyter = False
# If False, we assume the platform is a Jupyter notebook
else:
self.jupyter = True
def output_to_platform(
self,
*,
title: str,
output_terminal: Union[TextDrawing, str],
output_jupyter: Union[Figure, str],
display_both_on_jupyter: Optional[bool] = False,
) -> None:
"""
Displays output to user's platform.
Args:
title (str): a title for the output.
output_terminal (Union[TextDrawing, str]): text to print for a terminal platform.
output_jupyter: (Union[Figure, str]): objects to display for a Jupyter notebook platform.
can handle `Figure` matplotlib objects or strings of paths to IFrame displayable file,
e.g PDF files.
display_both_on_jupyter (Optional[bool] = False): if True, displays both
`output_terminal` and `output_jupyter` in a Jupyter notebook platform.
Raises:
TypeError - in the case of misusing the `output_jupyter` argument.
"""
print()
print(title)
if self.jupyter:
if isinstance(output_jupyter, str):
display.display(display.IFrame(output_jupyter, width=IFRAME_WIDTH, height=IFRAME_HEIGHT))
elif isinstance(output_jupyter, Figure):
display.display(output_jupyter)
else:
raise TypeError("output_jupyter must be an str (path to image file) or a Figure object.")
if display_both_on_jupyter:
print(output_terminal)
else:
print(output_terminal)
def interactive_interface(self) -> None:
"""
An interactive CLI that allows exploiting most (but not all) of the package's features.
Uses functions of the form `interactive_XXX_inputs` from the `interactive_inputs.py` module.
Divided into 3 main stages:
1. Obtaining Grover's operator for the SAT problem.
2. Obtaining the overall SAT cirucit.
3. Executing the circuit and parsing the results.
The interface is built in a modular manner such that a user can halt at any stage.
The defualt settings for the interactive user intreface are:
1. `name = "SAT"`.
2. `save_data = True`.
3. `display = True`.
4. `transpile_kwargs = {'basis_gates': ['u', 'cx'], 'optimization_level': 3}`.
5. Backends are limited to those defined in the global-constant-like function `BACKENDS`:
- Those are the local `aer_simulator` and the remote `ibmq_qasm_simulator` for now.
Due to these default settings the interactive CLI is somewhat restrictive,
for full flexibility a user should use the API and not the CLI.
"""
# Handling operator part
operator_inputs = interactive_operator_inputs()
self.num_input_qubits = operator_inputs["num_input_qubits"]
self.high_to_low_map = operator_inputs["high_to_low_map"]
self.constraints_string = operator_inputs["constraints_string"]
self.high_level_constraints_string = operator_inputs["high_level_constraints_string"]
self.high_level_vars = operator_inputs["high_level_vars"]
self.parsed_constraints = ParsedConstraints(
self.constraints_string, self.high_level_constraints_string
)
self.update_metadata(
{
"num_input_qubits": self.num_input_qubits,
"constraints_string": self.constraints_string,
"high_level_constraints_string": self.high_level_constraints_string,
"high_level_vars": self.high_level_vars,
}
)
obtain_grover_operator_output = self.obtain_grover_operator()
self.save_display_grover_operator(obtain_grover_operator_output)
# Handling overall circuit part
solutions_num = interactive_solutions_num_input()
if solutions_num is not None:
backend = None
if solutions_num == -1:
backend = interactive_backend_input()
overall_circuit_data = self.obtain_overall_sat_circuit(
obtain_grover_operator_output["operator"], solutions_num, backend
)
self.save_display_overall_circuit(overall_circuit_data)
# Handling circuit execution part
if interactive_run_input():
if backend is None:
backend = interactive_backend_input()
shots = interactive_shots_input()
counts_parsed = self.run_overall_sat_circuit(
overall_circuit_data["circuit"], backend, shots
)
self.save_display_results(counts_parsed)
print()
print(f"Done saving data into '{self.dir_path}'.")
def obtain_grover_operator(
self, transpile_kwargs: Optional[Dict[str, Any]] = None
) -> Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]:
"""
Obtains the suitable `GroverConstraintsOperator` object for the constraints,
decomposes it using the `circuit_decomposition.py` module and transpiles it
according to `transpile_kwargs`.
Args:
transpile_kwargs (Optional[Dict[str, Any]]): kwargs for Qiskit's transpile function.
The defualt is set to the global constant `TRANSPILE_KWARGS`.
Returns:
(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit, Dict[str, List[int]]]]):
- 'operator' (GroverConstraintsOperator):the high-level blocks operator.
- 'decomposed_operator' (QuantumCircuit): decomposed to building-blocks operator.
* For annotations regarding the decomposition method see the
`circuit_decomposition` module.
- 'transpiled_operator' (QuantumCircuit): the transpiled operator.
*** The high-level operator and the decomposed operator are generated with barriers
between constraints as default for visualizations purposes. The barriers are stripped
off before transpiling so the the transpiled operator object contains no barriers. ***
- 'high_level_to_bit_indexes_map' (Optional[Dict[str, List[int]]] = None):
A map of high-level variables with their allocated bit-indexes in the input register.
"""
print()
print(
"The system synthesizes and transpiles a Grover's "
"operator for the given constraints. Please wait.."
)
if transpile_kwargs is None:
transpile_kwargs = TRANSPILE_KWARGS
self.transpile_kwargs = transpile_kwargs
operator = GroverConstraintsOperator(
self.parsed_constraints, self.num_input_qubits, insert_barriers=True
)
decomposed_operator = decompose_operator(operator)
no_baerriers_operator = RemoveBarriers()(operator)
transpiled_operator = transpile(no_baerriers_operator, **transpile_kwargs)
print("Done.")
return {
"operator": operator,
"decomposed_operator": decomposed_operator,
"transpiled_operator": transpiled_operator,
"high_level_to_bit_indexes_map": self.high_to_low_map,
}
def save_display_grover_operator(
self,
obtain_grover_operator_output: Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]],
display: Optional[bool] = True,
) -> None:
"""
Handles saving and displaying data generated by the `self.obtain_grover_operator` method.
Args:
obtain_grover_operator_output(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]):
the dictionary returned upon calling the `self.obtain_grover_operator` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
# Creating a directory to save operator's data
operator_dir_path = f"{self.dir_path}grover_operator/"
os.mkdir(operator_dir_path)
# Titles for displaying objects, by order of `obtain_grover_operator_output`
titles = [
"The operator diagram - high level blocks:",
"The operator diagram - decomposed:",
f"The transpiled operator diagram saved into '{operator_dir_path}'.\n"
f"It's not presented here due to its complexity.\n"
f"Please note that barriers appear in the high-level diagrams above only for convenient\n"
f"visual separation between constraints.\n"
f"Before transpilation all barriers are removed to avoid redundant inefficiencies.",
]
for index, (op_name, op_obj) in enumerate(obtain_grover_operator_output.items()):
# Generic path and name for files to be saved
files_path = f"{operator_dir_path}{op_name}"
# Generating a circuit diagrams figure
figure_path = f"{files_path}.pdf"
op_obj.draw("mpl", filename=figure_path, fold=-1)
# Generating a QPY serialization file for the circuit object
qpy_file_path = f"{files_path}.qpy"
with open(qpy_file_path, "wb") as qpy_file:
qpy.dump(op_obj, qpy_file)
# Original high-level operator and decomposed operator
if index < 2 and display:
# Displaying to user
self.output_to_platform(
title=titles[index], output_terminal=op_obj.draw("text"), output_jupyter=figure_path
)
# Transpiled operator
elif index == 2:
# Output to user, not including the circuit diagram
print()
print(titles[index])
print()
print(f"The transpilation kwargs are: {self.transpile_kwargs}.")
transpiled_operator_depth = op_obj.depth()
transpiled_operator_gates_count = op_obj.count_ops()
print(f"Transpiled operator depth: {transpiled_operator_depth}.")
print(f"Transpiled operator gates count: {transpiled_operator_gates_count}.")
print(f"Total number of qubits: {op_obj.num_qubits}.")
# Generating QASM 2.0 file only for the (flattened = no registers) tranpsiled operator
qasm_file_path = f"{files_path}.qasm"
flatten_circuit(op_obj).qasm(filename=qasm_file_path)
# Index 3 is 'high_level_to_bit_indexes_map' so it's time to break from the loop
break
# Mapping from high-level variables to bit-indexes will be displayed as well
mapping = obtain_grover_operator_output["high_level_to_bit_indexes_map"]
if mapping:
print()
print(f"The high-level variables mapping to bit-indexes:\n{mapping}")
print()
print(
f"Saved into '{operator_dir_path}':\n",
" Circuit diagrams for all levels.\n",
" QPY serialization exports for all levels.\n",
" QASM 2.0 export only for the transpiled level.",
)
with open(f"{operator_dir_path}operator.qpy", "rb") as qpy_file:
operator_qpy_sha256 = sha256(qpy_file.read()).hexdigest()
self.update_metadata(
{
"high_level_to_bit_indexes_map": self.high_to_low_map,
"transpile_kwargs": self.transpile_kwargs,
"transpiled_operator_depth": transpiled_operator_depth,
"transpiled_operator_gates_count": transpiled_operator_gates_count,
"operator_qpy_sha256": operator_qpy_sha256,
}
)
def obtain_overall_sat_circuit(
self,
grover_operator: GroverConstraintsOperator,
solutions_num: int,
backend: Optional[Backend] = None,
) -> Dict[str, SATCircuit]:
"""
Obtains the suitable `SATCircuit` object (= the overall SAT circuit) for the SAT problem.
Args:
grover_operator (GroverConstraintsOperator): Grover's operator for the SAT problem.
solutions_num (int): number of solutions for the SAT problem. In the case the number
of solutions is unknown, specific negative values are accepted:
* '-1' - for launching a classical iterative stochastic process that finds an adequate
number of iterations - by calling the `find_iterations_unknown` function (see its
docstrings for more information).
* '-2' - for generating a dynamic circuit that iterates over Grover's iterator until
a solution is obtained, using weak measurements. TODO - this feature isn't ready yet.
backend (Optional[Backend] = None): in the case of a '-1' value given to `solutions_num`,
a backend object to execute the depicted iterative prcess upon should be provided.
Returns:
(Dict[str, SATCircuit]):
- 'circuit' key for the overall SAT circuit.
- 'concise_circuit' key for the overall SAT circuit, with only 1 iteration over Grover's
iterator (operator + diffuser). Useful for visualization purposes.
*** The concise circuit is generated with barriers between segments as default
for visualizations purposes. In the actual circuit there no barriers. ***
"""
# -1 = Unknown number of solutions - iterative stochastic process
print()
if solutions_num == -1:
assert backend is not None, "Need to specify a backend if `solutions_num == -1`."
print("Please wait while the system checks various solutions..")
circuit, iterations = find_iterations_unknown(
self.num_input_qubits,
grover_operator,
self.parsed_constraints,
precision=10,
backend=backend,
)
print()
print(f"An adequate number of iterations found = {iterations}.")
# -2 = Unknown number of solutions - implement a dynamic circuit
# TODO this feature isn't fully implemented yet
elif solutions_num == -2:
print("The system builds a dynamic circuit..")
circuit = SATCircuit(self.num_input_qubits, grover_operator, iterations=None)
circuit.add_input_reg_measurement()
iterations = None
# Known number of solutions
else:
print("The system builds the overall circuit..")
iterations = calc_iterations(self.num_input_qubits, solutions_num)
print(f"\nFor {solutions_num} solutions, {iterations} iterations needed.")
circuit = SATCircuit(
self.num_input_qubits, grover_operator, iterations, insert_barriers=False
)
circuit.add_input_reg_measurement()
self.iterations = iterations
# Obtaining a SATCircuit object with one iteration for concise representation
concise_circuit = SATCircuit(
self.num_input_qubits, grover_operator, iterations=1, insert_barriers=True
)
concise_circuit.add_input_reg_measurement()
return {"circuit": circuit, "concise_circuit": concise_circuit}
def save_display_overall_circuit(
self, obtain_overall_sat_circuit_output: Dict[str, SATCircuit], display: Optional[bool] = True
) -> None:
"""
Handles saving and displaying data generated by the `self.obtain_overall_sat_circuit` method.
Args:
obtain_overall_sat_circuit_output(Dict[str, SATCircuit]):
the dictionary returned upon calling the `self.obtain_overall_sat_circuit` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
circuit = obtain_overall_sat_circuit_output["circuit"]
concise_circuit = obtain_overall_sat_circuit_output["concise_circuit"]
# Creating a directory to save overall circuit's data
overall_circuit_dir_path = f"{self.dir_path}overall_circuit/"
os.mkdir(overall_circuit_dir_path)
# Generating a figure of the overall SAT circuit with just 1 iteration (i.e "concise")
concise_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_1_iteration.pdf"
concise_circuit.draw("mpl", filename=concise_circuit_fig_path, fold=-1)
# Displaying the concise circuit to user
if display:
if self.iterations:
self.output_to_platform(
title=(
f"The high level circuit contains {self.iterations}"
f" iterations of the following form:"
),
output_terminal=concise_circuit.draw("text"),
output_jupyter=concise_circuit_fig_path,
)
# Dynamic circuit case - TODO NOT FULLY IMPLEMENTED YET
else:
dynamic_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_dynamic.pdf"
circuit.draw("mpl", filename=dynamic_circuit_fig_path, fold=-1)
self.output_to_platform(
title="The dynamic circuit diagram:",
output_terminal=circuit.draw("text"),
output_jupyter=dynamic_circuit_fig_path,
)
if self.iterations:
transpiled_overall_circuit = transpile(flatten_circuit(circuit), **self.transpile_kwargs)
print()
print(f"The transpilation kwargs are: {self.transpile_kwargs}.")
transpiled_overall_circuit_depth = transpiled_overall_circuit.depth()
transpiled_overall_circuit_gates_count = transpiled_overall_circuit.count_ops()
print(f"Transpiled overall-circuit depth: {transpiled_overall_circuit_depth}.")
print(f"Transpiled overall-circuit gates count: {transpiled_overall_circuit_gates_count}.")
print(f"Total number of qubits: {transpiled_overall_circuit.num_qubits}.")
print()
print("Exporting the full overall SAT circuit object..")
export_files_path = f"{overall_circuit_dir_path}overall_circuit"
with open(f"{export_files_path}.qpy", "wb") as qpy_file:
qpy.dump(circuit, qpy_file)
if self.iterations:
transpiled_overall_circuit.qasm(filename=f"{export_files_path}.qasm")
print()
print(
f"Saved into '{overall_circuit_dir_path}':\n",
" A concised (1 iteration) circuit diagram of the high-level overall SAT circuit.\n",
" QPY serialization export for the full overall SAT circuit object.",
)
if self.iterations:
print(" QASM 2.0 export for the transpiled full overall SAT circuit object.")
metadata_update = {
"num_total_qubits": circuit.num_qubits,
"num_iterations": circuit.iterations,
}
if self.iterations:
metadata_update["transpiled_overall_circuit_depth"] = (transpiled_overall_circuit_depth,)
metadata_update[
"transpiled_overall_circuit_gates_count"
] = transpiled_overall_circuit_gates_count
self.update_metadata(metadata_update)
@timer_dec("Circuit simulation execution time = ")
def run_overall_sat_circuit(
self, circuit: QuantumCircuit, backend: Backend, shots: int
) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]:
"""
Executes a `circuit` on `backend` transpiled w.r.t backend, `shots` times.
Args:
circuit (QuantumCircuit): `QuantumCircuit` object or child-object (a.k.a `SATCircuit`)
to execute.
backend (Backend): backend to execute `circuit` upon.
shots (int): number of execution shots.
Returns:
(Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]):
dict object returned by `self.parse_counts` - see this method's docstrings for annotations.
"""
# Defines also instance attributes to use in other methods
self.backend = backend
self.shots = shots
print()
print(f"The system is running the circuit {shots} times on {backend}, please wait..")
print("This process might take a while.")
job = backend.run(transpile(circuit, backend), shots=shots)
counts = job.result().get_counts()
print("Done.")
parsed_counts = self.parse_counts(counts)
return parsed_counts
def parse_counts(
self, counts: Counts
) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]:
"""
Parses a `Counts` object into several desired datas (see 'Returns' section).
Args:
counts (Counts): the `Counts` object to parse.
Returns:
(Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]):
'counts' (Counts) - the original `Counts` object.
'counts_sorted' (List[Tuple[Union[str, int]]]) - results sorted in a descending order.
'distilled_solutions' (List[str]): list of solutions (bitstrings).
'high_level_vars_values' (List[Dict[str, int]]): list of solutions (each solution is a
dictionary with variable-names as keys and their integer values as values).
"""
# Sorting results in an a descending order
counts_sorted = sorted(counts.items(), key=lambda x: x[1], reverse=True)
# Generating a set of distilled verified-only solutions
verifier = ClassicalVerifier(self.parsed_constraints)
distilled_solutions = set()
for count_item in counts_sorted:
if not verifier.verify(count_item[0]):
break
distilled_solutions.add(count_item[0])
# In the case of high-level format in use, translating `distilled_solutions` into integer values
high_level_vars_values = None
if self.high_level_constraints_string and self.high_level_vars:
# Container for dictionaries with variables integer values
high_level_vars_values = []
for solution in distilled_solutions:
# Keys are variable-names and values are their integer values
solution_vars = {}
for var, bits_bundle in self.high_to_low_map.items():
reversed_solution = solution[::-1]
var_bitstring = ""
for bit_index in bits_bundle:
var_bitstring += reversed_solution[bit_index]
# Translating to integer value
solution_vars[var] = int(var_bitstring, 2)
high_level_vars_values.append(solution_vars)
return {
"counts": counts,
"counts_sorted": counts_sorted,
"distilled_solutions": distilled_solutions,
"high_level_vars_values": high_level_vars_values,
}
def save_display_results(
self,
run_overall_sat_circuit_output: Dict[
str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]
],
display: Optional[bool] = True,
) -> None:
"""
Handles saving and displaying data generated by the `self.run_overall_sat_circuit` method.
Args:
run_overall_sat_circuit_output (Dict[str, Union[Counts, List[Tuple[Union[str, int]]],
List[str], List[Dict[str, int]]]]): the dictionary returned upon calling
the `self.run_overall_sat_circuit` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
counts = run_overall_sat_circuit_output["counts"]
counts_sorted = run_overall_sat_circuit_output["counts_sorted"]
distilled_solutions = run_overall_sat_circuit_output["distilled_solutions"]
high_level_vars_values = run_overall_sat_circuit_output["high_level_vars_values"]
# Creating a directory to save results data
results_dir_path = f"{self.dir_path}results/"
os.mkdir(results_dir_path)
# Defining custom dimensions for the custom `plot_histogram` of this package
histogram_fig_width = max((len(counts) * self.num_input_qubits * (10 / 72)), 7)
histogram_fig_height = 5
histogram_figsize = (histogram_fig_width, histogram_fig_height)
histogram_path = f"{results_dir_path}histogram.pdf"
plot_histogram(counts, figsize=histogram_figsize, sort="value_desc", filename=histogram_path)
if display:
# Basic output text
output_text = (
f"All counts:\n{counts_sorted}\n"
f"\nDistilled solutions ({len(distilled_solutions)} total):\n"
f"{distilled_solutions}"
)
# Additional outputs for a high-level constraints format
if high_level_vars_values:
# Mapping from high-level variables to bit-indexes will be displayed as well
output_text += (
f"\n\nThe high-level variables mapping to bit-indexes:" f"\n{self.high_to_low_map}"
)
# Actual integer solutions will be displayed as well
additional_text = ""
for solution_index, solution in enumerate(high_level_vars_values):
additional_text += f"Solution {solution_index + 1}: "
for var_index, (var, value) in enumerate(solution.items()):
additional_text += f"{var} = {value}"
if var_index != len(solution) - 1:
additional_text += ", "
else:
additional_text += "\n"
output_text += f"\n\nHigh-level format solutions: \n{additional_text}"
self.output_to_platform(
title=f"The results for {self.shots} shots are:",
output_terminal=output_text,
output_jupyter=histogram_path,
display_both_on_jupyter=True,
)
results_dict = {
"high_level_to_bit_indexes_map": self.high_to_low_map,
"solutions": list(distilled_solutions),
"high_level_solutions": high_level_vars_values,
"counts": counts_sorted,
}
with open(f"{results_dir_path}results.json", "w") as results_file:
json.dump(results_dict, results_file, indent=4)
self.update_metadata(
{
"num_solutions": len(distilled_solutions),
"backend": str(self.backend),
"shots": self.shots,
}
)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
print(f"Number of qubits: {H2_op.num_qubits}")
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit.opflow import PauliSumOp
numpy_solver = NumPyMinimumEigensolver()
result = numpy_solver.compute_minimum_eigenvalue(operator=PauliSumOp(H2_op))
ref_value = result.eigenvalue.real
print(f"Reference value: {ref_value:.5f}")
# define ansatz and optimizer
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms.optimizers import SPSA
iterations = 125
ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
spsa = SPSA(maxiter=iterations)
# define callback
# note: Re-run this cell to restart lists before training
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
# define Aer Estimator for noiseless statevector simulation
from qiskit.utils import algorithm_globals
from qiskit_aer.primitives import Estimator as AerEstimator
seed = 170
algorithm_globals.random_seed = seed
noiseless_estimator = AerEstimator(
run_options={"seed": seed, "shots": 1024},
transpile_options={"seed_transpiler": seed},
)
# instantiate and run VQE
from qiskit.algorithms.minimum_eigensolvers import VQE
vqe = VQE(
noiseless_estimator, ansatz, optimizer=spsa, callback=store_intermediate_result
)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}")
print(
f"Delta from reference energy value is {(result.eigenvalue.real - ref_value):.5f}"
)
import pylab
pylab.rcParams["figure.figsize"] = (12, 4)
pylab.plot(counts, values)
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Convergence with no noise")
from qiskit_aer.noise import NoiseModel
from qiskit.providers.fake_provider import FakeVigo
# fake providers contain data from real IBM Quantum devices stored in Qiskit Terra,
# and are useful for extracting realistic noise models.
device = FakeVigo()
coupling_map = device.configuration().coupling_map
noise_model = NoiseModel.from_backend(device)
print(noise_model)
noisy_estimator = AerEstimator(
backend_options={
"method": "density_matrix",
"coupling_map": coupling_map,
"noise_model": noise_model,
},
run_options={"seed": seed, "shots": 1024},
transpile_options={"seed_transpiler": seed},
)
# re-start callback variables
counts = []
values = []
vqe.estimator = noisy_estimator
result1 = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}")
print(
f"Delta from reference energy value is {(result1.eigenvalue.real - ref_value):.5f}"
)
if counts or values:
pylab.rcParams["figure.figsize"] = (12, 4)
pylab.plot(counts, values)
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Convergence with noise")
print(f"Reference value: {ref_value:.5f}")
print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}")
print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
# TODO, show differences related to post-selecting for depth vs post-selectng for total gates added
from qiskit.transpiler import CouplingMap
from mirror_gates.pass_managers import Mirage, QiskitLevel3
from transpile_benchy.metrics.gate_counts import DepthMetric, TotalMetric
from mirror_gates.logging import transpile_benchy_logger
from transpile_benchy.library import CircuitLibrary
library = CircuitLibrary.from_txt("../../circuits/medium_circuits.txt")
coupling_map = CouplingMap.from_heavy_hex(5)
transpilers = [
QiskitLevel3(coupling_map), # 20,4,20
Mirage(
coupling_map,
name="Mirage-Min-Swaps",
cost_function="basic",
fixed_aggression=1,
),
Mirage(
coupling_map,
name="Mirage-Min-Depth",
fixed_aggression=1,
),
]
metrics = [DepthMetric(consolidate=False), TotalMetric(consolidate=False)]
from transpile_benchy.benchmark import Benchmark
# only interested in TimeMetric, is there by default
benchmark = Benchmark(
transpilers=transpilers,
circuit_library=library,
metrics=metrics,
num_runs=5,
logger=transpile_benchy_logger,
)
benchmark.run()
benchmark.summary_statistics(transpilers[0], transpilers[1])
benchmark.summary_statistics(transpilers[1], transpilers[2])
benchmark.summary_statistics(transpilers[0], transpilers[2])
from transpile_benchy.render import plot_benchmark
plot_benchmark(
benchmark,
save=1,
legend_show=1,
filename="post",
override_legend=["Qiskit", "MIRAGE-Swaps", "MIRAGE-Depth"],
)
print(benchmark)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
def trotter_gate(dt, to_instruction = True):
qc = QuantumCircuit(2)
qc.rx(2*dt,0)
qc.rz(2*dt,1)
qc.h(1)
qc.cx(1,0)
qc.rz(-2*dt, 0)
qc.rx(-2*dt, 1)
qc.rz(2*dt, 1)
qc.cx(1,0)
qc.h(1)
qc.rz(2*dt, 0)
return qc.to_instruction() if to_instruction else qc
trotter_gate(np.pi / 6, to_instruction=False).draw("mpl")
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
Trot_gate = trotter_gate(dt)
# Number of trotter steps
trotter_steps = 15 ### CAN BE >= 4
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(7)
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
qc.x([2]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, [qr[1], qr[2]])
qc.cx(qr[1], qr[0])
qc.cx(qr[2], qr[1])
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time/trotter_steps})
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(t3_qc, [qr[0], qr[1], qr[2]])
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw("mpl") # only view trotter gates
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibm_lagos")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3)
print('Job ID', cal_job.job_id())
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = []
for job in jobs:
mit_results.append( meas_fitter.filter.apply(job.result()) )
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Compute tomography fidelities for each repetition
fids = []
for result in mit_results:
fid = state_tomo(result, st_qcs)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/tuf65651/quantum-research
|
tuf65651
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import math
# Loading your IBM Q account(s)
IBMQ.load_accounts()
backend = Aer.get_backend("qasm_simulator")
def bin_expansion(circ, q, N):
"""Places q of |0> into binary expansion of N"""
for i in range(N + 1):
# while N >= 0:
if N & (1 << i):
circ.x(q[i])
q = QuantumRegister(5, 'x')
c = ClassicalRegister(5, 'y')
qc = QuantumCircuit(q, c)
bin_expansion(qc, q, 5)
for i in range(5):
qc.measure(q[i], c[i])
qc.draw()
simulate = execute(qc, backend=backend, shots=1024).result()
def raw_bin_exp(N):
place_mask = 1
bins = []
# more_digits = True
while place_mask <= N:
# while N >= 0:
if N & place_mask:
bins = [1] + bins
else:
bins = [0] + bins
# place += 1
place_mask = place_mask * 2
# more_digits
if bins == []:
bins = [0]
return bins
simulate.get_counts()
|
https://github.com/AnikenC/JaxifiedQiskit
|
AnikenC
|
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from typing import Optional, Union
import qiskit
from qiskit import IBMQ, pulse
from library.dynamics_backend_estimator import DynamicsBackendEstimator
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-nus', group='default', project='default')
backend = provider.get_backend('ibm_cairo')
estimator = DynamicsBackendEstimator(backend)
estimator.run(
)
backend = JaxifiedDynamicsBackend() # Contains JaxSolver methods instead of Standard Solver
estimator = DynamicsBackendEstimator(backend)
estimator.run(
observables, # Either Qiskit Operators, Custom Class, or processed ndarrays
batch_params,
)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can show the phase of each state and use
# degrees instead of radians
from qiskit.quantum_info import DensityMatrix
import numpy as np
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
qc.z(1)
matrix = DensityMatrix(qc)
plot_state_qsphere(matrix,
show_state_phases = True, use_degrees = True)
|
https://github.com/a24l/IBM_Qiskit_QGSS
|
a24l
|
import numpy as np
from numpy import pi
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader.challenges.qgss_2022 import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader.challenges.qgss_2022 import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
qc.x(0)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader.challenges.qgss_2022 import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
qc.x(0)
qc.h(0)
qc.s(0)
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader.challenges.qgss_2022 import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
# This time, we not only want two qubits, but also two classical bits for the measurement
qc = QuantumCircuit(2)
#
#
qc.h(0)
qc.x(1)
qc.cx(0,1)
#
#
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader.challenges.qgss_2022 import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure_all() # we measure all the qubits
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
# This time, we need 3 qubits and also add 3 classical bits in case we want to measure
qc = QuantumCircuit(3)
qc.x(0)
qc.h(0)
qc.x(1)
qc.cx(1,2)
qc.cx(0,2)
qc.cx(0,1)
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
qc.measure_all() # we measure all the qubits
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
from qc_grader.challenges.qgss_2022 import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
print(qc.size())
print(qc.num_nonlocal_gates())
def qft_rotations(circuit, n):
"""Performs qft on the first n qubits in circuit (without swaps)"""
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
# At the end of our function, we call the same function again on
# the next qubits (we reduced n by one earlier in the function)
qft_rotations(circuit, n)
def swap_registers(circuit, n):
"""Swaps registers to match the definition"""
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
"""QFT on the first n qubits in circuit"""
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
qft_rotations(qc,3)
print(qc.size())
print(qc.num_nonlocal_gates())
qc.draw()
def lab1_ex7(n:int) -> int:
#Here we want you to build a function calculating the number of gates needed by the fourier rotation for n qubits.
#numberOfGates=0
#
# FILL YOUR CODE IN HERE
# TRY TO FIND AN EXPLIZIT (NON RECURSIVE) FUNCTION
numberOfGates = (n*(n+1))/2
#
return numberOfGates
print(lab1_ex7(3))
print(lab1_ex7(4))
print(lab1_ex7(5))
print(lab1_ex7(10))
print(lab1_ex7(100))
print(lab1_ex7(200))
# Lab 1, Exercise 7
from qc_grader.challenges.qgss_2022 import grade_lab1_ex7
# Note that the grading function is expecting as input a function!
#(And the function takes n as an input and outputs the number of gates constructed)
grade_lab1_ex7(lab1_ex7)
qc = QuantumCircuit(4)
qc.h(0)
qc.s(0)
qc.s(0)
qc.s(0)
qc.cx(0,1)
qc.cx(1,3)
print(qc.depth())
qc.draw()
qc2 = QuantumCircuit(4)
qc2.h(0)
qc2.s(1)
qc2.cx(0,1)
qc2.s(2)
qc2.s(3)
qc2.cx(2,3)
print(qc2.depth())
qc2.draw()
qc = QuantumCircuit(16)
#Step 1: Preparing the first qubit in superposition
qc.h(0)
#Step 2: Entangling all other qubits with it (1 is included 16 is exclude)
for x in range(1, 16):
qc.cx(0,x)
print(qc.depth())
qc.draw()
def lab1_ex8():
qc = QuantumCircuit(16) #Same as above
#Step 1: Preparing the first qubit in superposition
qc.h(0)
qc.cx(0,3)
qc.cx(0,1)
qc.cx(3,5)
qc.cx(0,7)
qc.cx(7,8)
qc.cx(5,6)
qc.cx(1,2)
qc.cx(3,4)
qc.cx(0,9)
for i in range(1,7):
qc.cx(i, 9+i)
return qc
qc = lab1_ex8()
print(qc.depth())
qc.draw()
from qc_grader.challenges.qgss_2022 import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex8(lab1_ex8())
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# 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.
r"""
MöttönenStatePreparation
==========================
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state.sparsevector._MöttönenStatePreparation
.. autosummary::
:nosignatures:
MöttönenStatePreparation
MöttönenStatePreparation
#########################
.. autoclass:: MöttönenStatePreparation
:members:
"""
from qiskit import QuantumCircuit
from scipy import sparse
from ._QmlSparseVectorStatePreparation import QmlSparseVectorStatePreparation
class QiskitNativeStatePreparation(QmlSparseVectorStatePreparation):
def prepare_state(self, qc, state_vector):
# type: (QmlSparseVectorStatePreparation, QuantumCircuit, sparse.dok_matrix) -> QuantumCircuit
"""
Apply the Möttönen state preparation routine on a quantum circuit using the given state vector.
The quantum circuit's quantum registers must be able to hold the state vector. Also it is expected
that the registers are initialized to the ground state ´´|0>´´ each.
:param qc: the quantum circuit to be used
:param state_vector: the (complex) state vector of unit length to be prepared
:return: the quantum circuit
"""
qregs = qc.qregs
# State Prep
register = [reg[i] for reg in qregs for i in range(0, reg.size)]
state = state_vector.toarray()[:,0]
qc.initialize(state, register)
return qc
def is_classifier_branch(self, branch_value):
# type: (QmlSparseVectorStatePreparation, int) -> bool
"""
The classifier will be directly usable if the branch label is 0.
:param branch_value: the branch measurement value
:return: True if the branch measurement was 0
"""
return branch_value == 0
|
https://github.com/pedroripper/qiskit_tutoriais
|
pedroripper
|
from qiskit import *
%matplotlib inline
import numpy as np
# Podemos encontrar o operador de densidade de estados
# Para isso vamos primeiramente usar o statevector_simulator para encontrar o vetor de
# estado desejado
qc = QuantumCircuit(1)
qc.rx(np.pi/2,0)
qc.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
job = execute(qc,backend)
result = job.result()
statevector = result.get_statevector()
# Aqui está o nosso vetor de estado
print(statevector)
# Agora para encontrar o seu operador de densidade
from qiskit.quantum_info import *
op_densidade = DensityMatrix(statevector)
print(op_densidade.data)
# Podemos ver o traço do nosso operador
op_densidade.trace()
estado = [np.sqrt(2),np.sqrt(2)]
print(np.inner(np.inner(estado, op_densidade.data), estado))
rho_2 = np.matmul(op_densidade.data,op_densidade.data)
trace = rho_2.trace()
print(trace)
def bloch_vector(op):
pauli_x = [[0,1],[1,0]]
pauli_y = [[0,-1j],[1j,0]]
pauli_z = [[1,0],[0,-1]]
x = np.matmul(op,pauli_x).trace()
y = np.matmul(op,pauli_y).trace()
z = np.matmul(op,pauli_z).trace()
return [np.absolute(x),np.absolute(y),np.absolute(z)]
from qiskit.tools.visualization import plot_bloch_vector
plot_bloch_vector(bloch_vector(op_densidade.data))
# Exemplo de estado misto:
estado_misto = [[0.5, 0.25],[0.25,0.5]]
plot_bloch_vector(bloch_vector(estado_misto))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import 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/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/msramalho/Teach-Me-Quantum
|
msramalho
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Choose the drawer you like best:
from qiskit.tools.visualization import matplotlib_circuit_drawer as draw
#from qiskit.tools.visualization import circuit_drawer as draw
from qiskit import IBMQ
IBMQ.load_accounts() # make sure you have setup your token locally to use this
%matplotlib inline
import matplotlib.pyplot as plt
def show_results(D):
# D is a dictionary with classical bits as keys and count as value
# example: D = {'000': 497, '001': 527}
plt.bar(range(len(D)), list(D.values()), align='center')
plt.xticks(range(len(D)), list(D.keys()))
plt.show()
from qiskit import Aer
# See a list of available local simulators
print("Aer backends: ", Aer.backends())
# see a list of available remote backends (these are freely given by IBM)
print("IBMQ Backends: ", IBMQ.backends())
# execute circuit and either display a histogram of the results
def execute_locally(qc, draw_circuit=False):
# Compile and run the Quantum circuit on a simulator backend
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
result_counts = result_sim.get_counts(qc)
# Print the results
print("simulation: ", result_sim, result_counts)
if draw_circuit: # draw the circuit
draw(qc)
else: # or show the results
show_results(result_counts)
from qiskit.backends.ibmq import least_busy
import time
# Compile and run on a real device backend
def execute_remotely(qc, draw_circuit=False):
if draw_circuit: # draw the circuit
draw(qc)
try:
# select least busy available device and execute.
least_busy_device = least_busy(IBMQ.backends(simulator=False))
print("Running on current least busy device: ", least_busy_device)
# running the job
job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10)
lapse, interval = 0, 10
while job_exp.status().name != 'DONE':
print('Status @ {} seconds'.format(interval * lapse))
print(job_exp.status())
time.sleep(interval)
lapse += 1
print(job_exp.status())
exp_result = job_exp.result()
result_counts = exp_result.get_counts(qc)
# Show the results
print("experiment: ", exp_result, result_counts)
if not draw_circuit: # show the results
show_results(result_counts)
except:
print("All devices are currently unavailable.")
def new_circuit(size):
# Create a Quantum Register with size qubits
qr = QuantumRegister(size)
# Create a Classical Register with size bits
cr = ClassicalRegister(size)
# Create a Quantum Circuit acting on the qr and cr register
return qr, cr, QuantumCircuit(qr, cr)
qr, cr, circuit = new_circuit(2)
# H gate on qubit 0
circuit.h(qr[0]);
# measure the specific qubit
circuit.measure(qr[0], cr[0]); # ; hides the output
# Try both commands:
execute_locally(circuit,draw_circuit=True)
# execute_locally(circuit,draw_circuit=False)
qr, cr, circuit = new_circuit(2)
# H gate on qubit 1
circuit.x(qr[1]);
# measure the specific qubit
circuit.measure(qr[1], cr[0]); # ; hides the output
# Try both commands:
execute_locally(circuit,draw_circuit=True)
# execute_circuit(circuit,draw_circuit=False)
qr, cr, circuit = new_circuit(2)
# CNOT gate
circuit.cx(qr[0], qr[1]);
# measure the specific qubit
circuit.measure(qr, cr); # ; hides the output
# Try both commands:
execute_locally(circuit,draw_circuit=True)
# execute_circuit(circuit,draw_circuit=False)
qr, cr, circuit = new_circuit(2)
# H gate on 2 qubits
circuit.h(qr);
# CNOT gate
circuit.cx(qr[0], qr[1]);
# measure
circuit.measure(qr, cr); # ; hides the output
# Try both commands:
execute_locally(circuit,draw_circuit=True)
# execute_circuit(circuit,draw_circuit=False)
qr, cr, circuit = new_circuit(5)
circuit.measure(qr, cr);
execute_remotely(circuit)
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
from matplotlib import pyplot
from qiskit import *
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua
from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector
from qiskit.quantum_info import Statevector
from qiskit.extensions import *
provider = IBMQ.load_account()
from qiskit.quantum_info import random_unitary
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
from math import pi, sqrt
from scipy.special import rel_entr
from random import seed
from random import random
import cmath
import sys
sys.path.append('../Pyfiles')
from circuits import *
#Possible Bin
bins_list=[];
for i in range(76):
bins_list.append((i)/75)
#Center of the Bean
bins_x=[]
for i in range(75):
bins_x.append(bins_list[1]+bins_list[i])
def P_harr(l,u,N):
return (1-l)**(N-1)-(1-u)**(N-1)
#Harr historgram
P_harr_hist=[]
for i in range(75):
P_harr_hist.append(P_harr(bins_list[i],bins_list[i+1],2))
#Imaginary
j=(-1)**(1/2)
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = 'ibmq_valencia'# you may choice here a different backend
fidelity_dic = {'ibmq_athens': 0.925110, 'ibmq_valencia': 0.809101, 'ibmq_ourense': 0.802380,
"ibmqx2": 0.627392, 'ibmq_santiago': 0.919399, 'ibmq_vigo': 0.908840, 'ideal_device': 1.0}
QV_dic = {'ibmq_athens': 32.0, 'ibmq_valencia': 16.0, 'ibmq_ourense': 8.0,
"ibmqx2": 8.0, 'ibmq_santiago': 32.0, 'ibmq_vigo': 16.0, 'ideal_device': np.inf}
dev_dic = {'ibmq_santiago': "San",'ibmq_athens': "Ath", 'ibmq_valencia': "Val", 'ibmq_vigo': 'Vig','ibmq_ourense': "Our",
"ibmqx2": 'Yor', 'ideal_device': "Ide"}
backend = provider.get_backend('ibmq_vigo')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
print(nshot,'shots per simulation',nparam,'distribution size')
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
qasm=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_qasm.txt",qasm,fmt='%.2f')
import random
for nsh in range(1,20,1):
print(int(round(1000*(nsh)**1.5,0)))
backend = Aer.get_backend('statevector_simulator')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
print(nshot,'shots per simulation',nparam,'distribution size')
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
statevector=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_statevector.txt",statevector,fmt='%.2f')
##Plot
import pandas as pd
import matplotlib.pyplot as plt
#loading dataset
x = [i+1 for i in range(19)]
y = [i[0] for i in arr]
plt.plot(x, y, 'o', color='red', label='L=1');
x = [i+1 for i in range(19)]
y = [i[1] for i in arr]
plt.plot(x, y, 'o', color='blue', label='L=2');
x = [i+1 for i in range(19)]
y = [i[2] for i in arr]
plt.plot(x, y, 'o', color='black', label='L=3');
x = [i+1 for i in range(19)]
y = [i[3] for i in arr]
plt.plot(x, y, 'o', color='green', label='L=4');
x = [i+1 for i in range(19)]
y = [i[3] for i in arr]
plt.plot(x, y, 'o', color='purple', label='L=5');
plt.legend(loc='upper right')
plt.yscale('log',base=10)
plt.xlabel('Circuit ID')
plt.ylabel('Expressibility')
# Create names on the x axis
plt.xticks([i+1 for i in range(19)])
plt.show()
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
# our backend is the Pulse Simulator
from resources import helper
from qiskit.providers.aer import PulseSimulator
backend_sim = PulseSimulator()
# sample duration for pulse instructions
dt = 1e-9
# create the model
duffing_model = helper.get_transmon(dt)
# get qubit frequency from Duffing model
qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift()
import numpy as np
# visualization tools
import matplotlib.pyplot as plt
plt.style.use('dark_background')
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
kHz = 1.0e3 # kilohertz
us = 1.0e-6 # microseconds
ns = 1.0e-9 # nanoseconds
from qiskit import pulse
from qiskit.pulse import Play, Acquire
from qiskit.pulse.pulse_lib import GaussianSquare
# qubit to be used throughout the notebook
qubit = 0
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Construct a measurement schedule and add it to an InstructionScheduleMap
meas_samples = 1200
meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150)
measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit))
inst_map = pulse.InstructionScheduleMap()
inst_map.add('measure', [qubit], measure_sched)
# save the measurement/acquire pulse for later
measure = inst_map.get('measure', qubits=[qubit])
from qiskit.pulse import pulse_lib
# the same spect pulse used in every schedule
drive_amp = 0.9
drive_sigma = 16
drive_duration = 128
spec_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp,
sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}")
# Construct an np array of the frequencies for our experiment
spec_freqs_GHz = np.arange(5.0, 5.2, 0.005)
# Create the base schedule
# Start with drive pulse acting on the drive channel
spec_schedules = []
for freq in spec_freqs_GHz:
sb_spec_pulse = helper.apply_sideband(spec_pulse, qubit_lo_freq[0]-freq*GHz, dt)
spec_schedule = pulse.Schedule(name='SB Frequency = {}'.format(freq))
spec_schedule += Play(sb_spec_pulse, drive_chan)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
spec_schedule += measure << spec_schedule.duration
spec_schedules.append(spec_schedule)
spec_schedules[0].draw()
from qiskit import assemble
# assemble the schedules into a Qobj
spec01_qobj = assemble(**helper.get_params('spec01', globals()))
# run the simulation
spec01_result = backend_sim.run(spec01_qobj, duffing_model).result()
# retrieve the data from the experiment
spec01_values = helper.get_values_from_result(spec01_result, qubit)
fit_params, y_fit = helper.fit_lorentzian(spec_freqs_GHz, spec01_values, [5, 5, 1, 0])
f01 = fit_params[1]
plt.scatter(spec_freqs_GHz, np.real(spec01_values), color='white') # plot real part of sweep values
plt.plot(spec_freqs_GHz, y_fit, color='red')
plt.xlim([min(spec_freqs_GHz), max(spec_freqs_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
print("01 Spectroscopy yields %f GHz"%f01)
x180_amp = 0.629070 #from lab 6 Rabi experiment
x_pulse = pulse_lib.gaussian(duration=drive_duration,
amp=x180_amp,
sigma=drive_sigma,
name='x_pulse')
anharmonicity_guess_GHz = -0.3
def build_spec12_pulse_schedule(freq):
sb12_spec_pulse = helper.apply_sideband(spec_pulse, (freq + anharmonicity_guess_GHz)*GHz, dt)
### create a 12 spectroscopy pulse schedule spec12_schedule (already done)
### play an x pulse on the drive channel
### play sidebanded spec pulse on the drive channel
### add measurement pulse to schedule
spec12_schedule = pulse.Schedule()
### WRITE YOUR CODE BETWEEN THESE LINES - START
spec12_schedule += Play(x_pulse, drive_chan)
spec12_schedule += Play(sb12_spec_pulse, drive_chan)
spec12_schedule += measure << spec12_schedule.duration
### WRITE YOUR CODE BETWEEN THESE LINES - STOP
return spec12_schedule
sb_freqs_GHz = np.arange(-.1, .1, 0.005) # sweep +/- 100 MHz around guess
# now vary the sideband frequency for each spec pulse
spec_schedules = []
for freq in sb_freqs_GHz:
spec_schedules.append(build_spec12_pulse_schedule(freq))
spec_schedules[0].draw()
# assemble the schedules into a Qobj
spec12_qobj = assemble(**helper.get_params('spec12', globals()))
answer1 = spec12_qobj
# run the simulation
spec12_result = backend_sim.run(spec12_qobj, duffing_model).result()
# retrieve the data from the experiment
spec12_values = helper.get_values_from_result(spec12_result, qubit)
anharm_offset = qubit_lo_freq[0]/GHz + anharmonicity_guess_GHz
fit_params, y_fit = helper.fit_lorentzian(anharm_offset + sb_freqs_GHz, spec12_values, [5, 4.5, .1, 3])
f12 = fit_params[1]
plt.scatter(anharm_offset + sb_freqs_GHz, np.real(spec12_values), color='white') # plot real part of sweep values
plt.plot(anharm_offset + sb_freqs_GHz, y_fit, color='red')
plt.xlim([anharm_offset + min(sb_freqs_GHz), anharm_offset + max(sb_freqs_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
print("12 Spectroscopy yields %f GHz"%f12)
print("Measured transmon anharmonicity is %f MHz"%((f12-f01)*GHz/MHz))
from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();'));
from grading_tools import send_code;send_code('ex1.ipynb')
|
https://github.com/vindem/quantumMD
|
vindem
|
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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.