repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
---|---|---|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open(filename, "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
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/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# 必要なライブラリのインポート
from qiskit import IBMQ, BasicAer, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
import numpy as np
# 描画ツールのインポート
from qiskit.visualization import plot_histogram
#qiskitのversion確認
import qiskit
qiskit.__qiskit_version__
#入力用量子ビットの数を設定
n = 3
const_f = QuantumCircuit(n+1,n) #量子回路を準備(アンシラ用にn+1個の量子レジスタを準備)
input = np.random.randint(2) #乱数生成にランダム関数をつかいます
if input == 1:
const_f.x(n)
for i in range(n):
const_f.measure(i, i)
const_f.draw()
const_f = QuantumCircuit(n+1,n)
input = np.random.randint(2) #乱数生成にランダム関数をつかいます
if input == 1:
const_f.id(n)
for i in range(n):
const_f.measure(i, i)
const_f.draw()
#上記の図のとおり4量子ビット回路を用意してください。
#各入力用量子ビットを制御に、出力用量子ビットを標的としたCNOT回路を作成してください。
q = QuantumCircuit(4) # 4量子ビット回路を用意
q.cx(0,3)
q.cx(1,3)
q.cx(2,3)
q.draw(output="mpl") # 回路を描画
# 上記回路にあるように入力|𝑞2𝑞1𝑞0⟩=|010⟩をつくって|𝑞3⟩の状態を確認してください。
q = QuantumCircuit(4) # 4量子ビット回路を用意
q.x(1) # Xゲートを1番目の量子ビットに操作します。
q.cx(0,3)
q.cx(1,3)
q.cx(2,3)
q.barrier() # 回路をみやすくするためにバリアを配置
q.x(1) # 最後にXゲートで1番目の量子ビットを挟みます。
q.draw(output="mpl") # 回路を描画
balanced_f = QuantumCircuit(n+1,n)
b_str = "101"
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_f.x(qubit)
balanced_f.draw()
balanced_f.barrier() #回路をみやすくするためにバリアを配置
for qubit in range(n): #入力用量子ビットにCNOTゲートを適用
balanced_f.cx(qubit, n)
balanced_f.barrier() #回路をみやすくするためにバリアを配置
balanced_f.draw()
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_f.x(qubit)
balanced_f.draw()
#ドイチ・ジョザアルゴリズムに均等な関数を実装した回路を"balanced_dj"と名付ける
balanced_dj = QuantumCircuit(n+1, n)
#Step 1: 各量子ビットはもともと|0>に初期化されているため、最後のアンシラだけ|1>に
balanced_dj.x(n) #Xゲートを最後のアンシラに適用
#Step 2: 全体にアダマールをかけて入力用量子ビットはすべて|+⟩ に、そして補助の量子ビットは|−⟩に
for qubit in range(n): #全量子ビットにアダマールを適用
balanced_dj.h(qubit)
#Step 3: オラクルUf |𝑥⟩|𝑦⟩↦|𝑥⟩|𝑓(𝑥)⊕𝑦⟩を適用
# 次ステップでUfを構築します
#Step 4: 最後の補助量子ビットにアダマールを適用して回路を描画
balanced_dj.h(n)
balanced_dj.draw()
balanced_dj += balanced_f #均等な関数の追加
balanced_dj.draw()
for qubit in range(n):
balanced_dj.h(qubit)
balanced_dj.barrier()
for i in range(n):
balanced_dj.measure(i, i)
balanced_dj.draw()
# 回路をシミュレーターに投げて結果を出力します
simulator = Aer.get_backend('qasm_simulator')
result = execute(balanced_dj, backend=simulator, shots=1).result()
# 結果をヒストグラムでプロットします
plot_histogram(result.get_counts(balanced_dj))
#IBM Q accountをロードししプロバイダを指定
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
#一番空いているバックエンドを自動的に選択して実行
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
#上記で特定したバックエンドを指定してジョブを実行します。
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(balanced_dj, backend=backend, shots=shots, optimization_level=3)
#プログラムの実行ステータスをモニターします。
job_monitor(job, interval = 2)
#計算結果(results)を取得し、答え(answer)をプロットします。
results = job.result()
answer = results.get_counts()
# 結果をヒストグラムでプロットします
plot_histogram(answer)
#必要に応じてQiskitのライブラリ等のインポート
# from qiskit import *
# %matplotlib inline
# from qiskit.tools.visualization import plot_histogram
#適当なバイナリ文字列を設定
s = '0110001'
#qcという名の量子回路を準備
qc = QuantumCircuit(6+1,6)
qc.x(6)
qc.h(6)
qc.h(range(6))
qc.draw()
# Step 1
s = '0110001'
#$n+1$ 量子ビットと結果を格納する $n$個の古典レジスタを用意する。$n$は秘密の文字列の長さと同じ。
n = len(s)
qc = QuantumCircuit(n+1,n)
# Step 2
qc.x(n) #最後の量子ビットを|1⟩にする
qc.barrier() #回路をみやすくするためにバリアを配置
# Step 3
qc.h(range(n+1)) #全体にHゲートを適用
qc.barrier() #回路をみやすくするためにバリアを配置
# Step 4
for ii, yesno in enumerate(reversed(s)):
if yesno == '1':
qc.cx(ii, n)
qc.barrier() #回路をみやすくするためにバリアを配置
# Step 5
qc.h(range(n+1)) #全量子ビットに再びHを適用
qc.barrier() #回路をみやすくするためにバリアを配置
qc.measure(range(n), range(n)) # 0 から n-1までの入力n量子ビットを測定し古典レジスタに結果を格納
%matplotlib inline
#回路図を描画
qc.draw(output='mpl')
# 回路をシミュレーターに投げて結果を出力します
simulator = Aer.get_backend('qasm_simulator')
# shots=1で実施
result = execute(qc, backend=simulator, shots=1).result()
# 結果をヒストグラムでプロットします
from qiskit.visualization import plot_histogram
plot_histogram(result.get_counts(qc))
# 必要似応じてIBM Q accountをロードししプロバイダを指定
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q')
#一番空いているバックエンドを自動的に選択して実行
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
#上記で特定したバックエンドを指定してジョブを実行します。
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(qc, backend=backend, shots=shots, optimization_level=3)
#プログラムの実行ステータスをモニターします。
job_monitor(job, interval = 2)
#計算結果(results)を取得し、答え(answer)をプロットします。
results = job.result()
answer = results.get_counts()
# 結果をヒストグラムでプロットします
plot_histogram(answer)
|
https://github.com/jvscursulim/qamp_fall22_project
|
jvscursulim
|
import time
import os
import copy
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import datasets, transforms
from qiskit.circuit import QuantumCircuit, ParameterVector
from qiskit.utils import QuantumInstance
from qiskit.opflow import AerPauliExpectation
from qiskit_aer import Aer
from qiskit_machine_learning.neural_networks import CircuitQNN
from qiskit_machine_learning.connectors import TorchConnector
from qiskit.opflow.expectations import PauliExpectation
from qiskit.opflow.primitive_ops import PauliOp
from qiskit.quantum_info.operators import Pauli
torch.manual_seed(42)
np.random.seed(42)
os.environ["OMP_NUM_THREADS"] = "1"
n_qubits = 4 # Number of qubits
step = 0.0004 # Learning rate
batch_size = 4 # Number of samples for each training step
num_epochs = 3 # Number of training epochs
q_depth = 6 # Depth of the quantum circuit (number of variational layers)
gamma_lr_scheduler = 0.1 # Learning rate reduction applied every 10 epochs.
q_delta = 0.01 # Initial spread of random quantum weights
start_time = time.time() # Start of the computation timer
dev = QuantumInstance(backend=Aer.get_backend("statevector_simulator"))
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
data_dir = "data/hymenoptera_data"
data_transforms = {
"train": transforms.Compose(
[
# transforms.RandomResizedCrop(224), # uncomment for data augmentation
# transforms.RandomHorizontalFlip(), # uncomment for data augmentation
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
# Normalize input channels using mean values and standard deviations of ImageNet.
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]
),
"val": transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]
),
}
image_datasets = {
x if x == "train" else "validation": datasets.ImageFolder(
os.path.join(data_dir, x), data_transforms[x]
)
for x in ["train", "val"]
}
dataset_sizes = {x: len(image_datasets[x]) for x in ["train", "validation"]}
class_names = image_datasets["train"].classes
# Initialize dataloader
dataloaders = {
x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True)
for x in ["train", "validation"]
}
# function to plot images
def imshow(inp, title=None):
"""Display image from tensor."""
inp = inp.numpy().transpose((1, 2, 0))
# Inverse of the initial normalization operation.
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
inp = std * inp + mean
inp = np.clip(inp, 0, 1)
plt.imshow(inp)
if title is not None:
plt.title(title)
# Get a batch of training data
inputs, classes = next(iter(dataloaders["validation"]))
# Make a grid from batch
out = torchvision.utils.make_grid(inputs)
imshow(out, title=[class_names[x] for x in classes])
dataloaders = {
x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True)
for x in ["train", "validation"]
}
def quantum_net(size_input_features=4, size_weights=4):
"""
The variational quantum circuit.
"""
qc = QuantumCircuit(n_qubits)
qc.h(qubit=[i for i in range(n_qubits)])
input_params = ParameterVector(name="input", length=size_input_features)
for idx, param in enumerate(input_params):
qc.ry(theta=param, qubit=idx)
for k in range(q_depth):
for i in range(0, n_qubits - 1, 2):
qc.cx(control_qubit=i, target_qubit=i+1)
for i in range(1, n_qubits - 1, 2):
qc.cx(control_qubit=i, target_qubit=i+1)
params = ParameterVector(name=f"q_weights_{k}", length=size_weights)
for idx, param in enumerate(params):
qc.ry(theta=param, qubit=idx)
qnn = CircuitQNN(qc,
qc.parameters[:4],
qc.parameters[4:],
input_gradients=True,
quantum_instance=dev
)
return qnn
class DressedQuantumNet(nn.Module):
"""
Torch module implementing the *dressed* quantum net.
"""
def __init__(self, qnn):
"""
Definition of the *dressed* layout.
"""
super().__init__()
self.pre_net = nn.Linear(512, n_qubits)
self.qnn = TorchConnector(qnn)
self.post_net = nn.Linear(16, 2)
def forward(self, x):
"""
Defining how tensors are supposed to move through the *dressed* quantum
net.
"""
x = self.pre_net(x)
x = torch.tanh(x) * np.pi/2.0
x = self.qnn(x)
x = self.post_net(x)
return x
model_hybrid = torchvision.models.resnet18(pretrained=True)
for param in model_hybrid.parameters():
param.requires_grad = False
# Notice that model_hybrid.fc is the last layer of ResNet18
model_hybrid.fc = DressedQuantumNet(qnn=quantum_net())
# Use CUDA or CPU according to the "device" object.
model_hybrid = model_hybrid.to(device)
criterion = nn.CrossEntropyLoss()
optimizer_hybrid = optim.Adam(model_hybrid.fc.parameters(), lr=step)
exp_lr_scheduler = lr_scheduler.StepLR(
optimizer_hybrid, step_size=10, gamma=gamma_lr_scheduler
)
def train_model(model, criterion, optimizer, scheduler, num_epochs):
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
best_loss = 10000.0 # Large arbitrary number
best_acc_train = 0.0
best_loss_train = 10000.0 # Large arbitrary number
print("Training started:")
for epoch in range(num_epochs):
# Each epoch has a training and validation phase
for phase in ["train", "validation"]:
if phase == "train":
# Set model to training mode
model.train()
else:
# Set model to evaluate mode
model.eval()
running_loss = 0.0
running_corrects = 0
# Iterate over data.
n_batches = dataset_sizes[phase] // batch_size
it = 0
for inputs, labels in dataloaders[phase]:
since_batch = time.time()
batch_size_ = len(inputs)
inputs = inputs.to(device)
labels = labels.to(device)
optimizer.zero_grad()
# Track/compute gradient and make an optimization step only when training
with torch.set_grad_enabled(phase == "train"):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
if phase == "train":
loss.backward()
optimizer.step()
# Print iteration results
running_loss += loss.item() * batch_size_
batch_corrects = torch.sum(preds == labels.data).item()
running_corrects += batch_corrects
print(
"Phase: {} Epoch: {}/{} Iter: {}/{} Batch time: {:.4f}".format(
phase,
epoch + 1,
num_epochs,
it + 1,
n_batches + 1,
time.time() - since_batch,
),
end="\r",
flush=True,
)
it += 1
# Print epoch results
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects / dataset_sizes[phase]
print(
"Phase: {} Epoch: {}/{} Loss: {:.4f} Acc: {:.4f} ".format(
"train" if phase == "train" else "validation ",
epoch + 1,
num_epochs,
epoch_loss,
epoch_acc,
)
)
# Check if this is the best model wrt previous epochs
if phase == "validation" and epoch_acc > best_acc:
best_acc = epoch_acc
best_model_wts = copy.deepcopy(model.state_dict())
if phase == "validation" and epoch_loss < best_loss:
best_loss = epoch_loss
if phase == "train" and epoch_acc > best_acc_train:
best_acc_train = epoch_acc
if phase == "train" and epoch_loss < best_loss_train:
best_loss_train = epoch_loss
# Update learning rate
if phase == "train":
scheduler.step()
# Print final results
model.load_state_dict(best_model_wts)
time_elapsed = time.time() - since
print(
"Training completed in {:.0f}m {:.0f}s".format(time_elapsed // 60, time_elapsed % 60)
)
print("Best test loss: {:.4f} | Best test accuracy: {:.4f}".format(best_loss, best_acc))
return model
model_hybrid = train_model(
model_hybrid, criterion, optimizer_hybrid, exp_lr_scheduler, num_epochs=num_epochs
)
def visualize_model(model, num_images=6, fig_name="Predictions"):
images_so_far = 0
_fig = plt.figure(fig_name)
model.eval()
with torch.no_grad():
for _i, (inputs, labels) in enumerate(dataloaders["validation"]):
inputs = inputs.to(device)
labels = labels.to(device)
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
for j in range(inputs.size()[0]):
images_so_far += 1
ax = plt.subplot(num_images // 2, 2, images_so_far)
ax.axis("off")
ax.set_title("[{}]".format(class_names[preds[j]]))
imshow(inputs.cpu().data[j])
if images_so_far == num_images:
return
visualize_model(model_hybrid, num_images=batch_size)
plt.show()
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
import math
import numpy as np
from qiskit import *
nshots = 8192
qiskit.IBMQ.load_account()
#provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
#device = provider.get_backend('ibmq_jakarta')
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
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.tools.monitor import backend_overview, backend_monitor
from qiskit.tools.visualization import plot_histogram
qc = QuantumCircuit(5)
th, ph, lb = 0.1, 0.2, 0.3; qc.u(th, ph, lb, [0]); qc.barrier() # qubit estate preparation
qc.cx([0],[1]); qc.cx([1], [2]); qc.h([0, 1, 2]); qc.barrier() # encoding
qc.z([0]); qc.barrier() # phase flip error
qc.draw(output = 'mpl')
qc.h([0, 1, 2]); qc.cx([0], [3]); qc.cx([1], [3]); qc.cx([1], [4]); qc.cx([2], [4])
qc.draw(output = 'mpl')
def qc_ec_pf(th, ph, lb, j):
qc = QuantumCircuit(5, name = 'EC_PF')
qc.u(th, ph, lb, [0]) # qubit state preparation
qc.barrier()
qc.cx([0], [1]); qc.cx([1], [2]); qc.h([0, 1, 2]) # encoding
qc.barrier()
if j == 0 or j == 1 or j == 2: # error
qc.z([j])
qc.barrier()
qc.h([0, 1, 2]); qc.cx([0], [3]); qc.cx([1], [3]); qc.cx([1], [4]); qc.cx([2], [4]) # syndrome detection
qc.barrier()
qc.x([3]); qc.ccx([4], [3], [2]); qc.x([3]); qc.ccx([4], [3], [1]) # correction
qc.x([4]); qc.ccx([4], [3], [0]); qc.x([4]) # correction
qc.barrier()
return qc
th, ph, lb = math.pi, 0.0, 0.0; j = 2; qc_ec_pf_ = qc_ec_pf(th, ph, lb, j)
qc_ec_pf_.draw(output = 'mpl')
# Teste da funcionalidade do circuito para correção do phase flip
qc = QuantumCircuit(5, 3);
j = 2 # sets the error
qc_ec_pf_ = qc_ec_pf(math.pi/2, 0.0, 0.0, j); qc.append(qc_ec_pf_, [0, 1, 2, 3, 4])
qc.measure([0, 1, 2], [0, 1, 2]);
#qc.decompose().draw(output = 'mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
plot_histogram(job_sim.result().get_counts(qc))
job_exp = execute(qc, backend = device, shots = nshots)
print(job_exp.job_id()); job_monitor(job_exp)
plot_histogram(job_exp.result().get_counts(qc))
qc = QuantumCircuit(2, 1)
th, ph, lb = math.pi, 0.0, 0.0; qc.u(th, ph, lb, [0]) # state preparation
qc.barrier(); qc.cx([0], [1]); qc.h([0]); qc.barrier()
qc.z([0]); qc.barrier()
qc.h([0]); qc.cx([0], [1]); qc.cx([1], [0])
qc.measure([0], [0])
qc.draw(output = 'mpl')
job = execute(qc, backend = simulator, shots = nshots)
plot_histogram(job.result().get_counts(qc))
job = execute(qc, backend = device, shots = nshots); job_monitor(job)
plot_histogram(job.result().get_counts(qc))
def qc_encoding_shor():
qc = QuantumCircuit(9, name = 'encoding')
qc.cx([0], [3]); qc.cx([0], [6])
qc.h([0, 3, 6])
qc.cx([0], [1]); qc.cx([0], [2]); qc.cx([3], [4])
qc.cx([3], [5]); qc.cx([6], [7]); qc.cx([6], [8])
return qc
qc_encoding_shor_ = qc_encoding_shor(); qc_encoding_shor_.draw(output = 'mpl')
def qc_gen_bf():
qc = QuantumCircuit(9+6, name = 'BF')
qc.decompose().draw(output = 'mpl')
qc.cx([0], [9]); qc.cx([1], [9]); qc.cx([1], [10]); qc.cx([2], [10])
qc.barrier()
qc.x([9]); qc.ccx([10], [9], [2]); qc.x([9]); qc.ccx([10], [9], [1]); qc.x([10]); qc.ccx([10], [9], [0]); qc.x([10])
qc.barrier()
qc.cx([3], [11]); qc.cx([4], [11]); qc.cx([4], [12]); qc.cx([5], [12])
qc.barrier()
qc.x([11]); qc.ccx([12], [11], [5]); qc.x([11]); qc.ccx([12], [11], [4]); qc.x([12]); qc.ccx([12], [11], [3]); qc.x([12])
qc.barrier()
qc.cx([6], [13]); qc.cx([7], [13]); qc.cx([7], [14]); qc.cx([8], [14])
qc.barrier()
qc.x([13]); qc.ccx([14], [13], [8]); qc.x([13]); qc.ccx([14], [13], [7]); qc.x([14]); qc.ccx([14], [13], [6]); qc.x([14])
return qc
qc_gen_bf_ = qc_gen_bf(); qc_gen_bf_.draw(output = 'mpl')
#qc.decompose().draw(output = 'mpl')
def qc_gen_pf():
qc = QuantumCircuit(9+2, name = 'PF')
qc.cx([0], [1]); qc.cx([0], [2]); qc.cx([3], [4]); qc.cx([3], [5]); qc.cx([6], [7]); qc.cx([6], [8]) # destrói o emaranhamento
qc.h([0, 3, 6]) # destrói a coerência
qc.cx([0], [9]); qc.cx([3], [9]); qc.cx([3], [10]); qc.cx([6], [10]) # medida de síndrome
qc.barrier()
qc.x([9]); qc.ccx([10], [9], [6]); qc.x([9]); qc.ccx([10], [9], [3]); qc.x([10]); qc.ccx([10], [9], [0]); qc.x([10]) # reversão do erro
qc.barrier()
qc.h([0, 3, 6]) # passa esses qubits para a base |+>,|->
qc.cx([0], [1]); qc.cx([0], [2]); qc.cx([3], [4]); qc.cx([3], [5]); qc.cx([6], [7]); qc.cx([6], [8]) # recria o emaranhamento
return qc
qc_gen_pf_ = qc_gen_pf(); qc_gen_pf_.draw(output = 'mpl')
def qc_decoding_shor():
qc = QuantumCircuit(9, name = 'decoding')
qc.cx([0], [2]); qc.cx([3], [5]); qc.cx([6], [8])
qc.cx([0], [1]); qc.cx([3], [4]); qc.cx([6], [7])
qc.h([0, 3, 6])
qc.cx([0], [3]); qc.cx([0], [6])
return qc
qc_decoding_shor_ = qc_decoding_shor(); qc_decoding_shor_.draw(output = 'mpl')
def qc_error():
qc = QuantumCircuit(9, name = 'error')
qc.x([0]); qc.z([0])
#qc.z(4); qc.x([5])
qc.x([8])
return qc
qc_error_ = qc_error(); qc_error_.draw(output = 'mpl')
qc = QuantumCircuit(9+6+2, 1)
qc.h([0]) # prepara o estado |1>
qc.barrier()
qc_encoding_shor_ = qc_encoding_shor(); qc.append(qc_encoding_shor_, [0,1,2,3,4,5,6,7,8])
qc.barrier()
qc_error_ = qc_error(); qc.append(qc_error_, [0,1,2,3,4,5,6,7,8])
qc.barrier()
qc_gen_bf_ = qc_gen_bf(); qc.append(qc_gen_bf_, [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14])
qc.barrier()
qc_gen_pf_ = qc_gen_pf(); qc.append(qc_gen_pf_, [0,1,2,3,4,5,6,7,8,15,16])
qc.barrier()
qc_decoding_shor_ = qc_decoding_shor(); qc.append(qc_decoding_shor_, [0,1,2,3,4,5,6,7,8])
qc.barrier()
qc.measure([0], 0)
qc.draw(output = 'mpl')
job = execute(qc, backend = simulator, shots = nshots)
plot_histogram(job.result().get_counts(qc))
qc = QuantumCircuit(9)
th, ph, lb = math.pi/2, 0.0, 0.0; qc.u(th, ph, lb, [0])
qc.barrier(); qc.x([0]); qc.z([0]); qc.barrier() # o erro
qc.cx([0], [1]); qc.cx([0], [2]); qc.cx([3], [4]); qc.cx([3], [5]); qc.cx([6], [7]); qc.cx([6], [8])
qc.ccx([2], [1], [0]); qc.ccx([5], [4], [3]); qc.ccx([8], [7], [6])
qc.h([0, 3, 6])
qc.cx([0], [3]); qc.cx([0], [6])
qc.ccx([6], [3], [0])
qc.draw(output = 'mpl')
qc = QuantumCircuit(3, 1)
th, ph, lb = math.pi, 0.0, 0.0; qc.u(th, ph, lb, [1]) # state preparation
qc.barrier(); qc.cx([1], [2]); qc.barrier()
qc.x([1]); qc.z([1]); qc.barrier()
qc.cx([1], [2]); qc.cx([2], [1])
qc.measure([1], [0])
qc.draw(output = 'mpl')
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
"""A wrapper class for the purposes of validating modifications to
QuantumCircuit.data while maintaining the interface of a python list."""
from collections.abc import MutableSequence
import qiskit._accelerate.circuit
from .exceptions import CircuitError
from .instruction import Instruction
from .operation import Operation
CircuitInstruction = qiskit._accelerate.circuit.CircuitInstruction
class QuantumCircuitData(MutableSequence):
"""A wrapper class for the purposes of validating modifications to
QuantumCircuit.data while maintaining the interface of a python list."""
def __init__(self, circuit):
self._circuit = circuit
def __getitem__(self, i):
return self._circuit._data[i]
def __setitem__(self, key, value):
# For now (Terra 0.21), the `QuantumCircuit.data` setter is meant to perform validation, so
# we do the same qubit checks that `QuantumCircuit.append` would do.
if isinstance(value, CircuitInstruction):
operation, qargs, cargs = value.operation, value.qubits, value.clbits
else:
# Handle the legacy 3-tuple format.
operation, qargs, cargs = value
value = self._resolve_legacy_value(operation, qargs, cargs)
self._circuit._data[key] = value
if isinstance(value.operation, Instruction):
self._circuit._update_parameter_table(value.operation)
def _resolve_legacy_value(self, operation, qargs, cargs) -> CircuitInstruction:
"""Resolve the old-style 3-tuple into the new :class:`CircuitInstruction` type."""
if not isinstance(operation, Operation) and hasattr(operation, "to_instruction"):
operation = operation.to_instruction()
if not isinstance(operation, Operation):
raise CircuitError("object is not an Operation.")
expanded_qargs = [self._circuit.qbit_argument_conversion(qarg) for qarg in qargs or []]
expanded_cargs = [self._circuit.cbit_argument_conversion(carg) for carg in cargs or []]
if isinstance(operation, Instruction):
broadcast_args = list(operation.broadcast_arguments(expanded_qargs, expanded_cargs))
else:
broadcast_args = list(
Instruction.broadcast_arguments(operation, expanded_qargs, expanded_cargs)
)
if len(broadcast_args) > 1:
raise CircuitError(
"QuantumCircuit.data modification does not support argument broadcasting."
)
qargs, cargs = broadcast_args[0]
self._circuit._check_dups(qargs)
return CircuitInstruction(operation, tuple(qargs), tuple(cargs))
def insert(self, index, value):
self._circuit._data.insert(index, CircuitInstruction(None, (), ()))
try:
self[index] = value
except CircuitError:
del self._circuit._data[index]
raise
def __iter__(self):
return iter(self._circuit._data)
def __delitem__(self, i):
del self._circuit._data[i]
def __len__(self):
return len(self._circuit._data)
def __cast(self, other):
return list(other._circuit._data) if isinstance(other, QuantumCircuitData) else other
def __repr__(self):
return repr(list(self._circuit._data))
def __lt__(self, other):
return list(self._circuit._data) < self.__cast(other)
def __le__(self, other):
return list(self._circuit._data) <= self.__cast(other)
def __eq__(self, other):
return self._circuit._data == self.__cast(other)
def __gt__(self, other):
return list(self._circuit._data) > self.__cast(other)
def __ge__(self, other):
return list(self._circuit._data) >= self.__cast(other)
def __add__(self, other):
return list(self._circuit._data) + self.__cast(other)
def __radd__(self, other):
return self.__cast(other) + list(self._circuit._data)
def __mul__(self, n):
return list(self._circuit._data) * n
def __rmul__(self, n):
return n * list(self._circuit._data)
def sort(self, *args, **kwargs):
"""In-place stable sort. Accepts arguments of list.sort."""
data = list(self._circuit._data)
data.sort(*args, **kwargs)
self._circuit._data.clear()
self._circuit._data.reserve(len(data))
self._circuit._data.extend(data)
def copy(self):
"""Returns a shallow copy of instruction list."""
return list(self._circuit._data)
|
https://github.com/snow0369/qiskit_tutorial_2021_summerschool
|
snow0369
|
import numpy as np
from qiskit.providers.aer import AerProvider
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.tools.visualization import plot_histogram
import qiskit.providers.aer.noise as noise
from qiskit.quantum_info import hellinger_fidelity
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
qc = QuantumCircuit(qr, cr)
tau = Parameter('τ')
qc.h(qr)
qc.cx(qr[0], qr[1])
qc.cx(qr[1], qr[2])
qc.rz(-2 * tau, qr[2])
qc.cx(qr[1], qr[2])
qc.cx(qr[0], qr[1])
qc.h(qr)
qc.draw('mpl')
meas = QuantumCircuit(qr, cr)
meas.measure(qr, cr)
meas.draw('mpl')
qasm_qc = qc.compose(meas)
qasm_qc.draw('mpl')
bind_qasm_qc = qasm_qc.bind_parameters({tau: np.pi/4})
qasm_backend = AerProvider().get_backend('qasm_simulator')
job_qasm = qasm_backend.run(bind_qasm_qc, shots=4096)
counts_qasm = job_qasm.result().get_counts()
print(counts_qasm)
plot_histogram(counts_qasm)
# Error probabilities
prob_1 = 0.001 # 1-qubit gate
prob_2 = 0.01 # 2-qubit gate
# Depolarizing quantum errors
error_1 = noise.depolarizing_error(prob_1, num_qubits=1)
error_2 = noise.depolarizing_error(prob_2, num_qubits=2)
# Add errors to noise model
noise_model = noise.NoiseModel()
noise_model.add_all_qubit_quantum_error(error_1, ['h', 'rz'])
noise_model.add_all_qubit_quantum_error(error_2, ['cx'])
job_qasm_noisy = qasm_backend.run(bind_qasm_qc, shots=4096, noise_model=noise_model)
counts_qasm_noisy = job_qasm_noisy.result().get_counts()
print(counts_qasm_noisy)
plot_histogram(counts_qasm_noisy)
print(hellinger_fidelity(counts_qasm, counts_qasm_noisy))
qc.draw('mpl')
bind_qc = qc.bind_parameters({tau: np.pi/4})
sv_backend = AerProvider().get_backend('statevector_simulator')
job_sv = sv_backend.run(bind_qc)
final_sv = job_sv.result().get_statevector()
np.set_printoptions(suppress=True)
print(final_sv)
unitary_backend = AerProvider().get_backend('unitary_simulator')
job_unitary = unitary_backend.run(bind_qc)
unitary = job_unitary.result().get_unitary()
print(unitary)
for idx, x in np.ndenumerate(unitary):
if abs(x) > 1e-7:
print(f"{idx}, {x.real if abs(x.real) > 1e-7 else 0.0} {' + j'+ str(x.imag) if abs(x.imag) > 1e-7 else 0.0}")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/epelaaez/QuantumLibrary
|
epelaaez
|
#Assign these values as per your requirements.
global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion
min_qubits=4
max_qubits=15 #reference files are upto 12 Qubits only
skip_qubits=2
max_circuits=3
num_shots=4092
gate_counts_plots = True
Noise_Inclusion = False
saveplots = False
Memory_utilization_plot = True
Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2"
backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends
#Change your Specification of Simulator in Declaring Backend Section
#By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2()
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute
from qiskit.opflow import PauliTrotterEvolution, Suzuki
from qiskit.opflow.primitive_ops import PauliSumOp
import time,os,json
import matplotlib.pyplot as plt
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error)
# Benchmark Name
benchmark_name = "VQE Simulation"
# Selection of basis gate set for transpilation
# Note: selector 1 is a hardware agnostic gate set
basis_selector = 1
basis_gates_array = [
[],
['rx', 'ry', 'rz', 'cx'], # a common basis set, default
['cx', 'rz', 'sx', 'x'], # IBM default basis set
['rx', 'ry', 'rxx'], # IonQ default basis set
['h', 'p', 'cx'], # another common basis set
['u', 'cx'] # general unitaries basis gates
]
np.random.seed(0)
def get_QV(backend):
import json
# Assuming backend.conf_filename is the filename and backend.dirname is the directory path
conf_filename = backend.dirname + "/" + backend.conf_filename
# Open the JSON file
with open(conf_filename, 'r') as file:
# Load the JSON data
data = json.load(file)
# Extract the quantum_volume parameter
QV = data.get('quantum_volume', None)
return QV
def checkbackend(backend_name,Type_of_Simulator):
if Type_of_Simulator == "built_in":
available_backends = []
for i in Aer.backends():
available_backends.append(i.name)
if backend_name in available_backends:
platform = backend_name
return platform
else:
print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!")
print(f"available backends are : {available_backends}")
platform = "qasm_simulator"
return platform
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2":
import qiskit.providers.fake_provider as fake_backends
if hasattr(fake_backends,backend_name) is True:
print(f"Backend {backend_name} is available for type {Type_of_Simulator}.")
backend_class = getattr(fake_backends,backend_name)
backend_instance = backend_class()
return backend_instance
else:
print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!")
if Type_of_Simulator == "FAKEV2":
backend_class = getattr(fake_backends,"FakeSantiagoV2")
else:
backend_class = getattr(fake_backends,"FakeSantiago")
backend_instance = backend_class()
return backend_instance
if Type_of_Simulator == "built_in":
platform = checkbackend(backend_name,Type_of_Simulator)
#By default using "Qasm Simulator"
backend = Aer.get_backend(platform)
QV_=None
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"backend version is {backend.backend_version}")
elif Type_of_Simulator == "FAKE":
basis_selector = 0
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting.
max_qubits=backend.configuration().n_qubits
print(f"{platform} device is capable of running {backend.configuration().n_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
elif Type_of_Simulator == "FAKEV2":
basis_selector = 0
if "V2" not in backend_name:
backend_name = backend_name+"V2"
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.name +"-" +backend.backend_version
max_qubits=backend.num_qubits
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
else:
print("Enter valid Simulator.....")
# saved circuits for display
QC_ = None
Hf_ = None
CO_ = None
################### Circuit Definition #######################################
# Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz
# param: n_spin_orbs - The number of spin orbitals.
# return: return a Qiskit circuit for this VQE ansatz
def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1):
# number of alpha spin orbitals
norb_a = int(n_spin_orbs / 2)
# construct the Hamiltonian
qubit_op = ReadHamiltonian(n_spin_orbs)
# allocate qubits
num_qubits = n_spin_orbs
qr = QuantumRegister(num_qubits)
qc = QuantumCircuit(qr, name=f"vqe-ansatz({method})-{num_qubits}-{circuit_id}")
# initialize the HF state
Hf = HartreeFock(num_qubits, na, nb)
qc.append(Hf, qr)
# form the list of single and double excitations
excitationList = []
for occ_a in range(na):
for vir_a in range(na, norb_a):
excitationList.append((occ_a, vir_a))
for occ_b in range(norb_a, norb_a+nb):
for vir_b in range(norb_a+nb, n_spin_orbs):
excitationList.append((occ_b, vir_b))
for occ_a in range(na):
for vir_a in range(na, norb_a):
for occ_b in range(norb_a, norb_a+nb):
for vir_b in range(norb_a+nb, n_spin_orbs):
excitationList.append((occ_a, vir_a, occ_b, vir_b))
# get cluster operators in Paulis
pauli_list = readPauliExcitation(n_spin_orbs, circuit_id)
# loop over the Pauli operators
for index, PauliOp in enumerate(pauli_list):
# get circuit for exp(-iP)
cluster_qc = ClusterOperatorCircuit(PauliOp, excitationList[index])
# add to ansatz
qc.append(cluster_qc, [i for i in range(cluster_qc.num_qubits)])
# method 1, only compute the last term in the Hamiltonian
if method == 1:
# last term in Hamiltonian
qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits)
# return the circuit
return qc_with_mea
# now we need to add the measurement parts to the circuit
# circuit list
qc_list = []
diag = []
off_diag = []
global normalization
normalization = 0.0
# add the first non-identity term
identity_qc = qc.copy()
identity_qc.measure_all()
qc_list.append(identity_qc) # add to circuit list
diag.append(qubit_op[1])
normalization += abs(qubit_op[1].coeffs[0]) # add to normalization factor
diag_coeff = abs(qubit_op[1].coeffs[0]) # add to coefficients of diagonal terms
# loop over rest of terms
for index, p in enumerate(qubit_op[2:]):
# get the circuit with expectation measurements
qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits)
# accumulate normalization
normalization += abs(p.coeffs[0])
# add to circuit list if non-diagonal
if not is_diag:
qc_list.append(qc_with_mea)
else:
diag_coeff += abs(p.coeffs[0])
# diagonal term
if is_diag:
diag.append(p)
# off-diagonal term
else:
off_diag.append(p)
# modify the name of diagonal circuit
qc_list[0].name = qubit_op[1].primitive.to_list()[0][0] + " " + str(np.real(diag_coeff))
normalization /= len(qc_list)
return qc_list
# Function that constructs the circuit for a given cluster operator
def ClusterOperatorCircuit(pauli_op, excitationIndex):
# compute exp(-iP)
exp_ip = pauli_op.exp_i()
# Trotter approximation
qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip)
# convert to circuit
qc = qc_op.to_circuit(); qc.name = f'Cluster Op {excitationIndex}'
global CO_
if CO_ == None or qc.num_qubits <= 4:
if qc.num_qubits < 7: CO_ = qc
# return this circuit
return qc
# Function that adds expectation measurements to the raw circuits
def ExpectationCircuit(qc, pauli, nqubit, method=2):
# copy the unrotated circuit
raw_qc = qc.copy()
# whether this term is diagonal
is_diag = True
# primitive Pauli string
PauliString = pauli.primitive.to_list()[0][0]
# coefficient
coeff = pauli.coeffs[0]
# basis rotation
for i, p in enumerate(PauliString):
target_qubit = nqubit - i - 1
if (p == "X"):
is_diag = False
raw_qc.h(target_qubit)
elif (p == "Y"):
raw_qc.sdg(target_qubit)
raw_qc.h(target_qubit)
is_diag = False
# perform measurements
raw_qc.measure_all()
# name of this circuit
raw_qc.name = PauliString + " " + str(np.real(coeff))
# save circuit
global QC_
if QC_ == None or nqubit <= 4:
if nqubit < 7: QC_ = raw_qc
return raw_qc, is_diag
# Function that implements the Hartree-Fock state
def HartreeFock(norb, na, nb):
# initialize the quantum circuit
qc = QuantumCircuit(norb, name="Hf")
# alpha electrons
for ia in range(na):
qc.x(ia)
# beta electrons
for ib in range(nb):
qc.x(ib+int(norb/2))
# Save smaller circuit
global Hf_
if Hf_ == None or norb <= 4:
if norb < 7: Hf_ = qc
# return the circuit
return qc
################ Helper Functions
# Function that converts a list of single and double excitation operators to Pauli operators
def readPauliExcitation(norb, circuit_id=0):
# load pre-computed data
filename = os.path.join(f'ansatzes/{norb}_qubit_{circuit_id}.txt')
with open(filename) as f:
data = f.read()
ansatz_dict = json.loads(data)
# initialize Pauli list
pauli_list = []
# current coefficients
cur_coeff = 1e5
# current Pauli list
cur_list = []
# loop over excitations
for ext in ansatz_dict:
if cur_coeff > 1e4:
cur_coeff = ansatz_dict[ext]
cur_list = [(ext, ansatz_dict[ext])]
elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4:
pauli_list.append(PauliSumOp.from_list(cur_list))
cur_coeff = ansatz_dict[ext]
cur_list = [(ext, ansatz_dict[ext])]
else:
cur_list.append((ext, ansatz_dict[ext]))
# add the last term
pauli_list.append(PauliSumOp.from_list(cur_list))
# return Pauli list
return pauli_list
# Get the Hamiltonian by reading in pre-computed file
def ReadHamiltonian(nqubit):
# load pre-computed data
filename = os.path.join(f'Hamiltonians/{nqubit}_qubit.txt')
with open(filename) as f:
data = f.read()
ham_dict = json.loads(data)
# pauli list
pauli_list = []
for p in ham_dict:
pauli_list.append( (p, ham_dict[p]) )
# build Hamiltonian
ham = PauliSumOp.from_list(pauli_list)
# return Hamiltonian
return ham
# Create an empty noise model
noise_parameters = NoiseModel()
if Type_of_Simulator == "built_in":
# Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5%
depol_one_qb_error = 0.05
depol_two_qb_error = 0.005
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx'])
# Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0%
amp_damp_one_qb_error = 0.0
amp_damp_two_qb_error = 0.0
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx'])
# Add reset noise to all single qubit resets
reset_to_zero_error = 0.005
reset_to_one_error = 0.005
noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"])
# Add readout error
p0given1_error = 0.000
p1given0_error = 0.000
error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]])
noise_parameters.add_all_qubit_readout_error(error_meas)
#print(noise_parameters)
elif Type_of_Simulator == "FAKE"or"FAKEV2":
noise_parameters = NoiseModel.from_backend(backend)
#print(noise_parameters)
### Analysis methods to be expanded and eventually compiled into a separate analysis.py file
import math, functools
def hellinger_fidelity_with_expected(p, q):
""" p: result distribution, may be passed as a counts distribution
q: the expected distribution to be compared against
References:
`Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_
Qiskit Hellinger Fidelity Function
"""
p_sum = sum(p.values())
q_sum = sum(q.values())
if q_sum == 0:
print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0")
return 0
p_normed = {}
for key, val in p.items():
p_normed[key] = val/p_sum
# if p_sum != 0:
# p_normed[key] = val/p_sum
# else:
# p_normed[key] = 0
q_normed = {}
for key, val in q.items():
q_normed[key] = val/q_sum
total = 0
for key, val in p_normed.items():
if key in q_normed.keys():
total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2
del q_normed[key]
else:
total += val
total += sum(q_normed.values())
# in some situations (error mitigation) this can go negative, use abs value
if total < 0:
print(f"WARNING: using absolute value in fidelity calculation")
total = abs(total)
dist = np.sqrt(total)/np.sqrt(2)
fidelity = (1-dist**2)**2
return fidelity
def polarization_fidelity(counts, correct_dist, thermal_dist=None):
"""
Combines Hellinger fidelity and polarization rescaling into fidelity calculation
used in every benchmark
counts: the measurement outcomes after `num_shots` algorithm runs
correct_dist: the distribution we expect to get for the algorithm running perfectly
thermal_dist: optional distribution to pass in distribution from a uniform
superposition over all states. If `None`: generated as
`uniform_dist` with the same qubits as in `counts`
returns both polarization fidelity and the hellinger fidelity
Polarization from: `https://arxiv.org/abs/2008.11294v1`
"""
num_measured_qubits = len(list(correct_dist.keys())[0])
#print(num_measured_qubits)
counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()}
# calculate hellinger fidelity between measured expectation values and correct distribution
hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist)
# to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits
if num_measured_qubits > 16:
return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity }
# if not provided, generate thermal dist based on number of qubits
if thermal_dist == None:
thermal_dist = uniform_dist(num_measured_qubits)
# set our fidelity rescaling value as the hellinger fidelity for a depolarized state
floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist)
# rescale fidelity result so uniform superposition (random guessing) returns fidelity
# rescaled to 0 to provide a better measure of success of the algorithm (polarization)
new_floor_fidelity = 0
fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity)
return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity }
## Uniform distribution function commonly used
def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity):
"""
Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks
fidelity: raw fidelity to rescale
floor_fidelity: threshold fidelity which is equivalent to random guessing
new_floor_fidelity: what we rescale the floor_fidelity to
Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0:
1 -> 1;
0.25 -> 0;
0.5 -> 0.3333;
"""
rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1
# ensure fidelity is within bounds (0, 1)
if rescaled_fidelity < 0:
rescaled_fidelity = 0.0
if rescaled_fidelity > 1:
rescaled_fidelity = 1.0
return rescaled_fidelity
def uniform_dist(num_state_qubits):
dist = {}
for i in range(2**num_state_qubits):
key = bin(i)[2:].zfill(num_state_qubits)
dist[key] = 1/(2**num_state_qubits)
return dist
from matplotlib.patches import Rectangle
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize
from matplotlib.patches import Circle
############### Color Map functions
# Create a selection of colormaps from which to choose; default to custom_spectral
cmap_spectral = plt.get_cmap('Spectral')
cmap_greys = plt.get_cmap('Greys')
cmap_blues = plt.get_cmap('Blues')
cmap_custom_spectral = None
# the default colormap is the spectral map
cmap = cmap_spectral
cmap_orig = cmap_spectral
# current cmap normalization function (default None)
cmap_norm = None
default_fade_low_fidelity_level = 0.16
default_fade_rate = 0.7
# Specify a normalization function here (default None)
def set_custom_cmap_norm(vmin, vmax):
global cmap_norm
if vmin == vmax or (vmin == 0.0 and vmax == 1.0):
print("... setting cmap norm to None")
cmap_norm = None
else:
print(f"... setting cmap norm to [{vmin}, {vmax}]")
cmap_norm = Normalize(vmin=vmin, vmax=vmax)
# Remake the custom spectral colormap with user settings
def set_custom_cmap_style(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
#print("... set custom map style")
global cmap, cmap_custom_spectral, cmap_orig
cmap_custom_spectral = create_custom_spectral_cmap(
fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate)
cmap = cmap_custom_spectral
cmap_orig = cmap_custom_spectral
# Create the custom spectral colormap from the base spectral
def create_custom_spectral_cmap(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
# determine the breakpoint from the fade level
num_colors = 100
breakpoint = round(fade_low_fidelity_level * num_colors)
# get color list for spectral map
spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)]
#print(fade_rate)
# create a list of colors to replace those below the breakpoint
# and fill with "faded" color entries (in reverse)
low_colors = [0] * breakpoint
#for i in reversed(range(breakpoint)):
for i in range(breakpoint):
# x is index of low colors, normalized 0 -> 1
x = i / breakpoint
# get color at this index
bc = spectral_colors[i]
r0 = bc[0]
g0 = bc[1]
b0 = bc[2]
z0 = bc[3]
r_delta = 0.92 - r0
#print(f"{x} {bc} {r_delta}")
# compute saturation and greyness ratio
sat_ratio = 1 - x
#grey_ratio = 1 - x
''' attempt at a reflective gradient
if i >= breakpoint/2:
xf = 2*(x - 0.5)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (yf + 0.5)
else:
xf = 2*(0.5 - x)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (0.5 - yf)
'''
grey_ratio = 1 - math.pow(x, 1/fade_rate)
#print(f" {xf} {yf} ")
#print(f" {sat_ratio} {grey_ratio}")
r = r0 + r_delta * sat_ratio
g_delta = r - g0
b_delta = r - b0
g = g0 + g_delta * grey_ratio
b = b0 + b_delta * grey_ratio
#print(f"{r} {g} {b}\n")
low_colors[i] = (r,g,b,z0)
#print(low_colors)
# combine the faded low colors with the regular spectral cmap to make a custom version
cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:])
#spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)]
#for i in range(10): print(spectral_colors[i])
#print("")
return cmap_custom_spectral
# Make the custom spectral color map the default on module init
set_custom_cmap_style()
# Arrange the stored annotations optimally and add to plot
def anno_volumetric_data(ax, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True):
# sort all arrays by the x point of the text (anno_offs)
global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos
all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos))
x_anno_offs = [a for a,b,c,d,e in all_annos]
y_anno_offs = [b for a,b,c,d,e in all_annos]
anno_labels = [c for a,b,c,d,e in all_annos]
x_annos = [d for a,b,c,d,e in all_annos]
y_annos = [e for a,b,c,d,e in all_annos]
#print(f"{x_anno_offs}")
#print(f"{y_anno_offs}")
#print(f"{anno_labels}")
for i in range(len(anno_labels)):
x_anno = x_annos[i]
y_anno = y_annos[i]
x_anno_off = x_anno_offs[i]
y_anno_off = y_anno_offs[i]
label = anno_labels[i]
if i > 0:
x_delta = abs(x_anno_off - x_anno_offs[i - 1])
y_delta = abs(y_anno_off - y_anno_offs[i - 1])
if y_delta < 0.7 and x_delta < 2:
y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6
#x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1
ax.annotate(label,
xy=(x_anno+0.0, y_anno+0.1),
arrowprops=dict(facecolor='black', shrink=0.0,
width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)),
xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]),
rotation=labelrot,
horizontalalignment='left', verticalalignment='baseline',
color=(0.2,0.2,0.2),
clip_on=True)
if saveplots == True:
plt.savefig("VolumetricPlotSample.jpg")
# Plot one group of data for volumetric presentation
def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True,
x_size=1.0, y_size=1.0, zorder=1, offset_flag=False,
max_depth=0, suppress_low_fidelity=False):
# since data may come back out of order, save point at max y for annotation
i_anno = 0
x_anno = 0
y_anno = 0
# plot data rectangles
low_fidelity_count = True
last_y = -1
k = 0
# determine y-axis dimension for one pixel to use for offset of bars that start at 0
(_, dy) = get_pixel_dims(ax)
# do this loop in reverse to handle the case where earlier cells are overlapped by later cells
for i in reversed(range(len(d_data))):
x = depth_index(d_data[i], depth_base)
y = float(w_data[i])
f = f_data[i]
# each time we star a new row, reset the offset counter
# DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars
# that represent time starting from 0 secs. We offset by one pixel each and center the group
if y != last_y:
last_y = y;
k = 3 # hardcoded for 8 cells, offset by 3
#print(f"{i = } {x = } {y = }")
if max_depth > 0 and d_data[i] > max_depth:
#print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}")
break;
# reject cells with low fidelity
if suppress_low_fidelity and f < suppress_low_fidelity_level:
if low_fidelity_count: break
else: low_fidelity_count = True
# the only time this is False is when doing merged gradation plots
if do_border == True:
# this case is for an array of x_sizes, i.e. each box has different width
if isinstance(x_size, list):
# draw each of the cells, with no offset
if not offset_flag:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder))
# use an offset for y value, AND account for x and width to draw starting at 0
else:
ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder))
# this case is for only a single cell
else:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size))
# save the annotation point with the largest y value
if y >= y_anno:
x_anno = x
y_anno = y
i_anno = i
# move the next bar down (if using offset)
k -= 1
# if no data rectangles plotted, no need for a label
if x_anno == 0 or y_anno == 0:
return
x_annos.append(x_anno)
y_annos.append(y_anno)
anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 )
# adjust radius of annotation circle based on maximum width of apps
anno_max = 10
if w_max > 10:
anno_max = 14
if w_max > 14:
anno_max = 18
scale = anno_max / anno_dist
# offset of text from end of arrow
if scale > 1:
x_anno_off = scale * x_anno - x_anno - 0.5
y_anno_off = scale * y_anno - y_anno
else:
x_anno_off = 0.7
y_anno_off = 0.5
x_anno_off += x_anno
y_anno_off += y_anno
# print(f"... {xx} {yy} {anno_dist}")
x_anno_offs.append(x_anno_off)
y_anno_offs.append(y_anno_off)
anno_labels.append(label)
if do_label:
ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot,
horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2))
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# init arrays to hold annotation points for label spreading
def vplot_anno_init ():
global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# Number of ticks on volumetric depth axis
max_depth_log = 22
# average transpile factor between base QV depth and our depth based on results from QV notebook
QV_transpile_factor = 12.7
# format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1
# (sign handling may be incorrect)
def format_number(num, digits=0):
if isinstance(num, str): num = float(num)
num = float('{:.3g}'.format(abs(num)))
sign = ''
metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1}
for index in metric:
num_check = num / metric[index]
if num_check >= 1:
num = round(num_check, digits)
sign = index
break
numstr = f"{str(num)}"
if '.' in numstr:
numstr = numstr.rstrip('0').rstrip('.')
return f"{numstr}{sign}"
# Return the color associated with the spcific value, using color map norm
def get_color(value):
# if there is a normalize function installed, scale the data
if cmap_norm:
value = float(cmap_norm(value))
if cmap == cmap_spectral:
value = 0.05 + value*0.9
elif cmap == cmap_blues:
value = 0.00 + value*1.0
else:
value = 0.0 + value*0.95
return cmap(value)
# Return the x and y equivalent to a single pixel for the given plot axis
def get_pixel_dims(ax):
# transform 0 -> 1 to pixel dimensions
pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0))
xpix = pixdims[1][0]
ypix = pixdims[0][1]
#determine x- and y-axis dimension for one pixel
dx = (1 / xpix)
dy = (1 / ypix)
return (dx, dy)
############### Helper functions
# return the base index for a circuit depth value
# take the log in the depth base, and add 1
def depth_index(d, depth_base):
if depth_base <= 1:
return d
if d == 0:
return 0
return math.log(d, depth_base) + 1
# draw a box at x,y with various attributes
def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1):
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5*y_size,
zorder=zorder)
# draw a circle at x,y with various attributes
def circle_at(x, y, value, type=1, fill=True):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Circle((x, y), size/2,
alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5)
def box4_at(x, y, value, type=1, fill=True, alpha=1.0):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.3,0.3,0.3)
ec = fc
return Rectangle((x - size/8, y - size/2), size/4, size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.1)
# Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value
def qv_box_at(x, y, qv_width, qv_depth, value, depth_base):
#print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}")
return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width,
edgecolor = (value,value,value),
facecolor = (value,value,value),
fill=True,
lw=1)
def bkg_box_at(x, y, value=0.9):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (value,value,value),
fill=True,
lw=0.5)
def bkg_empty_box_at(x, y):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (1.0,1.0,1.0),
fill=True,
lw=0.5)
# Plot the background for the volumetric analysis
def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"):
if suptitle == None:
suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}"
QV0 = QV
qv_estimate = False
est_str = ""
if QV == 0: # QV = 0 indicates "do not draw QV background or label"
QV = 2048
elif QV < 0: # QV < 0 indicates "add est. to label"
QV = -QV
qv_estimate = True
est_str = " (est.)"
if avail_qubits > 0 and max_qubits > avail_qubits:
max_qubits = avail_qubits
max_width = 13
if max_qubits > 11: max_width = 18
if max_qubits > 14: max_width = 20
if max_qubits > 16: max_width = 24
if max_qubits > 24: max_width = 33
#print(f"... {avail_qubits} {max_qubits} {max_width}")
plot_width = 6.8
plot_height = 0.5 + plot_width * (max_width / max_depth_log)
#print(f"... {plot_width} {plot_height}")
# define matplotlib figure and axis; use constrained layout to fit colorbar to right
fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True)
plt.suptitle(suptitle)
plt.xlim(0, max_depth_log)
plt.ylim(0, max_width)
# circuit depth axis (x axis)
xbasis = [x for x in range(1,max_depth_log)]
xround = [depth_base**(x-1) for x in xbasis]
xlabels = [format_number(x) for x in xround]
ax.set_xlabel('Circuit Depth')
ax.set_xticks(xbasis)
plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor")
# other label options
#plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left')
#plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor")
# circuit width axis (y axis)
ybasis = [y for y in range(1,max_width)]
yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now
ylabels = [str(y) for y in yround] # not used now
#ax.set_ylabel('Circuit Width (Number of Qubits)')
ax.set_ylabel('Circuit Width')
ax.set_yticks(ybasis)
#create simple line plot (not used right now)
#ax.plot([0, 10],[0, 10])
log2QV = math.log2(QV)
QV_width = log2QV
QV_depth = log2QV * QV_transpile_factor
# show a quantum volume rectangle of QV = 64 e.g. (6 x 6)
if QV0 != 0:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base))
else:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base))
# the untranspiled version is commented out - we do not show this by default
# also show a quantum volume rectangle un-transpiled
# ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base))
# show 2D array of volumetric cells based on this QV_transpiled
# DEVNOTE: we use +1 only to make the visuals work; s/b without
# Also, the second arg of the min( below seems incorrect, needs correction
maxprod = (QV_width + 1) * (QV_depth + 1)
for w in range(1, min(max_width, round(QV) + 1)):
# don't show VB squares if width greater than known available qubits
if avail_qubits != 0 and w > avail_qubits:
continue
i_success = 0
for d in xround:
# polarization factor for low circuit widths
maxtest = maxprod / ( 1 - 1 / (2**w) )
# if circuit would fail here, don't draw box
if d > maxtest: continue
if w * d > maxtest: continue
# guess for how to capture how hardware decays with width, not entirely correct
# # reduce maxtext by a factor of number of qubits > QV_width
# # just an approximation to account for qubit distances
# if w > QV_width:
# over = w - QV_width
# maxtest = maxtest / (1 + (over/QV_width))
# draw a box at this width and depth
id = depth_index(d, depth_base)
# show vb rectangles; if not showing QV, make all hollow (or less dark)
if QV0 == 0:
#ax.add_patch(bkg_empty_box_at(id, w))
ax.add_patch(bkg_box_at(id, w, 0.95))
else:
ax.add_patch(bkg_box_at(id, w, 0.9))
# save index of last successful depth
i_success += 1
# plot empty rectangle after others
d = xround[i_success]
id = depth_index(d, depth_base)
ax.add_patch(bkg_empty_box_at(id, w))
# Add annotation showing quantum volume
if QV0 != 0:
t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12,
horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2),
bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1))
# add colorbar to right of plot
plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax,
shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7))
return ax
# Function to calculate circuit depth
def calculate_circuit_depth(qc):
# Calculate the depth of the circuit
depth = qc.depth()
return depth
def calculate_transpiled_depth(qc,basis_selector):
# use either the backend or one of the basis gate sets
if basis_selector == 0:
qc = transpile(qc, backend)
else:
basis_gates = basis_gates_array[basis_selector]
qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0)
transpiled_depth = qc.depth()
return transpiled_depth,qc
def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title):
avg_fidelity_means = []
avg_Hf_fidelity_means = []
avg_num_qubits_values = list(fidelity_data.keys())
# Calculate the average fidelity and Hamming fidelity for each unique number of qubits
for num_qubits in avg_num_qubits_values:
avg_fidelity = np.average(fidelity_data[num_qubits])
avg_fidelity_means.append(avg_fidelity)
avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits])
avg_Hf_fidelity_means.append(avg_Hf_fidelity)
return avg_fidelity_means,avg_Hf_fidelity_means
list_of_gates = []
def list_of_standardgates():
import qiskit.circuit.library as lib
from qiskit.circuit import Gate
import inspect
# List all the attributes of the library module
gate_list = dir(lib)
# Filter out non-gate classes (like functions, variables, etc.)
gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)]
# Get method names from QuantumCircuit
circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction)
method_names = [name for name, _ in circuit_methods]
# Map gate class names to method names
gate_to_method = {}
for gate in gates:
gate_class = getattr(lib, gate)
class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name
for method in method_names:
if method == class_name or method == class_name.replace('cr', 'c-r'):
gate_to_method[gate] = method
break
# Add common operations that are not strictly gates
additional_operations = {
'Measure': 'measure',
'Barrier': 'barrier',
}
gate_to_method.update(additional_operations)
for k,v in gate_to_method.items():
list_of_gates.append(v)
def update_counts(gates,custom_gates):
operations = {}
for key, value in gates.items():
operations[key] = value
for key, value in custom_gates.items():
if key in operations:
operations[key] += value
else:
operations[key] = value
return operations
def get_gate_counts(gates,custom_gate_defs):
result = gates.copy()
# Iterate over the gate counts in the quantum circuit
for gate, count in gates.items():
if gate in custom_gate_defs:
custom_gate_ops = custom_gate_defs[gate]
# Multiply custom gate operations by the count of the custom gate in the circuit
for _ in range(count):
result = update_counts(result, custom_gate_ops)
# Remove the custom gate entry as we have expanded it
del result[gate]
return result
dict_of_qc = dict()
custom_gates_defs = dict()
# Function to count operations recursively
def count_operations(qc):
dict_of_qc.clear()
circuit_traverser(qc)
operations = dict()
operations = dict_of_qc[qc.name]
del dict_of_qc[qc.name]
# print("operations :",operations)
# print("dict_of_qc :",dict_of_qc)
for keys in operations.keys():
if keys not in list_of_gates:
for k,v in dict_of_qc.items():
if k in operations.keys():
custom_gates_defs[k] = v
operations=get_gate_counts(operations,custom_gates_defs)
custom_gates_defs.clear()
return operations
def circuit_traverser(qc):
dict_of_qc[qc.name]=dict(qc.count_ops())
for i in qc.data:
if str(i.operation.name) not in list_of_gates:
qc_1 = i.operation.definition
circuit_traverser(qc_1)
def get_memory():
import resource
usage = resource.getrusage(resource.RUSAGE_SELF)
max_mem = usage.ru_maxrss/1024 #in MB
return max_mem
def analyzer(qc,references,num_qubits):
# total circuit name (pauli string + coefficient)
total_name = qc.name
# pauli string
pauli_string = total_name.split()[0]
# get the correct measurement
if (len(total_name.split()) == 2):
correct_dist = references[pauli_string]
else:
circuit_id = int(total_name.split()[2])
correct_dist = references[f"Qubits - {num_qubits} - {circuit_id}"]
return correct_dist,total_name
# Max qubits must be 12 since the referenced files only go to 12 qubits
MAX_QUBITS = 12
method = 1
def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=2,
max_circuits=max_circuits, num_shots=num_shots):
creation_times = []
elapsed_times = []
quantum_times = []
circuit_depths = []
transpiled_depths = []
fidelity_data = {}
Hf_fidelity_data = {}
numckts = []
mem_usage = []
algorithmic_1Q_gate_counts = []
algorithmic_2Q_gate_counts = []
transpiled_1Q_gate_counts = []
transpiled_2Q_gate_counts = []
print(f"{benchmark_name} Benchmark Program - {platform}")
#defining all the standard gates supported by qiskit in a list
if gate_counts_plots == True:
list_of_standardgates()
max_qubits = max(max_qubits, min_qubits) # max must be >= min
# validate parameters (smallest circuit is 4 qubits and largest is 10 qubits)
max_qubits = min(max_qubits, MAX_QUBITS)
min_qubits = min(max(4, min_qubits), max_qubits)
if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even
skip_qubits = max(1, skip_qubits)
if method == 2: max_circuits = 1
if max_qubits < 4:
print(f"Max number of qubits {max_qubits} is too low to run method {method} of VQE algorithm")
return
global max_ckts
max_ckts = max_circuits
global min_qbits,max_qbits,skp_qubits
min_qbits = min_qubits
max_qbits = max_qubits
skp_qubits = skip_qubits
print(f"min, max qubits = {min_qubits} {max_qubits}")
# Execute Benchmark Program N times for multiple circuit sizes
for input_size in range(min_qubits, max_qubits + 1, skip_qubits):
# reset random seed
np.random.seed(0)
# determine the number of circuits to execute for this group
num_circuits = min(3, max_circuits)
num_qubits = input_size
fidelity_data[num_qubits] = []
Hf_fidelity_data[num_qubits] = []
# decides number of electrons
na = int(num_qubits/4)
nb = int(num_qubits/4)
# random seed
np.random.seed(0)
numckts.append(num_circuits)
# create the circuit for given qubit size and simulation parameters, store time metric
ts = time.time()
# circuit list
qc_list = []
# Method 1 (default)
if method == 1:
# loop over circuits
for circuit_id in range(num_circuits):
# construct circuit
qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method)
qc_single.name = qc_single.name + " " + str(circuit_id)
# add to list
qc_list.append(qc_single)
# method 2
elif method == 2:
# construct all circuits
qc_list = VQEEnergy(num_qubits, na, nb, 0, method)
print(qc_list)
print(f"************\nExecuting [{len(qc_list)}] circuits with num_qubits = {num_qubits}")
for qc in qc_list:
print("*********************************************")
#print(f"qc of {qc} qubits for qc_list value: {qc_list}")
# get circuit id
if method == 1:
circuit_id = qc.name.split()[2]
else:
circuit_id = qc.name.split()[0]
#creation time
creation_time = time.time() - ts
creation_times.append(creation_time)
#print(qc)
print(f"creation time = {creation_time*1000} ms")
# Calculate gate count for the algorithmic circuit (excluding barriers and measurements)
if gate_counts_plots == True:
operations = count_operations(qc)
n1q = 0; n2q = 0
if operations != None:
for key, value in operations.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c") or key.startswith("mc"):
n2q += value
else:
n1q += value
print("operations: ",operations)
algorithmic_1Q_gate_counts.append(n1q)
algorithmic_2Q_gate_counts.append(n2q)
# collapse the sub-circuit levels used in this benchmark (for qiskit)
qc=qc.decompose()
#print(qc)
# Calculate circuit depth
depth = calculate_circuit_depth(qc)
circuit_depths.append(depth)
# Calculate transpiled circuit depth
transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector)
transpiled_depths.append(transpiled_depth)
#print(qc)
print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}")
if gate_counts_plots == True:
# Calculate gate count for the transpiled circuit (excluding barriers and measurements)
tr_ops = qc.count_ops()
#print("tr_ops = ",tr_ops)
tr_n1q = 0; tr_n2q = 0
if tr_ops != None:
for key, value in tr_ops.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c"): tr_n2q += value
else: tr_n1q += value
transpiled_1Q_gate_counts.append(tr_n1q)
transpiled_2Q_gate_counts.append(tr_n2q)
print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}")
print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}")
#execution
if Type_of_Simulator == "built_in":
#To check if Noise is required
if Noise_Inclusion == True:
noise_model = noise_parameters
else:
noise_model = None
ts = time.time()
job = execute(qc, backend, shots=num_shots, noise_model=noise_model)
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" :
ts = time.time()
job = backend.run(qc,shots=num_shots, noise_model=noise_parameters)
#retrieving the result
result = job.result()
#print(result)
#calculating elapsed time
elapsed_time = time.time() - ts
elapsed_times.append(elapsed_time)
# Calculate quantum processing time
quantum_time = result.time_taken
quantum_times.append(quantum_time)
print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms")
#counts in result object
counts = result.get_counts()
# load pre-computed data
if len(qc.name.split()) == 2:
filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit.json')
with open(filename) as f:
references = json.load(f)
else:
filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit_method2.json')
with open(filename) as f:
references = json.load(f)
#Correct distribution to compare with counts
correct_dist,total_name = analyzer(qc,references,num_qubits)
#fidelity calculation comparision of counts and correct_dist
fidelity_dict = polarization_fidelity(counts, correct_dist)
print(fidelity_dict)
# modify fidelity based on the coefficient
if (len(total_name.split()) == 2):
fidelity_dict *= ( abs(float(total_name.split()[1])) / normalization )
fidelity_data[num_qubits].append(fidelity_dict['fidelity'])
Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity'])
#maximum memory utilization (if required)
if Memory_utilization_plot == True:
max_mem = get_memory()
print(f"Maximum Memory Utilized: {max_mem} MB")
mem_usage.append(max_mem)
print("*********************************************")
##########
# print a sample circuit
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
print("\nHartree Fock Generator 'Hf' ="); print(Hf_ if Hf_ != None else " ... too large!")
print("\nCluster Operator Example 'Cluster Op' ="); print(CO_ if CO_ != None else " ... too large!")
return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths,
fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts,
transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage)
# Execute the benchmark program, accumulate metrics, and calculate circuit depths
(creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts,
algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run()
# Define the range of qubits for the x-axis
num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits)
print("num_qubits_range =",num_qubits_range)
# Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits
avg_creation_times = []
avg_elapsed_times = []
avg_quantum_times = []
avg_circuit_depths = []
avg_transpiled_depths = []
avg_1Q_algorithmic_gate_counts = []
avg_2Q_algorithmic_gate_counts = []
avg_1Q_Transpiled_gate_counts = []
avg_2Q_Transpiled_gate_counts = []
max_memory = []
start = 0
for num in numckts:
avg_creation_times.append(np.mean(creation_times[start:start+num]))
avg_elapsed_times.append(np.mean(elapsed_times[start:start+num]))
avg_quantum_times.append(np.mean(quantum_times[start:start+num]))
avg_circuit_depths.append(np.mean(circuit_depths[start:start+num]))
avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num]))
if gate_counts_plots == True:
avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num])))
avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num])))
avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num])))
avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num])))
if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num]))
start += num
# Calculate the fidelity data
avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison")
# Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits
# Add labels to the bars
def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"):
for rect in rects:
height = rect.get_height()
ax.annotate(str.format(height), # Formatting to two decimal places
xy=(rect.get_x() + rect.get_width() / 2, height / 2),
xytext=(0, 0),
textcoords="offset points",
ha='center', va=va,color=text_color,rotation=90)
bar_width = 0.3
# Determine the number of subplots and their arrangement
if Memory_utilization_plot and gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30))
# Plotting for both memory utilization and gate counts
# ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available
elif Memory_utilization_plot:
fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30))
# Plotting for memory utilization only
# ax1, ax2, ax3, ax6, ax7 are available
elif gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30))
# Plotting for gate counts only
# ax1, ax2, ax3, ax4, ax5, ax6 are available
else:
fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30))
# Default plotting
# ax1, ax2, ax3, ax6 are available
fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16)
for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000
avg_creation_times[i] *= 1000
ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue')
autolabel(ax1.patches, ax1)
ax1.set_xlabel('Number of Qubits')
ax1.set_ylabel('Average Creation Time (ms)')
ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14)
ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000
avg_elapsed_times[i] *= 1000
for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000
avg_quantum_times[i] *= 1000
Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time')
Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time')
autolabel(Elapsed,ax2,str='{:.1f}')
autolabel(Quantum,ax2,str='{:.1f}')
ax2.set_xlabel('Number of Qubits')
ax2.set_ylabel('Average Time (ms)')
ax2.set_title('Average Time vs Number of Qubits')
ax2.legend()
ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here
Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here
autolabel(Normalized,ax3,str='{:.2f}')
autolabel(Algorithmic,ax3,str='{:.2f}')
ax3.set_xlabel('Number of Qubits')
ax3.set_ylabel('Average Circuit Depth')
ax3.set_title('Average Circuit Depth vs Number of Qubits')
ax3.legend()
if gate_counts_plots == True:
ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_1Q_counts,ax4,str='{}')
autolabel(Algorithmic_1Q_counts,ax4,str='{}')
ax4.set_xlabel('Number of Qubits')
ax4.set_ylabel('Average 1-Qubit Gate Counts')
ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits')
ax4.legend()
ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_2Q_counts,ax5,str='{}')
autolabel(Algorithmic_2Q_counts,ax5,str='{}')
ax5.set_xlabel('Number of Qubits')
ax5.set_ylabel('Average 2-Qubit Gate Counts')
ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits')
ax5.legend()
ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here
Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here
autolabel(Hellinger,ax6,str='{:.2f}')
autolabel(Normalized,ax6,str='{:.2f}')
ax6.set_xlabel('Number of Qubits')
ax6.set_ylabel('Average Value')
ax6.set_title("Fidelity Comparison")
ax6.legend()
if Memory_utilization_plot == True:
ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations")
autolabel(ax7.patches, ax7)
ax7.set_xlabel('Number of Qubits')
ax7.set_ylabel('Maximum Memory Utilized (MB)')
ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14)
plt.tight_layout(rect=[0, 0, 1, 0.96])
if saveplots == True:
plt.savefig("ParameterPlotsSample.jpg")
plt.show()
# Quantum Volume Plot
Suptitle = f"Volumetric Positioning - {platform}"
appname=benchmark_name
if QV_ == None:
QV=2048
else:
QV=QV_
depth_base =2
ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity")
w_data = num_qubits_range
# determine width for circuit
w_max = 0
for i in range(len(w_data)):
y = float(w_data[i])
w_max = max(w_max, y)
d_tr_data = avg_transpiled_depths
f_data = avg_f
plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max)
anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
|
jonasmaziero
|
from sympy import Matrix, sqrt, init_printing; init_printing(use_unicode=True)
ket0 = Matrix([[1],[0]]); ket1 = Matrix([[0],[1]]); from sympy.physics.quantum import TensorProduct as tp
ket00 = tp(ket0,ket0); ket01 = tp(ket0,ket1); ket10 = tp(ket1,ket0); ket11 = tp(ket1,ket1)
Psim = (ket01-ket10)/sqrt(2); Psim.T
X = Matrix([[0,1],[1,0]]); Z = Matrix([[1,0],[0,-1]]); (tp(Z,Z)*Psim).T, (tp(X,X)*Psim).T
A1 = Z; A2 = X; B1 = (Z+X)/sqrt(2); B2 = (Z-X)/sqrt(2); O = tp(A1,B1)+tp(A1,B2)+tp(A2,B1)-tp(A2,B2)
O, sqrt(2)*(tp(Z,Z)+tp(X,X))
from qiskit import QuantumCircuit
def qc_Psim(): # função que cria o circuito quantico para preparar o estado de Bell |Psi->
qc = QuantumCircuit(2, name=r'$|\Psi_-\rangle$')
qc.x([0,1])
qc.h(0)
qc.cx(0,1)
#qc.z(0)
#qc.x(1)
return qc
qc_Psim_ = qc_Psim()
qc_Psim_.draw('mpl')
import qiskit
from qiskit.quantum_info import Statevector
qc_Psim_ = qc_Psim()
state = Statevector(qc_Psim_)
qiskit.visualization.plot_state_city(state)
from sympy import Matrix
Psim = Matrix([[0],[1],[-1],[0]])/sqrt(2)
#Psim
from sympy.physics.quantum.dagger import Dagger
rho_Psim = Psim*Dagger(Psim)
rho_Psim
qc = QuantumCircuit(2,2)
qc_Psim_ = qc_Psim()
qc.append(qc_Psim_,[0,1])
qc.measure([0,1],[0,1])
qc.draw('mpl')
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
job = execute(qc, backend=simulator, shots=nshots)
counts = job.result().get_counts()
p00=0; p01=0; p10=0; p11=0
for j in (0,2):
for k in (0,2):
if '00' in counts:
p00 = counts['00']/nshots
if '01' in counts:
p01 = counts['01']/nshots
if '10' in counts:
p10 = counts['10']/nshots
if '11' in counts:
p11 = counts['11']/nshots
ZZ_avg = (p00+p11)-(p01+p10)
ZZ_avg
qc = QuantumCircuit(2,2)
qc_Psim_ = qc_Psim()
qc.append(qc_Psim_,[0,1])
qc.h([0,1])
qc.measure([0,1],[0,1])
qc.draw('mpl')
from qiskit import Aer
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
job = execute(qc, backend=simulator, shots=nshots)
counts = job.result().get_counts()
p00=0; p01=0; p10=0; p11=0
for j in (0,2):
for k in (0,2):
if '00' in counts:
p00 = counts['00']/nshots
if '01' in counts:
p01 = counts['01']/nshots
if '10' in counts:
p10 = counts['10']/nshots
if '11' in counts:
p11 = counts['11']/nshots
XX_avg = (p00+p11)-(p01+p10)
XX_avg
O_avg = sqrt(2)*(ZZ_avg + XX_avg)
O_avg, float(O_avg)
import qiskit
qiskit.IBMQ.save_account('5a0140fc106f9f8ae43104d5751baf65c726195f8b45b1f42e161f0182b5fe79ca6dbb1405159301e1e44d40d680223ea572d9b8737205bfa6f90485f1f88123',
overwrite = True)
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibm_nairobi')
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_,[0,1]); qc.measure([0,1],[0,1])
job = execute(qc, backend = device, shots = nshots); print(job.job_id())
device = provider.get_backend('ibm_nairobi'); job = device.retrieve_job('cmfbdw78vz2g008daj90')
counts = job.result().get_counts()
p00=0; p01=0; p10=0; p11=0
for j in (0,2):
for k in (0,2):
if '00' in counts:
p00 = counts['00']/nshots
if '01' in counts:
p01 = counts['01']/nshots
if '10' in counts:
p10 = counts['10']/nshots
if '11' in counts:
p11 = counts['11']/nshots
ZZ_avg_exp = (p00+p11)-(p01+p10); ZZ_avg_exp
device = provider.get_backend('ibm_nairobi')
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_,[0,1]); qc.h([0,1]); qc.measure([0,1],[0,1])
job = execute(qc, backend = device, shots = nshots); jobid = job.job_id()
print(jobid)
device = provider.get_backend('ibm_nairobi'); job = device.retrieve_job('cmfbekafysfg008t2y4g')
counts = job.result().get_counts()
p00=0; p01=0; p10=0; p11=0
for j in (0,2):
for k in (0,2):
if '00' in counts:
p00 = counts['00']/nshots
if '01' in counts:
p01 = counts['01']/nshots
if '10' in counts:
p10 = counts['10']/nshots
if '11' in counts:
p11 = counts['11']/nshots
XX_avg_exp = (p00+p11)-(p01+p10); XX_avg_exp
O_avg_exp = sqrt(2.)*(ZZ_avg_exp + XX_avg_exp)
O_avg_exp
import numpy as np
import math
th_max = math.pi/2; npt = 100; dth = th_max/npt; th = np.arange(0,th_max+dth,dth)
Oteo = -math.sqrt(2)*(1+np.sin(th))
Odl = -2*np.ones(len(th))
from matplotlib import pyplot as plt
plt.plot(th, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$')
plt.plot(th, Odl, label = 'LHV limit')
plt.xlabel(r'$\theta$')
plt.legend(); plt.show()
# circuito quântico para preparação do estado Psi
def qc_Psi(th):
qc = QuantumCircuit(2)
qc.u(th,0,0, 0)
qc.cx(0,1)
qc.z(0)
qc.x(1)
return qc
import math
th = math.pi/4
qc_Psi_ = qc_Psi(th)
qc_Psi_.draw('mpl')
# função para calcular as médias tipo <A\otimes B>, com A,B=+1,-1, dadas as probabilidades
def ABavg(result, nshots):
avg = 0
if '00' in result:
avg += result['00']
if '01' in result:
avg -= result['01']
if '10' in result:
avg -= result['10']
if '11' in result:
avg += result['11']
return avg/nshots # = (N(00)-N(01)-N(10)+N(11))/nshots
th_max = math.pi/2; npe = 5; dth = th_max/npe; th = np.arange(0,th_max+dth,dth)
Osim = np.zeros(len(th))
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
for j in range(0,len(th)):
# mede ZZ
qc = QuantumCircuit(2,2)
qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1])
qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots)
result = job.result().get_counts()
ZZavg = ABavg(result, nshots)
# mede XX
qc = QuantumCircuit(2,2)
qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1])
qc.h([0,1])
qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots)
result = job.result().get_counts()
XXavg = ABavg(result, nshots)
# média de O
Osim[j] = math.sqrt(2)*(ZZavg + XXavg)
Osim
import numpy as np; import math
th_max = math.pi/2; dtht = th_max/npt; tht = np.arange(0,th_max+dtht,dtht)
Oteo = -math.sqrt(2)*(1+np.sin(tht)); Odl = -2*np.ones(len(tht))
dth = th_max/npe; th = np.arange(0,th_max+dth,dth)
from matplotlib import pyplot as plt
plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$')
plt.plot(tht, Odl, label = 'LHV limit')
plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$')
plt.xlabel(r'$\theta$')
plt.legend(); plt.show()
import qiskit
qiskit.IBMQ.save_account('45b1db3a3c2ecae609e6c98184250919ccd31c9ea24100440abe0821fe6312c2b05a67239806c5b0020754eb3072f924547adb621e1e3931200aee13583a776f',
overwrite = True)
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
th_max = math.pi/2; dth = th_max/npe; th = np.arange(0,th_max+dth,dth)
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
jobs_ids_ZZ = []; jobs_ids_XX = []
for j in range(0,len(th)):
# mede ZZ
qc = QuantumCircuit(2,2); qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1]); qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots)
print('ZZ',job.job_id()); jobs_ids_ZZ.append(job.job_id())
# mede XX
qc = QuantumCircuit(2,2); qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1]); qc.h([0,1]); qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots)
print('XX',job.job_id()); jobs_ids_XX.append(job.job_id())
f = open("jobs_ids_ZZ.txt", "w"); f.write(str(jobs_ids_ZZ)); f.close()
f = open("jobs_ids_XX.txt", "w"); f.write(str(jobs_ids_XX)); f.close()
f = open("jobs_ids_ZZ.txt","r")
list_ids_ZZ = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
f = open("jobs_ids_XX.txt","r")
list_ids_XX = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
th_max = math.pi/2; dth = th_max/npe; th = np.arange(0,th_max+dth,dth)
Oexp = np.zeros(len(th))
for j in range(0,len(th)):
# média de ZZ
job = device.retrieve_job(list_ids_ZZ[j])
result = job.result().get_counts()
ZZavg = ABavg(result, nshots)
# média de XX
job = device.retrieve_job(list_ids_XX[j])
result = job.result().get_counts()
XXavg = ABavg(result, nshots)
# média de O
Oexp[j] = math.sqrt(2)*(ZZavg + XXavg)
Oexp
import numpy as np; import math
th_max = math.pi/2; dtht = th_max/npt; tht = np.arange(0,th_max+dtht,dtht)
Oteo = -math.sqrt(2)*(1+np.sin(tht)); Odl = -2*np.ones(len(tht))
dth = th_max/npe; th = np.arange(0,th_max+dth,dth)
from matplotlib import pyplot as plt
plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$')
plt.plot(tht, Odl, label = 'LHV limit')
plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$')
plt.plot(th, Oexp, '*', label = r'$\langle O\rangle_{\Psi}^{exp}$')
plt.xlabel(r'$\theta$'); plt.legend(); plt.show()
def f_Oavg(O,psi):
from sympy.physics.quantum.dagger import Dagger
return Dagger(psi)*O*psi
from sympy import Matrix, symbols, cos, sin, sqrt, simplify
from sympy.physics.quantum import TensorProduct as tp
Psim = Matrix([[0],[1],[-1],[0]])/sqrt(2)
X = Matrix([[0,1],[1,0]])
Z = Matrix([[1,0],[0,-1]])
th = symbols('theta')
A1B1 = tp(Z,cos(th)*Z+sin(th)*X)
A1B1avg = f_Oavg(A1B1,Psim)
A1B2 = tp(Z,(Z-X)/sqrt(2))
A1B2avg = f_Oavg(A1B2,Psim)
A2B1 = tp(X,cos(th)*Z+sin(th)*X)
A2B1avg = f_Oavg(A2B1,Psim)
A2B2 = tp(X,(Z-X)/sqrt(2))
A2B2avg = f_Oavg(A2B2,Psim)
Oavg = A1B1avg + A1B2avg + A2B1avg - A2B2avg
A1B1avg, A1B2avg, A2B1avg, A2B2avg, simplify(Oavg)
import numpy as np; import math
th_max = math.pi/4; npt = 100; dth = th_max/npt; tht = np.arange(-th_max,th_max+dth,dth)
Oteo = -math.sqrt(2)*(1+np.sin(tht+math.pi/4))
Odl = -2*np.ones(len(tht))
from matplotlib import pyplot as plt
plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$')
plt.plot(tht, Odl, label = 'LHV limit')
plt.xlabel(r'$\theta$')
plt.legend(); plt.show()
th_max = math.pi/4; npe = 4; dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth); Osim = np.zeros(len(th))
from qiskit import *; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13
for j in range(0,len(th)):
# mede <A1B1>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(th[j],0,math.pi, 1); qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A1B1avg = ABavg(result, nshots)
# mede <A1B2>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(-math.pi/4,0,math.pi, 1); qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A1B2avg = ABavg(result, nshots)
# mede <A2B1>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(th[j],0,math.pi, 1); qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A2B1avg = ABavg(result, nshots)
# mede <A2B2>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(-math.pi/4,0,math.pi, 1); qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A2B2avg = ABavg(result, nshots)
# média de O
Osim[j] = A1B1avg + A1B2avg + A2B1avg - A2B2avg
Osim
import numpy as np; import math
th_max = math.pi/4; dtht = 2*th_max/npt; tht = np.arange(-th_max,th_max+dtht,dtht)
Oteo = -math.sqrt(2)*(1+np.sin(tht+math.pi/4)); Odl = -2*np.ones(len(tht))
dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth)
from matplotlib import pyplot as plt
plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$')
plt.plot(tht, Odl, label = 'LHV limit')
plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$')
plt.xlabel(r'$\theta$')
plt.legend(); plt.show()
import qiskit
qiskit.IBMQ.save_account('45b1db3a3c2ecae609e6c98184250919ccd31c9ea24100440abe0821fe6312c2b05a67239806c5b0020754eb3072f924547adb621e1e3931200aee13583a776f',
overwrite = True)
qiskit.IBMQ.load_account()
#provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main')
th_max = math.pi/4; npe = 4; dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth)
from qiskit import *; device = provider.get_backend('ibm_nairobi'); nshots = 2**13
jobs_ids_A1B1 = []; jobs_ids_A1B2 = []; jobs_ids_A2B1 = []; jobs_ids_A2B2 = []
for j in range(0,len(th)):
# mede <A1B1>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(th[j],0,math.pi, 1)
qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots); print('A1B1:',job.job_id()); jobs_ids_A1B1.append(job.job_id())
# mede <A1B2>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(-math.pi/4,0,math.pi, 1)
qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots); print('A1B2:',job.job_id()); jobs_ids_A1B2.append(job.job_id())
# mede <A2B1>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(th[j],0,math.pi, 1)
qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots); print('A2B1:',job.job_id()); jobs_ids_A2B1.append(job.job_id())
# mede <A2B2>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(-math.pi/4,0,math.pi, 1)
qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots); print('A2B2:',job.job_id()); jobs_ids_A2B2.append(job.job_id())
f = open("jobs_ids_A1B1.txt", "w"); f.write(str(jobs_ids_A1B1)); f.close()
f = open("jobs_ids_A1B2.txt", "w"); f.write(str(jobs_ids_A1B2)); f.close()
f = open("jobs_ids_A2B1.txt", "w"); f.write(str(jobs_ids_A2B1)); f.close()
f = open("jobs_ids_A2B2.txt", "w"); f.write(str(jobs_ids_A2B2)); f.close()
device = provider.get_backend('ibm_nairobi')
f = open("jobs_ids_A1B1.txt","r")
list_ids_A1B1 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close()
f = open("jobs_ids_A1B2.txt","r")
list_ids_A1B2 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close()
f = open("jobs_ids_A2B1.txt","r")
list_ids_A2B1 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close()
f = open("jobs_ids_A2B2.txt","r")
list_ids_A2B2 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close()
th_max = math.pi/4; dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth); Oexp = np.zeros(len(th))
for j in range(0,len(th)):
# média de A1B1
job = device.retrieve_job(list_ids_A1B1[j]); result = job.result().get_counts(); A1B1avg = ABavg(result, nshots)
# média de A1B2
job = device.retrieve_job(list_ids_A1B2[j]); result = job.result().get_counts(); A1B2avg = ABavg(result, nshots)
# média de A2B1
job = device.retrieve_job(list_ids_A2B1[j]); result = job.result().get_counts(); A2B1avg = ABavg(result, nshots)
# média de A2B2
job = device.retrieve_job(list_ids_A2B2[j]); result = job.result().get_counts(); A2B2avg = ABavg(result, nshots)
# média de O
Oexp[j] = A1B1avg + A1B2avg + A2B1avg - A2B2avg
Oexp
import numpy as np; import math
th_max = math.pi/4; dtht = 2*th_max/npt; tht = np.arange(-th_max,th_max+dtht,dtht)
Oteo = -math.sqrt(2)*(1+np.sin(tht+math.pi/4)); Odl = -2*np.ones(len(tht))
dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth)
from matplotlib import pyplot as plt
plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$')
plt.plot(tht, Odl, label = 'LHV limit')
plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$')
plt.plot(th, Oexp, '*', label = r'$\langle O\rangle_{\Psi}^{exp}$')
plt.xlabel(r'$\theta$'); plt.legend(); plt.show()
|
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
|
alejomonbar
|
%load_ext autoreload
%autoreload 2
# pip install pennylane
import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import NesterovMomentumOptimizer
import tensorflow as tf
import pandas as pd
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from IPython.display import clear_output
clear_output(wait=False)
import os
import tensorflow as tf
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)
dev = qml.device("default.qubit", wires=4)
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_wires = 4
n_block_wires = 2
n_params_block = 2
n_blocks = qml.TTN.get_n_blocks(range(n_wires),n_block_wires)
n_blocks
@qml.qnode(dev)
def circuit(weights, x):
qml.AmplitudeEmbedding(x, wires=[0,1,2,3],normalize=True,pad_with=True)
for w in weights:
qml.TTN(range(n_wires),n_block_wires,block, n_params_block, w)
#print(w)
#print(x)
return qml.expval(qml.PauliZ(3))
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_pred = [np.sign(variational_classifier(weights, bias, f)) for f in x_test]
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_pred ]
y_pred_1 = ["{}\n".format(i) for i in y_pred_1]
with open(r'ttn_1_layers.csv', 'w') as fp:
fp.writelines(y_pred_1)
|
https://github.com/ardieb/QiskitPlayground
|
ardieb
|
from qiskit import *
from qiskit.quantum_info import *
from qiskit.visualization import *
from qiskit.circuit.library import *
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import itertools
import collections
import typing
%matplotlib inline
Array = np.ndarray
def teleporter(phi: Array):
assert phi.shape[0] == 2, "initialized state must have 2 entries (single qubit)"
qr = QuantumRegister(3, 'q')
crz = ClassicalRegister(1, 'crz')
crx = ClassicalRegister(1, 'crx')
circ = QuantumCircuit(qr, crz, crx)
circ.reset(qr[1])
circ.reset(qr[2])
circ.h(qr[1])
circ.cx(qr[1], qr[2])
circ.initialize(phi, qr[0])
circ.barrier()
circ.cx(qr[0], qr[1])
circ.h(qr[0])
circ.barrier()
circ.measure(qr[1], crx)
circ.measure(qr[0], crz)
circ.barrier()
circ.x(qr[2]).c_if(crx, 1)
circ.z(qr[2]).c_if(crz, 1)
return circ
sv_simulator = Aer.get_backend('statevector_simulator')
# Let's teleport the state 1/sqrt(2) [1, exp(i pi / 4)]
phi = np.array([1/np.sqrt(2), 1/np.sqrt(2) * np.exp(1j * np.pi / 4)])
circ = teleporter(phi)
display(circ.draw('mpl'))
result = execute(circ, sv_simulator).result()
display(plot_bloch_multivector(result.get_statevector(circ, decimals = 3)))
def key_update(a: int, b: int, c: int, d: int):
assert all(0 <= x <= 1 for x in [a,b,c,d]), "inputs must be an integer modulo 2"
return {'H': f'{b}{a}', 'X': f'{a}{b}', 'Z': f'{a}{b}', 'S': f'{a}{a ^ b}', 'cX': f'{a}{b ^ d}{a ^ c}{d}'}
df = []
for a in (0, 1):
for b in (0, 1):
for c in (0, 1):
for d in (0, 1):
update = key_update(a, b, c, d)
update['abcd'] = f'{a}{b}{c}{d}'
df.append(update)
df = pd.DataFrame(df)
df.set_index('abcd', inplace = True)
print(df)
# rho = 1/2 * np.array([[1,3], [3, 1]])
# tau = 0.8
qr = QuantumRegister(5, 'q')
cr = ClassicalRegister(5, 'c')
qpce = QuantumCircuit(qr, cr)
# prepare the state
theta1, theta2, alpha = 0.643, 2.498, 2.094
qpce.h(qr[3])
qpce.x(qr[3])
qpce.cu(theta1, 0, 0, 0, qr[3], qr[4])
qpce.x(qr[3])
qpce.cu(theta2, 0, 0, 0, qr[3], qr[4])
qpce.barrier()
# phase estimation
qpce.h(qr[1])
qpce.h(qr[2])
qpce.cu(-np.pi/2, -np.pi/2, np.pi/2, 0, qr[2], qr[3])
qpce.p(3*np.pi/4, qr[2])
qpce.cx(qr[1], qr[3])
qpce.swap(qr[1], qr[2])
qpce.h(qr[2])
qpce.cp(-np.pi/2, qr[1], qr[2])
qpce.h(qr[1])
qpce.barrier()
# Controlled rotation
qpce.cx(qr[1], qr[2])
qpce.cu(alpha, 0, 0, 0, qr[1], qr[0])
qpce.cu(alpha, 0, 0, 0, qr[2], qr[0])
qpce.cx(qr[1], qr[2])
qpce.barrier()
# Inverse phase estimation
qpce.h(qr[1])
qpce.cp(np.pi/2, qr[1], qr[2])
qpce.h(qr[2])
qpce.swap(qr[1], qr[2])
qpce.cx(qr[1], qr[3])
qpce.h(qr[1])
qpce.p(-3*np.pi/4, qr[2])
qpce.cu(-np.pi/2, -np.pi/2, np.pi/2, 0, qr[2], qr[3])
qpce.h(qr[2])
qpce.barrier()
# Measurement
qpce.measure(qr[0], cr[0])
qpce.measure(qr[1], cr[1])
qpce.measure(qr[2], cr[2])
qpce.measure(qr[3], cr[3])
qpce.measure(qr[4], cr[4])
qpce.draw('mpl')
qasm_simulator = Aer.get_backend('qasm_simulator')
result = execute(qpce, qasm_simulator, shots=2048).result()
display(plot_histogram(result.get_counts()))
# The operation is HTHT
# a0, b0 = 1, 1
qr = QuantumRegister(5, 'q')
cr = ClassicalRegister(5, 'c')
qku = QuantumCircuit(qr, cr)
# initialize
qku.reset(qr[0])
qku.reset(qr[1])
qku.reset(qr[3])
qku.h(qr[0])
qku.h(qr[1])
qku.h(qr[3])
qku.x(qr[0])
qku.cx(qr[1], qr[2])
qku.cx(qr[3], qr[4])
qku.z(qr[0])
qku.t(qr[0])
qku.swap(qr[0], qr[1])
qku.h(qr[0])
qku.s(qr[1])
qku.t(qr[0])
qku.cx(qr[1], qr[2])
qku.h(qr[1])
qku.swap(qr[0], qr[3])
qku.h(qr[0])
qku.s(qr[3])
qku.cx(qr[3], qr[4])
qku.h(qr[3])
qku.barrier()
qku.measure(qr[4], cr[4])
qku.measure(qr[3], cr[3])
qku.measure(qr[2], cr[2])
qku.measure(qr[1], cr[1])
qku.measure(qr[0], cr[0])
qku.draw('mpl')
result = execute(qku, qasm_simulator, shots=2048).result()
display(plot_histogram(result.get_counts(), figsize=(10,10)))
# The operation is HTHT
# a0, b0 = 0, 1
qr = QuantumRegister(5, 'q')
cr = ClassicalRegister(5, 'c')
qku = QuantumCircuit(qr, cr)
# initialize
qku.reset(qr[0])
qku.reset(qr[1])
qku.reset(qr[3])
qku.h(qr[0])
qku.h(qr[1])
qku.h(qr[3])
# qku.x(qr[0]) a = 0
qku.cx(qr[1], qr[2])
qku.cx(qr[3], qr[4])
qku.z(qr[0])
qku.t(qr[0])
qku.swap(qr[0], qr[1])
qku.h(qr[0])
qku.s(qr[1])
qku.t(qr[0])
qku.cx(qr[1], qr[2])
qku.h(qr[1])
qku.swap(qr[0], qr[3])
qku.h(qr[0])
qku.s(qr[3])
qku.cx(qr[3], qr[4])
qku.h(qr[3])
qku.barrier()
#ra(2)
qku.measure(qr[4], cr[4])
#rb(2)
qku.measure(qr[3], cr[3])
#ra(1)
qku.measure(qr[2], cr[2])
#rb(1)
qku.measure(qr[1], cr[1])
#q0
qku.measure(qr[0], cr[0])
qku.draw('mpl')
result = execute(qku, qasm_simulator, shots=2048).result()
display(plot_histogram(result.get_counts(), figsize=(10,10)))
# Select 4 measurements with high probability, here we choose > 0.05
import random
sample = []
counts = list(result.get_counts().items())
total = sum(x for _, x in counts)
while len(sample) < 4:
state, count = counts[random.randint(0,len(counts)-1)]
if count / total >= 0.05:
sample.append(state)
print(sample)
a0, b0 = 0, 1
for state in sample:
ra2, rb2, ra1, rb1, q0 = [int(c) for c in state]
af = b0 ^ ra1 ^ rb1 ^ rb2
bf = a0 ^ b0 ^ rb1 ^ ra2
print(f'Measurements are {state}')
print(f'Final decyption keys: {af}, {bf}')
print(f'Final state measurement: {q0}')
# here we find the opposite of the researchers result, where if af = 0 we measure q0 = 0 and if af = 1 we measure q0 = 1
|
https://github.com/hkhetawat/QArithmetic
|
hkhetawat
|
# Import the Qiskit SDK
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, Aer
from QArithmetic import square
# Input N
N = 3
a = QuantumRegister(N)
b = QuantumRegister(2*N)
cb = ClassicalRegister(2*N)
qc = QuantumCircuit(a, b, cb)
# Input
# a = 111 = 7
qc.x(a[0])
qc.x(a[1])
qc.x(a[2])
square(qc, a, b)
qc.measure(b, cb)
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
|
https://github.com/quantastica/quantum-circuit
|
quantastica
|
operation ExportedQsharpCode() : Result {
using(q_reg = Qubit[3]) {
X(q_reg[0]);
X(q_reg[1]);
X(q_reg[2]);
CCNOT(q_reg[0], q_reg[1], q_reg[2]);
let r = M(q_reg[2]);
ResetAll(q_reg);
return r;
}
}
%simulate ExportedQsharpCode
|
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 = []
for _ in range(100):
depths.append(
transpile(
ghz,
backend,
layout_method='trivial' # Fixed layout mapped in circuit order
).depth()
)
plt.figure(figsize=(8, 6))
plt.hist(depths, align='left', color='#AC557C')
plt.xlabel('Depth', fontsize=14)
plt.ylabel('Counts', fontsize=14);
|
https://github.com/Qottmann/Quantum-anomaly-detection
|
Qottmann
|
import sys
sys.path.insert(1, '..') # sets the import path to the parent folder
import time
import datetime
import numpy as np
from matplotlib import pyplot as plt
anti = -1
L = 5
num_trash = 2
name = "jakarta_execute"
filename = '../data/jakarta_execute'
# load data from simulation and experiment
temp = np.load(filename + "_executed_-real-device-True.npz",allow_pickle=True)
gx_list = temp["gx_list"]
gz = 0
gz_list = [0]
Qmag_sim = temp["Qmag_sim"]
QZ_sim = temp["QZ_sim"]
Qmag_device = temp["Qmag_device"]
QZ_device = temp["QZ_device"]
Qen_sim = temp["Qen_sim"]
Sen = temp["Sen"]
Smag = temp["Smag"]
opt_params = temp["opt_params"]
paramss = temp["paramss"]; valuess = temp["valuess"]; countss = temp["countss"]
run1 = np.load(filename + "run1_device2.npz",allow_pickle=True) # alt: run1_device2
sim1 = np.load(filename + "run1_sim2.npz",allow_pickle=True)
run2 = np.load(filename + "run2_device.npz",allow_pickle=True) # alt: _overnight
sim2 = np.load(filename + "run2_sim.npz",allow_pickle=True)
fig, axs = plt.subplots(nrows=2,figsize=(6,6),sharex=True,gridspec_kw={'height_ratios': [2, 2]})
ax = axs[0]
cost_sim = sim1["cost"]
ax.plot(gx_list, cost_sim,".:", label="cost noisy sim.")
cost_device = run1["cost"]
ax.plot(gx_list, cost_device,".:", label="cost ibmq_jakarta")
ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$|\hat{S}|$ noisy sim.")
ax.plot(gx_list, np.abs(Qmag_device),"x--", label="$|\hat{S}|$ ibmq_jakarta")
ax.set_xscale("log")
ax.plot(gx_list[0],cost_device[0], "X",markersize=20,alpha=0.4,color="magenta")
ax = axs[1]
cost_sim = sim2["cost"]
ax.plot(gx_list, cost_sim,".:", label="cost noisy sim.")
cost_device = run2["cost"]
ax.plot(gx_list, cost_device,".:", label="cost ibmq_jakarta")
ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$|\hat{S}|$ noisy sim.")
ax.plot(gx_list, np.abs(Qmag_device),"x--", label="$|\hat{S}|$ ibmq_jakarta")
ax.set_xscale("log")
ax.plot(gx_list[-1],cost_device[-1],"X",markersize=16,alpha=0.4,color="magenta", label= "Training point")
for ax in axs:
ax.tick_params(labelsize=14)
axs[1].legend() #ncol=5
axs[-1].set_xlabel("$g_x$", fontsize=14)
plt.tight_layout()
axs[0].text(0.01,0.9,"a", fontweight="bold", size=18, transform = axs[0].transAxes)
axs[1].text(0.01,0.9,"b", fontweight="bold", size=18, transform = axs[1].transAxes)
plt.savefig("../plots/" + name + "_mainplot.png", bbox_inches='tight')
plt.savefig("../plots/" + name + "_mainplot.pdf", bbox_inches='tight')
run1 = np.load(filename + "run1_device.npz",allow_pickle=True) # alt: run1_device2
sim1 = np.load(filename + "run1_sim.npz",allow_pickle=True)
run2 = np.load(filename + "run2_device_overnight.npz",allow_pickle=True) # alt: run2_device_
sim2 = np.load(filename + "run2_sim.npz",allow_pickle=True)
fig, axs = plt.subplots(nrows=2,figsize=(6,6),sharex=True,gridspec_kw={'height_ratios': [2, 2]})
ax = axs[0]
cost_sim = sim1["cost"]
ax.plot(gx_list, cost_sim,".:", label="cost noisy sim.")
cost_device = run1["cost"]
ax.plot(gx_list, cost_device,".:", label="cost ibmq_jakarta")
ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$|\hat{S}|$ noisy sim.")
ax.plot(gx_list, np.abs(Qmag_device),"x--", label="$|\hat{S}|$ ibmq_jakarta")
ax.set_xscale("log")
ax.plot(gx_list[0],cost_device[0], "X",markersize=20,alpha=0.4,color="magenta")
ax = axs[1]
cost_sim = sim2["cost"]
ax.plot(gx_list, cost_sim,".:", label="cost noisy sim.")
cost_device = run2["cost"]
ax.plot(gx_list, cost_device,".:", label="cost ibmq_jakarta")
ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$|\hat{S}|$ noisy sim.")
ax.plot(gx_list, np.abs(Qmag_device),"x--", label="$|\hat{S}|$ ibmq_jakarta")
ax.set_xscale("log")
ax.plot(gx_list[-1],cost_device[-1],"X",markersize=20,alpha=0.4,color="magenta", label= "Training point")
for ax in axs:
ax.tick_params(labelsize=14)
axs[1].legend() #ncol=5
axs[-1].set_xlabel("$g_x$", fontsize=14)
plt.tight_layout()
axs[0].text(0.01,0.9,"a", fontweight="bold", size=18, transform = axs[0].transAxes)
axs[1].text(0.01,0.9,"b", fontweight="bold", size=18, transform = axs[1].transAxes)
plt.savefig("../plots/" + name + "_mainplot_alt.png", bbox_inches='tight')
plt.savefig("../plots/" + name + "_mainplot_alt.pdf", bbox_inches='tight')
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
##The following statement imports Qiskit libraries in the notebook!
import qiskit
##To create a Quantum Circuit with 1 qubit
from qiskit import QuantumCircuit as qc
cirq = qc(1)
##To plot the circuit using MatplotLib
cirq.draw('mpl')
#To make a state vector and see it
from qiskit.quantum_info import Statevector
sv = Statevector.from_label('0')
sv
#To see the specific Array data
sv.data
#To apply the new state vector over the constructed circuit
new_sv = sv.evolve(cirq)
new_sv
#To check the State Fidelity
from qiskit.quantum_info import state_fidelity
state_fidelity(sv , new_sv)
#To plot the Q-Sphere
from qiskit.visualization import plot_state_qsphere
plot_state_qsphere(new_sv.data)
#Adding an X gate for qubit flip
cirq1 = qc(1)
cirq1.x(0)
cirq1.draw('mpl')
#Adding a hadamard gate to create a superposition
cirq2 = qc(1)
cirq2.h(0)
cirq2.draw('mpl')
#Adding a t gate
cirq3 = qc(1)
cirq3.t(0)
cirq3.draw('mpl')
#Adding a s gate
cirq4 = qc(1)
cirq4.s(0)
cirq4.draw('mpl')
#Creating a multi state vector |00>
sv = Statevector.from_label('10010')
plot_state_qsphere(sv.data)
my_cirq = qc(3, 3)
my_sv = Statevector.from_label('000')
my_cirq.h(0)
my_cirq.cx(0 , 1)
my_cirq.cx(0 , 2)
display(my_cirq.draw('mpl'))
print(my_sv)
new_my_sv = my_sv.evolve(my_cirq)
print(new_my_sv)
plot_state_qsphere(new_my_sv.data)
##Setting numer of shots and plotting the Histogram
counts = new_my_sv.sample_counts(shots = 1000)
from qiskit.visualization import *
from matplotlib import style
style.use('bmh')
style.use('dark_background')
plot_histogram(counts)
plot_state_city(my_sv)
my_cirq.measure([0,1], [0,1])
my_cirq.draw('mpl')
from qiskit import *
#SIMULATION
simulator = Aer.get_backend('qasm_simulator')
result = execute(my_cirq, simulator, shots=10000).result()
count = result.get_counts(my_cirq)
plot_histogram(count)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test pulse builder with backendV2 context utilities."""
import numpy as np
from qiskit import circuit, pulse
from qiskit.pulse import builder, macros
from qiskit.pulse.instructions import directives
from qiskit.pulse.transforms import target_qobj_transform
from qiskit.providers.fake_provider import FakeMumbaiV2
from qiskit.pulse import instructions
from qiskit.test import QiskitTestCase
class TestBuilderV2(QiskitTestCase):
"""Test the pulse builder context with backendV2."""
def setUp(self):
super().setUp()
self.backend = FakeMumbaiV2()
def assertScheduleEqual(self, program, target):
"""Assert an error when two pulse programs are not equal.
.. note:: Two programs are converted into standard execution format then compared.
"""
self.assertEqual(target_qobj_transform(program), target_qobj_transform(target))
class TestContextsV2(TestBuilderV2):
"""Test builder contexts."""
def test_transpiler_settings(self):
"""Test the transpiler settings context.
Tests that two cx gates are optimized away with higher optimization level.
"""
twice_cx_qc = circuit.QuantumCircuit(2)
twice_cx_qc.cx(0, 1)
twice_cx_qc.cx(0, 1)
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(optimization_level=0):
builder.call(twice_cx_qc)
self.assertNotEqual(len(schedule.instructions), 0)
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(optimization_level=3):
builder.call(twice_cx_qc)
self.assertEqual(len(schedule.instructions), 0)
def test_scheduler_settings(self):
"""Test the circuit scheduler settings context."""
inst_map = pulse.InstructionScheduleMap()
d0 = pulse.DriveChannel(0)
test_x_sched = pulse.Schedule()
test_x_sched += instructions.Delay(10, d0)
inst_map.add("x", (0,), test_x_sched)
ref_sched = pulse.Schedule()
ref_sched += pulse.instructions.Call(test_x_sched)
x_qc = circuit.QuantumCircuit(2)
x_qc.x(0)
with pulse.build(backend=self.backend) as schedule:
with pulse.transpiler_settings(basis_gates=["x"]):
with pulse.circuit_scheduler_settings(inst_map=inst_map):
builder.call(x_qc)
self.assertScheduleEqual(schedule, ref_sched)
def test_phase_compensated_frequency_offset(self):
"""Test that the phase offset context properly compensates for phase
accumulation with backendV2."""
d0 = pulse.DriveChannel(0)
with pulse.build(self.backend) as schedule:
with pulse.frequency_offset(1e9, d0, compensate_phase=True):
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.ShiftFrequency(1e9, d0)
reference += instructions.Delay(10, d0)
reference += instructions.ShiftPhase(
-2 * np.pi * ((1e9 * 10 * self.backend.target.dt) % 1), d0
)
reference += instructions.ShiftFrequency(-1e9, d0)
self.assertScheduleEqual(schedule, reference)
class TestChannelsV2(TestBuilderV2):
"""Test builder channels."""
def test_drive_channel(self):
"""Text context builder drive channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.drive_channel(0), pulse.DriveChannel(0))
def test_measure_channel(self):
"""Text context builder measure channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.measure_channel(0), pulse.MeasureChannel(0))
def test_acquire_channel(self):
"""Text context builder acquire channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.acquire_channel(0), pulse.AcquireChannel(0))
def test_control_channel(self):
"""Text context builder control channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.control_channels(0, 1)[0], pulse.ControlChannel(0))
class TestDirectivesV2(TestBuilderV2):
"""Test builder directives."""
def test_barrier_on_qubits(self):
"""Test barrier directive on qubits with backendV2.
A part of qubits map of Mumbai
0 -- 1 -- 4 --
|
|
2
"""
with pulse.build(self.backend) as schedule:
pulse.barrier(0, 1)
reference = pulse.ScheduleBlock()
reference += directives.RelativeBarrier(
pulse.DriveChannel(0),
pulse.DriveChannel(1),
pulse.MeasureChannel(0),
pulse.MeasureChannel(1),
pulse.ControlChannel(0),
pulse.ControlChannel(1),
pulse.ControlChannel(2),
pulse.ControlChannel(3),
pulse.ControlChannel(4),
pulse.ControlChannel(8),
pulse.AcquireChannel(0),
pulse.AcquireChannel(1),
)
self.assertEqual(schedule, reference)
class TestUtilitiesV2(TestBuilderV2):
"""Test builder utilities."""
def test_active_backend(self):
"""Test getting active builder backend."""
with pulse.build(self.backend):
self.assertEqual(pulse.active_backend(), self.backend)
def test_qubit_channels(self):
"""Test getting the qubit channels of the active builder's backend."""
with pulse.build(self.backend):
qubit_channels = pulse.qubit_channels(0)
self.assertEqual(
qubit_channels,
{
pulse.DriveChannel(0),
pulse.MeasureChannel(0),
pulse.AcquireChannel(0),
pulse.ControlChannel(0),
pulse.ControlChannel(1),
},
)
def test_active_transpiler_settings(self):
"""Test setting settings of active builder's transpiler."""
with pulse.build(self.backend):
self.assertFalse(pulse.active_transpiler_settings())
with pulse.transpiler_settings(test_setting=1):
self.assertEqual(pulse.active_transpiler_settings()["test_setting"], 1)
def test_active_circuit_scheduler_settings(self):
"""Test setting settings of active builder's circuit scheduler."""
with pulse.build(self.backend):
self.assertFalse(pulse.active_circuit_scheduler_settings())
with pulse.circuit_scheduler_settings(test_setting=1):
self.assertEqual(pulse.active_circuit_scheduler_settings()["test_setting"], 1)
def test_num_qubits(self):
"""Test builder utility to get number of qubits with backendV2."""
with pulse.build(self.backend):
self.assertEqual(pulse.num_qubits(), 27)
def test_samples_to_seconds(self):
"""Test samples to time with backendV2"""
target = self.backend.target
target.dt = 0.1
with pulse.build(self.backend):
time = pulse.samples_to_seconds(100)
self.assertTrue(isinstance(time, float))
self.assertEqual(pulse.samples_to_seconds(100), 10)
def test_samples_to_seconds_array(self):
"""Test samples to time (array format) with backendV2."""
target = self.backend.target
target.dt = 0.1
with pulse.build(self.backend):
samples = np.array([100, 200, 300])
times = pulse.samples_to_seconds(samples)
self.assertTrue(np.issubdtype(times.dtype, np.floating))
np.testing.assert_allclose(times, np.array([10, 20, 30]))
def test_seconds_to_samples(self):
"""Test time to samples with backendV2"""
target = self.backend.target
target.dt = 0.1
with pulse.build(self.backend):
samples = pulse.seconds_to_samples(10)
self.assertTrue(isinstance(samples, int))
self.assertEqual(pulse.seconds_to_samples(10), 100)
def test_seconds_to_samples_array(self):
"""Test time to samples (array format) with backendV2."""
target = self.backend.target
target.dt = 0.1
with pulse.build(self.backend):
times = np.array([10, 20, 30])
samples = pulse.seconds_to_samples(times)
self.assertTrue(np.issubdtype(samples.dtype, np.integer))
np.testing.assert_allclose(pulse.seconds_to_samples(times), np.array([100, 200, 300]))
class TestMacrosV2(TestBuilderV2):
"""Test builder macros with backendV2."""
def test_macro(self):
"""Test builder macro decorator."""
@pulse.macro
def nested(a):
pulse.play(pulse.Gaussian(100, a, 20), pulse.drive_channel(0))
return a * 2
@pulse.macro
def test():
pulse.play(pulse.Constant(100, 1.0), pulse.drive_channel(0))
output = nested(0.5)
return output
with pulse.build(self.backend) as schedule:
output = test()
self.assertEqual(output, 0.5 * 2)
reference = pulse.Schedule()
reference += pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0))
reference += pulse.Play(pulse.Gaussian(100, 0.5, 20), pulse.DriveChannel(0))
self.assertScheduleEqual(schedule, reference)
def test_measure(self):
"""Test utility function - measure with backendV2."""
with pulse.build(self.backend) as schedule:
reg = pulse.measure(0)
self.assertEqual(reg, pulse.MemorySlot(0))
reference = macros.measure(qubits=[0], backend=self.backend, meas_map=self.backend.meas_map)
self.assertScheduleEqual(schedule, reference)
def test_measure_multi_qubits(self):
"""Test utility function - measure with multi qubits with backendV2."""
with pulse.build(self.backend) as schedule:
regs = pulse.measure([0, 1])
self.assertListEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)])
reference = macros.measure(
qubits=[0, 1], backend=self.backend, meas_map=self.backend.meas_map
)
self.assertScheduleEqual(schedule, reference)
def test_measure_all(self):
"""Test utility function - measure with backendV2.."""
with pulse.build(self.backend) as schedule:
regs = pulse.measure_all()
self.assertEqual(regs, [pulse.MemorySlot(i) for i in range(self.backend.num_qubits)])
reference = macros.measure_all(self.backend)
self.assertScheduleEqual(schedule, reference)
def test_delay_qubit(self):
"""Test delaying on a qubit macro."""
with pulse.build(self.backend) as schedule:
pulse.delay_qubits(10, 0)
d0 = pulse.DriveChannel(0)
m0 = pulse.MeasureChannel(0)
a0 = pulse.AcquireChannel(0)
u0 = pulse.ControlChannel(0)
u1 = pulse.ControlChannel(1)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
reference += instructions.Delay(10, m0)
reference += instructions.Delay(10, a0)
reference += instructions.Delay(10, u0)
reference += instructions.Delay(10, u1)
self.assertScheduleEqual(schedule, reference)
def test_delay_qubits(self):
"""Test delaying on multiple qubits with backendV2 to make sure we don't insert delays twice."""
with pulse.build(self.backend) as schedule:
pulse.delay_qubits(10, 0, 1)
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
m0 = pulse.MeasureChannel(0)
m1 = pulse.MeasureChannel(1)
a0 = pulse.AcquireChannel(0)
a1 = pulse.AcquireChannel(1)
u0 = pulse.ControlChannel(0)
u1 = pulse.ControlChannel(1)
u2 = pulse.ControlChannel(2)
u3 = pulse.ControlChannel(3)
u4 = pulse.ControlChannel(4)
u8 = pulse.ControlChannel(8)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
reference += instructions.Delay(10, d1)
reference += instructions.Delay(10, m0)
reference += instructions.Delay(10, m1)
reference += instructions.Delay(10, a0)
reference += instructions.Delay(10, a1)
reference += instructions.Delay(10, u0)
reference += instructions.Delay(10, u1)
reference += instructions.Delay(10, u2)
reference += instructions.Delay(10, u3)
reference += instructions.Delay(10, u4)
reference += instructions.Delay(10, u8)
self.assertScheduleEqual(schedule, reference)
|
https://github.com/Innanov/Qiskit-Global-Summer-School-2022
|
Innanov
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.sdg(0)
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.cx(0,1)
qc.x(0)
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
#
#
# FILL YOUR CODE IN HERE
#
#
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.y(1)
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
oraclenr = 4 # determines the oracle (can range from 1 to 5)
oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles
oracle.name = "DJ-Oracle"
def dj_classical(n, input_str):
# build a quantum circuit with n qubits and 1 classical readout bit
dj_circuit = QuantumCircuit(n+1,1)
# Prepare the initial state corresponding to your input bit string
for i in range(n):
if input_str[i] == '1':
dj_circuit.x(i)
# append oracle
dj_circuit.append(oracle, range(n+1))
# measure the fourth qubit
dj_circuit.measure(n,0)
return dj_circuit
n = 4 # number of qubits
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
dj_circuit.draw() # draw the circuit
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit, qasm_sim)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def lab1_ex7():
min_nr_inputs = 2
max_nr_inputs = 9
return [min_nr_inputs, max_nr_inputs]
from qc_grader import grade_lab1_ex7
# Note that the grading function is expecting a list of two integers
grade_lab1_ex7(lab1_ex7())
n=4
def psi_0(n):
qc = QuantumCircuit(n+1,n)
# Build the state (|00000> - |10000>)/sqrt(2)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(4)
qc.h(4)
return qc
dj_circuit = psi_0(n)
dj_circuit.draw()
def psi_1(n):
# obtain the |psi_0> = |00001> state
qc = psi_0(n)
# create the superposition state |psi_1>
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
#
#
qc.barrier()
return qc
dj_circuit = psi_1(n)
dj_circuit.draw()
def psi_2(oracle,n):
# circuit to obtain psi_1
qc = psi_1(n)
# append the oracle
qc.append(oracle, range(n+1))
return qc
dj_circuit = psi_2(oracle, n)
dj_circuit.draw()
def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25])
qc = psi_2(oracle, n)
# apply n-fold hadamard gate
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
# add the measurement by connecting qubits to classical bits
#
#
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
#
#
return qc
dj_circuit = lab1_ex8(oracle, n)
dj_circuit.draw()
from qc_grader import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit with measurements
grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n))
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/EavCmr/QKD-E91
|
EavCmr
|
#!pip install qiskit
from qiskit import QuantumCircuit, Aer, transpile, assemble, execute, IBMQ
from qiskit.visualization import plot_histogram
import numpy as np
import random
import math
import warnings
warnings.filterwarnings('ignore')
# Determine the amount of entanglement between these bits using the CHSH value
def entanglement_amount(alice_choices, alice_bits, bob_choices, bob_bits):
# count the different measurement results
# rows correspond to Alice and Bob's circuit choices: 00, 02, 20, 22
# NOTE: We do not consider circuits 1 or 3 for this test
# columns correspond to Alice and Bob's qubit measurements: 00, 01, 10, and 11
circuits = {'00': 0, '02': 1, '20': 2, '22': 3}
counts = [[0]*4 for i in range(4)]
for i in range(len(alice_choices)):
circuit = str(alice_choices[i]) + str(bob_choices[i])
state = int(alice_bits[i]) + 2*int(bob_bits[i])
if circuit in circuits: counts[circuits[circuit]][state] += 1
# expectation values calculated by
# adding times Alice and Bob's bits agreed and
# subtracting times Alice and Bob's bits disagreed
expectations = []
for circuit in range(4):
expectations += [counts[circuit][0] + counts[circuit][3] - counts[circuit][1] - counts[circuit][2]]
total = sum(counts[circuit])
if total != 0: expectations[circuit] /= total
# returning CHSH correlation
return expectations[0] - expectations[1] + expectations[2] + expectations[3]
print("Libraries Imported Successfully!")
alice_bob_qubits = QuantumCircuit(2, 2)
alice_bob_qubits.h(0)
alice_bob_qubits.cx(0,1)
alice_bob_qubits.x(0)
alice_bob_qubits.z(0)
alice_bob_qubits.draw()
alice_option_1 = QuantumCircuit(1, 1)
alice_option_1.rz(0,0)
alice_option_1.h(0)
alice_option_1.measure(0, 0)
alice_option_2 = QuantumCircuit(1, 1)
alice_option_2.rz(math.pi/4,0) # COMPLETE THIS LINE
alice_option_2.h(0)
alice_option_2.measure(0, 0)
alice_option_3 = QuantumCircuit(1, 1)
alice_option_3.rz(math.pi/2,0) # COMPLETE THIS LINE
alice_option_3.h(0)
alice_option_3.measure(0, 0)
alice_options = [alice_option_1,alice_option_2,alice_option_3] # COMPLETE THIS LINE WITH THE OTHER OPTIONS
alice_choice = random.randint(0, 2)
alice_circuit = alice_options[alice_choice]
alice_circuit.draw()
alice_bob_qubits = alice_bob_qubits.compose(alice_circuit, qubits = [0] , clbits = [0])
alice_bob_qubits.draw()
bob_option_1 = QuantumCircuit(1, 1)
bob_option_1.rz(math.pi/4,0)# COMPLETE THIS LINE
bob_option_1.h(0) # COMPLETE THIS LINE
bob_option_1.measure(0, 0)
bob_option_2 = QuantumCircuit(1, 1)
bob_option_2.rz(math.pi/4,0)# COMPLETE THIS LINE
bob_option_2.h(0) # COMPLETE THIS CODE
bob_option_2.measure(0, 0)
bob_option_3= QuantumCircuit(1, 1) # COMPLETE THIS CODE
bob_option_3.rz(math.pi*3/4,0)
bob_option_3.h(0)
bob_option_3.measure(0, 0)
bob_options = [bob_option_1,bob_option_2,bob_option_3]# COMPLETE THIS LINE
bob_choice = random.randint(0, 2)
bob_circuit = bob_options[bob_choice]
bob_circuit.draw()
alice_bob_qubits = alice_bob_qubits.compose(bob_circuit, qubits = [1], clbits = [1])
alice_bob_qubits.draw()
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1024)
result = job.result()
counts = result.get_counts()
bits = random.choices(list(counts.keys()), weights = counts.values(), k = 1)[0]
alice_bits = bits[0]
bob_bits = bits[1]
plot_histogram(counts)
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
# MATCHING CHOICE
if alice_options[alice_choice] == bob_options[bob_choice]:
alice_key += [int(alice_bits[0])]
bob_key += [1 - int(bob_bits[0])]
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [alice_choice]
bob_mismatched_choices += [bob_choice]
alice_mismatched_choice_bits += [alice_bits[0]]
bob_mismatched_choice_bits += [bob_bits[0]]
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
#========
# STEP 1
#========
alice_bob_qubits = QuantumCircuit(2, 2)
alice_bob_qubits.h(0)
alice_bob_qubits.cx(0,1)
alice_bob_qubits.x(0)
alice_bob_qubits.z(0)
alice_bob_qubits.draw()
#========
# STEP 2
#========
alice_choice = random.randint(0, 2)
alice_circuit = alice_options[alice_choice]
alice_circuit.draw()
#========
# STEP 3
#========
alice_bob_qubits = alice_bob_qubits.compose(alice_circuit, qubits = [0], clbits = [0])
#========
# STEP 4
#========
bob_choice = random.randint(0, 2)
bob_circuit = bob_options[bob_choice]
#========
# STEP 5
#========
alice_bob_qubits = alice_bob_qubits.compose(bob_circuit, qubits = [1], clbits = [1])
#======================
# SIMULATE THE CIRCUIT
#======================
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1024)
result = job.result()
counts = result.get_counts()
bits = random.choices(list(counts.keys()), weights = counts.values(), k = 1)[0]
alice_bits = bits[0]
bob_bits = bits[1]
plot_histogram(counts)
#========
# STEP 6
#========
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
# MATCHING CHOICE
if alice_options[alice_choice] == bob_options[bob_choice]:
alice_key += [int(alice_bits[0])]
bob_key += [1 - int(bob_bits[0])]
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [alice_choice]
bob_mismatched_choices += [bob_choice]
alice_mismatched_choice_bits += [alice_bits[0]]
bob_mismatched_choice_bits += [bob_bits[0]]
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
n = 100
alice_bob_qubits = []
for i in range(n):
alice_bob_qubits += [QuantumCircuit(2,2)]
alice_bob_qubits[i].h(0)
alice_bob_qubits[i].cx(0,1)
alice_bob_qubits[i].x(0)
alice_bob_qubits[i].z(0)
alice_choices = []
alice_circuits = []
for i in range(n):
alice_choices += [random.randint(0, 2)]
alice_circuits += [alice_options[alice_choices[i]]]
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [0] , clbits = [0])
bob_choices = []
bob_circuits = []
for i in range(n):
bob_choices += [random.randint(0, 2)]
bob_circuits += [bob_options[bob_choices[i]]]
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [1] , clbits = [1])
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
alice_bits = []
bob_bits = []
for i in range(n):
bits = list(counts[i].keys())[0]
alice_bits += [bits[0]]
bob_bits += [bits[1]]
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
for i in range(n):
# MATCHING CHOICE
if alice_options[alice_choices[i]] == bob_options[bob_choices[i]]:
alice_key += [int(alice_bits[i])]
bob_key += [1 - int(bob_bits[i])]
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [alice_choices[i]]
bob_mismatched_choices += [bob_choices[i]] # COMPLETE THIS LINE
alice_mismatched_choice_bits += [alice_bits[i]] # COMPLETE THIS LINE
bob_mismatched_choice_bits += [bob_bits[i]] # COMPLETE THIS LINE
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
print("Key Length: " + str(len(bob_key)))
print("Number of Disagreeing Key Bits: " + str(sum([alice_key[i] != bob_key[i] for i in range(len(alice_key))])))
#========
# STEP 1
#========
n = 100
#========
# STEP 2
#========
alice_bob_qubits = []
for i in range(n):
alice_bob_qubits += [QuantumCircuit(2,2)]
alice_bob_qubits[i].h(0)
alice_bob_qubits[i].cx(0,1)
alice_bob_qubits[i].x(0)
alice_bob_qubits[i].z(0)
#========
# STEP 3
#========
alice_choices = []
alice_circuits = []
for i in range(n):
alice_choices += [random.randint(0, 2)]
alice_circuits += alice_options[alice_choice]
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [0] , clbits = [0])
#========
# STEP 4
#========
bob_choices = []
bob_circuits = []
for i in range(n):
bob_choices += [random.randint(0, 2)]
bob_circuits += bob_options[bob_choice]
#========
# STEP 5
#========
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [1] , clbits = [1])
#======================
# SIMULATE THE CIRCUIT
#======================
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
alice_bits = []
bob_bits = []
for i in range(n):
bits = list(counts[i].keys())[0]
alice_bits += [bits[0]]
bob_bits += [bits[1]]
#========
# STEP 6
#========
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
for i in range(n):
# MATCHING CHOICE
if alice_options[alice_choices[i]] == bob_options[bob_choices[i]]:
alice_key += [int(alice_bits[i])]
bob_key += [1 - int(bob_bits[i])]
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [alice_choices[i]]
bob_mismatched_choices += [bob_choices[i]]
alice_mismatched_choice_bits += [alice_bits[i]]
bob_mismatched_choice_bits += [bob_bits[i]]
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
print("Key Length: " + str(len(bob_key)))
print("Number of Disagreeing Key Bits: " + str(sum([alice_key[i] != bob_key[i] for i in range(len(alice_key))])))
#========
# STEP 1
#========
n = 100
# COMPLETE THIS CODE WITH YOUR SOLUTION FROM PART 2
#================
# EVE INTERCEPTS!
#================
for i in range(n):
alice_bob_qubits[i].measure(0,0)
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
eve_alice_bits = []
eve_bob_bits = []
for i in range(100):# COMPLETE THIS LINE
# Looks at measurement results
bits = list(counts[i].keys())[0]
eve_alice_bits += [bits[0]]
eve_bob_bits += [bits[1]]
# Prepares new qubits for Alice and Bob
alice_bob_qubits[i] = QuantumCircuit(2,2)
# Makes sure they are in the same state she measured
if eve_alice_bits[i] == 1: alice_bob_qubits[i] == 1
if eve_bob_bits[i] == 1: alice_bob_qubits[i] ==1
alice_choices = []
alice_circuits = []
for i in range(n):
alice_choices += [random.randint(0, 2)]
alice_circuits += alice_options[alice_choice]
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [0] , clbits = [0])
#========
# STEP 4
#========
bob_choices = []
bob_circuits = []
for i in range(n):
bob_choices += [random.randint(0, 2)]
bob_circuits += bob_options[bob_choice]
#========
# STEP 5
#========
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [1] , clbits = [1])
#======================
# SIMULATE THE CIRCUIT
#======================
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
alice_bits = []
bob_bits = []
for i in range(n):
bits = list(counts[i].keys())[0]
alice_bits += [bits[0]]
bob_bits += [bits[1]]
#========
# STEP 6
#========
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
eve_key = []
eve_mismatched_choices = []
eve_mismatched_choice_bits = []
for i in range(n):
# MATCHING CHOICE
if alice_options[alice_choices[i]] == bob_options[bob_choices[i]]:
alice_key += [int(alice_bits[i])]
bob_key += [1 - int(bob_bits[i])]
eve_key += [int(eve_bob_bits[i])]
else:
alice_mismatched_choices += [alice_choices[i]]
bob_mismatched_choices += [bob_choices[i]]
bob_mismatched_choices += [bob_choices[i]]
alice_mismatched_choice_bits += [alice_bits[i]]
bob_mismatched_choice_bits += [bob_bits[i]]
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
print("Eve's Key: " + str(eve_key))
print("Key Length: " + str(len(bob_key)))
print("Number of Disagreeing Key Bits between Alice and Bob: " + str(sum([alice_key[i] != bob_key[i] for i in range(len(alice_key))])))
print("Number of Disagreeing Key Bits between Alice and Eve: " + str(sum([alice_key[i] != eve_key[i] for i in range(len(alice_key))])))
print("Number of Disagreeing Key Bits between Bob and Eve: " + str(sum([bob_key[i] != eve_key[i] for i in range(len(alice_key))])))
n = 100
# COMPLETE THIS CODE WITH YOUR SOLUTION FROM PART 2
alice_bob_qubits = []
for i in range(n):# COMPLETE THIS LINE
alice_bob_qubits += [QuantumCircuit(2,2)]# COMPLETE THIS LINE
alice_bob_qubits[i].h(0) # COMPLETE THIS LINE
alice_bob_qubits[i].cx(0,1) # COMPLETE THIS LINE
alice_bob_qubits[i].x(0) # COMPLETE THIS LINE
alice_bob_qubits[i].z(0) # COMPLETE THIS LINE
#========
# STEP 3
#========
alice_choices = []
alice_circuits = []
for i in range(n): # COMPLETE THIS LINE
alice_choices += [random.randint(0, 2)]
alice_circuits += [alice_options[alice_choices[i]]] # COMPLETE THIS LINE
for i in range(100): # COMPLETE THIS LINE
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [0] , clbits = [0])# COMPLETE THIS LINE
#========
# STEP 4
#========
bob_choices = []
bob_circuits = []
for i in range(n): # COMPLETE THIS LINE
bob_choices += [random.randint(0, 2)]
bob_circuits += [bob_options[bob_choices[i]]]# COMPLETE THIS CODE
#========
# STEP 5
#========
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [1] , clbits = [1])# COMPLETE THIS CODE
#================
# EVE INTERCEPTS!
#================
for i in range(n):# COMPLETE THIS LINE
alice_bob_qubits[i].measure(0,0)# COMPLETE THIS LINE
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
#================
#================
eve_alice_bits = []
eve_bob_bits = []
for i in range(100):# COMPLETE THIS LINE
# Looks at measurement results
bits = list(counts[i].keys())[0]
eve_alice_bits += [bits[0]]
eve_bob_bits += [bits[1]]# COMPLETE THIS LINE
# Prepares new qubits for Alice and Bob
alice_bob_qubits[i] = QuantumCircuit(2,2)# COMPLETE THIS LINE
# Makes sure they are in the same state she measured
if eve_alice_bits[i] == 1: alice_bob_qubits[i].measure(0,0)# COMPLETE THIS LINE
if eve_bob_bits[i] == 1: alice_bob_qubits[i].measure(0,0) # COMPLETE THIS LINE
#================
#================
alice_choices = []
alice_circuits = []
for i in range(n): # COMPLETE THIS LINE
alice_choices += [random.randint(0, 2)]
alice_circuits += [alice_options[alice_choices[i]]] # COMPLETE THIS LINE
for i in range(100): # COMPLETE THIS LINE
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [0] , clbits = [0])# COMPLETE THIS LINE
#========
# STEP 4
#========
bob_choices = []
bob_circuits = []
for i in range(n): # COMPLETE THIS LINE
bob_choices += [random.randint(0, 2)]
bob_circuits += [bob_options[bob_choices[i]]]# COMPLETE THIS CODE
#========
# STEP 5
#========
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [1] , clbits = [1])# COMPLETE THIS CODE
#======================
# SIMULATE THE CIRCUIT
#======================
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
alice_bits = []
bob_bits = []
for i in range(n):
bits = list(counts[i].keys())[0]
alice_bits += [bits[0]]
bob_bits += [bits[1]]
#========
# STEP 6
#========
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
eve_key = []
eve_mismatched_choices = []
eve_mismatched_choice_bits = []
for i in range(n):# COMPLETE THIS LINE
# MATCHING CHOICE
if alice_options[alice_choices[i]] == bob_options[bob_choices[i]]: # COMPLETE THIS LINE
alice_key += [int(alice_bits[i])]
bob_key += [1 - int(bob_bits[i])]# COMPLETE THIS LINE
eve_key += [int(eve_bob_bits[i])]
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [alice_choices[i]]
bob_mismatched_choices += [bob_choices[i]] # COMPLETE THIS LINE
alice_mismatched_choice_bits += [alice_bits[i]] # COMPLETE THIS LINE
bob_mismatched_choice_bits += [bob_bits[i]] # COMPLETE THIS LINE# COMPLETE THIS CODE
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
print("Eve's Key: " + str(eve_key))
print("Key Length: " + str(len(bob_key)))
print("Number of Disagreeing Key Bits between Alice and Bob: " + str(sum([alice_key[i] != bob_key[i] for i in range(len(alice_key))])))
print("Number of Disagreeing Key Bits between Alice and Eve: " + str(sum([alice_key[i] != eve_key[i] for i in range(len(alice_key))])))
print("Number of Disagreeing Key Bits between Bob and Eve: " + str(sum([bob_key[i] != eve_key[i] for i in range(len(alice_key))])))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can set a color for all the bars.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Quantum teleportation example.
Note: if you have only cloned the Qiskit repository but not
used `pip install`, the examples only work from the root directory.
"""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import BasicAer
from qiskit import execute
###############################################################
# Set the backend name and coupling map.
###############################################################
coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]]
backend = BasicAer.get_backend("qasm_simulator")
###############################################################
# Make a quantum program for quantum teleportation.
###############################################################
q = QuantumRegister(3, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
qc = QuantumCircuit(q, c0, c1, c2, name="teleport")
# Prepare an initial state
qc.u(0.3, 0.2, 0.1, q[0])
# Prepare a Bell pair
qc.h(q[1])
qc.cx(q[1], q[2])
# Barrier following state preparation
qc.barrier(q)
# Measure in the Bell basis
qc.cx(q[0], q[1])
qc.h(q[0])
qc.measure(q[0], c0[0])
qc.measure(q[1], c1[0])
# Apply a correction
qc.barrier(q)
qc.z(q[2]).c_if(c0, 1)
qc.x(q[2]).c_if(c1, 1)
qc.measure(q[2], c2[0])
###############################################################
# Execute.
# Experiment does not support feedback, so we use the simulator
###############################################################
# First version: not mapped
initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2}
job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout)
result = job.result()
print(result.get_counts(qc))
# Second version: mapped to 2x8 array coupling graph
job = execute(
qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout
)
result = job.result()
print(result.get_counts(qc))
# Both versions should give the same distribution
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
import unittest
import hypothesis.strategies as st
from hypothesis import given, settings, note
import matplotlib.pyplot as plt
import numpy as np
import math
import cirq
from cirq.ops import H, X, I
from numpy.random import randint
import pandas as pd
from fractions import Fraction
from math import gcd # greatest common divisor
"""Function to compute the elements of Z_n."""
def multiplicative_group(n):
"""Returns the multiplicative group modulo n.
Args:
n: Modulus of the multiplicative group.
"""
print("multiplicative group")
assert n > 1
group = [1]
for x in range(2, n):
if math.gcd(x, n) == 1:
group.append(x)
return group
def qft_dagger_cirq(qc, qubits, n):
for qubit in range(n//2):
qc.append(cirq.SWAP(qubits[qubit], qubits[n-qubit-1]))
for j in range(n):
for m in range(j):
qc.append((cirq.CZ**(-1/2**(j-m)))(qubits[m],qubits[j]))
qc.append(cirq.H(qubits[j]))
def general_modular_exp(a, N, power):
mult_group = multiplicative_group(N)
if a not in mult_group:
raise ValueError("'a' must be in " + str(mult_group))
print(mult_group)
general_modular_exp(7, 15, 2)
def VBE_Adder(qubit_size, qubits):
#outputs a + b
#inverse outputs b - a (but in two's complement)
#move to carry
#qubits = cirq.LineQubit.range(3*qubit_size + 1)
qc = cirq.Circuit()
for i in range(qubit_size-1):
qc.append(cirq.CCNOT(qubits[i], qubits[i+qubit_size], qubits[2+i+(2*qubit_size)]))
#toffoli to second register
qc.append(cirq.CCNOT(qubits[qubit_size-1], qubits[(2*qubit_size)-1], qubits[2*qubit_size]))
#add a to b
for i in range(qubit_size):
qc.append(cirq.CNOT(qubits[i], qubits[i+qubit_size]))
#second register carry and last b
for i in range(qubit_size-1):
qc.append(cirq.CCNOT(qubits[i+qubit_size], qubits[1+i+(2*qubit_size)], qubits[2+i+(2*qubit_size)]))
qc.append(cirq.CCNOT(qubits[(2*qubit_size)-1], qubits[3*qubit_size], qubits[2*qubit_size]))
qc.append(cirq.CNOT(qubits[3*qubit_size], qubits[(2*qubit_size)-1]))
#adder overflow
for i in range(qubit_size-1):
qc.append(cirq.CCNOT(qubits[(2*qubit_size) - 2 - i], qubits[(3*qubit_size) - i - 1], qubits[(3*qubit_size) - i]))
qc.append(cirq.CNOT(qubits[(qubit_size) - 2 - i], qubits[(2*qubit_size) - 2 - i]))
qc.append(cirq.CCNOT(qubits[(qubit_size) - 2 - i], qubits[(2*qubit_size) - 2 - i], qubits[(3*qubit_size) - i]))
qc.append(cirq.CNOT(qubits[(qubit_size) - 2 - i], qubits[(2*qubit_size) - 2 - i]))
qc.append(cirq.CNOT(qubits[(3*qubit_size) - i - 1], qubits[(2*qubit_size) - 2 - i]))
#print(qc.draw(output='text'))
qc.name = "VBE ADDER"
return qc
#VBE_Adder(4)
def Modular_adder(qubit_size, N, qubits):
binN = bin(N)[2:].zfill(qubit_size)[::-1]
#move to carry
#qubits = cirq.LineQubit.range(4*qubit_size + 2)
qc = cirq.Circuit()
qc.append(VBE_Adder(qubit_size, qubits[0:3*qubit_size+1]))
for i in range(qubit_size):
qc.append(cirq.SWAP(qubits[i], qubits[i + 1 + 3*qubit_size]))
qc.append(cirq.inverse(VBE_Adder(qubit_size, qubits[0:3*qubit_size+1])))
qc.append(cirq.X(qubits[2*qubit_size]))
qc.append(cirq.CNOT(qubits[2*qubit_size], qubits[4*qubit_size+1]))
qc.append(cirq.X(qubits[2*qubit_size]))
for i in range(qubit_size):
if binN[i] == "1":
qc.append(cirq.CNOT(qubits[4*qubit_size + 1], qubits[i]))
qc.append(VBE_Adder(qubit_size, qubits[0:3*qubit_size+1]))
for i in range(qubit_size):
if binN[i] == "1":
qc.append(cirq.CNOT(qubits[4*qubit_size + 1], qubits[i]))
for i in range(qubit_size):
qc.append(cirq.SWAP(qubits[i], qubits[i + 1 + 3*qubit_size]))
qc.append(cirq.inverse(VBE_Adder(qubit_size, qubits[0:3*qubit_size+1])))
qc.append(cirq.CNOT(qubits[2*qubit_size], qubits[4*qubit_size+1]))
qc.append(VBE_Adder(qubit_size, qubits[0:3*qubit_size+1]))
qc.name = "MODULAR ADDER"
return qc
#Modular_adder(4,11,qubits)
# from IPython.core.display import display, HTML
# display(HTML("<style>.container { width:60% !important; }</style>"))
# size = 4
# N = 7
# qc = QuantumCircuit(4*size + 2)
# # a = 3,2,1,0
# #qc.x(3)
# qc.x(2)
# qc.x(1)
# qc.x(0)
# # b = 8,7,6,5,4
# #qc.x(7)
# qc.x(6)
# qc.x(5)
# qc.x(4)
# # carry = 12,11,10,9
# # modulus N = 16,15,14,13
# binN = bin(N)[2:].zfill(size)[::-1]
# for i in range(size):
# if binN[i] == "1":
# qc.x(3*size + 1 + i)
# # temporary carry = 17
# print(qc)
# qc.measure_all()
# qc.append(Modular_adder(size,N), [i for i in range(4*size+2)])
# qc.measure_all()
# backend = Aer.get_backend('aer_simulator')
# job = execute(qc, backend, shots=1, memory=True)
# readings = job.result().get_memory()
# second_set = readings[0][0:4*size+2]
# first_set = readings[0][(4*size)+3:(8*size)+6]
# print(readings)
# print(first_set)
# print(second_set)
# print('a = ' + str(first_set[3*size + 2: 4*size + 2]))
# print('b = ' + str(first_set[2*size + 1: 3*size + 2]))
# print('b out = ' + str(second_set[2*size + 1: 3*size + 2]))
# #print('carry = ' + str(second_set[0:size]))
def Modular_multiplier(qubit_size, N, a, qubits):
qc = cirq.Circuit()
for i in range(qubit_size):
mod = bin(a*(2**i) % N)[2:].zfill(qubit_size)[::-1]
for j in range(qubit_size):
if mod[j] == "1":
qc.append(cirq.CCNOT(qubits[0], qubits[i+1], qubits[qubit_size + 1 + j]))
qc.append(Modular_adder(qubit_size, N, qubits[qubit_size + 1:(5*qubit_size+3)]))
#can just repeat the above method, but this looks symmetric
#the circuit diagram is more intuitive
for j in range(qubit_size):
if mod[::-1][j] == "1":
qc.append(cirq.CCNOT(qubits[0], qubits[i+1], qubits[2*qubit_size - j]))
#set x if control is false
qc.append(cirq.X(qubits[0]))
for i in range(qubit_size):
qc.append(cirq.CCNOT(qubits[0], qubits[i+1], qubits[2*qubit_size + 1 + i]))
qc.append(cirq.X(qubits[0]))
qc.name = "MODULAR MULTIPLIER " + str(a) + "x mod " + str(N)
#print(qc.inverse().draw(output='text'))
return qc
#Modular_multiplier(4, 15, 13)
size = 2
N = 2
a = 1
qubits = cirq.LineQubit.range(5*size + 3)
qc = cirq.Circuit()
#control qubit
qc.append(cirq.X(qubits[0]))
# x = 4,3,2,1
#qc.append(cirq.X(qubits[4]))
#qc.append(cirq.X(qubits[3]))
#qc.append(cirq.X(qubits[2]))
#qc.append(cirq.X(qubits[1]))
# N = 21,20,19,18
binN = bin(N)[2:].zfill(size)[::-1]
for i in range(size):
if binN[i] == "1":
qc.append(cirq.X(qubits[4*size + 2 + i]))
# temporary carry = 17
#print(qc)
qc.append(cirq.measure(*qubits[0:5*size+3], key='m1'))
qc.append(Modular_multiplier(size, N, a, qubits[0:(5*size+3)]))
#print(qc)
qc.append(cirq.measure(*qubits[0:5*size+3], key='m2'))
simulator = cirq.Simulator()
results = simulator.run(qc , repetitions =1)
first_set = np.array2string(results.measurements['m1'][0], separator='')[1:-1][::-1]
second_set = np.array2string(results.measurements['m2'][0], separator='')[1:-1][::-1]
print(first_set)
print(second_set)
print('x = ' + str(first_set[4*size + 2: 5*size + 2]))
print('b = ' + str(first_set[2*size + 1: 3*size + 2]))
print('b out = ' + str(second_set[2*size + 1: 3*size + 2]))
#print('carry = ' + str(second_set[0:size]))
def Modular_exponentiation(qubit_size, N, a, qubits):
qc = cirq.Circuit()
#need to set x to 1
qc.append(cirq.X(qubits[qubit_size+1]))
for i in range(qubit_size):
qc.append(cirq.CNOT(qubits[i],qubits[qubit_size]))
qc.append(Modular_multiplier(qubit_size, N, a**(2**i)%N, qubits[qubit_size:(6*qubit_size+3)]))
for j in range(qubit_size):
qc.append(cirq.SWAP(qubits[qubit_size+1+j], qubits[3*qubit_size+1+j]))
#we dont use A for this multiplier because we need the modular multiplicative inverse
#print(a**(2**i)%N)
#print(pow(a**(2**i)%N, -1, N))
qc.append(cirq.inverse(Modular_multiplier(qubit_size, N, pow(a**(2**i)%N, -1, N), qubits[qubit_size:(6*qubit_size+3)])))
qc.append(cirq.CNOT(qubits[i],qubits[qubit_size]))
qc.name = "MODULAR EXPONENTIATION"
#print(qc.draw(output='text'))
return qc
#qubits = cirq.LineQubit.range(6*3 + 3)
#Modular_exponentiation(3, 7, 3,qubits)
# qubit_size = 2
# N = 3
# a = 1
# qc = QuantumCircuit(6*qubit_size + 3)
# # x = 3,2,1,0
# #qc.x(3)
# qc.x(2)
# #qc.x(1)
# #qc.x(0)
# # N = 21,20,19,18
# binN = bin(N)[2:].zfill(qubit_size)[::-1]
# print(binN)
# for i in range(qubit_size):
# if binN[i] == "1":
# qc.x(5*qubit_size + 2 + i)
# #print(qc)
# qc.measure_all()
# qc.append(Modular_exponentiation(qubit_size, N, a), [i for i in range(6*qubit_size+3)])
# qc.measure_all()
# #print(qc)
# backend = Aer.get_backend('aer_simulator')
# job = execute(qc, backend, shots=1, memory=True)
# readings = job.result().get_memory()[0].split(' ')
# second_set = readings[0]
# first_set = readings[1]
# print(first_set)
# print(second_set)
# first_set_exp = first_set[(5 * qubit_size) + 3 : (6 * qubit_size) + 3]
# first_set_x = first_set[(4 * qubit_size) + 2 : (5 * qubit_size) + 2]
# first_set_a = first_set[(3 * qubit_size) + 2 : (4 * qubit_size) + 2]
# first_set_b = first_set[(2 * qubit_size) + 1 : (3 * qubit_size) + 2]
# first_set_N = first_set[qubit_size + 1 : (2 * qubit_size) + 1]
# second_set_exp = second_set[(5 * qubit_size) + 3 : (6 * qubit_size) + 3]
# second_set_x = second_set[(4 * qubit_size) + 2 : (5 * qubit_size) + 2]
# second_set_a = second_set[(3 * qubit_size) + 2 : (4 * qubit_size) + 2]
# second_set_b = second_set[(2 * qubit_size) + 1 : (3 * qubit_size) + 2]
# second_set_N = second_set[qubit_size + 1 : (2 * qubit_size) + 1]
# print("A = " + str(a))
# print("exps 1 -> 2 = " + str(first_set_exp) + " -> " + str(second_set_exp))
# print("xs 1 -> 2 = " + str(first_set_x) + " -> " + str(second_set_x))
# print("as 1 -> 2 = " + str(first_set_a) + " -> " + str(second_set_a))
# print("bs 1 -> 2 = " + str(first_set_b) + " -> " + str(second_set_b))
# print("Ns 1 -> 2 = " + str(first_set_N) + " -> " + str(second_set_N))
# #print('carry = ' + str(second_set[0:size]))
def run_shors(qubit_size, N, a, run_amt):
qubits = cirq.LineQubit.range(6*qubit_size + 3)
qc = cirq.Circuit()
# N = 21,20,19,18
binN = bin(N)[2:].zfill(qubit_size)[::-1]
for i in range(qubit_size):
qc.append(cirq.H(qubits[i]))
for i in range(qubit_size):
if binN[i] == "1":
qc.append(cirq.X(qubits[5*qubit_size + 2 + i]))
qc.append(Modular_exponentiation(qubit_size, N, a, qubits[0:(6*qubit_size+3)]))
qft_dagger_cirq(qc, qubits[:qubit_size], qubit_size)
qc.append(cirq.measure(*qubits[:qubit_size]))
#backend = Aer.get_backend('aer_simulator')
#job = execute(qc, backend, shots=run_amt, memory=True)
# return(job.result().get_memory())
simulator = cirq.Simulator()
results = simulator.run(qc , repetitions =run_amt)
#readings = np.array2string(results.measurements['m'][0], separator='')[1:-1][::-1]
return results
#print(run_shors(3,7,3,1))
#%timeit run_shors(10,26,7,20)
# for loop at the bootom from qiskit textbook for postpro
# https://qiskit.org/textbook/ch-algorithms/shor.html#:~:text=if%20phase%20!%3D%200,guess)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20factor_found%20%3D%20True
def shors_with_postpro(N, a, tries):
factors = []
if not a < N:
raise ValueError("a(%i) must be less than N(%i)"%(a,N))
common_denom = gcd(a,N)
if not common_denom == 1:
raise ValueError("a(%i) and N(%i) must be coprime but they have a gcd of (%i)"%(a, N, common_denom))
length_message = len(bin(N)[2:])*2
if length_message > 8:
print(f"The length of the number you are trying to factor is large ({length_message}), it may fail or take a long time")
res = run_shors(len(bin(N)[2:])*2, N, a, tries)
for result in res:
phase = (int(result,2)/(2**length_message))
frac = Fraction(phase).limit_denominator(N)
r = frac.denominator
print(r)
#if phase != 0:
# guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)]
# for guess in guesses:
# if guess not in [1,N] and (N % guess) == 0:
# factors += [guess]
# return factors
shors_with_postpro(7, 3, 4)
def twos_comp_to_int(binNum):
binNum = int(binNum,2) ^ ((2**len(binNum))-1)
binNum = bin(binNum + 1)
return -int(binNum,2)
@st.composite
def draw_pair_of_ints(draw):
size = draw(st.integers(min_value=1, max_value=6))
a = draw(st.integers(min_value=0, max_value=(2**size)-1))
b = draw(st.integers(min_value=0, max_value=(2**size)-1))
return(a, b, size)
@st.composite
def draw_shors_variables(draw):
size = draw(st.integers(min_value=2, max_value=5))
mod = draw(st.integers(min_value=3, max_value=(2**size)-1))
a = draw(st.integers(min_value=2, max_value=mod-1))
return(a, mod, size)
@st.composite
def draw_pair_of_ints_and_mod(draw):
size = draw(st.integers(min_value=2, max_value=4))
mod = draw(st.integers(min_value=2, max_value=(2**size)-1))
a = draw(st.integers(min_value=0, max_value=mod-1))
b = draw(st.integers(min_value=0, max_value=mod-1))
return(a, b, size, mod)
# @given(draw_shors_variables())
# @settings(deadline=None)
# def test_shors_with_postpro(vals):
# a = vals[0]
# N = vals[1]
# size = vals[2]
# for i in range(size):
# try:
# pow(a**(2**i)%N, -1, N)
# except ValueError:
# assert(not(math.gcd(a,N) == 1))
# if math.gcd(a,N) == 1:
# factors = shors_with_postpro(N, a, 20)
# for factor in factors:
# print(f"N {N}, factor {factor}")
# assert(N % factor == 0)
# @given(draw_pair_of_ints_and_mod())
# @settings(deadline=None)
# def test_modular_exponentiation(vals):
# a = vals[0]
# x = vals[1]
# size = vals[2]
# N = vals[3]
# for i in range(size):
# try:
# pow(a**(2**i)%N, -1, N)
# except ValueError:
# assert(not(math.gcd(a,N) == 1))
# if math.gcd(a,N) == 1:
# qubits = cirq.LineQubit.range(6*size + 3)
# qc = cirq.Circuit()
# binX = bin(x)[2:].zfill(size)[::-1]
# binN = bin(N)[2:].zfill(size)[::-1]
# print("size " + str(size))
# print("a " + str(a))
# print("x " + str(x))
# print("N " + str(N))
# print("\n")
# # x = 3,2,1,0
# for i in range(size):
# if binX[i] == "1":
# qc.x(i)
# for i in range(size):
# if binN[i] == "1":
# qc.x(5*size + 2 + i)
# #print(qc)
# qc.measure_all()
# qc.append(Modular_exponentiation(size, N, a), [i for i in range(6*size+3)])
# qc.measure_all()
# backend = Aer.get_backend('aer_simulator')
# job = execute(qc, backend, shots=1, memory=True)
# readings = job.result().get_memory()[0].split(' ')
# second_set = readings[0]
# first_set = readings[1]
# print(first_set)
# print(second_set)
# first_set_exp = first_set[(5 * size) + 3 : (6 * size) + 3]
# first_set_x = first_set[(4 * size) + 2 : (5 * size) + 2]
# first_set_a = first_set[(3 * size) + 2 : (4 * size) + 2]
# first_set_b = first_set[(2 * size) + 1 : (3 * size) + 2]
# first_set_N = first_set[size + 1 : (2 * size) + 1]
# second_set_exp = second_set[(5 * size) + 3 : (6 * size) + 3]
# second_set_x = second_set[(4 * size) + 2 : (5 * size) + 2]
# second_set_a = second_set[(3 * size) + 2 : (4 * size) + 2]
# second_set_b = second_set[(2 * size) + 1 : (3 * size) + 2]
# second_set_N = second_set[size + 1 : (2 * size) + 1]
# print("A = " + str(a))
# print("exps 1 -> 2 = " + str(first_set_exp) + " -> " + str(second_set_exp))
# print("xs 1 -> 2 = " + str(first_set_x) + " -> " + str(second_set_x))
# print("as 1 -> 2 = " + str(first_set_a) + " -> " + str(second_set_a))
# print("bs 1 -> 2 = " + str(first_set_b) + " -> " + str(second_set_b))
# print("Ns 1 -> 2 = " + str(first_set_N) + " -> " + str(second_set_N))
# print(a)
# print(x)
# print(N)
# print('\n\n')
# assert((a ** x) % N == int(second_set_x, 2))
# @given(draw_pair_of_ints_and_mod(), st.booleans())
# @settings(deadline=None)
# def test_modular_multiplier_then_inverse_returns_original_values(vals, control):
# a = vals[0]
# x = vals[1]
# size = vals[2]
# N = vals[3]
# qubits = cirq.LineQubit.range(5*size + 3)
# qc = cirq.Circuit()
# binX = bin(x)[2:].zfill(size)[::-1]
# binN = bin(N)[2:].zfill(size)[::-1]
# print("size " + str(size))
# print("a " + str(a))
# print("x " + str(x))
# print("N " + str(N))
# print("control " + str(control))
# print("\n")
# #control qubit
# if control == True:
# qc.x(0)
# # x = 3,2,1,0
# for i in range(size):
# if binX[i] == "1":
# qc.x(i+1)
# for i in range(size):
# if binN[i] == "1":
# qc.x(4*size + 2 + i)
# print(qc)
# qc.measure_all()
# qc.append(Modular_multiplier(size, N, a), [i for i in range(5*size+3)])
# qc.append(Modular_multiplier(size, N, a).inverse(), [i for i in range(5*size+3)])
# qc.measure_all()
# backend = Aer.get_backend('aer_simulator')
# job = execute(qc, backend, shots=1, memory=True)
# readings = job.result().get_memory()
# second_set = readings[0][0:5*size+3]
# first_set = readings[0][(5*size)+4:(10*size)+7]
# print("readings " + str(readings))
# print("first set " + str(first_set))
# print("second set " + str(second_set))
# assert(first_set == second_set)
@given(draw_pair_of_ints_and_mod(), st.booleans())
@settings(deadline=None)
def test_modular_multiplier(vals, control):
a = vals[0]
x = vals[1]
size = vals[2]
N = vals[3]
print(a)
print(x)
print(size)
print(N)
qubits = cirq.LineQubit.range(5*size + 3)
qc = cirq.Circuit()
binX = bin(x)[2:].zfill(size)[::-1]
binN = bin(N)[2:].zfill(size)[::-1]
#control qubit
if control == True:
qc.append(cirq.X(qubits[0]))
# x = 3,2,1,0
for i in range(size):
if binX[i] == "1":
qc.append(cirq.X(qubits[i+1]))
for i in range(size):
if binN[i] == "1":
qc.append(cirq.X(qubits[4*size + 2 + i]))
qc.append(cirq.measure(*qubits[0:5*size + 3], key='m1'))
qc.append(Modular_multiplier(size, N, a, qubits[0:(5*size+3)]))
qc.append(cirq.measure(*qubits[0:5*size + 3], key='m2'))
simulator = cirq.Simulator()
results = simulator.run(qc , repetitions =1)
first_set = np.array2string(results.measurements['m1'][0], separator='')[1:-1][::-1]
second_set = np.array2string(results.measurements['m2'][0], separator='')[1:-1][::-1]
print("f " + first_set)
print('s ' + second_set)
x = int(first_set[4*size + 2: 5*size + 2], 2)
print(first_set[4*size + 2: 5*size + 2])
b = int(first_set[2*size + 1: 3*size + 2], 2)
bout = int(second_set[2*size + 1: 3*size + 2], 2)
print("control " + str(control))
print("size = " + str(size))
print('b = ' + str(b))
print('a = ' + str(a))
print('x = ' + str(x))
print("N = " + str(N))
print('b out = ' + str(bout))
print('\n\n')
if (control == False):
assert(bout == x)
else:
assert((a * x) % N == bout)
@given(draw_pair_of_ints_and_mod())
@settings(deadline=None)
def test_modular_adder(vals):
a = vals[0]
b = vals[1]
size = vals[2]
N = vals[3]
qubits = cirq.LineQubit.range(4*size + 2)
qc = cirq.Circuit()
binA = bin(a)[2:].zfill(size)[::-1]
binB = bin(b)[2:].zfill(size)[::-1]
binN = bin(N)[2:].zfill(size)[::-1]
print("size " + str(size))
print("a " + str(a))
print("b " + str(b))
print("N " + str(N))
print("\n")
# a = 3,2,1,0
for i in range(size):
if binA[i] == "1":
qc.append(cirq.X(qubits[i]))
# b = 8,7,6,5,4
for i in range(size):
if binB[i] == "1":
qc.append(cirq.X(qubits[i+size]))
# carry = 12,11,10,9
# modulus N = 16,15,14,13
for i in range(size):
if binN[i] == "1":
qc.append(cirq.X(qubits[3*size + 1 + i]))
# temporary carry = 17
#print(qc)
qc.append(cirq.measure(*qubits[0:4*size+2], key='m1'))
qc.append(Modular_adder(size,N, qubits[0:4*size+2]))
qc.append(cirq.measure(*qubits[0:4*size+2], key='m2'))
simulator = cirq.Simulator()
results = simulator.run(qc , repetitions =1)
first_set = np.array2string(results.measurements['m1'][0], separator='')[1:-1][::-1]
second_set = np.array2string(results.measurements['m2'][0], separator='')[1:-1][::-1]
a = int(first_set[3*size + 2: 4*size + 2], 2)
b = int(first_set[2*size + 1: 3*size + 2], 2)
bout = int(second_set[2*size + 1: 3*size + 2], 2)
print('a = ' + str(a))
print('b = ' + str(b))
print('b out = ' + str(bout))
print('\n\n')
assert((a+b)%N == bout)
@given(draw_pair_of_ints())
@settings(deadline=None)
def test_add_using_VBE_Adder(vals):
a = vals[0]
b = vals[1]
size = vals[2]
qubits = cirq.LineQubit.range(3*size + 1)
qc = cirq.Circuit()
binA = bin(a)[2:].zfill(size)[::-1]
binB = bin(b)[2:].zfill(size)[::-1]
print("size " + str(size))
print("a " + str(a))
print(binA)
print("b " + str(b))
print(binB)
# a = 3,2,1,0
for i in range(size):
if binA[i] == "1":
qc.append(cirq.X(qubits[i]))
# b = 8,7,6,5,4
for i in range(size):
if binB[i] == "1":
qc.append(cirq.X(qubits[i+size]))
# carry = 12,11,10,9
qc.append(cirq.measure(*qubits[0:3*size+1], key='m1'))
qc.append(VBE_Adder(size, qubits[0:3*size+1]))
qc.append(cirq.measure(*qubits[0:3*size+1], key='m2'))
simulator = cirq.Simulator()
results = simulator.run(qc , repetitions =1)
first_set = np.array2string(results.measurements['m1'][0], separator='')[1:-1][::-1]
second_set = np.array2string(results.measurements['m2'][0], separator='')[1:-1][::-1]
a = int(first_set[2*size + 1: 3*size + 1],2)
b = int(first_set[size: 2*size + 1],2)
bout = int(second_set[size: 2*size + 1],2)
carry = int(second_set[0: size],2)
print('a = ' + str(a))
print('b = ' + str(b))
print('b out = ' + str(bout))
print('\n\n')
assert(a+b == bout)
assert(carry == 0)
@given(draw_pair_of_ints())
@settings(deadline=None)
def test_subtract_using_VBE_Adder_inverse(vals):
a = vals[0]
b = vals[1]
size = vals[2]
qubits = cirq.LineQubit.range(3*size + 1)
qc = cirq.Circuit()
binA = bin(a)[2:].zfill(size)[::-1]
binB = bin(b)[2:].zfill(size)[::-1]
print("size " + str(size))
print("a " + str(a))
print(binA)
print("b " + str(b))
print(binB)
# a = 3,2,1,0
for i in range(size):
if binA[i] == "1":
qc.append(cirq.X(qubits[i]))
# b = 8,7,6,5,4
for i in range(size):
if binB[i] == "1":
qc.append(cirq.X(qubits[i+size]))
# carry = 12,11,10,9
qc.append(cirq.measure(*qubits[0:3*size+1], key='m1'))
qc.append(cirq.inverse(VBE_Adder(size,qubits[0:3*size+1])))
qc.append(cirq.measure(*qubits[0:3*size+1], key='m2'))
simulator = cirq.Simulator()
results = simulator.run(qc , repetitions =1)
first_set = np.array2string(results.measurements['m1'][0], separator='')[1:-1][::-1]
second_set = np.array2string(results.measurements['m2'][0], separator='')[1:-1][::-1]
a = int(first_set[2*size + 1: 3*size + 1],2)
b = int(first_set[size: 2*size + 1],2)
if (b < a):
bout = twos_comp_to_int(second_set[size: 2*size + 1])
else:
bout = int(second_set[size: 2*size + 1],2)
carry = int(second_set[0: size],2)
print('a = ' + str(a))
print('b = ' + str(b))
print('b out = ' + str(bout))
print('\n\n')
assert(b-a == bout)
assert(carry == 0)
if __name__ == '__main__':
#test_shors_with_postpro()
#test_modular_exponentiation()
#test_modular_multiplier_then_inverse_returns_original_values()
test_modular_multiplier()
#test_modular_adder()
#test_add_using_VBE_Adder()
#test_subtract_using_VBE_Adder_inverse()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.algorithms import AmplificationProblem
# the state we desire to find is '11'
good_state = ['11']
# specify the oracle that marks the state '11' as a good solution
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
# define Grover's algorithm
problem = AmplificationProblem(oracle, is_good_state=good_state)
# now we can have a look at the Grover operator that is used in running the algorithm
# (Algorithm circuits are wrapped in a gate to appear in composition as a block
# so we have to decompose() the op to see it expanded into its component gates.)
problem.grover_operator.decompose().draw(output='mpl')
from qiskit.algorithms import Grover
from qiskit.primitives import Sampler
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Result type:', type(result))
print()
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
from qiskit.quantum_info import Statevector
oracle = Statevector.from_label('11')
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Result type:', type(result))
print()
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
problem.grover_operator.oracle.decompose().draw(output='mpl')
from qiskit.circuit.library.phase_oracle import PhaseOracle
from qiskit.exceptions import MissingOptionalLibraryError
# `Oracle` (`PhaseOracle`) as the `oracle` argument
expression = '(a & b)'
try:
oracle = PhaseOracle(expression)
problem = AmplificationProblem(oracle)
display(problem.grover_operator.oracle.decompose().draw(output='mpl'))
except MissingOptionalLibraryError as ex:
print(ex)
import numpy as np
# Specifying `state_preparation`
# to prepare a superposition of |01>, |10>, and |11>
oracle = QuantumCircuit(3)
oracle.ccz(0, 1, 2)
theta = 2 * np.arccos(1 / np.sqrt(3))
state_preparation = QuantumCircuit(3)
state_preparation.ry(theta, 0)
state_preparation.ch(0,1)
state_preparation.x(1)
state_preparation.h(2)
# we only care about the first two bits being in state 1, thus add both possibilities for the last qubit
problem = AmplificationProblem(oracle, state_preparation=state_preparation, is_good_state=['110', '111'])
# state_preparation
print('state preparation circuit:')
problem.grover_operator.state_preparation.draw(output='mpl')
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
oracle = QuantumCircuit(5)
oracle.ccz(0, 1, 2)
oracle.draw(output='mpl')
from qiskit.circuit.library import GroverOperator
grover_op = GroverOperator(oracle, insert_barriers=True)
grover_op.decompose().draw(output='mpl')
grover_op = GroverOperator(oracle, reflection_qubits=[0, 1, 2], insert_barriers=True)
grover_op.decompose().draw(output='mpl')
# a list of binary strings good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = ['11', '00']
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# a list of integer good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = [0, 1]
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
from qiskit.quantum_info import Statevector
# `Statevector` good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = Statevector.from_label('11')
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# Callable good state
def callable_good_state(bitstr):
if bitstr == "11":
return True
return False
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# integer iteration
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=1)
# list iteration
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=[1, 2, 3])
# using sample_from_iterations
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=[1, 2, 3], sample_from_iterations=True)
iterations = Grover.optimal_num_iterations(num_solutions=1, num_qubits=8)
iterations
def to_DIAMACS_CNF_format(bit_rep):
return [index+1 if val==1 else -1 * (index + 1) for index, val in enumerate(bit_rep)]
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'], post_processing=to_DIAMACS_CNF_format)
problem.post_processing([1, 0, 1])
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Soumyo2121/Basic-Quantum-Algorithms
|
Soumyo2121
|
from qiskit import *
from qiskit.visualization import plot_histogram
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.measure([0,1,2],[0,1,2])
qc.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 1024).result()
plot_histogram(result.get_counts(qc))
from qiskit import IBMQ
IBMQ.save_account('a9783f33a64e88d038689c3d3a67cb4235d7715268ca95f986cf1e3e514cd601c77d52d8d8cffda397c63ad4f4cd488a6e907452415bf854dd028ae21c78c927')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
device = provider.get_backend('ibmqx2')
job = execute(qc, backend = device, shots = 1024)
print(job.job_id())
from qiskit.tools.monitor import job_monitor
job_monitor(job)
device_result = job.result()
plot_histogram(device_result.get_counts(qc))
from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter)
cal_circuits, state_labels = complete_meas_cal(qr = qc.qregs[0], circlabel = 'measerrormitigationcal')
cal_circuits[2].draw('mpl')
len(cal_circuits)
cal_job = execute(cal_circuits, backend = device, shots = 1024, optimization_level = 0)
print(cal_job.job_id())
job_monitor(cal_job)
cal_results = cal_job.result()
plot_histogram(cal_results.get_counts(cal_circuits[3]))
meas_fitter = CompleteMeasFitter(cal_results, state_labels)
meas_fitter.plot_calibration()
meas_filter = meas_fitter.filter
mitigated_result = meas_filter.apply(device_result)
device_counts = device_result.get_counts(qc)
mitigated_counts = mitigated_result.get_counts(qc)
plot_histogram([device_counts,mitigated_counts], legend = ['device, noisy', 'device,mitigated'])
circuit = QuantumCircuit(3,3)
circuit.x(1)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(1,2)
circuit.measure([0,1,2],[0,1,2])
circuit.draw('mpl')
plot_histogram(execute(circuit, backend = simulator, shots = 1024).result().get_counts(circuit))
device_counts_1 = execute(circuit, backend = device,shots = 1024).result().get_counts(circuit)
plot_histogram(device_counts_1)
device_mitigated_counts_1 = meas_filter.apply(device_counts_1)
plot_histogram(device_mitigated_counts_1)
|
https://github.com/bagmk/qiskit-quantum-state-classifier
|
bagmk
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import numpy as np
import time
import copy
from qiskit import transpile
def circuit_builder(Circuit, q_list, state_1, state_2):
if state_1 == "GHZ":
Circuit.h(q_list[0])
Circuit.cx(q_list[0],q_list[1])
Circuit.cx(q_list[1],q_list[2])
elif state_1[0] == "W":
Circuit.x(q_list[2])
Circuit.ry(-0.955316618124509, q_list[1])
Circuit.cz(q_list[2],q_list[1])
Circuit.ry(0.955316618124509, q_list[1])
Circuit.ry(-np.pi/4, q_list[0])
Circuit.cz(q_list[1],q_list[0])
Circuit.ry(np.pi/4, q_list[0])
Circuit.cx(q_list[0],q_list[1])
Circuit.cx(q_list[0],q_list[2])
Circuit.cx(q_list[1],q_list[2])
if state_1[1:] == "bar":
Circuit.x(q_list[0])
Circuit.x(q_list[1])
Circuit.x(q_list[2])
# common for Phi+ and Phi+ states:
Circuit.h(q_list[3])
Circuit.cx(q_list[3],q_list[4])
if state_2 == "Psi+":
Circuit.x(q_list[4])
return Circuit
def add_barrier_and_measure(Circuit, q_list):
Circuit.barrier()
Circuit.measure(q_list,q_list)
return Circuit
def prepare_circuits(qubit_list,cqi_list, circ_ori, nb_trials, level, seed_trans, device, coupling_map, nb_id_gates=0, verbose=False):
#version with a limit of trials
start_time = time.strftime('%d/%m/%Y %H:%M:%S')
print("Start at DMY: ",start_time)
summary_dic = {}
for cqi in cqi_list:
circuit = copy.deepcopy(circ_ori[cqi])
if nb_id_gates > 0:
circuit.barrier()
for id_nb_id_gates in range(nb_id_gates):
for index, value in enumerate(qubit_list):
circuit.id(value)
add_barrier_and_measure(circuit, qubit_list)
summary = []
depth_list = []
count_run = 0
max_count_run = nb_trials * 3
break_flag = False
for j in range(nb_trials):
if seed_trans != None:
seed_transpiler=seed_trans[j*len(cqi_list)+1]
else:
seed_transpiler = None
new_depth = 0
while not break_flag and (new_depth == 0 or depth_list.count(new_depth) != 0):
Q_state_opt_new = transpile(circuit, backend=device,
coupling_map = coupling_map,
seed_transpiler=seed_transpiler,
optimization_level=level,
initial_layout=qubit_list)
new_depth = Q_state_opt_new.depth()
if count_run == 0:
to_insert = {"depth": new_depth, 'circuit':Q_state_opt_new}
count_run += 1
if count_run == max_count_run:
break_flag = True
if not break_flag:
depth_list.append(new_depth)
summary.append({"depth": new_depth, 'circuit':Q_state_opt_new})
if break_flag:
len_list = len(depth_list)
for i_trial in range(nb_trials - len_list):
summary.insert(0, to_insert)
break
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
if verbose:
print("%2i" % cqi,"DMY: ",time_exp)
summary_dic[cqi] = summary
end_time = time.strftime('%d/%m/%Y %H:%M:%S')
print("Completed at DMY: ",end_time)
return summary_dic
|
https://github.com/codigoscupom/QuantumAlgs
|
codigoscupom
|
import numpy as np
from qiskit import *
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
# circ.draw('mpl')
|
https://github.com/apcarrik/qiskit-dev
|
apcarrik
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from matplotlib import pyplot
### Drawing a Quantum Circuit
# Build a quantum circuit
circuit = QuantumCircuit(3,3)
circuit.x(1)
circuit.h(range(3))
circuit.cx(0,1)
circuit.measure(range(3), range(3))
# Print ASCII art version of circuit diagram to stdout
print(circuit)
### Alternative Renderers for Circuits
# Create matplotlib circuit diagram
circuit.draw('mpl')
pyplot.show()
# # Create matplotlib circuit diagram
# circuit.draw('latex')
# # TODO: this does not work - need to figure out why
### Customizing the Output
# Draw a new circuit with barriers and more registers
q_a = QuantumRegister(3, name='qa')
q_b = QuantumRegister(5, name='qb')
c_a = ClassicalRegister(3)
c_b = ClassicalRegister(5)
circuit = QuantumCircuit(q_a, q_b, c_a, c_b)
circuit.x(q_a[1])
circuit.x(q_b[1])
circuit.x(q_b[2])
circuit.x(q_b[4])
circuit.barrier()
circuit.h(q_a)
circuit.barrier(q_a)
circuit.h(q_b)
circuit.cswap(q_b[0], q_b[1], q_b[2])
circuit.cswap(q_b[2], q_b[3], q_b[4])
circuit.cswap(q_b[3], q_b[4], q_b[0])
circuit.barrier(q_b)
circuit.measure(q_a, c_a)
circuit.measure(q_b, c_b)
# Draw the circuit
circuit.draw('mpl')
pyplot.show()
# Draw the circuit with reversed bit order
circuit.draw('mpl', reverse_bits=True)
pyplot.show()
# Draw the circuit without barriers
circuit.draw('mpl', plot_barriers=False)
pyplot.show()
### Backend-specific Customizations
# Set the line length to 80 for above circuit
print(circuit)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circuit.draw('mpl', style=style)
pyplot.show()
# Scale the mpl output to 1/2 the normal size
circuit.draw('mpl', scale=0.5)
pyplot.show()
### Display using circuit_drawer() as function
from qiskit.tools.visualization import circuit_drawer
circuit_drawer(circuit, output='mpl', plot_barriers=False)
|
https://github.com/QC-Hub/Examples
|
QC-Hub
|
import matplotlib.pyplot as plt
import numpy as np
from math import pi
from qiskit import QuantumCircuit ,QuantumRegister ,ClassicalRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.u3(pi/2 ,pi/2 ,pi/2 ,q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This program realises the quantum k-means algorithm
'''
import numpy as np
from qiskit import *
from qiskit.tools.visualization import plot_histogram
from matplotlib.pyplot import plot, draw, show
circuit_name = 'k_means'
backend = Aer.get_backend('qasm_simulator')
theta_list = [0.01, 0.02, 0.03, 0.04, 0.05,
1.31, 1.32, 1.33, 1.34, 1.35]
qr = QuantumRegister(5,'q')
cr = ClassicalRegister(5, 'c')
qc = QuantumCircuit(qr, cr, name=circuit_name)
# define a loop to compute the distance between each pair of points
for i in range(len(theta_list)-1):
for j in range(1,len(theta_list)-i):
# set the parameters theta about different points
theta_1 = theta_list[i]
theta_2 = theta_list[i+j]
qc.h(qr[2])
qc.h(qr[1])
qc.h(qr[4])
qc.u3(theta_1, np.pi, np.pi, qr[1])
qc.u3(theta_2, np.pi, np.pi, qr[4])
qc.cswap(qr[2], qr[1], qr[4])
qc.h(qr[2])
qc.measure(qr[2], cr[2])
qc.reset(qr)
job = execute(qc, backend=backend, shots=1024)
result = job.result()
print(result.get_counts())
print('theta_1: ', theta_1, '\t', 'theta_2: ', theta_2)
plot_histogram(result.get_counts())
|
https://github.com/GyeonghunKim/2022-Feb-Qiskit-Metal-Study
|
GyeonghunKim
|
%load_ext autoreload
%autoreload 2
import numpy as np
import qiskit_metal as metal
from qiskit_metal import designs, draw
from qiskit_metal import MetalGUI, Dict, open_docs
%metal_heading Welcome to Qiskit Metal Study!
# To start qiskit-metal, you have to create instance of below two.
# After runing this cell, metal gui will appear.
design = designs.DesignPlanar()
gui = MetalGUI(design)
# If you delete all components in the current design, you can use delete_all_components method.
design.delete_all_components()
# To apply changes in design instance to your gui, you can use rebuild method in gui.
gui.rebuild()
# You can import templated qubit class from qiskit_metal.qlibrary.qubits.
# For transmon pocket,
from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket
# For most simplest case, you can create TransmonPocket instance with default options as below.
# Methods for creating QComponent with options will be explained in the section 2.4
# Please ignore warnings here. These are caused by Shapely's future update, and would not make any troubles now.
q1 = TransmonPocket(design, 'Q1')
gui.rebuild()
# If you call TransmonPocket instance, you can see the parameters of it.
q1
# Above options are same with TransmonPocket's default option
TransmonPocket.default_options
# If you want to change parameters of Transmon qubit,
# you can simply change the parameters in the q1.options as below
q1.options.pos_x = '2.0 mm' # Note that if you don't input the unit here, default length unit is mm not um.
q1.options.pos_y = '2.0 mm'
q1.options.pad_height = '250 um'
q1.options.pad_width = '300 um'
# By rebuilding gui, you can check the parameters are changed.
gui.rebuild()
# In many cases, copying QComponents is very useful.
# To copy single QComponent, you can use copy_qcomponent method for design instance.
q2 = design.copy_qcomponent(q1, 'Q2')
# If you want to change parameters for copyed object, you can do it with two different way.
# First method is same with above explained changing parameters.
q2.options.pos_x = '-2.0mm'
gui.rebuild()
# By runing below, you can automatly scale the gui.
gui.autoscale()
# Second method is giving options to the copy_qcomponent as below.
q3 = design.copy_qcomponent(q1, 'Q3', dict(pos_x='-4.0mm'))
# If you want to copy multiple qcomponent, you can use below method.
newcopies = design.copy_multiple_qcomponents([q1, q2], ['Q3', 'Q4'], [dict(pos_y='-2.0mm'), dict(pos_y='-2.0mm')])
gui.rebuild()
gui.autoscale()
design.delete_all_components()
gui.rebuild()
# To create Transmon Qubit with option, the only thing you have to do is
# creating dictionary of options and give it as a input when you create TransmonPocket instance.
# You can give options directly, without create dictionary as variable, like below,
# Adding connection pads also can be done by add "connection_pads" in your option dictionary as below.
q1 = TransmonPocket(design, 'Q1',
options = dict(
pos_x='-1.5mm',
pos_y='+0.0mm',
pad_width = '425 um',
pocket_height = '650um',
connection_pads = dict(
a = dict(loc_W=+1,loc_H=+1), # (low_W, low_H) = (1, 1) => First Quadrant
b = dict(loc_W=-1,loc_H=+1, pad_height='30um'), # (low_W, low_H) = (-1, 1) => Second Quadrant
c = dict(loc_W=+1,loc_H=-1, pad_width='200um'), # (low_W, low_H) = (1, -1) => Fourth Quadrant
d = dict(loc_W=-1,loc_H=-1, pad_height='50um') # (low_W, low_H) = (-1, -1) => Third Quadrant
) # Note that connection_pads have two geometrical options pad_height and pad_weight.
# You can modify those values from default, by add them in option as above.
)
)
gui.rebuild()
design.delete_all_components()
gui.rebuild()
# I prefer below method, which is very convenient for reusing the parameters.
optionsQ = dict(
pad_width = '425 um',
pocket_height = '650um',
connection_pads = dict( # Qbits defined to have 4 pins
a = dict(loc_W=+1,loc_H=+1),
b = dict(loc_W=-1,loc_H=+1, pad_height='30um'),
c = dict(loc_W=+1,loc_H=-1, pad_width='200um'),
d = dict(loc_W=-1,loc_H=-1, pad_height='50um')
)
)
q1 = TransmonPocket(design, 'Q1', options = dict(pos_x='-1.5mm', pos_y='+0.0mm', **optionsQ))
q2 = TransmonPocket(design, 'Q2', options = dict(pos_x='+0.35mm', pos_y='+1.0mm', orientation = '90',**optionsQ))
q3 = TransmonPocket(design, 'Q3', options = dict(pos_x='2.0mm', pos_y='+0.0mm', **optionsQ))
gui.rebuild()
gui.autoscale()
gui.highlight_components(['Q1', 'Q2', 'Q3']) # This is to show the pins, so we can choose what to connect
gui.rebuild()
gui.autoscale()
# You can import RouteMeander class as below
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
# Same with TransmonPocket, it also have its default options
RouteMeander.get_template_options(design)
# Connecting two TransmonPocket with RouteMinder is very easy.
# It can be done by setting start_pin and end_pin in option as below
ops=dict(fillet='90um')
options = Dict(
total_length= '8mm', # This parameter is key parameter for changing resonant frequency
hfss_wire_bonds = True,
pin_inputs=Dict(
start_pin=Dict(
component= 'Q1', # Start component Name
pin= 'a'), # Start Pin in component
end_pin=Dict(
component= 'Q2',
pin= 'b')),
lead=Dict(
start_straight='0mm', # How long go straight from the starting point
end_straight='0.5mm'), # How long go straight to the end point
meander=Dict(
asymmetry='-1mm'),
**ops # Remark that this syntax usually used for reusing options.
)
cpw = RouteMeander(design, options=options)
gui.rebuild()
gui.autoscale()
cpw.options.lead.start_straight='100um'
gui.rebuild()
gui.autoscale()
cpw.options['fillet']='30um'
gui.rebuild()
gui.autoscale()
from collections import OrderedDict
jogs = OrderedDict()
jogs[0] = ["L", '800um']
jogs[1] = ["L", '500um']
jogs[2] = ["R", '200um']
jogs[3] = ["R", '500um']
options = Dict(
total_length= '14mm',
pin_inputs=Dict(
start_pin=Dict(
component= 'Q1',
pin= 'd'),
end_pin=Dict(
component= 'Q3',
pin= 'd')),
lead=Dict(
start_straight='0.1mm',
end_straight='0.1mm',
start_jogged_extension=jogs,
end_jogged_extension=jogs),
meander=Dict(
asymmetry='-1.2mm'),
**ops
)
try:
cpw5.delete()
except NameError: pass
cpw5 = RouteMeander(design,options=options)
gui.rebuild()
gui.autoscale()
# Before showing examples of anchors, I will reset design and add some new transmon pockets.
design.delete_all_components()
gui.rebuild()
options = dict(
pad_width = '425 um',
pocket_height = '650um',
connection_pads=dict( # pin connectors
a = dict(loc_W=+1,loc_H=+1),
b = dict(loc_W=-1,loc_H=+1, pad_height='30um'),
c = dict(loc_W=+1,loc_H=-1, pad_width='200um'),
d = dict(loc_W=-1,loc_H=-1, pad_height='50um')
)
)
q0 = TransmonPocket(design, 'Q0', options = dict(pos_x='-1.0mm', pos_y='-1.0mm', **options))
q1 = TransmonPocket(design, 'Q1', options = dict(pos_x='1.0mm', pos_y='+0.0mm', **options))
gui.rebuild()
gui.autoscale()
# You can import RoutePathfinder as below
from qiskit_metal.qlibrary.tlines.pathfinder import RoutePathfinder
from collections import OrderedDict
# You should add anchors in OrderedDict because the order in anchors are very important.
anchors = OrderedDict()
anchors[0] = np.array([-0.452, -0.555])
anchors[1] = np.array([-0.452, -1.5])
anchors[2] = np.array([0.048, -1.5])
options = {'pin_inputs':
{'start_pin': {'component': 'Q0', 'pin': 'b'},
'end_pin': {'component': 'Q1', 'pin': 'b'}},
'lead': {'start_straight': '91um', 'end_straight': '95um'},
'step_size': '0.25mm',
'anchors': anchors,
**ops
}
qa = RoutePathfinder(design, 'line', options)
gui.rebuild()
gui.autoscale()
|
https://github.com/MuhammadMiqdadKhan/Improvement-of-Quantum-Circuits-Using-H-U-H-Sandwich-Technique-with-Diagonal-Matrix-Implementation
|
MuhammadMiqdadKhan
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(2)
print(u)
qc = QuantumCircuit(2)
qc.iso(u, [0], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(2)
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (2):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(2)
qc.diagonal(c2, [0])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(4)
print(u)
qc = QuantumCircuit(4)
qc.iso(u, [0,1], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(4)/2
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (4):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(4)
qc.diagonal(c2, [0, 1])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(8)
print(u)
qc = QuantumCircuit(4)
qc.iso(u, [0, 1, 2], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(8)/3
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (8):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(4)
qc.diagonal(c2, [0, 1, 2])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(16)
print(u)
qc = QuantumCircuit(4)
qc.iso(u, [0, 1, 2, 3], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(16)/4
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (16):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(4)
qc.diagonal(c2, [0, 1, 2, 3])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(32)
print(u)
qc = QuantumCircuit(8)
qc.iso(u, [0, 1, 2, 3, 4], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(32)/5
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (32):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(8)
qc.diagonal(c2, [0, 1, 2, 3, 4])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(64)
print(u)
qc = QuantumCircuit(8)
qc.iso(u, [0, 1, 2, 3, 4, 5], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(64)/6
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (64):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(8)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(128)
print(u)
qc = QuantumCircuit(8)
qc.iso(u, [0, 1, 2, 3, 4, 5, 6], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(128)/7
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (128):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(8)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(256)
print(u)
qc = QuantumCircuit(8)
qc.iso(u, [0, 1, 2, 3, 4, 5, 6, 7], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(256)/8
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (256):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(8)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6, 7])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(512)
print(u)
qc = QuantumCircuit(16)
qc.iso(u, [0, 1, 2, 3, 4, 5, 6, 7, 8], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(512)/9
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (512):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(16)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6, 7, 8])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(1024)
print(u)
qc = QuantumCircuit(16)
qc.iso(u, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(1024)/10
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (1024):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(16)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import transpile
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc_basis = transpile(qc, backend)
qc_basis.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator
from qiskit.transpiler.passes import UnitarySynthesis
circuit = QuantumCircuit(1)
circuit.rx(0.8, 0)
unitary = Operator(circuit).data
unitary_circ = QuantumCircuit(1)
unitary_circ.unitary(unitary, [0])
synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk")
out = synth(unitary_circ)
out.draw('mpl')
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the TemplateOptimization pass."""
import unittest
from test.python.quantum_info.operators.symplectic.test_clifford import random_clifford_circuit
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.quantum_info import Operator
from qiskit.circuit.library.templates.nct import template_nct_2a_2, template_nct_5a_3
from qiskit.circuit.library.templates.clifford import (
clifford_2_1,
clifford_2_2,
clifford_2_3,
clifford_2_4,
clifford_3_1,
clifford_4_1,
clifford_4_2,
)
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.converters.circuit_to_dagdependency import circuit_to_dagdependency
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import TemplateOptimization
from qiskit.transpiler.passes.calibration.rzx_templates import rzx_templates
from qiskit.test import QiskitTestCase
from qiskit.transpiler.exceptions import TranspilerError
def _ry_to_rz_template_pass(parameter: Parameter = None, extra_costs=None):
"""Create a simple pass manager that runs a template optimisation with a single transformation.
It turns ``RX(pi/2).RY(parameter).RX(-pi/2)`` into the equivalent virtual ``RZ`` rotation, where
if ``parameter`` is given, it will be the instance used in the template."""
if parameter is None:
parameter = Parameter("_ry_rz_template_inner")
template = QuantumCircuit(1)
template.rx(-np.pi / 2, 0)
template.ry(parameter, 0)
template.rx(np.pi / 2, 0)
template.rz(-parameter, 0) # pylint: disable=invalid-unary-operand-type
costs = {"rx": 16, "ry": 16, "rz": 0}
if extra_costs is not None:
costs.update(extra_costs)
return PassManager(TemplateOptimization([template], user_cost_dict=costs))
class TestTemplateMatching(QiskitTestCase):
"""Test the TemplateOptimization pass."""
def test_pass_cx_cancellation_no_template_given(self):
"""
Check the cancellation of CX gates for the apply of the three basic
template x-x, cx-cx. ccx-ccx.
"""
qr = QuantumRegister(3)
circuit_in = QuantumCircuit(qr)
circuit_in.h(qr[0])
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[1], qr[0])
circuit_in.cx(qr[1], qr[0])
pass_manager = PassManager()
pass_manager.append(TemplateOptimization())
circuit_in_opt = pass_manager.run(circuit_in)
circuit_out = QuantumCircuit(qr)
circuit_out.h(qr[0])
circuit_out.h(qr[0])
self.assertEqual(circuit_in_opt, circuit_out)
def test_pass_cx_cancellation_own_template(self):
"""
Check the cancellation of CX gates for the apply of a self made template cx-cx.
"""
qr = QuantumRegister(2, "qr")
circuit_in = QuantumCircuit(qr)
circuit_in.h(qr[0])
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[1], qr[0])
circuit_in.cx(qr[1], qr[0])
dag_in = circuit_to_dag(circuit_in)
qrt = QuantumRegister(2, "qrc")
qct = QuantumCircuit(qrt)
qct.cx(0, 1)
qct.cx(0, 1)
template_list = [qct]
pass_ = TemplateOptimization(template_list)
dag_opt = pass_.run(dag_in)
circuit_expected = QuantumCircuit(qr)
circuit_expected.h(qr[0])
circuit_expected.h(qr[0])
dag_expected = circuit_to_dag(circuit_expected)
self.assertEqual(dag_opt, dag_expected)
def test_pass_cx_cancellation_template_from_library(self):
"""
Check the cancellation of CX gates for the apply of the library template cx-cx (2a_2).
"""
qr = QuantumRegister(2, "qr")
circuit_in = QuantumCircuit(qr)
circuit_in.h(qr[0])
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[1], qr[0])
circuit_in.cx(qr[1], qr[0])
dag_in = circuit_to_dag(circuit_in)
template_list = [template_nct_2a_2()]
pass_ = TemplateOptimization(template_list)
dag_opt = pass_.run(dag_in)
circuit_expected = QuantumCircuit(qr)
circuit_expected.h(qr[0])
circuit_expected.h(qr[0])
dag_expected = circuit_to_dag(circuit_expected)
self.assertEqual(dag_opt, dag_expected)
def test_pass_template_nct_5a(self):
"""
Verify the result of template matching and substitution with the template 5a_3.
q_0: ───────■─────────■────■──
┌─┴─┐ ┌─┴─┐ │
q_1: ──■──┤ X ├──■──┤ X ├──┼──
┌─┴─┐└───┘┌─┴─┐└───┘┌─┴─┐
q_2: ┤ X ├─────┤ X ├─────┤ X ├
└───┘ └───┘ └───┘
The circuit before optimization is:
┌───┐ ┌───┐
qr_0: ┤ X ├───────────────┤ X ├─────
└─┬─┘ ┌───┐┌───┐└─┬─┘
qr_1: ──┼────■──┤ X ├┤ Z ├──┼────■──
│ │ └─┬─┘└───┘ │ │
qr_2: ──┼────┼────■────■────■────┼──
│ │ ┌───┐┌─┴─┐ │ │
qr_3: ──■────┼──┤ H ├┤ X ├──■────┼──
│ ┌─┴─┐└───┘└───┘ ┌─┴─┐
qr_4: ──■──┤ X ├───────────────┤ X ├
└───┘ └───┘
The match is given by [0,1][1,2][2,7], after substitution the circuit becomes:
┌───┐ ┌───┐
qr_0: ┤ X ├───────────────┤ X ├
└─┬─┘ ┌───┐┌───┐└─┬─┘
qr_1: ──┼───────┤ X ├┤ Z ├──┼──
│ └─┬─┘└───┘ │
qr_2: ──┼────■────■────■────■──
│ │ ┌───┐┌─┴─┐ │
qr_3: ──■────┼──┤ H ├┤ X ├──■──
│ ┌─┴─┐└───┘└───┘
qr_4: ──■──┤ X ├───────────────
└───┘
"""
qr = QuantumRegister(5, "qr")
circuit_in = QuantumCircuit(qr)
circuit_in.ccx(qr[3], qr[4], qr[0])
circuit_in.cx(qr[1], qr[4])
circuit_in.cx(qr[2], qr[1])
circuit_in.h(qr[3])
circuit_in.z(qr[1])
circuit_in.cx(qr[2], qr[3])
circuit_in.ccx(qr[2], qr[3], qr[0])
circuit_in.cx(qr[1], qr[4])
dag_in = circuit_to_dag(circuit_in)
template_list = [template_nct_5a_3()]
pass_ = TemplateOptimization(template_list)
dag_opt = pass_.run(dag_in)
# note: cx(2, 1) commutes both with ccx(3, 4, 0) and with cx(2, 4),
# so there is no real difference with the circuit drawn on the picture above.
circuit_expected = QuantumCircuit(qr)
circuit_expected.cx(qr[2], qr[1])
circuit_expected.ccx(qr[3], qr[4], qr[0])
circuit_expected.cx(qr[2], qr[4])
circuit_expected.z(qr[1])
circuit_expected.h(qr[3])
circuit_expected.cx(qr[2], qr[3])
circuit_expected.ccx(qr[2], qr[3], qr[0])
dag_expected = circuit_to_dag(circuit_expected)
self.assertEqual(dag_opt, dag_expected)
def test_pass_template_wrong_type(self):
"""
If a template is not equivalent to the identity, it raises an error.
"""
qr = QuantumRegister(2, "qr")
circuit_in = QuantumCircuit(qr)
circuit_in.h(qr[0])
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[1], qr[0])
circuit_in.cx(qr[1], qr[0])
dag_in = circuit_to_dag(circuit_in)
qrt = QuantumRegister(2, "qrc")
qct = QuantumCircuit(qrt)
qct.cx(0, 1)
qct.x(0)
qct.h(1)
template_list = [qct]
pass_ = TemplateOptimization(template_list)
self.assertRaises(TranspilerError, pass_.run, dag_in)
def test_accept_dagdependency(self):
"""
Check that users can supply DAGDependency in the template list.
"""
circuit_in = QuantumCircuit(2)
circuit_in.cnot(0, 1)
circuit_in.cnot(0, 1)
templates = [circuit_to_dagdependency(circuit_in)]
pass_ = TemplateOptimization(template_list=templates)
circuit_out = PassManager(pass_).run(circuit_in)
# these are NOT equal if template optimization works
self.assertNotEqual(circuit_in, circuit_out)
# however these are equivalent if the operators are the same
self.assertTrue(Operator(circuit_in).equiv(circuit_out))
def test_parametric_template(self):
"""
Check matching where template has parameters.
┌───────────┐ ┌────────┐
q_0: ┤ P(-1.0*β) ├──■────────────■──┤0 ├
├───────────┤┌─┴─┐┌──────┐┌─┴─┐│ CU(2β)│
q_1: ┤ P(-1.0*β) ├┤ X ├┤ P(β) ├┤ X ├┤1 ├
└───────────┘└───┘└──────┘└───┘└────────┘
First test try match on
┌───────┐
q_0: ┤ P(-2) ├──■────────────■─────────────────────────────
├───────┤┌─┴─┐┌──────┐┌─┴─┐┌───────┐
q_1: ┤ P(-2) ├┤ X ├┤ P(2) ├┤ X ├┤ P(-3) ├──■────────────■──
├───────┤└───┘└──────┘└───┘└───────┘┌─┴─┐┌──────┐┌─┴─┐
q_2: ┤ P(-3) ├───────────────────────────┤ X ├┤ P(3) ├┤ X ├
└───────┘ └───┘└──────┘└───┘
Second test try match on
┌───────┐
q_0: ┤ P(-2) ├──■────────────■────────────────────────────
├───────┤┌─┴─┐┌──────┐┌─┴─┐┌──────┐
q_1: ┤ P(-2) ├┤ X ├┤ P(2) ├┤ X ├┤ P(3) ├──■────────────■──
└┬──────┤└───┘└──────┘└───┘└──────┘┌─┴─┐┌──────┐┌─┴─┐
q_2: ─┤ P(3) ├──────────────────────────┤ X ├┤ P(3) ├┤ X ├
└──────┘ └───┘└──────┘└───┘
"""
beta = Parameter("β")
template = QuantumCircuit(2)
template.p(-beta, 0)
template.p(-beta, 1)
template.cx(0, 1)
template.p(beta, 1)
template.cx(0, 1)
template.cu(0, 2.0 * beta, 0, 0, 0, 1)
def count_cx(qc):
"""Counts the number of CX gates for testing."""
return qc.count_ops().get("cx", 0)
circuit_in = QuantumCircuit(3)
circuit_in.p(-2, 0)
circuit_in.p(-2, 1)
circuit_in.cx(0, 1)
circuit_in.p(2, 1)
circuit_in.cx(0, 1)
circuit_in.p(-3, 1)
circuit_in.p(-3, 2)
circuit_in.cx(1, 2)
circuit_in.p(3, 2)
circuit_in.cx(1, 2)
pass_ = TemplateOptimization(
template_list=[template],
user_cost_dict={"cx": 6, "p": 0, "cu": 8},
)
circuit_out = PassManager(pass_).run(circuit_in)
np.testing.assert_almost_equal(Operator(circuit_out).data[3, 3], np.exp(-4.0j))
np.testing.assert_almost_equal(Operator(circuit_out).data[7, 7], np.exp(-10.0j))
self.assertEqual(count_cx(circuit_out), 0) # Two matches => no CX gates.
np.testing.assert_almost_equal(Operator(circuit_in).data, Operator(circuit_out).data)
circuit_in = QuantumCircuit(3)
circuit_in.p(-2, 0)
circuit_in.p(-2, 1)
circuit_in.cx(0, 1)
circuit_in.p(2, 1)
circuit_in.cx(0, 1)
circuit_in.p(3, 1)
circuit_in.p(3, 2)
circuit_in.cx(1, 2)
circuit_in.p(3, 2)
circuit_in.cx(1, 2)
pass_ = TemplateOptimization(
template_list=[template],
user_cost_dict={"cx": 6, "p": 0, "cu": 8},
)
circuit_out = PassManager(pass_).run(circuit_in)
# these are NOT equal if template optimization works
self.assertNotEqual(circuit_in, circuit_out)
# however these are equivalent if the operators are the same
self.assertTrue(Operator(circuit_in).equiv(circuit_out))
def test_optimizer_does_not_replace_unbound_partial_match(self):
"""
Test that partial matches with parameters will not raise errors.
This tests that if parameters are still in the temporary template after
_attempt_bind then they will not be used.
"""
beta = Parameter("β")
template = QuantumCircuit(2)
template.cx(1, 0)
template.cx(1, 0)
template.p(beta, 1)
template.cu(0, 0, 0, -beta, 0, 1)
circuit_in = QuantumCircuit(2)
circuit_in.cx(1, 0)
circuit_in.cx(1, 0)
pass_ = TemplateOptimization(
template_list=[template],
user_cost_dict={"cx": 6, "p": 0, "cu": 8},
)
circuit_out = PassManager(pass_).run(circuit_in)
# The template optimisation should not have replaced anything, because
# that would require it to leave dummy parameters in place without
# binding them.
self.assertEqual(circuit_in, circuit_out)
def test_unbound_parameters_in_rzx_template(self):
"""
Test that rzx template ('zz2') functions correctly for a simple
circuit with an unbound ParameterExpression. This uses the same
Parameter (theta) as the template, so this also checks that template
substitution handle this correctly.
"""
theta = Parameter("ϴ")
circuit_in = QuantumCircuit(2)
circuit_in.cx(0, 1)
circuit_in.p(2 * theta, 1)
circuit_in.cx(0, 1)
pass_ = TemplateOptimization(**rzx_templates(["zz2"]))
circuit_out = PassManager(pass_).run(circuit_in)
# these are NOT equal if template optimization works
self.assertNotEqual(circuit_in, circuit_out)
# however these are equivalent if the operators are the same
theta_set = 0.42
self.assertTrue(
Operator(circuit_in.bind_parameters({theta: theta_set})).equiv(
circuit_out.bind_parameters({theta: theta_set})
)
)
def test_two_parameter_template(self):
"""
Test a two-Parameter template based on rzx_templates(["zz3"]),
┌───┐┌───────┐┌───┐┌────────────┐»
q_0: ──■─────────────■──┤ X ├┤ Rz(φ) ├┤ X ├┤ Rz(-1.0*φ) ├»
┌─┴─┐┌───────┐┌─┴─┐└─┬─┘└───────┘└─┬─┘└────────────┘»
q_1: ┤ X ├┤ Rz(θ) ├┤ X ├──■─────────────■────────────────»
└───┘└───────┘└───┘
« ┌─────────┐┌─────────┐┌─────────┐┌───────────┐┌──────────────┐»
«q_0: ┤ Rz(π/2) ├┤ Rx(π/2) ├┤ Rz(π/2) ├┤ Rx(1.0*φ) ├┤1 ├»
« └─────────┘└─────────┘└─────────┘└───────────┘│ Rzx(-1.0*φ) │»
«q_1: ──────────────────────────────────────────────┤0 ├»
« └──────────────┘»
« ┌─────────┐ ┌─────────┐┌─────────┐ »
«q_0: ─┤ Rz(π/2) ├──┤ Rx(π/2) ├┤ Rz(π/2) ├────────────────────────»
« ┌┴─────────┴─┐├─────────┤├─────────┤┌─────────┐┌───────────┐»
«q_1: ┤ Rz(-1.0*θ) ├┤ Rz(π/2) ├┤ Rx(π/2) ├┤ Rz(π/2) ├┤ Rx(1.0*θ) ├»
« └────────────┘└─────────┘└─────────┘└─────────┘└───────────┘»
« ┌──────────────┐
«q_0: ┤0 ├─────────────────────────────────
« │ Rzx(-1.0*θ) │┌─────────┐┌─────────┐┌─────────┐
«q_1: ┤1 ├┤ Rz(π/2) ├┤ Rx(π/2) ├┤ Rz(π/2) ├
« └──────────────┘└─────────┘└─────────┘└─────────┘
correctly template matches into a unique circuit, but that it is
equivalent to the input circuit when the Parameters are bound to floats
and checked with Operator equivalence.
"""
theta = Parameter("θ")
phi = Parameter("φ")
template = QuantumCircuit(2)
template.cx(0, 1)
template.rz(theta, 1)
template.cx(0, 1)
template.cx(1, 0)
template.rz(phi, 0)
template.cx(1, 0)
template.rz(-phi, 0)
template.rz(np.pi / 2, 0)
template.rx(np.pi / 2, 0)
template.rz(np.pi / 2, 0)
template.rx(phi, 0)
template.rzx(-phi, 1, 0)
template.rz(np.pi / 2, 0)
template.rz(-theta, 1)
template.rx(np.pi / 2, 0)
template.rz(np.pi / 2, 1)
template.rz(np.pi / 2, 0)
template.rx(np.pi / 2, 1)
template.rz(np.pi / 2, 1)
template.rx(theta, 1)
template.rzx(-theta, 0, 1)
template.rz(np.pi / 2, 1)
template.rx(np.pi / 2, 1)
template.rz(np.pi / 2, 1)
alpha = Parameter("$\\alpha$")
beta = Parameter("$\\beta$")
circuit_in = QuantumCircuit(2)
circuit_in.cx(0, 1)
circuit_in.rz(2 * alpha, 1)
circuit_in.cx(0, 1)
circuit_in.cx(1, 0)
circuit_in.rz(3 * beta, 0)
circuit_in.cx(1, 0)
pass_ = TemplateOptimization(
[template],
user_cost_dict={"cx": 6, "rz": 0, "rx": 1, "rzx": 0},
)
circuit_out = PassManager(pass_).run(circuit_in)
# these are NOT equal if template optimization works
self.assertNotEqual(circuit_in, circuit_out)
# however these are equivalent if the operators are the same
alpha_set = 0.37
beta_set = 0.42
self.assertTrue(
Operator(circuit_in.bind_parameters({alpha: alpha_set, beta: beta_set})).equiv(
circuit_out.bind_parameters({alpha: alpha_set, beta: beta_set})
)
)
def test_exact_substitution_numeric_parameter(self):
"""Test that a template match produces the expected value for numeric parameters."""
circuit_in = QuantumCircuit(1)
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(1.45, 0)
circuit_in.rx(np.pi / 2, 0)
circuit_out = _ry_to_rz_template_pass().run(circuit_in)
expected = QuantumCircuit(1)
expected.rz(1.45, 0)
self.assertEqual(circuit_out, expected)
def test_exact_substitution_symbolic_parameter(self):
"""Test that a template match produces the expected value for numeric parameters."""
a_circuit = Parameter("a")
circuit_in = QuantumCircuit(1)
circuit_in.h(0)
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(a_circuit, 0)
circuit_in.rx(np.pi / 2, 0)
circuit_out = _ry_to_rz_template_pass(extra_costs={"h": 1}).run(circuit_in)
expected = QuantumCircuit(1)
expected.h(0)
expected.rz(a_circuit, 0)
self.assertEqual(circuit_out, expected)
def test_naming_clash(self):
"""Test that the template matching works and correctly replaces a template if there is a
naming clash between it and the circuit. This should include binding a partial match with a
parameter."""
# Two instances of parameters with the same name---this is how naming clashes might occur.
a_template = Parameter("a")
a_circuit = Parameter("a")
circuit_in = QuantumCircuit(1)
circuit_in.h(0)
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(a_circuit, 0)
circuit_in.rx(np.pi / 2, 0)
circuit_out = _ry_to_rz_template_pass(a_template, extra_costs={"h": 1}).run(circuit_in)
expected = QuantumCircuit(1)
expected.h(0)
expected.rz(a_circuit, 0)
self.assertEqual(circuit_out, expected)
# Ensure that the bound parameter in the output is referentially the same as the one we put
# in the input circuit..
self.assertEqual(len(circuit_out.parameters), 1)
self.assertIs(circuit_in.parameters[0], a_circuit)
self.assertIs(circuit_out.parameters[0], a_circuit)
def test_naming_clash_in_expression(self):
"""Test that the template matching works and correctly replaces a template if there is a
naming clash between it and the circuit. This should include binding a partial match with a
parameter."""
a_template = Parameter("a")
a_circuit = Parameter("a")
circuit_in = QuantumCircuit(1)
circuit_in.h(0)
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(2 * a_circuit, 0)
circuit_in.rx(np.pi / 2, 0)
circuit_out = _ry_to_rz_template_pass(a_template, extra_costs={"h": 1}).run(circuit_in)
expected = QuantumCircuit(1)
expected.h(0)
expected.rz(2 * a_circuit, 0)
self.assertEqual(circuit_out, expected)
# Ensure that the bound parameter in the output is referentially the same as the one we put
# in the input circuit..
self.assertEqual(len(circuit_out.parameters), 1)
self.assertIs(circuit_in.parameters[0], a_circuit)
self.assertIs(circuit_out.parameters[0], a_circuit)
def test_template_match_with_uninvolved_parameter(self):
"""Test that the template matching algorithm succeeds at matching a circuit that contains an
unbound parameter that is not involved in the subcircuit that matches."""
b_circuit = Parameter("b")
circuit_in = QuantumCircuit(2)
circuit_in.rz(b_circuit, 0)
circuit_in.rx(-np.pi / 2, 1)
circuit_in.ry(1.45, 1)
circuit_in.rx(np.pi / 2, 1)
circuit_out = _ry_to_rz_template_pass().run(circuit_in)
expected = QuantumCircuit(2)
expected.rz(b_circuit, 0)
expected.rz(1.45, 1)
self.assertEqual(circuit_out, expected)
def test_multiple_numeric_matches_same_template(self):
"""Test that the template matching will change both instances of a partial match within a
longer circuit."""
circuit_in = QuantumCircuit(2)
# Qubit 0
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(1.32, 0)
circuit_in.rx(np.pi / 2, 0)
# Qubit 1
circuit_in.rx(-np.pi / 2, 1)
circuit_in.ry(2.54, 1)
circuit_in.rx(np.pi / 2, 1)
circuit_out = _ry_to_rz_template_pass().run(circuit_in)
expected = QuantumCircuit(2)
expected.rz(1.32, 0)
expected.rz(2.54, 1)
self.assertEqual(circuit_out, expected)
def test_multiple_symbolic_matches_same_template(self):
"""Test that the template matching will change both instances of a partial match within a
longer circuit."""
a, b = Parameter("a"), Parameter("b")
circuit_in = QuantumCircuit(2)
# Qubit 0
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(a, 0)
circuit_in.rx(np.pi / 2, 0)
# Qubit 1
circuit_in.rx(-np.pi / 2, 1)
circuit_in.ry(b, 1)
circuit_in.rx(np.pi / 2, 1)
circuit_out = _ry_to_rz_template_pass().run(circuit_in)
expected = QuantumCircuit(2)
expected.rz(a, 0)
expected.rz(b, 1)
self.assertEqual(circuit_out, expected)
def test_template_match_multiparameter(self):
"""Test that the template matching works on instructions that take more than one
parameter."""
a = Parameter("a")
b = Parameter("b")
template = QuantumCircuit(1)
template.u(0, a, b, 0)
template.rz(-a - b, 0)
circuit_in = QuantumCircuit(1)
circuit_in.u(0, 1.23, 2.45, 0)
pm = PassManager(TemplateOptimization([template], user_cost_dict={"u": 16, "rz": 0}))
circuit_out = pm.run(circuit_in)
expected = QuantumCircuit(1)
expected.rz(1.23 + 2.45, 0)
self.assertEqual(circuit_out, expected)
def test_naming_clash_multiparameter(self):
"""Test that the naming clash prevention mechanism works with instructions that take
multiple parameters."""
a_template = Parameter("a")
b_template = Parameter("b")
template = QuantumCircuit(1)
template.u(0, a_template, b_template, 0)
template.rz(-a_template - b_template, 0)
a_circuit = Parameter("a")
b_circuit = Parameter("b")
circuit_in = QuantumCircuit(1)
circuit_in.u(0, a_circuit, b_circuit, 0)
pm = PassManager(TemplateOptimization([template], user_cost_dict={"u": 16, "rz": 0}))
circuit_out = pm.run(circuit_in)
expected = QuantumCircuit(1)
expected.rz(a_circuit + b_circuit, 0)
self.assertEqual(circuit_out, expected)
def test_consecutive_templates_apply(self):
"""Test the scenario where one template optimization creates an opportunity for
another template optimization.
This is the original circuit:
┌───┐
q_0: ┤ X ├──■───X───────■─
└─┬─┘┌─┴─┐ │ ┌───┐ │
q_1: ──■──┤ X ├─X─┤ H ├─■─
└───┘ └───┘
The clifford_4_1 template allows to replace the two CNOTs followed by the SWAP by a
single CNOT:
q_0: ──■────────■─
┌─┴─┐┌───┐ │
q_1: ┤ X ├┤ H ├─■─
└───┘└───┘
At these point, the clifford_4_2 template allows to replace the circuit by a single
Hadamard gate:
q_0: ─────
┌───┐
q_1: ┤ H ├
└───┘
The second optimization would not have been possible without the applying the first
optimization.
"""
qc = QuantumCircuit(2)
qc.cx(1, 0)
qc.cx(0, 1)
qc.swap(0, 1)
qc.h(1)
qc.cz(0, 1)
qc_expected = QuantumCircuit(2)
qc_expected.h(1)
costs = {"h": 1, "cx": 2, "cz": 2, "swap": 3}
# Check that consecutively applying both templates leads to the expected circuit.
qc_opt = TemplateOptimization(
template_list=[clifford_4_1(), clifford_4_2()], user_cost_dict=costs
)(qc)
self.assertEqual(qc_opt, qc_expected)
# Also check that applying the second template by itself does not do anything.
qc_non_opt = TemplateOptimization(template_list=[clifford_4_2()], user_cost_dict=costs)(qc)
self.assertEqual(qc, qc_non_opt)
def test_consecutive_templates_do_not_apply(self):
"""Test that applying one template optimization does not allow incorrectly
applying other templates (which could happen if the DagDependency graph is
not constructed correctly after the optimization).
"""
template_list = [
clifford_2_2(),
clifford_2_3(),
]
pm = PassManager(TemplateOptimization(template_list=template_list))
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.cx(0, 1)
qc.h(0)
qc.swap(0, 1)
qc.h(0)
qc_opt = pm.run(qc)
self.assertTrue(Operator(qc) == Operator(qc_opt))
def test_clifford_templates(self):
"""Tests TemplateOptimization pass on several larger examples."""
template_list = [
clifford_2_1(),
clifford_2_2(),
clifford_2_3(),
clifford_2_4(),
clifford_3_1(),
]
pm = PassManager(TemplateOptimization(template_list=template_list))
for seed in range(10):
qc = random_clifford_circuit(
num_qubits=5,
num_gates=100,
gates=["x", "y", "z", "h", "s", "sdg", "cx", "cz", "swap"],
seed=seed,
)
qc_opt = pm.run(qc)
self.assertTrue(Operator(qc) == Operator(qc_opt))
if __name__ == "__main__":
unittest.main()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for DensityMatrix quantum state class."""
import logging
import unittest
import numpy as np
from ddt import data, ddt
from numpy.testing import assert_allclose
from qiskit import QiskitError, QuantumCircuit, QuantumRegister
from qiskit.circuit.library import QFT, HGate
from qiskit.quantum_info.operators.operator import Operator
from qiskit.quantum_info.operators.symplectic import Pauli, SparsePauliOp
from qiskit.quantum_info.random import random_density_matrix, random_pauli, random_unitary
from qiskit.quantum_info.states import DensityMatrix, Statevector
from qiskit.test import QiskitTestCase
from qiskit.utils import optionals
logger = logging.getLogger(__name__)
@ddt
class TestDensityMatrix(QiskitTestCase):
"""Tests for DensityMatrix class."""
@classmethod
def rand_vec(cls, n, normalize=False):
"""Return complex vector or statevector"""
seed = np.random.randint(0, np.iinfo(np.int32).max)
logger.debug("rand_vec default_rng seeded with seed=%s", seed)
rng = np.random.default_rng(seed)
vec = rng.random(n) + 1j * rng.random(n)
if normalize:
vec /= np.sqrt(np.dot(vec, np.conj(vec)))
return vec
@classmethod
def rand_rho(cls, n):
"""Return random pure state density matrix"""
rho = cls.rand_vec(n, normalize=True)
return np.outer(rho, np.conjugate(rho))
def test_init_array_qubit(self):
"""Test subsystem initialization from N-qubit array."""
# Test automatic inference of qubit subsystems
rho = self.rand_rho(8)
for dims in [None, 8]:
state = DensityMatrix(rho, dims=dims)
assert_allclose(state.data, rho)
self.assertEqual(state.dim, 8)
self.assertEqual(state.dims(), (2, 2, 2))
self.assertEqual(state.num_qubits, 3)
def test_init_array(self):
"""Test initialization from array."""
rho = self.rand_rho(3)
state = DensityMatrix(rho)
assert_allclose(state.data, rho)
self.assertEqual(state.dim, 3)
self.assertEqual(state.dims(), (3,))
self.assertIsNone(state.num_qubits)
rho = self.rand_rho(2 * 3 * 4)
state = DensityMatrix(rho, dims=[2, 3, 4])
assert_allclose(state.data, rho)
self.assertEqual(state.dim, 2 * 3 * 4)
self.assertEqual(state.dims(), (2, 3, 4))
self.assertIsNone(state.num_qubits)
def test_init_array_except(self):
"""Test initialization exception from array."""
rho = self.rand_rho(4)
self.assertRaises(QiskitError, DensityMatrix, rho, dims=[4, 2])
self.assertRaises(QiskitError, DensityMatrix, rho, dims=[2, 4])
self.assertRaises(QiskitError, DensityMatrix, rho, dims=5)
def test_init_densitymatrix(self):
"""Test initialization from DensityMatrix."""
rho1 = DensityMatrix(self.rand_rho(4))
rho2 = DensityMatrix(rho1)
self.assertEqual(rho1, rho2)
def test_init_statevector(self):
"""Test initialization from DensityMatrix."""
vec = self.rand_vec(4)
target = DensityMatrix(np.outer(vec, np.conjugate(vec)))
rho = DensityMatrix(Statevector(vec))
self.assertEqual(rho, target)
def test_init_circuit(self):
"""Test initialization from a circuit."""
# random unitaries
u0 = random_unitary(2).data
u1 = random_unitary(2).data
# add to circuit
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.unitary(u0, [qr[0]])
circ.unitary(u1, [qr[1]])
target_vec = Statevector(np.kron(u1, u0).dot([1, 0, 0, 0]))
target = DensityMatrix(target_vec)
rho = DensityMatrix(circ)
self.assertEqual(rho, target)
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
target = DensityMatrix.from_label("000").evolve(Operator(circuit))
rho = DensityMatrix(circuit)
self.assertEqual(rho, target)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.h(1)
circuit.cp(lam, 0, 1)
target = DensityMatrix.from_label("00").evolve(Operator(circuit))
rho = DensityMatrix(circuit)
self.assertEqual(rho, target)
def test_from_circuit(self):
"""Test initialization from a circuit."""
# random unitaries
u0 = random_unitary(2).data
u1 = random_unitary(2).data
# add to circuit
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.unitary(u0, [qr[0]])
circ.unitary(u1, [qr[1]])
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circ.x(0)
circuit.ch(0, 1)
target = DensityMatrix.from_label("00").evolve(Operator(circuit))
rho = DensityMatrix.from_instruction(circuit)
self.assertEqual(rho, target)
# Test initialize instruction
init = Statevector([1, 0, 0, 1j]) / np.sqrt(2)
target = DensityMatrix(init)
circuit = QuantumCircuit(2)
circuit.initialize(init.data, [0, 1])
rho = DensityMatrix.from_instruction(circuit)
self.assertEqual(rho, target)
# Test reset instruction
target = DensityMatrix([1, 0])
circuit = QuantumCircuit(1)
circuit.h(0)
circuit.reset(0)
rho = DensityMatrix.from_instruction(circuit)
self.assertEqual(rho, target)
def test_from_instruction(self):
"""Test initialization from an instruction."""
target_vec = Statevector(np.dot(HGate().to_matrix(), [1, 0]))
target = DensityMatrix(target_vec)
rho = DensityMatrix.from_instruction(HGate())
self.assertEqual(rho, target)
def test_from_label(self):
"""Test initialization from a label"""
x_p = DensityMatrix(np.array([[0.5, 0.5], [0.5, 0.5]]))
x_m = DensityMatrix(np.array([[0.5, -0.5], [-0.5, 0.5]]))
y_p = DensityMatrix(np.array([[0.5, -0.5j], [0.5j, 0.5]]))
y_m = DensityMatrix(np.array([[0.5, 0.5j], [-0.5j, 0.5]]))
z_p = DensityMatrix(np.diag([1, 0]))
z_m = DensityMatrix(np.diag([0, 1]))
label = "0+r"
target = z_p.tensor(x_p).tensor(y_p)
self.assertEqual(target, DensityMatrix.from_label(label))
label = "-l1"
target = x_m.tensor(y_m).tensor(z_m)
self.assertEqual(target, DensityMatrix.from_label(label))
def test_equal(self):
"""Test __eq__ method"""
for _ in range(10):
rho = self.rand_rho(4)
self.assertEqual(DensityMatrix(rho), DensityMatrix(rho.tolist()))
def test_copy(self):
"""Test DensityMatrix copy method"""
for _ in range(5):
rho = self.rand_rho(4)
orig = DensityMatrix(rho)
cpy = orig.copy()
cpy._data[0] += 1.0
self.assertFalse(cpy == orig)
def test_is_valid(self):
"""Test is_valid method."""
state = DensityMatrix(np.eye(2))
self.assertFalse(state.is_valid())
for _ in range(10):
state = DensityMatrix(self.rand_rho(4))
self.assertTrue(state.is_valid())
def test_to_operator(self):
"""Test to_operator method for returning projector."""
for _ in range(10):
rho = self.rand_rho(4)
target = Operator(rho)
op = DensityMatrix(rho).to_operator()
self.assertEqual(op, target)
def test_evolve(self):
"""Test evolve method for operators."""
for _ in range(10):
op = random_unitary(4)
rho = self.rand_rho(4)
target = DensityMatrix(np.dot(op.data, rho).dot(op.adjoint().data))
evolved = DensityMatrix(rho).evolve(op)
self.assertEqual(target, evolved)
def test_evolve_subsystem(self):
"""Test subsystem evolve method for operators."""
# Test evolving single-qubit of 3-qubit system
for _ in range(5):
rho = self.rand_rho(8)
state = DensityMatrix(rho)
op0 = random_unitary(2)
op1 = random_unitary(2)
op2 = random_unitary(2)
# Test evolve on 1-qubit
op = op0
op_full = Operator(np.eye(4)).tensor(op)
target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data))
self.assertEqual(state.evolve(op, qargs=[0]), target)
# Evolve on qubit 1
op_full = Operator(np.eye(2)).tensor(op).tensor(np.eye(2))
target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data))
self.assertEqual(state.evolve(op, qargs=[1]), target)
# Evolve on qubit 2
op_full = op.tensor(np.eye(4))
target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data))
self.assertEqual(state.evolve(op, qargs=[2]), target)
# Test evolve on 2-qubits
op = op1.tensor(op0)
# Evolve on qubits [0, 2]
op_full = op1.tensor(np.eye(2)).tensor(op0)
target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data))
self.assertEqual(state.evolve(op, qargs=[0, 2]), target)
# Evolve on qubits [2, 0]
op_full = op0.tensor(np.eye(2)).tensor(op1)
target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data))
self.assertEqual(state.evolve(op, qargs=[2, 0]), target)
# Test evolve on 3-qubits
op = op2.tensor(op1).tensor(op0)
# Evolve on qubits [0, 1, 2]
op_full = op
target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data))
self.assertEqual(state.evolve(op, qargs=[0, 1, 2]), target)
# Evolve on qubits [2, 1, 0]
op_full = op0.tensor(op1).tensor(op2)
target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data))
self.assertEqual(state.evolve(op, qargs=[2, 1, 0]), target)
def test_evolve_qudit_subsystems(self):
"""Test nested evolve calls on qudit subsystems."""
dims = (3, 4, 5)
init = self.rand_rho(np.prod(dims))
ops = [random_unitary((dim,)) for dim in dims]
state = DensityMatrix(init, dims)
for i, op in enumerate(ops):
state = state.evolve(op, [i])
target_op = np.eye(1)
for op in ops:
target_op = np.kron(op.data, target_op)
target = DensityMatrix(np.dot(target_op, init).dot(target_op.conj().T), dims)
self.assertEqual(state, target)
def test_conjugate(self):
"""Test conjugate method."""
for _ in range(10):
rho = self.rand_rho(4)
target = DensityMatrix(np.conj(rho))
state = DensityMatrix(rho).conjugate()
self.assertEqual(state, target)
def test_expand(self):
"""Test expand method."""
for _ in range(10):
rho0 = self.rand_rho(2)
rho1 = self.rand_rho(3)
target = np.kron(rho1, rho0)
state = DensityMatrix(rho0).expand(DensityMatrix(rho1))
self.assertEqual(state.dim, 6)
self.assertEqual(state.dims(), (2, 3))
assert_allclose(state.data, target)
def test_tensor(self):
"""Test tensor method."""
for _ in range(10):
rho0 = self.rand_rho(2)
rho1 = self.rand_rho(3)
target = np.kron(rho0, rho1)
state = DensityMatrix(rho0).tensor(DensityMatrix(rho1))
self.assertEqual(state.dim, 6)
self.assertEqual(state.dims(), (3, 2))
assert_allclose(state.data, target)
def test_add(self):
"""Test add method."""
for _ in range(10):
rho0 = self.rand_rho(4)
rho1 = self.rand_rho(4)
state0 = DensityMatrix(rho0)
state1 = DensityMatrix(rho1)
self.assertEqual(state0 + state1, DensityMatrix(rho0 + rho1))
def test_add_except(self):
"""Test add method raises exceptions."""
state1 = DensityMatrix(self.rand_rho(2))
state2 = DensityMatrix(self.rand_rho(3))
self.assertRaises(QiskitError, state1.__add__, state2)
def test_subtract(self):
"""Test subtract method."""
for _ in range(10):
rho0 = self.rand_rho(4)
rho1 = self.rand_rho(4)
state0 = DensityMatrix(rho0)
state1 = DensityMatrix(rho1)
self.assertEqual(state0 - state1, DensityMatrix(rho0 - rho1))
def test_multiply(self):
"""Test multiply method."""
for _ in range(10):
rho = self.rand_rho(4)
state = DensityMatrix(rho)
val = np.random.rand() + 1j * np.random.rand()
self.assertEqual(val * state, DensityMatrix(val * state))
def test_negate(self):
"""Test negate method"""
for _ in range(10):
rho = self.rand_rho(4)
state = DensityMatrix(rho)
self.assertEqual(-state, DensityMatrix(-1 * rho))
def test_to_dict(self):
"""Test to_dict method"""
with self.subTest(msg="dims = (2, 2)"):
rho = DensityMatrix(np.arange(1, 17).reshape(4, 4))
target = {
"00|00": 1,
"01|00": 2,
"10|00": 3,
"11|00": 4,
"00|01": 5,
"01|01": 6,
"10|01": 7,
"11|01": 8,
"00|10": 9,
"01|10": 10,
"10|10": 11,
"11|10": 12,
"00|11": 13,
"01|11": 14,
"10|11": 15,
"11|11": 16,
}
self.assertDictAlmostEqual(target, rho.to_dict())
with self.subTest(msg="dims = (2, 3)"):
rho = DensityMatrix(np.diag(np.arange(1, 7)), dims=(2, 3))
target = {}
for i in range(2):
for j in range(3):
key = "{1}{0}|{1}{0}".format(i, j)
target[key] = 2 * j + i + 1
self.assertDictAlmostEqual(target, rho.to_dict())
with self.subTest(msg="dims = (2, 11)"):
vec = DensityMatrix(np.diag(np.arange(1, 23)), dims=(2, 11))
target = {}
for i in range(2):
for j in range(11):
key = "{1},{0}|{1},{0}".format(i, j)
target[key] = 2 * j + i + 1
self.assertDictAlmostEqual(target, vec.to_dict())
def test_densitymatrix_to_statevector_pure(self):
"""Test converting a pure density matrix to statevector."""
state = 1 / np.sqrt(2) * (np.array([1, 0, 0, 0, 0, 0, 0, 1]))
psi = Statevector(state)
rho = DensityMatrix(psi)
phi = rho.to_statevector()
self.assertTrue(psi.equiv(phi))
def test_densitymatrix_to_statevector_mixed(self):
"""Test converting a pure density matrix to statevector."""
state_1 = 1 / np.sqrt(2) * (np.array([1, 0, 0, 0, 0, 0, 0, 1]))
state_2 = 1 / np.sqrt(2) * (np.array([0, 0, 0, 0, 0, 0, 1, 1]))
psi = 0.5 * (Statevector(state_1) + Statevector(state_2))
rho = DensityMatrix(psi)
self.assertRaises(QiskitError, rho.to_statevector)
def test_probabilities_product(self):
"""Test probabilities method for product state"""
state = DensityMatrix.from_label("+0")
# 2-qubit qargs
with self.subTest(msg="P(None)"):
probs = state.probabilities()
target = np.array([0.5, 0, 0.5, 0])
self.assertTrue(np.allclose(probs, target))
with self.subTest(msg="P([0, 1])"):
probs = state.probabilities([0, 1])
target = np.array([0.5, 0, 0.5, 0])
self.assertTrue(np.allclose(probs, target))
with self.subTest(msg="P([1, 0]"):
probs = state.probabilities([1, 0])
target = np.array([0.5, 0.5, 0, 0])
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
with self.subTest(msg="P([0])"):
probs = state.probabilities([0])
target = np.array([1, 0])
self.assertTrue(np.allclose(probs, target))
with self.subTest(msg="P([1])"):
probs = state.probabilities([1])
target = np.array([0.5, 0.5])
self.assertTrue(np.allclose(probs, target))
def test_probabilities_ghz(self):
"""Test probabilities method for GHZ state"""
psi = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
state = DensityMatrix(psi)
# 3-qubit qargs
target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5])
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 2-qubit qargs
target = np.array([0.5, 0, 0, 0.5])
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
target = np.array([0.5, 0.5])
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
def test_probabilities_w(self):
"""Test probabilities method with W state"""
psi = (
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
) / np.sqrt(3)
state = DensityMatrix(psi)
# 3-qubit qargs
target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0])
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 2-qubit qargs
target = np.array([1 / 3, 1 / 3, 1 / 3, 0])
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
target = np.array([2 / 3, 1 / 3])
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
def test_probabilities_dict_product(self):
"""Test probabilities_dict method for product state"""
state = DensityMatrix.from_label("+0")
# 2-qubit qargs
with self.subTest(msg="P(None)"):
probs = state.probabilities_dict()
target = {"00": 0.5, "10": 0.5}
self.assertDictAlmostEqual(probs, target)
with self.subTest(msg="P([0, 1])"):
probs = state.probabilities_dict([0, 1])
target = {"00": 0.5, "10": 0.5}
self.assertDictAlmostEqual(probs, target)
with self.subTest(msg="P([1, 0]"):
probs = state.probabilities_dict([1, 0])
target = {"00": 0.5, "01": 0.5}
self.assertDictAlmostEqual(probs, target)
# 1-qubit qargs
with self.subTest(msg="P([0])"):
probs = state.probabilities_dict([0])
target = {"0": 1}
self.assertDictAlmostEqual(probs, target)
with self.subTest(msg="P([1])"):
probs = state.probabilities_dict([1])
target = {"0": 0.5, "1": 0.5}
self.assertDictAlmostEqual(probs, target)
def test_probabilities_dict_ghz(self):
"""Test probabilities_dict method for GHZ state"""
psi = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
state = DensityMatrix(psi)
# 3-qubit qargs
target = {"000": 0.5, "111": 0.5}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 2-qubit qargs
target = {"00": 0.5, "11": 0.5}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 1-qubit qargs
target = {"0": 0.5, "1": 0.5}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
def test_probabilities_dict_w(self):
"""Test probabilities_dict method with W state"""
psi = (
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
) / np.sqrt(3)
state = DensityMatrix(psi)
# 3-qubit qargs
target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0])
target = {"001": 1 / 3, "010": 1 / 3, "100": 1 / 3}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 2-qubit qargs
target = {"00": 1 / 3, "01": 1 / 3, "10": 1 / 3}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 1-qubit qargs
target = {"0": 2 / 3, "1": 1 / 3}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
def test_sample_counts_ghz(self):
"""Test sample_counts method for GHZ state"""
shots = 2000
threshold = 0.02 * shots
state = DensityMatrix(
(Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
)
state.seed(100)
# 3-qubit qargs
target = {"000": shots / 2, "111": shots / 2}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 2-qubit qargs
target = {"00": shots / 2, "11": shots / 2}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 1-qubit qargs
target = {"0": shots / 2, "1": shots / 2}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
def test_sample_counts_w(self):
"""Test sample_counts method for W state"""
shots = 3000
threshold = 0.02 * shots
state = DensityMatrix(
(
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
)
/ np.sqrt(3)
)
state.seed(100)
target = {"001": shots / 3, "010": shots / 3, "100": shots / 3}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 2-qubit qargs
target = {"00": shots / 3, "01": shots / 3, "10": shots / 3}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 1-qubit qargs
target = {"0": 2 * shots / 3, "1": shots / 3}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
def test_probabilities_dict_unequal_dims(self):
"""Test probabilities_dict for a state with unequal subsystem dimensions."""
vec = np.zeros(60, dtype=float)
vec[15:20] = np.ones(5)
vec[40:46] = np.ones(6)
state = DensityMatrix(vec / np.sqrt(11.0), dims=[3, 4, 5])
p = 1.0 / 11.0
self.assertDictEqual(
state.probabilities_dict(),
{
s: p
for s in [
"110",
"111",
"112",
"120",
"121",
"311",
"312",
"320",
"321",
"322",
"330",
]
},
)
# differences due to rounding
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[0]), {"0": 4 * p, "1": 4 * p, "2": 3 * p}, delta=1e-10
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[1]), {"1": 5 * p, "2": 5 * p, "3": p}, delta=1e-10
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[2]), {"1": 5 * p, "3": 6 * p}, delta=1e-10
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[0, 1]),
{"10": p, "11": 2 * p, "12": 2 * p, "20": 2 * p, "21": 2 * p, "22": p, "30": p},
delta=1e-10,
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[1, 0]),
{"01": p, "11": 2 * p, "21": 2 * p, "02": 2 * p, "12": 2 * p, "22": p, "03": p},
delta=1e-10,
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[0, 2]),
{"10": 2 * p, "11": 2 * p, "12": p, "31": 2 * p, "32": 2 * p, "30": 2 * p},
delta=1e-10,
)
def test_sample_counts_qutrit(self):
"""Test sample_counts method for qutrit state"""
p = 0.3
shots = 1000
threshold = 0.03 * shots
state = DensityMatrix(np.diag([p, 0, 1 - p]))
state.seed(100)
with self.subTest(msg="counts"):
target = {"0": shots * p, "2": shots * (1 - p)}
counts = state.sample_counts(shots=shots)
self.assertDictAlmostEqual(counts, target, threshold)
def test_sample_memory_ghz(self):
"""Test sample_memory method for GHZ state"""
shots = 2000
state = DensityMatrix(
(Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
)
state.seed(100)
# 3-qubit qargs
target = {"000": shots / 2, "111": shots / 2}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 2-qubit qargs
target = {"00": shots / 2, "11": shots / 2}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 1-qubit qargs
target = {"0": shots / 2, "1": shots / 2}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
def test_sample_memory_w(self):
"""Test sample_memory method for W state"""
shots = 3000
state = DensityMatrix(
(
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
)
/ np.sqrt(3)
)
state.seed(100)
target = {"001": shots / 3, "010": shots / 3, "100": shots / 3}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 2-qubit qargs
target = {"00": shots / 3, "01": shots / 3, "10": shots / 3}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 1-qubit qargs
target = {"0": 2 * shots / 3, "1": shots / 3}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
def test_sample_memory_qutrit(self):
"""Test sample_memory method for qutrit state"""
p = 0.3
shots = 1000
state = DensityMatrix(np.diag([p, 0, 1 - p]))
state.seed(100)
with self.subTest(msg="memory"):
memory = state.sample_memory(shots)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), {"0", "2"})
def test_reset_2qubit(self):
"""Test reset method for 2-qubit state"""
state = DensityMatrix(np.diag([0.5, 0, 0, 0.5]))
with self.subTest(msg="reset"):
rho = state.copy()
value = rho.reset()
target = DensityMatrix(np.diag([1, 0, 0, 0]))
self.assertEqual(value, target)
with self.subTest(msg="reset"):
rho = state.copy()
value = rho.reset([0, 1])
target = DensityMatrix(np.diag([1, 0, 0, 0]))
self.assertEqual(value, target)
with self.subTest(msg="reset [0]"):
rho = state.copy()
value = rho.reset([0])
target = DensityMatrix(np.diag([0.5, 0, 0.5, 0]))
self.assertEqual(value, target)
with self.subTest(msg="reset [0]"):
rho = state.copy()
value = rho.reset([1])
target = DensityMatrix(np.diag([0.5, 0.5, 0, 0]))
self.assertEqual(value, target)
def test_reset_qutrit(self):
"""Test reset method for qutrit"""
state = DensityMatrix(np.diag([1, 1, 1]) / 3)
state.seed(200)
value = state.reset()
target = DensityMatrix(np.diag([1, 0, 0]))
self.assertEqual(value, target)
def test_measure_2qubit(self):
"""Test measure method for 2-qubit state"""
state = DensityMatrix.from_label("+0")
seed = 200
shots = 100
with self.subTest(msg="measure"):
for i in range(shots):
rho = state.copy()
rho.seed(seed + i)
outcome, value = rho.measure()
self.assertIn(outcome, ["00", "10"])
if outcome == "00":
target = DensityMatrix.from_label("00")
self.assertEqual(value, target)
else:
target = DensityMatrix.from_label("10")
self.assertEqual(value, target)
with self.subTest(msg="measure [0, 1]"):
for i in range(shots):
rho = state.copy()
outcome, value = rho.measure([0, 1])
self.assertIn(outcome, ["00", "10"])
if outcome == "00":
target = DensityMatrix.from_label("00")
self.assertEqual(value, target)
else:
target = DensityMatrix.from_label("10")
self.assertEqual(value, target)
with self.subTest(msg="measure [1, 0]"):
for i in range(shots):
rho = state.copy()
outcome, value = rho.measure([1, 0])
self.assertIn(outcome, ["00", "01"])
if outcome == "00":
target = DensityMatrix.from_label("00")
self.assertEqual(value, target)
else:
target = DensityMatrix.from_label("10")
self.assertEqual(value, target)
with self.subTest(msg="measure [0]"):
for i in range(shots):
rho = state.copy()
outcome, value = rho.measure([0])
self.assertEqual(outcome, "0")
target = DensityMatrix.from_label("+0")
self.assertEqual(value, target)
with self.subTest(msg="measure [1]"):
for i in range(shots):
rho = state.copy()
outcome, value = rho.measure([1])
self.assertIn(outcome, ["0", "1"])
if outcome == "0":
target = DensityMatrix.from_label("00")
self.assertEqual(value, target)
else:
target = DensityMatrix.from_label("10")
self.assertEqual(value, target)
def test_measure_qutrit(self):
"""Test measure method for qutrit"""
state = DensityMatrix(np.diag([1, 1, 1]) / 3)
seed = 200
shots = 100
for i in range(shots):
rho = state.copy()
rho.seed(seed + i)
outcome, value = rho.measure()
self.assertIn(outcome, ["0", "1", "2"])
if outcome == "0":
target = DensityMatrix(np.diag([1, 0, 0]))
self.assertEqual(value, target)
elif outcome == "1":
target = DensityMatrix(np.diag([0, 1, 0]))
self.assertEqual(value, target)
else:
target = DensityMatrix(np.diag([0, 0, 1]))
self.assertEqual(value, target)
def test_from_int(self):
"""Test from_int method"""
with self.subTest(msg="from_int(0, 4)"):
target = DensityMatrix([1, 0, 0, 0])
value = DensityMatrix.from_int(0, 4)
self.assertEqual(target, value)
with self.subTest(msg="from_int(3, 4)"):
target = DensityMatrix([0, 0, 0, 1])
value = DensityMatrix.from_int(3, 4)
self.assertEqual(target, value)
with self.subTest(msg="from_int(8, (3, 3))"):
target = DensityMatrix([0, 0, 0, 0, 0, 0, 0, 0, 1], dims=(3, 3))
value = DensityMatrix.from_int(8, (3, 3))
self.assertEqual(target, value)
def test_expval(self):
"""Test expectation_value method"""
psi = Statevector([1, 0, 0, 1]) / np.sqrt(2)
rho = DensityMatrix(psi)
for label, target in [
("II", 1),
("XX", 1),
("YY", -1),
("ZZ", 1),
("IX", 0),
("YZ", 0),
("ZX", 0),
("YI", 0),
]:
with self.subTest(msg=f"<{label}>"):
op = Pauli(label)
expval = rho.expectation_value(op)
self.assertAlmostEqual(expval, target)
psi = Statevector([np.sqrt(2), 0, 0, 0, 0, 0, 0, 1 + 1j]) / 2
rho = DensityMatrix(psi)
for label, target in [
("XXX", np.sqrt(2) / 2),
("YYY", -np.sqrt(2) / 2),
("ZZZ", 0),
("XYZ", 0),
("YIY", 0),
]:
with self.subTest(msg=f"<{label}>"):
op = Pauli(label)
expval = rho.expectation_value(op)
self.assertAlmostEqual(expval, target)
labels = ["XXX", "IXI", "YYY", "III"]
coeffs = [3.0, 5.5, -1j, 23]
spp_op = SparsePauliOp.from_list(list(zip(labels, coeffs)))
expval = rho.expectation_value(spp_op)
target = 25.121320343559642 + 0.7071067811865476j
self.assertAlmostEqual(expval, target)
@data(
"II",
"IX",
"IY",
"IZ",
"XI",
"XX",
"XY",
"XZ",
"YI",
"YX",
"YY",
"YZ",
"ZI",
"ZX",
"ZY",
"ZZ",
"-II",
"-IX",
"-IY",
"-IZ",
"-XI",
"-XX",
"-XY",
"-XZ",
"-YI",
"-YX",
"-YY",
"-YZ",
"-ZI",
"-ZX",
"-ZY",
"-ZZ",
"iII",
"iIX",
"iIY",
"iIZ",
"iXI",
"iXX",
"iXY",
"iXZ",
"iYI",
"iYX",
"iYY",
"iYZ",
"iZI",
"iZX",
"iZY",
"iZZ",
"-iII",
"-iIX",
"-iIY",
"-iIZ",
"-iXI",
"-iXX",
"-iXY",
"-iXZ",
"-iYI",
"-iYX",
"-iYY",
"-iYZ",
"-iZI",
"-iZX",
"-iZY",
"-iZZ",
)
def test_expval_pauli_f_contiguous(self, pauli):
"""Test expectation_value method for Pauli op"""
seed = 1020
op = Pauli(pauli)
rho = random_density_matrix(2**op.num_qubits, seed=seed)
rho._data = np.reshape(rho.data.flatten(order="F"), rho.data.shape, order="F")
target = rho.expectation_value(op.to_matrix())
expval = rho.expectation_value(op)
self.assertAlmostEqual(expval, target)
@data(
"II",
"IX",
"IY",
"IZ",
"XI",
"XX",
"XY",
"XZ",
"YI",
"YX",
"YY",
"YZ",
"ZI",
"ZX",
"ZY",
"ZZ",
"-II",
"-IX",
"-IY",
"-IZ",
"-XI",
"-XX",
"-XY",
"-XZ",
"-YI",
"-YX",
"-YY",
"-YZ",
"-ZI",
"-ZX",
"-ZY",
"-ZZ",
"iII",
"iIX",
"iIY",
"iIZ",
"iXI",
"iXX",
"iXY",
"iXZ",
"iYI",
"iYX",
"iYY",
"iYZ",
"iZI",
"iZX",
"iZY",
"iZZ",
"-iII",
"-iIX",
"-iIY",
"-iIZ",
"-iXI",
"-iXX",
"-iXY",
"-iXZ",
"-iYI",
"-iYX",
"-iYY",
"-iYZ",
"-iZI",
"-iZX",
"-iZY",
"-iZZ",
)
def test_expval_pauli_c_contiguous(self, pauli):
"""Test expectation_value method for Pauli op"""
seed = 1020
op = Pauli(pauli)
rho = random_density_matrix(2**op.num_qubits, seed=seed)
rho._data = np.reshape(rho.data.flatten(order="C"), rho.data.shape, order="C")
target = rho.expectation_value(op.to_matrix())
expval = rho.expectation_value(op)
self.assertAlmostEqual(expval, target)
@data([0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1])
def test_expval_pauli_qargs(self, qubits):
"""Test expectation_value method for Pauli op"""
seed = 1020
op = random_pauli(2, seed=seed)
state = random_density_matrix(2**3, seed=seed)
target = state.expectation_value(op.to_matrix(), qubits)
expval = state.expectation_value(op, qubits)
self.assertAlmostEqual(expval, target)
def test_reverse_qargs(self):
"""Test reverse_qargs method"""
circ1 = QFT(5)
circ2 = circ1.reverse_bits()
state1 = DensityMatrix.from_instruction(circ1)
state2 = DensityMatrix.from_instruction(circ2)
self.assertEqual(state1.reverse_qargs(), state2)
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "requires matplotlib")
@unittest.skipUnless(optionals.HAS_PYLATEX, "requires pylatexenc")
def test_drawings(self):
"""Test draw method"""
qc1 = QFT(5)
dm = DensityMatrix.from_instruction(qc1)
with self.subTest(msg="str(density_matrix)"):
str(dm)
for drawtype in ["repr", "text", "latex", "latex_source", "qsphere", "hinton", "bloch"]:
with self.subTest(msg=f"draw('{drawtype}')"):
dm.draw(drawtype)
def test_density_matrix_partial_transpose(self):
"""Test partial_transpose function on density matrices"""
with self.subTest(msg="separable"):
rho = DensityMatrix.from_label("10+")
rho1 = np.zeros((8, 8), complex)
rho1[4, 4] = 0.5
rho1[4, 5] = 0.5
rho1[5, 4] = 0.5
rho1[5, 5] = 0.5
self.assertEqual(rho.partial_transpose([0, 1]), DensityMatrix(rho1))
self.assertEqual(rho.partial_transpose([0, 2]), DensityMatrix(rho1))
with self.subTest(msg="entangled"):
rho = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5, 0], [0, -0.5, 0.5, 0], [0, 0, 0, 0]])
rho1 = DensityMatrix([[0, 0, 0, -0.5], [0, 0.5, 0, 0], [0, 0, 0.5, 0], [-0.5, 0, 0, 0]])
self.assertEqual(rho.partial_transpose([0]), DensityMatrix(rho1))
self.assertEqual(rho.partial_transpose([1]), DensityMatrix(rho1))
with self.subTest(msg="dims(3,3)"):
mat = np.zeros((9, 9))
mat1 = np.zeros((9, 9))
mat[8, 0] = 1
mat1[0, 8] = 1
rho = DensityMatrix(mat, dims=(3, 3))
rho1 = DensityMatrix(mat1, dims=(3, 3))
self.assertEqual(rho.partial_transpose([0, 1]), rho1)
def test_clip_probabilities(self):
"""Test probabilities are clipped to [0, 1]."""
dm = DensityMatrix([[1.1, 0], [0, 0]])
self.assertEqual(list(dm.probabilities()), [1.0, 0.0])
# The "1" key should be exactly zero and therefore omitted.
self.assertEqual(dm.probabilities_dict(), {"0": 1.0})
def test_round_probabilities(self):
"""Test probabilities are correctly rounded.
This is good to test to ensure clipping, renormalizing and rounding work together.
"""
p = np.sqrt(1 / 3)
amplitudes = [p, p, p, 0]
dm = DensityMatrix(np.outer(amplitudes, amplitudes))
expected = [0.33, 0.33, 0.33, 0]
# Exact floating-point check because fixing the rounding should ensure this is exact.
self.assertEqual(list(dm.probabilities(decimals=2)), expected)
if __name__ == "__main__":
unittest.main()
|
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()
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/deveshq/QC-with-qiskit
|
deveshq
|
# Importing some important libraries
import numpy as np
from numpy import math
from qiskit import *
from numpy import pi as pi
from math import asin, sqrt
import qiskit.quantum_info as qi
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from numpy.random import seed
import IPython
from IPython.display import display,Latex,Markdown
# Defining a function which flip the sign of the marked state, in the superpositon of all the states.
def orc(d):
op = np.identity(2**n)
for i in d:
op[i][i] = op[i][i]*(-1)
display(i)
return op
# Defining another function which flip all the states about the average.
def dif():
op = np.identity(2**n)
for i in range(2**n):
if ( i != 0):
op[i][i] = op[i][i]*(-1)
#display(op)
return op
# Taking vector of integer number as input.
display(Latex(r'Expected a vector of length $2^n$ as input!'))
n = int(input('Enter n: '))
a = []
print('Enter the vector:')
for i in range(2**n):
a.append(int(input()))
print(f'a = {a}')
#Extracting the indices of the input for which two adjacent bits will always have different values.
d = []
b_d = []
c = len('{0:b}'.format(max(a))) #number of bits in binary form of highest number in a.
def cd(x):
b = '{0:0{d}b}'.format(x,d=c)
return all(b[i] != b[i+1] for i in range(c-1) )
for i in range(len(a)):
if cd(a[i]) is True:
d.append(i)
b_d.append('{0:0{d}b}'.format(a[i],d=c))
print(f'Indices: {d}, Numbers: {b_d}')
if (n<3):
if (len(d)>1):
n = 3 #Because this program requires atleast three qubits to deal with more than one targets.
else:
n = n
#Initiating a quantum circuit
qc = QuantumCircuit(n,n)
qc.h(range(n))
qc.draw()
#To find the number of repetition.
theta = asin(1/sqrt(2**n))
t = int((pi/(2*theta) - 1)/2)
#Finally applying all the component on the circuit.
for i in range(t):
qc.unitary(orc(d), range(n))
qc.h(range(n))
qc.unitary(dif(), range(n))
qc.h(range(n))
qc.draw()
#To print the statevector.
s_qc = qi.Statevector.from_instruction(qc)
#s_qc.draw('latex', prefix='State = ')
print(s_qc)
#Applying the measurements.
qc.measure(range(n),range(n))
qc.draw()
#Simulating the circuit
qasm_sim = Aer.get_backend('aer_simulator')
tqc = transpile(qc, basis_gates=['u', 'cx'], optimization_level=3)
print(f"circuit depth: {tqc.depth()}")
print(f"circuit contains {tqc.count_ops()['cx']} CNOTs")
#Getting final state probabilities.
counts = qasm_sim.run(tqc).result().get_counts()
print(counts)
plot_histogram(counts)
|
https://github.com/mentesniker/Quantum-Cryptography
|
mentesniker
|
%matplotlib inline
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from random import randint
import hashlib
#Alice cell, Bob can't see what's going in on here
m0 = randint(0,1)
Alice_base = randint(0,1)
qubits = list()
mycircuit = QuantumCircuit(1,1)
if(Alice_base == 0):
if(m0 == 1):
mycircuit.x(0)
else:
if(m0 == 0):
mycircuit.h(0)
else:
mycircuit.x(0)
mycircuit.h(0)
qubits.append(mycircuit)
#Bob cell, Alice can't see what's going in on here
backend = Aer.get_backend('qasm_simulator')
a = 0
qubit = qubits[0]
if(Alice_base == 0):
qubit.measure(0,0)
else:
qubit.h(0)
qubit.measure(0,0)
result = execute(qubit, backend, shots=1, memory=True).result()
a = int(result.get_memory()[0])
#Bob cell, Alice can't see what's going in on here
m1 = randint(0,1)
Bob_base = randint(0,1)
qubitsB = list()
mycircuitB = QuantumCircuit(1,1)
if(Bob_base == 0):
if(m1 == 1):
mycircuitB.x(0)
else:
if(m1 == 0):
mycircuitB.h(0)
else:
mycircuitB.x(0)
mycircuitB.h(0)
qubitsB.append(mycircuitB)
#Alice cell, Bob can't see what's going in on here
backend = Aer.get_backend('qasm_simulator')
b = 0
qubit = qubitsB[0]
if(Bob_base == 0):
qubit.measure(0,0)
else:
qubit.h(0)
qubit.measure(0,0)
result = execute(qubit, backend, shots=1, memory=True).result()
b = int(result.get_memory()[0])
#Alice cell, Bob can't see what's going in on here
print("The result of the coin flip was: " + str(b ^ m0))
#Bob cell, Alice can't see what's going in on here
print("The result of the coin flip was: " + str(m1 ^ a))
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the DenseLayout pass"""
import unittest
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit import Parameter, Qubit
from qiskit.circuit.library import CXGate, UGate, ECRGate, RZGate
from qiskit.transpiler import CouplingMap, Target, InstructionProperties, TranspilerError
from qiskit.transpiler.passes import DenseLayout
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeTokyo
from qiskit.transpiler.passes.layout.dense_layout import _build_error_matrix
class TestDenseLayout(QiskitTestCase):
"""Tests the DenseLayout pass"""
def setUp(self):
super().setUp()
self.cmap20 = FakeTokyo().configuration().coupling_map
self.target_19 = Target()
rng = np.random.default_rng(12345)
instruction_props = {
edge: InstructionProperties(
duration=rng.uniform(1e-7, 1e-6), error=rng.uniform(1e-4, 1e-3)
)
for edge in CouplingMap.from_heavy_hex(3).get_edges()
}
self.target_19.add_instruction(CXGate(), instruction_props)
def test_5q_circuit_20q_coupling(self):
"""Test finds dense 5q corner in 20q coupling map."""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(CouplingMap(self.cmap20))
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 11)
self.assertEqual(layout[qr[1]], 10)
self.assertEqual(layout[qr[2]], 6)
self.assertEqual(layout[qr[3]], 5)
self.assertEqual(layout[qr[4]], 0)
def test_6q_circuit_20q_coupling(self):
"""Test finds dense 5q corner in 20q coupling map."""
qr0 = QuantumRegister(3, "q0")
qr1 = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[0], qr1[2])
circuit.cx(qr1[1], qr0[2])
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(CouplingMap(self.cmap20))
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr0[0]], 11)
self.assertEqual(layout[qr0[1]], 10)
self.assertEqual(layout[qr0[2]], 6)
self.assertEqual(layout[qr1[0]], 5)
self.assertEqual(layout[qr1[1]], 1)
self.assertEqual(layout[qr1[2]], 0)
def test_5q_circuit_19q_target_with_noise(self):
"""Test layout works finds a dense 5q subgraph in a 19q heavy hex target."""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(target=self.target_19)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 9)
self.assertEqual(layout[qr[1]], 3)
self.assertEqual(layout[qr[2]], 11)
self.assertEqual(layout[qr[3]], 15)
self.assertEqual(layout[qr[4]], 4)
def test_5q_circuit_19q_target_without_noise(self):
"""Test layout works finds a dense 5q subgraph in a 19q heavy hex target with no noise."""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
instruction_props = {edge: None for edge in CouplingMap.from_heavy_hex(3).get_edges()}
noiseless_target = Target()
noiseless_target.add_instruction(CXGate(), instruction_props)
pass_ = DenseLayout(target=noiseless_target)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 1)
self.assertEqual(layout[qr[1]], 13)
self.assertEqual(layout[qr[2]], 0)
self.assertEqual(layout[qr[3]], 9)
self.assertEqual(layout[qr[4]], 3)
def test_ideal_target_no_coupling(self):
"""Test pass fails as expected if a target without edge constraints exists."""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
target = Target(num_qubits=19)
target.add_instruction(CXGate())
layout_pass = DenseLayout(target=target)
with self.assertRaises(TranspilerError):
layout_pass.run(dag)
def test_target_too_small_for_circuit(self):
"""Test error is raised when target is too small for circuit."""
target = Target()
target.add_instruction(
CXGate(), {edge: None for edge in CouplingMap.from_line(3).get_edges()}
)
dag = circuit_to_dag(QuantumCircuit(5))
layout_pass = DenseLayout(target=target)
with self.assertRaises(TranspilerError):
layout_pass.run(dag)
def test_19q_target_with_noise_error_matrix(self):
"""Test the error matrix construction works for a just cx target."""
expected_error_mat = np.zeros((19, 19))
for qargs, props in self.target_19["cx"].items():
error = props.error
expected_error_mat[qargs[0]][qargs[1]] = error
error_mat = _build_error_matrix(
self.target_19.num_qubits,
{i: i for i in range(self.target_19.num_qubits)},
target=self.target_19,
)[0]
np.testing.assert_array_equal(expected_error_mat, error_mat)
def test_multiple_gate_error_matrix(self):
"""Test error matrix ona small target with multiple gets on each qubit generates"""
target = Target(num_qubits=3)
phi = Parameter("phi")
lam = Parameter("lam")
theta = Parameter("theta")
target.add_instruction(
RZGate(phi), {(i,): InstructionProperties(duration=0, error=0) for i in range(3)}
)
target.add_instruction(
UGate(theta, phi, lam),
{(i,): InstructionProperties(duration=1e-7, error=1e-2) for i in range(3)},
)
cx_props = {
(0, 1): InstructionProperties(error=1e-3),
(0, 2): InstructionProperties(error=1e-3),
(1, 0): InstructionProperties(error=1e-3),
(1, 2): InstructionProperties(error=1e-3),
(2, 0): InstructionProperties(error=1e-3),
(2, 1): InstructionProperties(error=1e-3),
}
target.add_instruction(CXGate(), cx_props)
ecr_props = {
(0, 1): InstructionProperties(error=2e-2),
(1, 2): InstructionProperties(error=2e-2),
(2, 0): InstructionProperties(error=2e-2),
}
target.add_instruction(ECRGate(), ecr_props)
expected_error_matrix = np.array(
[
[1e-2, 2e-2, 1e-3],
[1e-3, 1e-2, 2e-2],
[2e-2, 1e-3, 1e-2],
]
)
error_mat = _build_error_matrix(
target.num_qubits, {i: i for i in range(target.num_qubits)}, target=target
)[0]
np.testing.assert_array_equal(expected_error_matrix, error_mat)
def test_5q_circuit_20q_with_if_else(self):
"""Test layout works finds a dense 5q subgraph in a 19q heavy hex target."""
qr = QuantumRegister(5, "q")
cr = ClassicalRegister(5)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr, cr)
false_body = QuantumCircuit(qr, cr)
true_body.cx(qr[0], qr[3])
true_body.cx(qr[3], qr[4])
false_body.cx(qr[3], qr[1])
false_body.cx(qr[0], qr[2])
circuit.if_else((cr, 0), true_body, false_body, qr, cr)
circuit.cx(0, 4)
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(CouplingMap(self.cmap20))
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 11)
self.assertEqual(layout[qr[1]], 10)
self.assertEqual(layout[qr[2]], 6)
self.assertEqual(layout[qr[3]], 5)
self.assertEqual(layout[qr[4]], 0)
def test_loose_bit_circuit(self):
"""Test dense layout works with loose bits outside a register."""
bits = [Qubit() for _ in range(5)]
circuit = QuantumCircuit()
circuit.add_bits(bits)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(CouplingMap(self.cmap20))
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[bits[0]], 11)
self.assertEqual(layout[bits[1]], 10)
self.assertEqual(layout[bits[2]], 6)
self.assertEqual(layout[bits[3]], 5)
self.assertEqual(layout[bits[4]], 0)
if __name__ == "__main__":
unittest.main()
|
https://github.com/riddheshMarkandeya/shors-algorithm-quantum
|
riddheshMarkandeya
|
from qiskit.quantum_info.operators import Operator
from qiskit.circuit.library import CU1Gate
#helper functions
def make_permutation_matrix(n, permutation):
r = np.zeros((n,n), dtype=int)
for i in range(n):
r[permutation(i), i] = 1
return r
def mult_mat(x,k,N):
n = math.ceil(math.log(N, 2))
return make_permutation_matrix(
2**n,
permutation=lambda y: y*pow(x,k) % N if y<N else y)
def c_mult_mat(x,k,N):
n = math.ceil(math.log(N, 2))
permutation = lambda y: y if y%2==0 or (y-1)/2 >= N else 2*(int((y-1)/2)*pow(x,k) % N) + 1
return make_permutation_matrix(2*(2**n), permutation )
def mult_op(x,k,N):
return Operator(mult_mat(x,k,N))
#controlled-U oracle
def c_mult_op(x,k,N):
return Operator(c_mult_mat(x,k,N))
# QFT and IQFT
def qft(circ, q, n):
"""n-qubit QFT on q in circ."""
for j in range(n):
circ.h(q[j])
for k in range(j+1,n):
circ.cu1(math.pi/float(2**(k-j)), q[k], q[j])
for i in range(n//2):
circ.swap(q[i], q[n-i-1])
def iqft(circ,q,n):
for j in range(n):
circ.h(q[j])
for k in range(j+1,n):
#circ.cu1(-math.pi/float(2**(k-j)), q[k], q[j])
gate = CU1Gate(-np.pi/float(2**(k-j)) )
circ.append(gate, [q[k],q[j]])
for i in range(n//2):
circ.swap(q[i], q[n-i-1])
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
CALCULATING NUMBER OF MEASUREMENTS NEEDED AGAINST AN ERROR RATE
Example: H2 molecule in sto3g basis
'''
import numpy as np
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper
# specifying the geometry of the molecule in question
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
hamiltonian = problem.hamiltonian
# electronic Hamiltonian of the system
second_q_op = hamiltonian.second_q_op()
# The Bravyi-Kitaev representation of the Fermionic Hamiltonian
mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = mapper.map(second_q_op)
print(bkencoded_hamiltonian)
def shadow_bound(error, observables, failure_rate=0.01):
"""
Method taken from: https://pennylane.ai/qml/demos/tutorial_classical_shadows
Calculate the shadow bound for the Pauli measurement scheme.
Implements Eq. (S13) from https://arxiv.org/pdf/2002.08953.pdf
Args:
error (float): The error on the estimator.
observables (list) : List of matrices corresponding to the observables we intend to
measure.
failure_rate (float): Rate of failure for the bound to hold.
Returns:
An integer that gives the number of samples required to satisfy the shadow bound and
the chunk size required attaining the specified failure rate.
"""
M = len(observables)
K = 2 * np.log(2 * M / failure_rate)
shadow_norm = (
lambda op: np.linalg.norm(
op - np.trace(op) / 2 ** int(np.log2(op.shape[0])), ord=np.inf
)
** 2
)
N = 34 * max(shadow_norm(o) for o in observables) / error ** 2
return int(np.ceil(N * K)), int(K)
matrix_observables = [obs.to_matrix().real for obs in bkencoded_hamiltonian]
num_measurements, chunk_size = shadow_bound(error=2e-1, observables=matrix_observables, failure_rate=0.01)
print('Number of measurements (error=2e-1):', num_measurements)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# load necessary Runtime libraries
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit.circuit import Parameter
from qiskit.opflow import I, X, Z
mu = Parameter('$\\mu$')
ham_pauli = mu * X
cc = Parameter('$c$')
ww = Parameter('$\\omega$')
ham_res = -(1/2)*ww*(I^Z) + cc*(X^X) + (ham_pauli^I)
tt = Parameter('$t$')
U_ham = (tt*ham_res).exp_i()
from qiskit import transpile
from qiskit.circuit import ClassicalRegister
from qiskit.opflow import PauliTrotterEvolution, Suzuki
import numpy as np
num_trot_steps = 5
total_time = 10
cr = ClassicalRegister(1, 'c')
spec_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=num_trot_steps)).convert(U_ham)
spec_circ = spec_op.to_circuit()
spec_circ_t = transpile(spec_circ, basis_gates=['sx', 'rz', 'cx'])
spec_circ_t.add_register(cr)
spec_circ_t.measure(0, cr[0])
spec_circ_t.draw('mpl')
# fixed Parameters
fixed_params = {
cc: 0.3,
mu: 0.7,
tt: total_time
}
# Parameter value for single circuit
param_keys = list(spec_circ_t.parameters)
# run through all the ww values to create a List of Lists of Parameter value
num_pts = 101
wvals = np.linspace(-2, 2, num_pts)
param_vals = []
for wval in wvals:
all_params = {**fixed_params, **{ww: wval}}
param_vals.append([all_params[key] for key in param_keys])
with Session(backend=backend):
sampler = Sampler()
job = sampler.run(
circuits=[spec_circ_t]*num_pts,
parameter_values=param_vals,
shots=1e5
)
result = job.result()
Zexps = []
for dist in result.quasi_dists:
if 1 in dist:
Zexps.append(1 - 2*dist[1])
else:
Zexps.append(1)
from qiskit.opflow import PauliExpectation, Zero
param_bind = {
cc: 0.3,
mu: 0.7,
tt: total_time
}
init_state = Zero^2
obsv = I^Z
Zexp_exact = (U_ham @ init_state).adjoint() @ obsv @ (U_ham @ init_state)
diag_meas_op = PauliExpectation().convert(Zexp_exact)
Zexact_values = []
for w_set in wvals:
param_bind[ww] = w_set
Zexact_values.append(np.real(diag_meas_op.bind_parameters(param_bind).eval()))
import matplotlib.pyplot as plt
plt.style.use('dark_background')
fig, ax = plt.subplots(dpi=100)
ax.plot([-param_bind[mu], -param_bind[mu]], [0, 1], ls='--', color='purple')
ax.plot([param_bind[mu], param_bind[mu]], [0, 1], ls='--', color='purple')
ax.plot(wvals, Zexact_values, label='Exact')
ax.plot(wvals, Zexps, label=f"{backend}")
ax.set_xlabel(r'$\omega$ (arb)')
ax.set_ylabel(r'$\langle Z \rangle$ Expectation')
ax.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import RealAmplitudes
from qiskit.algorithms.optimizers import COBYLA
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, SamplingVQE
from qiskit.primitives import Sampler
from qiskit_optimization.converters import LinearEqualityToPenalty
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.translators import from_docplex_mp
from qiskit.utils import algorithm_globals
import numpy as np
import matplotlib.pyplot as plt
from docplex.mp.model import Model
algorithm_globals.random_seed = 123456
# prepare problem instance
n = 6 # number of assets
q = 0.5 # risk factor
budget = n // 2 # budget
penalty = 2 * n # scaling of penalty term
# instance from [1]
mu = np.array([0.7313, 0.9893, 0.2725, 0.8750, 0.7667, 0.3622])
sigma = np.array(
[
[0.7312, -0.6233, 0.4689, -0.5452, -0.0082, -0.3809],
[-0.6233, 2.4732, -0.7538, 2.4659, -0.0733, 0.8945],
[0.4689, -0.7538, 1.1543, -1.4095, 0.0007, -0.4301],
[-0.5452, 2.4659, -1.4095, 3.5067, 0.2012, 1.0922],
[-0.0082, -0.0733, 0.0007, 0.2012, 0.6231, 0.1509],
[-0.3809, 0.8945, -0.4301, 1.0922, 0.1509, 0.8992],
]
)
# or create random instance
# mu, sigma = portfolio.random_model(n, seed=123) # expected returns and covariance matrix
# create docplex model
mdl = Model("portfolio_optimization")
x = mdl.binary_var_list(range(n), name="x")
objective = mdl.sum([mu[i] * x[i] for i in range(n)])
objective -= q * mdl.sum([sigma[i, j] * x[i] * x[j] for i in range(n) for j in range(n)])
mdl.maximize(objective)
mdl.add_constraint(mdl.sum(x[i] for i in range(n)) == budget)
# case to
qp = from_docplex_mp(mdl)
# solve classically as reference
opt_result = MinimumEigenOptimizer(NumPyMinimumEigensolver()).solve(qp)
print(opt_result.prettyprint())
# we convert the problem to an unconstrained problem for further analysis,
# otherwise this would not be necessary as the MinimumEigenSolver would do this
# translation automatically
linear2penalty = LinearEqualityToPenalty(penalty=penalty)
qp = linear2penalty.convert(qp)
_, offset = qp.to_ising()
# set classical optimizer
maxiter = 100
optimizer = COBYLA(maxiter=maxiter)
# set variational ansatz
ansatz = RealAmplitudes(n, reps=1)
m = ansatz.num_parameters
# set sampler
sampler = Sampler()
# run variational optimization for different values of alpha
alphas = [1.0, 0.50, 0.25] # confidence levels to be evaluated
# dictionaries to store optimization progress and results
objectives = {alpha: [] for alpha in alphas} # set of tested objective functions w.r.t. alpha
results = {} # results of minimum eigensolver w.r.t alpha
# callback to store intermediate results
def callback(i, params, obj, stddev, alpha):
# we translate the objective from the internal Ising representation
# to the original optimization problem
objectives[alpha].append(np.real_if_close(-(obj + offset)))
# loop over all given alpha values
for alpha in alphas:
# initialize SamplingVQE using CVaR
vqe = SamplingVQE(
sampler=sampler,
ansatz=ansatz,
optimizer=optimizer,
aggregation=alpha,
callback=lambda i, params, obj, stddev: callback(i, params, obj, stddev, alpha),
)
# initialize optimization algorithm based on CVaR-SamplingVQE
opt_alg = MinimumEigenOptimizer(vqe)
# solve problem
results[alpha] = opt_alg.solve(qp)
# print results
print("alpha = {}:".format(alpha))
print(results[alpha].prettyprint())
print()
# plot resulting history of objective values
plt.figure(figsize=(10, 5))
plt.plot([0, maxiter], [opt_result.fval, opt_result.fval], "r--", linewidth=2, label="optimum")
for alpha in alphas:
plt.plot(objectives[alpha], label="alpha = %.2f" % alpha, linewidth=2)
plt.legend(loc="lower right", fontsize=14)
plt.xlim(0, maxiter)
plt.xticks(fontsize=14)
plt.xlabel("iterations", fontsize=14)
plt.yticks(fontsize=14)
plt.ylabel("objective value", fontsize=14)
plt.show()
# evaluate and sort all objective values
objective_values = np.zeros(2**n)
for i in range(2**n):
x_bin = ("{0:0%sb}" % n).format(i)
x = [0 if x_ == "0" else 1 for x_ in reversed(x_bin)]
objective_values[i] = qp.objective.evaluate(x)
ind = np.argsort(objective_values)
# evaluate final optimal probability for each alpha
for alpha in alphas:
probabilities = np.fromiter(
results[alpha].min_eigen_solver_result.eigenstate.binary_probabilities().values(),
dtype=float,
)
print("optimal probability (alpha = %.2f): %.4f" % (alpha, probabilities[ind][-1:]))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
#Program 4.1 Apply CX-gate to qubit
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.cx(0,1)
qc.draw('mpl')
#Program 4.2 Show unitary matrix of CX-gate (MSB as target bit)
from qiskit import QuantumCircuit, Aer
from qiskit.visualization import array_to_latex
qc = QuantumCircuit(2)
qc.cx(0,1)
display(qc.draw('mpl'))
sim = Aer.get_backend('aer_simulator')
qc.save_unitary()
unitary = sim.run(qc).result().get_unitary()
display(array_to_latex(unitary, prefix="\\text{CNOT (MSB as target bit) = }"))
#Program 4.3 Show unitary matrix of CX-gate (LSB as target bit)
from qiskit import QuantumCircuit, Aer
from qiskit.visualization import array_to_latex
sim = Aer.get_backend('aer_simulator')
qc = QuantumCircuit(2)
qc.cx(1,0)
display(qc.draw('mpl'))
qc.save_unitary()
unitary = sim.run(qc).result().get_unitary()
display(array_to_latex(unitary, prefix="\\text{CNOT (LSB as target bit) = }"))
#Program 4.4a Appliy CX-gate to qubit
from qiskit import QuantumCircuit,execute
from qiskit.quantum_info import Statevector
qc = QuantumCircuit(8,8)
sv = Statevector.from_label('11011000')
qc.initialize(sv,range(8))
qc.cx(0,1)
qc.cx(2,3)
qc.cx(4,5)
qc.cx(6,7)
qc.measure(range(8),range(8))
qc.draw('mpl')
#Program 4.4b Measure state of qubit w/ CX-gate
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)
#Program 4.5 Build Bell state via H- and CX-gate
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1,0)
print("Below is the Bell state (top: q0 for target; bottom: q1 for control):")
display(qc.draw('mpl'))
print("Below is the Bell state (top: q1 for control; bottom: q0 for traget):")
display(qc.draw('mpl',reverse_bits=True))
#Program 4.6a Build Bell state via H- and CX-gate
from qiskit import QuantumCircuit
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.measure(range(2),range(2))
qc.draw('mpl')
#Program 4.6b Measure state of qubit in Bell state
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)
#Program 4.7a Iinitialize qubit and build Bell state via H- and CX-gate
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')
#Program 4.7b Measure state of qubit in Bell state
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)
#Program 4.8 Show quantum circuit for quantum teleportation
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
qs = QuantumRegister(1,'qs')
qa = QuantumRegister(1,'qa')
qb = QuantumRegister(1,'qb')
cr = ClassicalRegister(2,'c')
qc = QuantumCircuit(qs,qa,qb,cr)
qc.h(qa)
qc.cx(qa,qb)
qc.barrier()
qc.cx(qs,qa)
qc.h(qs)
qc.measure(qs,0)
qc.measure(qa,1)
qc.barrier()
qc.x(qb)
qc.z(qb)
qc.draw('mpl')
#Program 4.9 Apply CX-, CY-, CZ-, CH-, and SWAP-gate to qubit
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
qc.cx(0,1)
qc.cy(2,3)
qc.cz(4,5)
qc.ch(6,7)
qc.swap(8,9)
qc.cx(10,11)
qc.cx(11,10)
qc.cx(10,11)
qc.draw('mpl')
#Program 4.10 Apply CCX-gate to qubit
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
qc.ccx(0,1,2)
qc.draw('mpl')
#Program 4.11 Show unitary matrix of CCX-gate
from qiskit import QuantumCircuit, Aer
from qiskit.visualization import array_to_latex
sim = Aer.get_backend('aer_simulator')
qc1 = QuantumCircuit(3)
qc1.ccx(0,1,2)
print("="*70,"\nBelow is quantum circuit of CCNOT gate (MSB as target bit):")
display(qc1.draw('mpl'))
qc1.save_unitary()
unitary = sim.run(qc1).result().get_unitary()
display(array_to_latex(unitary, prefix="\\text{CCNOT (MSB as target bit) = }\n"))
qc2 = QuantumCircuit(3)
qc2.ccx(2,1,0)
print("="*70,"\nBelow is quantum circuit of CCNOT gate (LSB as target bit):")
display(qc2.draw('mpl'))
qc2.save_unitary()
unitary = sim.run(qc2).result().get_unitary()
display(array_to_latex(unitary, prefix="\\text{CCNOT (LSB as target bit) = }\n"))
#Program 4.12 Apply CCCCX-gate to qubit
from qiskit import QuantumCircuit
qc = QuantumCircuit(7)
qc.ccx(0,1,4)
qc.ccx(2,3,5)
qc.ccx(4,5,6)
qc.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
pw_approximation._build()
qc = QuantumCircuit(pw_approximation.num_qubits)
qc.h(list(range(num_state_qubits)))
qc.append(pw_approximation.to_instruction(), qc.qubits)
qc.draw(output='mpl')
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
import qiskit
from qiskit_aer.backends.aerbackend import AerBackend
from dc_qiskit_qml.encoding_maps import NormedAmplitudeEncoding
from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier
from dc_qiskit_qml.distance_based.hadamard.state import QmlGenericStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import MottonenStatePreparation
initial_state_builder = QmlGenericStateCircuitBuilder(MottonenStatePreparation())
execution_backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator')
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
classifier_circuit_factory=initial_state_builder,
encoding_map=NormedAmplitudeEncoding())
import numpy as np
from sklearn.preprocessing import StandardScaler, Normalizer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=42)
pipeline = Pipeline([
('scaler', StandardScaler()),
('pca2', PCA(n_components=2)),
('l2norm', Normalizer(norm='l2', copy=True)),
('qml', qml)
])
import matplotlib.pyplot as plt
_X = pipeline.fit_transform(X, y)
figure = plt.figure(figsize=(5,5), num=2)
sub1 = figure.subplots(nrows=1, ncols=1)
class_0_data = np.asarray([_X[i] for i in range(len(_X)) if y[i] == 0])
class_1_data = np.asarray([_X[i] for i in range(len(_X)) if y[i] == 1])
class_2_data = np.asarray([_X[i] for i in range(len(_X)) if y[i] == 2])
class_0 = sub1.scatter(class_0_data[:,0], class_0_data[:,1], color='red', marker='x', s=50)
class_1 = sub1.scatter(class_1_data[:,0], class_1_data[:,1], color='blue', marker='x', s=50)
class_2 = sub1.scatter(class_2_data[:,0], class_2_data[:,1], color='green', marker='x', s=50)
sub1.plot([np.cos(x) for x in np.arange(0, 2*np.pi, 0.1)], [np.sin(x) for x in np.arange(0, 2*np.pi, 0.1)],
color='black', linewidth=1)
sub1.set_title("Iris Data")
sub1.legend([class_0, class_1, class_2], ["Class 1", "Class 2", "Class 3"])
sub1.axvline(color='gray')
sub1.axhline(color='gray')
_X_train = pipeline.transform(X_train)
_X_test = pipeline.transform(X_test)
figure = plt.figure(figsize=(10,4.5), num=2)
sub1, sub2 = figure.subplots(nrows=1, ncols=2)
class_0_data = np.asarray([_X_train[i] for i in range(len(_X_train)) if y_train[i] == 0])
class_1_data = np.asarray([_X_train[i] for i in range(len(_X_train)) if y_train[i] == 1])
class_2_data = np.asarray([_X_train[i] for i in range(len(_X_train)) if y_train[i] == 2])
class_0 = sub1.scatter(class_0_data[:,0], class_0_data[:,1], color='red', marker='x', s=50)
class_1 = sub1.scatter(class_1_data[:,0], class_1_data[:,1], color='blue', marker='x', s=50)
class_2 = sub1.scatter(class_2_data[:,0], class_2_data[:,1], color='green', marker='x', s=50)
sub1.plot([np.cos(x) for x in np.arange(0, 2*np.pi, 0.1)], [np.sin(x) for x in np.arange(0, 2*np.pi, 0.1)],
color='black', linewidth=1)
sub1.set_title("Training data")
sub1.legend([class_0, class_1, class_2], ["Class 1", "Class 2", "Class 3"])
sub1.axvline(color='gray')
sub1.axhline(color='gray')
class_0_data_test = np.asarray([_X_test[i] for i in range(len(_X_test)) if y_test[i] == 0])
class_1_data_test = np.asarray([_X_test[i] for i in range(len(_X_test)) if y_test[i] == 1])
class_2_data_test = np.asarray([_X_test[i] for i in range(len(_X_test)) if y_test[i] == 2])
class_0 = sub2.scatter(class_0_data_test[:,0], class_0_data_test[:,1], color='red', marker='x', s=50)
class_1 = sub2.scatter(class_1_data_test[:,0], class_1_data_test[:,1], color='blue', marker='x', s=50)
class_2 = sub2.scatter(class_2_data_test[:,0], class_2_data_test[:,1], color='green', marker='x', s=50)
sub2.plot([np.cos(x) for x in np.arange(0, 2*np.pi, 0.1)], [np.sin(x) for x in np.arange(0, 2*np.pi, 0.1)],
color='black', linewidth=1)
sub2.set_title("Testing data")
sub2.legend([class_0, class_1, class_2], ["Class 1", "Class 2", "Class 3"])
sub2.axvline(color='gray')
sub2.axhline(color='gray')
pipeline.fit(X_train, y_train)
prediction = pipeline.predict(X_test)
prediction
"Test Accuracy: {}".format(
sum([1 if p == t else 0 for p, t in zip(prediction, y_test)])/len(prediction)
)
prediction_train = pipeline.predict(X_train)
"Train Accuracy: {}".format(
sum([1 if p == t else 0 for p, t in zip(prediction_train, y_train)])/len(prediction_train)
)
for i in range(len(_X_test)):
p_acc_theory = QmlHadamardNeighborClassifier.p_acc_theory(_X_train, y_train, _X_test[i])
print(f"{qml.last_predict_p_acc[i]:.4f} ~~ {p_acc_theory:.4f}")
for i in range(len(_X_test)):
p_label_theory = QmlHadamardNeighborClassifier.p_label_theory(_X_train, y_train, _X_test[i], prediction[i])
print(f"{qml.last_predict_probability[i]:.4f} ~~ {p_label_theory:.4f}")
print(qml._last_predict_circuits[0].qasm())
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
# Checking the version of PYTHON; we only support > 3.5
import sys
if sys.version_info < (3,5):
raise Exception('Please use Python version 3.5 or greater.')
# useful additional packages
import numpy as np
import random
import re # regular expressions module
# importing the QISKit
from qiskit import QuantumCircuit, QuantumProgram
#import Qconfig
# Quantum program setup
Q_program = QuantumProgram()
#Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url
# Creating registers
qr = Q_program.create_quantum_register("qr", 2)
cr = Q_program.create_classical_register("cr", 4)
singlet = Q_program.create_circuit('singlet', [qr], [cr])
singlet.x(qr[0])
singlet.x(qr[1])
singlet.h(qr[0])
singlet.cx(qr[0],qr[1])
## Alice's measurement circuits
# measure the spin projection of Alice's qubit onto the a_1 direction (X basis)
measureA1 = Q_program.create_circuit('measureA1', [qr], [cr])
measureA1.h(qr[0])
measureA1.measure(qr[0],cr[0])
# measure the spin projection of Alice's qubit onto the a_2 direction (W basis)
measureA2 = Q_program.create_circuit('measureA2', [qr], [cr])
measureA2.s(qr[0])
measureA2.h(qr[0])
measureA2.t(qr[0])
measureA2.h(qr[0])
measureA2.measure(qr[0],cr[0])
# measure the spin projection of Alice's qubit onto the a_3 direction (standard Z basis)
measureA3 = Q_program.create_circuit('measureA3', [qr], [cr])
measureA3.measure(qr[0],cr[0])
## Bob's measurement circuits
# measure the spin projection of Bob's qubit onto the b_1 direction (W basis)
measureB1 = Q_program.create_circuit('measureB1', [qr], [cr])
measureB1.s(qr[1])
measureB1.h(qr[1])
measureB1.t(qr[1])
measureB1.h(qr[1])
measureB1.measure(qr[1],cr[1])
# measure the spin projection of Bob's qubit onto the b_2 direction (standard Z basis)
measureB2 = Q_program.create_circuit('measureB2', [qr], [cr])
measureB2.measure(qr[1],cr[1])
# measure the spin projection of Bob's qubit onto the b_3 direction (V basis)
measureB3 = Q_program.create_circuit('measureB3', [qr], [cr])
measureB3.s(qr[1])
measureB3.h(qr[1])
measureB3.tdg(qr[1])
measureB3.h(qr[1])
measureB3.measure(qr[1],cr[1])
## Lists of measurement circuits
aliceMeasurements = [measureA1, measureA2, measureA3]
bobMeasurements = [measureB1, measureB2, measureB3]
# Define the number of singlets N
numberOfSinglets = 500
aliceMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b of Alice
bobMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b' of Bob
circuits = [] # the list in which the created circuits will be stored
for i in range(numberOfSinglets):
# create the name of the i-th circuit depending on Alice's and Bob's measurement choices
circuitName = str(i) + ':A' + str(aliceMeasurementChoices[i]) + '_B' + str(bobMeasurementChoices[i])
# create the joint measurement circuit
# add Alice's and Bob's measurement circuits to the singlet state curcuit
Q_program.add_circuit(circuitName,
singlet + # singlet state circuit
aliceMeasurements[aliceMeasurementChoices[i]-1] + # measurement circuit of Alice
bobMeasurements[bobMeasurementChoices[i]-1] # measurement circuit of Bob
)
# add the created circuit to the circuits list
circuits.append(circuitName)
print(circuits[0])
result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240)
print(result)
result.get_counts(circuits[0])
abPatterns = [
re.compile('..00$'), # search for the '..00' output (Alice obtained -1 and Bob obtained -1)
re.compile('..01$'), # search for the '..01' output
re.compile('..10$'), # search for the '..10' output (Alice obtained -1 and Bob obtained 1)
re.compile('..11$') # search for the '..11' output
]
aliceResults = [] # Alice's results (string a)
bobResults = [] # Bob's results (string a')
for i in range(numberOfSinglets):
res = list(result.get_counts(circuits[i]).keys())[0] # extract the key from the dict and transform it to str; execution result of the i-th circuit
if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(-1) # Bob got the result -1
if abPatterns[1].search(res):
aliceResults.append(1)
bobResults.append(-1)
if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(1) # Bob got the result 1
if abPatterns[3].search(res):
aliceResults.append(1)
bobResults.append(1)
aliceKey = [] # Alice's key string k
bobKey = [] # Bob's key string k'
# comparing the stings with measurement choices
for i in range(numberOfSinglets):
# if Alice and Bob have measured the spin projections onto the a_2/b_1 or a_3/b_2 directions
if (aliceMeasurementChoices[i] == 2 and bobMeasurementChoices[i] == 1) or (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 2):
aliceKey.append(aliceResults[i]) # record the i-th result obtained by Alice as the bit of the secret key k
bobKey.append(- bobResults[i]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k'
keyLength = len(aliceKey) # length of the secret key
abKeyMismatches = 0 # number of mismatching bits in Alice's and Bob's keys
for j in range(keyLength):
if aliceKey[j] != bobKey[j]:
abKeyMismatches += 1
# function that calculates CHSH correlation value
def chsh_corr(result):
# lists with the counts of measurement results
# each element represents the number of (-1,-1), (-1,1), (1,-1) and (1,1) results respectively
countA1B1 = [0, 0, 0, 0] # XW observable
countA1B3 = [0, 0, 0, 0] # XV observable
countA3B1 = [0, 0, 0, 0] # ZW observable
countA3B3 = [0, 0, 0, 0] # ZV observable
for i in range(numberOfSinglets):
res = list(result.get_counts(circuits[i]).keys())[0]
# if the spins of the qubits of the i-th singlet were projected onto the a_1/b_1 directions
if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 1):
for j in range(4):
if abPatterns[j].search(res):
countA1B1[j] += 1
if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 3):
for j in range(4):
if abPatterns[j].search(res):
countA1B3[j] += 1
if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 1):
for j in range(4):
if abPatterns[j].search(res):
countA3B1[j] += 1
# if the spins of the qubits of the i-th singlet were projected onto the a_3/b_3 directions
if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 3):
for j in range(4):
if abPatterns[j].search(res):
countA3B3[j] += 1
# number of the results obtained from the measurements in a particular basis
total11 = sum(countA1B1)
total13 = sum(countA1B3)
total31 = sum(countA3B1)
total33 = sum(countA3B3)
# expectation values of XW, XV, ZW and ZV observables (2)
expect11 = (countA1B1[0] - countA1B1[1] - countA1B1[2] + countA1B1[3])/total11 # -1/sqrt(2)
expect13 = (countA1B3[0] - countA1B3[1] - countA1B3[2] + countA1B3[3])/total13 # 1/sqrt(2)
expect31 = (countA3B1[0] - countA3B1[1] - countA3B1[2] + countA3B1[3])/total31 # -1/sqrt(2)
expect33 = (countA3B3[0] - countA3B3[1] - countA3B3[2] + countA3B3[3])/total33 # -1/sqrt(2)
corr = expect11 - expect13 + expect31 + expect33 # calculate the CHSC correlation value (3)
return corr
corr = chsh_corr(result) # CHSH correlation value
# CHSH inequality test
print('CHSH correlation value: ' + str(round(corr, 3)))
# Keys
print('Length of the key: ' + str(keyLength))
print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n')
# measurement of the spin projection of Alice's qubit onto the a_2 direction (W basis)
measureEA2 = Q_program.create_circuit('measureEA2', [qr], [cr])
measureEA2.s(qr[0])
measureEA2.h(qr[0])
measureEA2.t(qr[0])
measureEA2.h(qr[0])
measureEA2.measure(qr[0],cr[2])
# measurement of the spin projection of Allice's qubit onto the a_3 direction (standard Z basis)
measureEA3 = Q_program.create_circuit('measureEA3', [qr], [cr])
measureEA3.measure(qr[0],cr[2])
# measurement of the spin projection of Bob's qubit onto the b_1 direction (W basis)
measureEB1 = Q_program.create_circuit('measureEB1', [qr], [cr])
measureEB1.s(qr[1])
measureEB1.h(qr[1])
measureEB1.t(qr[1])
measureEB1.h(qr[1])
measureEB1.measure(qr[1],cr[3])
# measurement of the spin projection of Bob's qubit onto the b_2 direction (standard Z measurement)
measureEB2 = Q_program.create_circuit('measureEB2', [qr], [cr])
measureEB2.measure(qr[1],cr[3])
# lists of measurement circuits
eveMeasurements = [measureEA2, measureEA3, measureEB1, measureEB2]
# list of Eve's measurement choices
# the first and the second elements of each row represent the measurement of Alice's and Bob's qubits by Eve respectively
eveMeasurementChoices = []
for j in range(numberOfSinglets):
if random.uniform(0, 1) <= 0.5: # in 50% of cases perform the WW measurement
eveMeasurementChoices.append([0, 2])
else: # in 50% of cases perform the ZZ measurement
eveMeasurementChoices.append([1, 3])
circuits = [] # the list in which the created circuits will be stored
for j in range(numberOfSinglets):
# create the name of the j-th circuit depending on Alice's, Bob's and Eve's choices of measurement
circuitName = str(j) + ':A' + str(aliceMeasurementChoices[j]) + '_B' + str(bobMeasurementChoices[j] + 2) + '_E' + str(eveMeasurementChoices[j][0]) + str(eveMeasurementChoices[j][1] - 1)
# create the joint measurement circuit
# add Alice's and Bob's measurement circuits to the singlet state curcuit
Q_program.add_circuit(circuitName,
singlet + # singlet state circuit
eveMeasurements[eveMeasurementChoices[j][0]-1] + # Eve's measurement circuit of Alice's qubit
eveMeasurements[eveMeasurementChoices[j][1]-1] + # Eve's measurement circuit of Bob's qubit
aliceMeasurements[aliceMeasurementChoices[j]-1] + # measurement circuit of Alice
bobMeasurements[bobMeasurementChoices[j]-1] # measurement circuit of Bob
)
# add the created circuit to the circuits list
circuits.append(circuitName)
result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240)
print(result)
print(str(circuits[0]) + '\t' + str(result.get_counts(circuits[0])))
ePatterns = [
re.compile('00..$'), # search for the '00..' result (Eve obtained the results -1 and -1 for Alice's and Bob's qubits)
re.compile('01..$'), # search for the '01..' result (Eve obtained the results 1 and -1 for Alice's and Bob's qubits)
re.compile('10..$'),
re.compile('11..$')
]
aliceResults = [] # Alice's results (string a)
bobResults = [] # Bob's results (string a')
# list of Eve's measurement results
# the elements in the 1-st column are the results obtaned from the measurements of Alice's qubits
# the elements in the 2-nd column are the results obtaned from the measurements of Bob's qubits
eveResults = []
# recording the measurement results
for j in range(numberOfSinglets):
res = list(result.get_counts(circuits[j]).keys())[0] # extract a key from the dict and transform it to str
# Alice and Bob
if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(-1) # Bob got the result -1
if abPatterns[1].search(res):
aliceResults.append(1)
bobResults.append(-1)
if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(1) # Bob got the result 1
if abPatterns[3].search(res):
aliceResults.append(1)
bobResults.append(1)
# Eve
if ePatterns[0].search(res): # check if the key is '00..'
eveResults.append([-1, -1]) # results of the measurement of Alice's and Bob's qubits are -1,-1
if ePatterns[1].search(res):
eveResults.append([1, -1])
if ePatterns[2].search(res):
eveResults.append([-1, 1])
if ePatterns[3].search(res):
eveResults.append([1, 1])
aliceKey = [] # Alice's key string a
bobKey = [] # Bob's key string a'
eveKeys = [] # Eve's keys; the 1-st column is the key of Alice, and the 2-nd is the key of Bob
# comparing the strings with measurement choices (b and b')
for j in range(numberOfSinglets):
# if Alice and Bob measured the spin projections onto the a_2/b_1 or a_3/b_2 directions
if (aliceMeasurementChoices[j] == 2 and bobMeasurementChoices[j] == 1) or (aliceMeasurementChoices[j] == 3 and bobMeasurementChoices[j] == 2):
aliceKey.append(aliceResults[j]) # record the i-th result obtained by Alice as the bit of the secret key k
bobKey.append(-bobResults[j]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k'
eveKeys.append([eveResults[j][0], -eveResults[j][1]]) # record the i-th bits of the keys of Eve
keyLength = len(aliceKey) # length of the secret skey
abKeyMismatches = 0 # number of mismatching bits in the keys of Alice and Bob
eaKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Alice
ebKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Bob
for j in range(keyLength):
if aliceKey[j] != bobKey[j]:
abKeyMismatches += 1
if eveKeys[j][0] != aliceKey[j]:
eaKeyMismatches += 1
if eveKeys[j][1] != bobKey[j]:
ebKeyMismatches += 1
eaKnowledge = (keyLength - eaKeyMismatches)/keyLength # Eve's knowledge of Bob's key
ebKnowledge = (keyLength - ebKeyMismatches)/keyLength # Eve's knowledge of Alice's key
corr = chsh_corr(result)
# CHSH inequality test
print('CHSH correlation value: ' + str(round(corr, 3)) + '\n')
# Keys
print('Length of the key: ' + str(keyLength))
print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n')
print('Eve\'s knowledge of Alice\'s key: ' + str(round(eaKnowledge * 100, 2)) + ' %')
print('Eve\'s knowledge of Bob\'s key: ' + str(round(ebKnowledge * 100, 2)) + ' %')
|
https://github.com/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/hephaex/Quantum-Computing-Awesome-List
|
hephaex
|
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram, plot_bloch_vector
from math import sqrt, pi
%config InlineBackend.figure_format = 'svg' # Makes the images look nice
qc = QuantumCircuit(1)
initial_state = [0,1]
qc.initialize(initial_state, 0)
qc.draw()
backend = Aer.get_backend('statevector_simulator')
result = execute(qc,backend).result()
state_vector = result.get_statevector()
print(state_vector)
qc.measure_all()
qc.draw()
result = execute(qc, backend).result()
counts = result.get_counts()
plot_histogram(counts)
initial_state = [1/sqrt(2), complex(0,1/sqrt(2))]
qc = QuantumCircuit(1)
qc.initialize(initial_state, 0)
qc.draw()
backend = Aer.get_backend('statevector_simulator')
result = execute(qc, backend).result()
statevector = result.get_statevector()
print(statevector)
counts = result.get_counts()
plot_histogram(counts)
initialize_state = [1/sqrt(3), sqrt(2/3)]
qc = QuantumCircuit(1)
qc.initialize(initialize_state, 0)
qc.draw()
result = execute(qc, backend).result()
counts = result.get_counts()
plot_histogram(counts)
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### removed h gate ###
return qc
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0, 4.0, 5.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder(qc, targets=[0,1,2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
t1 = time.perf_counter()
qc = qc.bind_parameters({dt: target_time / num_steps})
t2 = time.perf_counter()
print("created qc,", t2 - t1, "s")
# Generate state tomography circuits to evaluate fidelity of simulation
t1 = time.perf_counter()
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
t2 = time.perf_counter()
print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s")
# remove barriers
t1 = time.perf_counter()
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
t2 = time.perf_counter()
print("removed barriers from st_qcs,", t2 - t1, "s")
# optimize circuit
t1 = time.perf_counter()
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s")
t3_st_qcs[0].draw("mpl")
# zne wrapping
t1 = time.perf_counter()
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors)
t2 = time.perf_counter()
print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
t2 = time.perf_counter()
print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
shots = 1 << 13
reps = 1 # unused
# Number of trotter steps
print("trotter step: ", num_steps)
# execute: reps = 1
job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors=scale_factors)
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fidelity = state_fidelity(rho, target_state)
print(fidelity)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
ghz.draw(output='mpl')
|
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
|
vandnaChaturvedi
|
#from qiskit_textbook.widgets import dj_widget
#dj_widget(size="small", case="balanced")
# initialization
####################################################################################################################### qiskit_edit_1
from qiskit import QuantumCircuit, execute
from qiskit import QuantumRegister, ClassicalRegister
from qiskit.tools.monitor import job_monitor
from qiskit import *
import time
import matplotlib.pyplot as plt
import argparse
import sys
from concurrent.futures import ThreadPoolExecutor
import resource
from time import sleep
#########################################################################################################################
import numpy as np
options = {
'plot': True,
"rotation_error": {'rx':[0.9, 0.9], 'ry':[0.9, 0.9], 'rz':[0.9, 0.9]},
"tsp_model_error": [0.9, 0.9],
"thermal_factor": 0.9,
"decoherence_factor": 0.9,
"depolarization_factor": 0.9,
"bell_depolarization_factor": 0.9,
"decay_factor": 0.89,
}
# importing Qiskit
#from qiskit import IBMQ, Aer
#from qiskit.providers.ibmq import least_busy
#from qiskit import QuantumCircuit, assemble, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw()
dj_circuit = QuantumCircuit(n+1, n+1)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
dj_circuit.draw()
dj_circuit = QuantumCircuit(n+1, n+1)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit += balanced_oracle
dj_circuit.draw()
dj_circuit = QuantumCircuit(n+1, n+1)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
# dj_circuit += balanced_oracle
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i, basis='Ensemble', add_param='Z')
# Display circuit
dj_circuit.draw()
# use local simulator
backend = qiskit.BasicAer.get_backend('dm_simulator')
job = execute(dj_circuit, backend=backend, shots=1)
#job1 = execute(dj_circuit, backend=backend, backend_options=options, shots=1)
job_result = job.result()
#job_result1 = job1.result()
#print(job_result['results'][0]['data']['densitymatrix'])
#print(job_result1['results'][0]['data']['densitymatrix'])
job_result['results'][0]['data']['ensemble_probability']
backend = qiskit.BasicAer.get_backend('dm_simulator')
job1 = execute(dj_circuit, backend=backend, backend_options=options, shots=1)
job_result1 = job1.result()
job_result1['results'][0]['data']['ensemble_probability']
no_noise=job_result['results'][0]['data']['ensemble_probability']
x= no_noise.keys()
y = no_noise.values()
plt.bar(x, y, width=0.6, label='No Noise')
plt.xlabel('combination of bits')
plt.ylabel('Probablities')
plt.title('Ensemble Probabilities')
plt.figure(figsize=(3, 3))
plt.show()
noisy=job_result1['results'][0]['data']['ensemble_probability']
x1 = noisy.keys()
y1 = noisy.values()
plt.bar(x1, y1, width=0.6, label='Noisy', color='coral')
plt.xlabel('combination of bits')
plt.ylabel('Probablities')
plt.title('Ensemble Probabilities Over Noisy data')
plt.show()
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i, basis='Ensemble', add_param='Z')
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw()
##NO_NOISE
backend = qiskit.BasicAer.get_backend('dm_simulator')
job = execute(dj_circuit, backend=backend, shots=1)
job_result = job.result()
print(job_result['results'][0]['data']['densitymatrix'])
##plot_histogram(answer) ###no histrogram because of single shot in DM simulator
## Noisy
job1 = execute(dj_circuit, backend=backend, backend_options=options, shots=1)
job_result1 = job1.result()
print(job_result1['results'][0]['data']['densitymatrix'])
from qiskit.visualization import plot_state_city
get_ipython().run_line_magic('matplotlib', 'inline')
plot_state_city(job_result1['results'][0]['data']['densitymatrix'], color=['midnightblue', 'midnightblue'],title="Density Matrix_no_noise")
##no_noise_ensemble_probabs
job_result['results'][0]['data']['ensemble_probability']
##noisy_ensemble_probabs
job_result1['results'][0]['data']['ensemble_probability']
no_noise=job_result['results'][0]['data']['ensemble_probability']
noisy=job_result1['results'][0]['data']['ensemble_probability']
labels = noisy.keys()
without_noise = no_noise.values()
with_noise = noisy.values()
x = np.arange(len(labels)) # the label locations
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise')
rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Probability')
ax.set_title('Ensemble Probabilities with Noise')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
plt.show()
# Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3)
job = backend.run(transpiled_dj_circuit)
job_monitor(job, interval=2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
from qiskit_textbook.problems import dj_problem_oracle
oracle = dj_problem_oracle(1)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/QPower-Research/QPowerAlgo
|
QPower-Research
|
from qiskit import *
from qiskit.visualization import *
import matplotlib.pyplot as plt
import numpy as np
import math
simulator = BasicAer.get_backend('qasm_simulator')
prob_distr = [8, 40, 35, 20, 15, 10, 5, 5]
#normalization
prob_distr = [k/sum(prob_distr) for k in prob_distr]
plt.bar(range(len(prob_distr)),prob_distr)
def ansatz(param, num_layers):
num_q = 3
qc = QuantumCircuit(num_q, num_q)
for j in range(num_layers):
for i in range(num_q):
qc.ry(param[i + j*num_q], i)
if j < num_layers-1:
qc.cx(0,1)
qc.cx(1,2)
qc.cx(2,0)
qc.barrier()
qc.measure(range(num_q), range(num_q))
return qc
ansatz(param = np.random.uniform(0, np.pi, 9), num_layers=3).draw('mpl',fold=-1)
num_layers = 5
def loss_function(params):
num_shots=1024
circ = ansatz(param=params, num_layers=num_layers)
counts = execute(circ, backend=simulator, shots=num_shots).result().get_counts(circ)
strings = ['000','001','010','011','100','101','110','111']
for i in strings:
if i not in counts:
counts[i] = 0
p = [counts[string]/num_shots for string in strings]
"""
cross_entropy = 0
for i in range(len(p)):
if p[i]>0:
cross_entropy -= prob_distr[i]*math.log2(p[i])
return cross_entropy
"""
return sum([(p[i] - prob_distr[i])**2 for i in range(len(prob_distr))])
#return sum([abs(p[i] - prob_distr[i]) for i in range(len(prob_distr))])
#return sum([ prob_distr[i]*math.log2(p[i]) for i in range(len(prob_distr))])
from qiskit.algorithms.optimizers import COBYLA,SLSQP,SPSA
optimizer = COBYLA(250)
ret = optimizer.optimize(num_vars=num_params, objective_function=loss_function, initial_point=np.ones(num_params))
num_shots = 1024
trained_circ = ansatz(param=ret[0], num_layers=num_layers)
counts = execute(trained_circ, backend=simulator, shots=num_shots).result().get_counts(trained_circ)
strings = ['000','001','010','011','100','101','110','111']
for k in strings:
if k not in counts:
counts[k]=0
counts = [counts[i]/1024 for i in strings]
plt.plot(range(len(counts)),counts, color='r')
plt.bar(range(len(prob_distr)), prob_distr)
plt.legend(["qGAN approx.", "Reference"])
plt.title("Probability distributions")
plt.grid()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
# TODO: This example should use a real mock backend.
backend = FakeOpenPulse3Q()
d2 = pulse.DriveChannel(2)
with pulse.build(backend) as bell_prep:
pulse.u2(0, math.pi, 0)
pulse.cx(0, 1)
with pulse.build(backend) as decoupled_bell_prep_and_measure:
# We call our bell state preparation schedule constructed above.
with pulse.align_right():
pulse.call(bell_prep)
pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2)
pulse.barrier(0, 1, 2)
registers = pulse.measure_all()
decoupled_bell_prep_and_measure.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
# You can reverse the order of the qubits.
from qiskit.quantum_info import DensityMatrix
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.t(1)
qc.s(0)
qc.cx(0,1)
matrix = DensityMatrix(qc)
plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
N = 2**10; th = asin(1/sqrt(N)); N, float(th), float(sin(th)), float(th*180/pi), sqrt(N)
my_list = [1,3,5,2,4,9,5,8,0,7,6]
def my_oracle(my_input):
solution = 2
if my_input == solution:
response = True
else:
response = False
return response
my_input = 7; res = my_oracle(my_input); print(res)
for j in range(0,len(my_list)):
if my_oracle(my_list[j]) == True:
print('Solução encontrada no índice',j, ', após ', j+1, ' consultas ao oráculo.')
from qiskit import *
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_belem')
from qiskit.tools.monitor import job_monitor
from qiskit.tools.visualization import plot_histogram
def qc_Uz(n): # 2|0><0| - I
qc = QuantumCircuit(n, name = 'Uz')
qrl = []
for j in range(0, n):
qrl.append(j)
qc.z(0); qc.x(0); qc.z(0); qc.x(0)
qc.x(qrl) # 00...0 -> 11...1
qc.h(n-1); qc.mcx(qrl[0:n-1],n-1); qc.h(n-1) # Cz multicontrolada. Multiplica 11...1 por -1
qc.x(qrl); # 11...1 -> 00...0
return qc
qc_Uz_ = qc_Uz(3); qc_Uz_.draw()
def qc_Uh(n): # 2|h><h| - I
qc = QuantumCircuit(n, name = 'Uh')
qrl = []
for j in range(0, n):
qrl.append(j)
qc.h(qrl) # transforma Uz em Uh
qc_Uz_ = qc_Uz(n); qc.append(qc_Uz_, qrl)
qc.h(qrl)
return qc
qc_Uh_ = qc_Uh(3); qc_Uh_.draw()
def qc_oracle(n):
# Nielsen & Chuang, Box 6.1 (N=4)
qc = QuantumCircuit(n+1, name = 'Oracle')
qc.ccx(0,1,2) # para a solução sendo o estado |11>
return qc
qc_oracle_ = qc_oracle(2)
qc_oracle_.draw('mpl')
def qc_grover_iteration(n):
qc = QuantumCircuit(n+1, name = 'G')
qrl = []
for j in range(0, n+1):
qrl.append(j)
qc_oracle_ = qc_oracle(n)
qc.append(qc_oracle_, qrl)
qc_Uh_ = qc_Uh(n); qc.append(qc_Uh_, qrl[0:n])
return qc
qc_grover_iteration_ = qc_grover_iteration(2)
qc_grover_iteration_.draw('mpl')
def qc_hadamard_state(n): # aplica a Hadamard em n qubits
qc = QuantumCircuit(n, name = 'H state') # começarei a não usar mais os qr[j]
qrl = [] # lista de registros quânticos
for j in range(0, n):
qrl.append(j)
qc.h(qrl) # aplica a hadamard em toda a lista de registros quânticos
return qc
qc_hadamard_state_ = qc_hadamard_state(3); qc_hadamard_state_.draw()
def qc_grover_search(n):
qc = QuantumCircuit(n+1, n)
qc.x(n)
qrl = [] # lista de registros quânticos
for j in range(0, n+1):
qrl.append(j)
qc_hadamard_state_ = qc_hadamard_state(n+1); qc.append(qc_hadamard_state_, qrl)
for j in range(0, int((math.pi*math.sqrt(2**n))/4 - 1/2)):
qc_grover_iteration_ = qc_grover_iteration(n); qc.append(qc_grover_iteration_, qrl)
qc.measure(qrl[0:n], qrl[0:n])
return qc
qc_grover_search_ = qc_grover_search(2); qc_grover_search_.draw()
qc_grover_search_ = qc_grover_search(2)
result = execute(qc_grover_search_, backend = simulator, shots = nshots).result()
plot_histogram(result.get_counts(qc_grover_search_))
job = execute(qc_grover_search_, backend = device, shots = nshots)
job_monitor(job)
plot_histogram(job.result().get_counts(qc_grover_search_))
|
https://github.com/samuraigab/Quantum-Basic-Algorithms
|
samuraigab
|
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
qc.barrier()
# Alice now sends the qubit to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
# Alice now sends the qubit to Bob
# but Eve intercepts and tries to read it
qc.measure(0, 0)
qc.barrier()
# Eve then passes this on to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
n = 100
## Step 1
# Alice generates bits.
alice_bits = np.random.randint(0,2,n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = np.random.randint(0,2,n)
# Function to compare the bits & bases generated by alice, and then 'encode' the message. Basically determines the state of the qubit/photon to send.
def encode_message(bits, bases):
message = []
for i in range(n):
qc = QuantumCircuit(1,1)
if bases[i] == 0: # Prepare qubit in Z-basis
if bits[i] == 0:
pass
else:
qc.x(0)
else: # Prepare qubit in X-basis
if bits[i] == 0:
qc.h(0)
else:
qc.x(0)
qc.h(0)
qc.barrier()
message.append(qc)
return message
# Alice computes the encoded message using the function defined above.
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = np.random.randint(0,2,n)
# Function to decode the message sent by alice by comparing qubit/photon states with Bob's generated bases.
def measure_message(message, bases):
backend = Aer.get_backend('aer_simulator')
measurements = []
for q in range(n):
if bases[q] == 0: # measuring in Z-basis
message[q].measure(0,0)
if bases[q] == 1: # measuring in X-basis
message[q].h(0)
message[q].measure(0,0)
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(message[q], shots=1, memory=True)
result = aer_sim.run(qobj).result()
measured_bit = int(result.get_memory()[0])
measurements.append(measured_bit)
return measurements
# Decode the message according to his bases
bob_results = measure_message(message, bob_bases)
## Step 4
# Function to perform sifting i.e. disregard the bits for which Bob's & A;ice's bases didnot match.
def remove_garbage(a_bases, b_bases, bits):
good_bits = []
for q in range(n):
if a_bases[q] == b_bases[q]:
# If both used the same basis, add
# this to the list of 'good' bits
good_bits.append(bits[q])
return good_bits
# Performing sifting for Alice's and Bob's bits.
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
print("Alice's key after sifting (without interception)", alice_key)
print("Bob's key after sifting (without interception) ", bob_key)
# # Step 5
# # Function for parameter estimation i.e. determining the error rate by comparing subsets taen from both Alice's key & Bob's key.
# def sample_bits(bits, selection):
# sample = []
# for i in selection:
# # use np.mod to make sure the
# # bit we sample is always in
# # the list range
# i = np.mod(i, len(bits))
# # pop(i) removes the element of the
# # list at index 'i'
# sample.append(bits.pop(i))
# return sample
# # Performing parameter estimation & disregarding the bits used for comparison from Alice's & Bob's key.
# sample_size = 15
# bit_selection = np.random.randint(0,n,size=sample_size)
# bob_sample = sample_bits(bob_key, bit_selection)
# alice_sample = sample_bits(alice_key, bit_selection)
num = 0
for i in range(0,len(bob_key)):
if alice_key[i] == bob_key[i]:
num = num + 1
matching_bits = (num/len(bob_key))*100
print(matching_bits,"% of the bits match.")
## Step 1
alice_bits = np.random.randint(2, size=n)
## Step 2
alice_bases = np.random.randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = np.random.randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = np.random.randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
print("Alice's key after sifting (with interception)", alice_key)
print("Bob's key after sifting (with interception) ", bob_key)
# ## Step 5
# sample_size = 15
# bit_selection = np.random.randint(n, size=sample_size)
# bob_sample = sample_bits(bob_key, bit_selection)
# alice_sample = sample_bits(alice_key, bit_selection)
num = 0
for i in range(0,len(bob_key)):
if alice_key[i] == bob_key[i]:
num = num + 1
matching_bits = (num/len(bob_key))*100
print(matching_bits,"% of the bits match.")
plt.rcParams['axes.linewidth'] = 2
mpl.rcParams['font.family'] = ['Georgia']
plt.figure(figsize=(10.5,6))
ax=plt.axes()
ax.set_title('')
ax.set_xlabel('$n$ (Number of bits drawn from the sifted keys for determining error rate)',fontsize = 18,labelpad=10)
ax.set_ylabel(r'$P(Eve\ detected)$',fontsize = 18,labelpad=10)
ax.xaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on')
ax.yaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on')
ax.tick_params(axis='x', labelsize=20)
ax.tick_params(axis='y', labelsize=20)
ax. xaxis. label. set_size(20)
ax. yaxis. label. set_size(20)
n = 30
x = np.arange(n+1)
y = 1 - 0.75**x
ax.plot(x,y,color = plt.cm.rainbow(np.linspace(0, 1, 5))[0], marker = "s", markerfacecolor='r')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for the wrapper functionality."""
import io
import unittest
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import BasicAer
from qiskit import execute
from qiskit.tools.monitor import job_monitor
from qiskit.test import QiskitTestCase
class TestJobMonitor(QiskitTestCase):
"""Tools test case."""
def test_job_monitor(self):
"""Test job_monitor"""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
qc = QuantumCircuit(qreg, creg)
qc.h(qreg[0])
qc.cx(qreg[0], qreg[1])
qc.measure(qreg, creg)
backend = BasicAer.get_backend("qasm_simulator")
job_sim = execute([qc] * 10, backend)
output = io.StringIO()
job_monitor(job_sim, output=output)
self.assertEqual(job_sim.status().name, "DONE")
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/t-imamichi/qiskit-utility
|
t-imamichi
|
#!/usr/bin/env python
# coding: utf-8
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
'''
Translate a QASM file to a QOBJ file.
Examples:
$ python qasm2qobj.py -i input.qasm -o output.qobj # mapping for all-to-all
$ python qasm2qobj.py -i input.qasm -o output.qobj -b ibmq_5_tenerife # mapping for ibmq_5_tenerife
'''
import json
from qiskit import register, available_backends, load_qasm_file, compile
from argparse import ArgumentParser
import numpy as np
import Qconfig
def backends(qconsole=False):
key = 'qconsole' if qconsole else 'qx'
token = Qconfig.APItoken[key]
config = Qconfig.config[key]
url = config.get('url', None)
hub = config.get('hub', None)
group = config.get('group', None)
project = config.get('project', None)
register(token, url, hub, group, project)
return available_backends()
def options():
parser = ArgumentParser()
parser.add_argument('-i', '--qasm', action='store', help='input QASM file')
parser.add_argument('-o', '--qobj', action='store', help='output QOBJ file')
parser.add_argument('-s', '--shots', action='store', help='number of shots', type=int, default=1024)
parser.add_argument('--out-qasm', action='store', help='output QASM file')
parser.add_argument('-b', '--backend', action='store', help='backend (default: local_qasm_simulator)',
default='local_qasm_simulator')
parser.add_argument('-z', '--qconsole', action='store_true', help='Use qconsole')
args = parser.parse_args()
print('options:', args)
if not args.qasm or not args.qobj:
parser.print_help()
quit()
set_backends = backends(args.qconsole)
print('backends:', set_backends)
if args.backend not in set_backends:
print('invalid backend: {}'.format(args.backend))
print('available backends: {}'.format(set_backends))
#quit()
return args
def support_npint(val):
if isinstance(val, (np.int32, np.int64)):
return int(val)
return val
def main():
args = options()
circuit = load_qasm_file(args.qasm, name=args.qasm)
qobj = compile(circuit, backend=args.backend, shots=args.shots)
with open(args.qobj, 'w') as outfile:
json.dump(qobj, outfile, indent=2, sort_keys=True, default=support_npint)
if args.out_qasm:
with open(args.out_qasm, 'w') as outfile:
outfile.write(qobj['circuits'][0]['compiled_circuit_qasm'])
if __name__ == '__main__':
main()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, IBMQ
from qiskit.compiler import transpile
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator
from qiskit.visualization import *
from qiskit.quantum_info import *
qc1 = QuantumCircuit(1)
qc1.x(0)
qc1.measure_all()
qc1.draw(output='mpl')
job1 = execute(qc1, backend=QasmSimulator(), shots=1024)
plot_histogram(job1.result().get_counts())
qc2 = QuantumCircuit(2)
# State Preparation
qc2.x(0)
qc2.barrier()
# Perform q_0 XOR 0
qc2.cx(0,1)
qc2.measure_all()
qc2.draw(output='mpl')
job2 = execute(qc2.reverse_bits(), backend=QasmSimulator(), shots=1024)
plot_histogram(job2.result().get_counts())
qc3 = QuantumCircuit(3)
# State Preparation
qc3.x(0)
qc3.x(1)
qc3.barrier()
# Perform q_0 XOR 0
qc3.ccx(0,1,2)
qc3.measure_all()
qc3.draw(output='mpl')
job3 = execute(qc3.reverse_bits(), backend=QasmSimulator(), shots=1024)
plot_histogram(job3.result().get_counts())
qc4 = QuantumCircuit(3)
# State Preparation
qc4.h(range(3))
qc4.measure_all()
qc4.draw(output='mpl')
job4 = execute(qc4.reverse_bits(), backend=QasmSimulator(), shots=8192)
plot_histogram(job4.result().get_counts())
from qiskit.providers.aer.noise import NoiseModel
from qiskit.test.mock import FakeMelbourne
device_backend = FakeMelbourne()
coupling_map = device_backend.configuration().coupling_map
noise_model = NoiseModel.from_backend(device_backend)
basis_gates = noise_model.basis_gates
result_noise = execute(qc4, QasmSimulator(),
shots=8192,
noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=basis_gates).result()
plot_histogram(result_noise.get_counts())
qc3_t = transpile(qc3, basis_gates=basis_gates)
qc3_t.draw(output='mpl')
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
provider.backends()
ibmq_backend = provider.get_backend('ibmq_16_melbourne')
result_device = execute(qc4, backend=ibmq_backend, shots=8192).result()
plot_histogram(result_device.get_counts())
|
https://github.com/Chibikuri/qwopt
|
Chibikuri
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.3.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import copy
from qiskit import QuantumCircuit, QuantumRegister, Aer, execute
np.set_printoptions(linewidth=10000, threshold=10000)
# +
def theoretical_prob(initial, step, ptran, nq):
Pi_op = Pi_operator(ptran)
swap = swap_operator(nq)
operator = (2*Pi_op) - np.identity(len(Pi_op))
Szegedy = np.dot(operator, swap)
Szegedy_n = copy.copy(Szegedy)
print(id(Szegedy), id(Szegedy_n))
if step == 0:
init_prob = np.array([abs(i)**2 for i in initial], dtype=np.float)
return init_prob
elif step == 1:
prob = np.array([abs(i)**2 for i in np.dot(Szegedy, initial)],
dtype=np.float)
return prob
else:
for n in range(step-1):
Szegedy_n = np.dot(Szegedy_n, Szegedy)
probs = np.array([abs(i)**2 for i in np.dot(initial, Szegedy_n)],
dtype=np.float)
return probs
def swap_operator(n_qubit):
q1 = QuantumRegister(n_qubit//2)
q2 = QuantumRegister(n_qubit//2)
qc = QuantumCircuit(q1, q2)
for c, t in zip(q1, q2):
qc.swap(c, t)
# FIXME
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend=backend)
swap = job.result().get_unitary(qc)
return swap
def Pi_operator(ptran):
'''
This is not a quantum operation,
just returning matrix
'''
lg = len(ptran)
psi_op = []
count = 0
for i in range(lg):
psi_vec = [0 for _ in range(lg**2)]
for j in range(lg):
psi_vec[count] = np.sqrt(ptran[j][i])
count += 1
psi_op.append(np.kron(np.array(psi_vec).T,
np.conjugate(psi_vec)).reshape((lg**2, lg**2)))
Pi = psi_op[0]
for i in psi_op[1:]:
Pi = np.add(Pi, i)
return Pi
def is_unitary(operator, tolerance=0.0001):
h, w = operator.shape
if not h == w:
return False
adjoint = np.conjugate(operator.transpose())
product1 = np.dot(operator, adjoint)
product2 = np.dot(adjoint, operator)
ida = np.eye(h)
return np.allclose(product1, ida) & np.allclose(product2, ida)
# +
alpha = 0.85
target_graph = np.array([[0, 1, 0, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0]])
E = np.array([[1/8, 1/2, 0, 0, 0, 0, 0, 1/2],
[1/8, 0, 1/2, 0, 0, 0, 0, 0],
[1/8, 1/2, 0, 1/2, 0, 0, 0, 0],
[1/8, 0, 1/2, 0, 1/2, 0, 0, 0],
[1/8, 0, 0, 1/2, 0, 1/2, 0, 0],
[1/8, 0, 0, 0, 1/2, 0, 1/2, 0],
[1/8, 0, 0, 0, 0, 1/2, 0, 1/2],
[1/8, 0, 0, 0, 0, 0, 1/2, 0]])
# use google matrix
lt = len(target_graph)
prob_dist = alpha*E + ((1-alpha)/lt)*np.ones((lt, lt))
init_state_eight = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(lt) for j in range(lt)])
# -
Pi_op = Pi_operator(prob_dist)
operator = (2*Pi_op) - np.identity(len(Pi_op))
lo = len(operator)
initial = np.array([0 if i != 32 else 1 for i in range(lo)])
# initial = np.array([np.sqrt(1/lo) for i in range(lo)])
ideal = theoretical_prob(initial, 2, prob_dist, 6)
for i, v in enumerate(ideal):
print(i, v)
import networkx as nx
import matplotlib.pyplot as plt
target_graph = np.array([[0, 1, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0]])
Gs = nx.from_numpy_matrix(target_graph)
G = nx.MultiDiGraph()
pos = [(1, 1), (5, 1), (5, 5), (1, 5)]
G.add_edges_from(Gs.edges())
plt.figure(figsize=(8,8))
nx.draw_networkx(G, pos, node_size=1000, width=3, arrowsize=50)
plt.show()
# +
target_graph = np.array([[0, 1, 0, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0]])
Gs = nx.from_numpy_matrix(target_graph)
G = nx.MultiDiGraph()
# pos = [(1, 1), (2, 2), (3, 3), (1, 5), (2, 2), (6, 2), (6, 6), (2, 6)]
pos = [(0, 0), (1, 1), (2, 2), (1, 3), (0, 4), (-1, 3), (-2, 2), (-1, 1)]
G.add_edges_from(Gs.edges())
# pos = nx.spring_layout(G)
plt.figure(figsize=(8,8))
nx.draw_networkx(G, pos, node_size=1000, width=3, arrowsize=50)
plt.show()
# +
target_graph = np.array([[0, 0, 0, 1, 1, 0, 0, 0],
[1, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 1, 1]])
Gs = nx.from_numpy_matrix(target_graph)
print(Gs.edges())
G = nx.MultiDiGraph()
# pos = [(1, 1), (2, 2), (3, 3), (1, 5), (2, 2), (6, 2), (6, 6), (2, 6)]
pos = [(0, 0), (3, 3), (2, 9), (-1, 5), (5, 1), (4, 5), (8, 5), (9, 3)]
G.add_edges_from(Gs.edges())
G.add_edges_from([(7, 6)])
# pos = nx.spring_layout(G, k=10)
plt.figure(figsize=(10, 10))
nx.draw_networkx(G, pos, node_size=1000, width=3, arrowsize=50)
plt.show()
# -
|
https://github.com/kuehnste/QiskitTutorial
|
kuehnste
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.visualization import *
from qiskit.quantum_info import state_fidelity
# Numpy for numeric functions
import numpy as np
# Magic function to render plots in the notebook after the cell executing the plot command
%matplotlib inline
def run_on_statevector_simulator(quantum_circuit, decimals=6):
"""Takes a circuit, and runs it on the state vector simulator backend."""
statevector_simulator = Aer.get_backend('statevector_simulator')
job = execute(quantum_circuit, backend=statevector_simulator)
result = job.result()
statevector = result.get_statevector(quantum_circuit, decimals=decimals)
return statevector
# Generate a quantum circuit for two qubits
# Add the gates which generate |psi_0>
# Draw the quantum circuit
# Run it on the state vector simulator
# Visualize the resulting state vector
# Add a CNOT gate to the circuit
# Draw the circuit
# Run it on the state vector simulator
# Visualize the resulting state vector
# Generate a quantum circuit qc2 for two qubits
qc2 = QuantumCircuit(2)
# Add the gates which generate |psi_0>
# Draw the quantum circuit
# Run it on the state vector simulator for various angles of Rx
# Number of steps
nsteps = 10
for i in range(nsteps):
# We copy the quantum circuit qc2 into a new circuit qc3
qc3 = QuantumCircuit(2)
qc3.compose(qc2, inplace=True)
# Add the controllec Rx gates between qubits 0 and 1 for various angles
# Hint set: the angle to i*4*np.pi/nsteps
# Run the resulting circuit on the state vector simulator
vec = run_on_statevector_simulator(qc3)
# Visualize the state vector
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# -*- 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/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import *
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error
def get_noise(p):
error_meas = pauli_error([('X',p), ('I', 1 - p)])
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error_meas, "measure") # measurement error is applied to measurements
return noise_model
noise_model = get_noise(0.01)
for state in ['00','01','10','11']:
qc = QuantumCircuit(2,2)
if state[0]=='1':
qc.x(1)
if state[1]=='1':
qc.x(0)
qc.measure(qc.qregs[0],qc.cregs[0])
print(state+' becomes',
execute(qc,Aer.get_backend('qasm_simulator'),noise_model=noise_model,shots=10000).result().get_counts())
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.measure(qc.qregs[0],qc.cregs[0])
print(execute(qc,Aer.get_backend('qasm_simulator'),noise_model=noise_model,shots=10000).result().get_counts())
import numpy as np
M = [[0.9808,0.0107,0.0095,0.0001],
[0.0095,0.9788,0.0001,0.0107],
[0.0096,0.0002,0.9814,0.0087],
[0.0001,0.0103,0.0090,0.9805]]
Cideal = [[0],
[5000],
[5000],
[0]]
Cnoisy = np.dot( M, Cideal)
print('C_noisy =\n',Cnoisy)
import scipy.linalg as la
M = [[0.9808,0.0107,0.0095,0.0001],
[0.0095,0.9788,0.0001,0.0107],
[0.0096,0.0002,0.9814,0.0087],
[0.0001,0.0103,0.0090,0.9805]]
Minv = la.pinv(M)
print(Minv)
Cmitigated = np.dot( Minv, Cnoisy)
print('C_mitigated =\n',Cmitigated)
from qiskit.ignis.mitigation.measurement import (complete_meas_cal,CompleteMeasFitter)
qr = qiskit.QuantumRegister(2)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
for circuit in meas_calibs:
print('Circuit',circuit.name)
print(circuit)
print()
# Execute the calibration circuits without noise
backend = qiskit.Aer.get_backend('qasm_simulator')
job = qiskit.execute(meas_calibs, backend=backend, shots=1000)
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
noise_model = get_noise(0.1)
backend = qiskit.Aer.get_backend('qasm_simulator')
job = qiskit.execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model)
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.measure(qc.qregs[0],qc.cregs[0])
results = qiskit.execute(qc, backend=backend, shots=10000, noise_model=noise_model).result()
noisy_counts = results.get_counts()
print(noisy_counts)
# Get the filter object
meas_filter = meas_fitter.filter
# Results with mitigation
mitigated_results = meas_filter.apply(results)
mitigated_counts = mitigated_results.get_counts(0)
from qiskit.tools.visualization import *
plot_histogram([noisy_counts, mitigated_counts], legend=['noisy', 'mitigated'])
|
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.
"""Qobj tests."""
import copy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler import assemble
from qiskit.qobj import (
QasmQobj,
PulseQobj,
QobjHeader,
PulseQobjInstruction,
PulseQobjExperiment,
PulseQobjConfig,
QobjMeasurementOption,
PulseLibraryItem,
QasmQobjInstruction,
QasmQobjExperiment,
QasmQobjConfig,
QasmExperimentCalibrations,
GateCalibration,
)
from qiskit.test import QiskitTestCase
class TestQASMQobj(QiskitTestCase):
"""Tests for QasmQobj."""
def setUp(self):
super().setUp()
self.valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
]
)
],
)
self.valid_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.2.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
]
}
],
}
self.bad_qobj = copy.deepcopy(self.valid_qobj)
self.bad_qobj.experiments = []
def test_from_dict_per_class(self):
"""Test Qobj and its subclass representations given a dictionary."""
test_parameters = {
QasmQobj: (self.valid_qobj, self.valid_dict),
QasmQobjConfig: (
QasmQobjConfig(shots=1, memory_slots=2),
{"shots": 1, "memory_slots": 2},
),
QasmQobjExperiment: (
QasmQobjExperiment(
instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])]
),
{"instructions": [{"name": "u1", "qubits": [1], "params": [0.4]}]},
),
QasmQobjInstruction: (
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
{"name": "u1", "qubits": [1], "params": [0.4]},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item, qobj_class.from_dict(expected_dict))
def test_snapshot_instruction_to_dict(self):
"""Test snapshot instruction to dict."""
valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
QasmQobjInstruction(
name="snapshot",
qubits=[1],
snapshot_type="statevector",
label="my_snap",
),
]
)
],
)
res = valid_qobj.to_dict()
expected_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.3.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
{
"name": "snapshot",
"qubits": [1],
"snapshot_type": "statevector",
"label": "my_snap",
},
],
"config": {},
"header": {},
}
],
}
self.assertEqual(expected_dict, res)
def test_snapshot_instruction_from_dict(self):
"""Test snapshot instruction from dict."""
expected_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
QasmQobjInstruction(
name="snapshot",
qubits=[1],
snapshot_type="statevector",
label="my_snap",
),
]
)
],
)
qobj_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.2.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
{
"name": "snapshot",
"qubits": [1],
"snapshot_type": "statevector",
"label": "my_snap",
},
]
}
],
}
self.assertEqual(expected_qobj, QasmQobj.from_dict(qobj_dict))
def test_change_qobj_after_compile(self):
"""Test modifying Qobj parameters after compile."""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
qc1 = QuantumCircuit(qr, cr)
qc2 = QuantumCircuit(qr, cr)
qc1.h(qr[0])
qc1.cx(qr[0], qr[1])
qc1.cx(qr[0], qr[2])
qc2.h(qr)
qc1.measure(qr, cr)
qc2.measure(qr, cr)
circuits = [qc1, qc2]
qobj1 = assemble(circuits, shots=1024, seed=88)
qobj1.experiments[0].config.shots = 50
qobj1.experiments[1].config.shots = 1
self.assertTrue(qobj1.experiments[0].config.shots == 50)
self.assertTrue(qobj1.experiments[1].config.shots == 1)
self.assertTrue(qobj1.config.shots == 1024)
def test_gate_calibrations_to_dict(self):
"""Test gate calibrations to dict."""
pulse_library = [PulseLibraryItem(name="test", samples=[1j, 1j])]
valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2, pulse_library=pulse_library),
experiments=[
QasmQobjExperiment(
instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])],
config=QasmQobjConfig(
calibrations=QasmExperimentCalibrations(
gates=[
GateCalibration(
name="u1", qubits=[1], params=[0.4], instructions=[]
)
]
)
),
)
],
)
res = valid_qobj.to_dict()
expected_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.3.0",
"header": {},
"config": {
"memory_slots": 2,
"shots": 1024,
"pulse_library": [{"name": "test", "samples": [1j, 1j]}],
},
"experiments": [
{
"instructions": [{"name": "u1", "params": [0.4], "qubits": [1]}],
"config": {
"calibrations": {
"gates": [
{"name": "u1", "qubits": [1], "params": [0.4], "instructions": []}
]
}
},
"header": {},
}
],
}
self.assertEqual(expected_dict, res)
class TestPulseQobj(QiskitTestCase):
"""Tests for PulseQobj."""
def setUp(self):
super().setUp()
self.valid_qobj = PulseQobj(
qobj_id="12345",
header=QobjHeader(),
config=PulseQobjConfig(
shots=1024,
memory_slots=2,
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[
PulseLibraryItem(name="pulse0", samples=[0.0 + 0.0j, 0.5 + 0.0j, 0.0 + 0.0j])
],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
experiments=[
PulseQobjExperiment(
instructions=[
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=1.57),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=0.0),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase="P1"),
PulseQobjInstruction(name="setp", t0=10, ch="d0", phase=3.14),
PulseQobjInstruction(name="setf", t0=10, ch="d0", frequency=8.0),
PulseQobjInstruction(name="shiftf", t0=10, ch="d0", frequency=4.0),
PulseQobjInstruction(
name="acquire",
t0=15,
duration=5,
qubits=[0],
memory_slot=[0],
kernels=[
QobjMeasurementOption(
name="boxcar", params={"start_window": 0, "stop_window": 5}
)
],
),
]
)
],
)
self.valid_dict = {
"qobj_id": "12345",
"type": "PULSE",
"schema_version": "1.2.0",
"header": {},
"config": {
"memory_slots": 2,
"shots": 1024,
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0, 0.5, 0]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
"experiments": [
{
"instructions": [
{"name": "pulse0", "t0": 0, "ch": "d0"},
{"name": "fc", "t0": 5, "ch": "d0", "phase": 1.57},
{"name": "fc", "t0": 5, "ch": "d0", "phase": 0},
{"name": "fc", "t0": 5, "ch": "d0", "phase": "P1"},
{"name": "setp", "t0": 10, "ch": "d0", "phase": 3.14},
{"name": "setf", "t0": 10, "ch": "d0", "frequency": 8.0},
{"name": "shiftf", "t0": 10, "ch": "d0", "frequency": 4.0},
{
"name": "acquire",
"t0": 15,
"duration": 5,
"qubits": [0],
"memory_slot": [0],
"kernels": [
{"name": "boxcar", "params": {"start_window": 0, "stop_window": 5}}
],
},
]
}
],
}
def test_from_dict_per_class(self):
"""Test converting to Qobj and its subclass representations given a dictionary."""
test_parameters = {
PulseQobj: (self.valid_qobj, self.valid_dict),
PulseQobjConfig: (
PulseQobjConfig(
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
{
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
),
PulseLibraryItem: (
PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]),
{"name": "pulse0", "samples": [0.1 + 0j]},
),
PulseQobjExperiment: (
PulseQobjExperiment(
instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")]
),
{"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]},
),
PulseQobjInstruction: (
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
{"name": "pulse0", "t0": 0, "ch": "d0"},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item, qobj_class.from_dict(expected_dict))
def test_to_dict_per_class(self):
"""Test converting from Qobj and its subclass representations given a dictionary."""
test_parameters = {
PulseQobj: (self.valid_qobj, self.valid_dict),
PulseQobjConfig: (
PulseQobjConfig(
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
{
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
),
PulseLibraryItem: (
PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]),
{"name": "pulse0", "samples": [0.1 + 0j]},
),
PulseQobjExperiment: (
PulseQobjExperiment(
instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")]
),
{"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]},
),
PulseQobjInstruction: (
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
{"name": "pulse0", "t0": 0, "ch": "d0"},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item.to_dict(), expected_dict)
def _nop():
pass
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Multiple-Control, Multiple-Target Gate.
"""
import logging
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.aqua import AquaError
logger = logging.getLogger(__name__)
def _ccx_v_chain_compute(qc, control_qubits, ancillary_qubits):
"""
First half (compute) of the multi-control basic mode. It progressively compute the
ccx of the control qubits and put the final result in the last ancillary
qubit
Args:
qc: the QuantumCircuit
control_qubits: the list of control qubits
ancillary_qubits: the list of ancillary qubits
"""
anci_idx = 0
qc.ccx(control_qubits[0], control_qubits[1], ancillary_qubits[anci_idx])
for idx in range(2, len(control_qubits)):
assert anci_idx + 1 < len(
ancillary_qubits
), "Insufficient number of ancillary qubits {0}.".format(
len(ancillary_qubits))
qc.ccx(control_qubits[idx], ancillary_qubits[anci_idx],
ancillary_qubits[anci_idx + 1])
anci_idx += 1
def _ccx_v_chain_uncompute(qc, control_qubits, ancillary_qubits):
"""
Second half (uncompute) of the multi-control basic mode. It progressively compute the
ccx of the control qubits and put the final result in the last ancillary
qubit
Args:
qc: the QuantumCircuit
control_qubits: the list of control qubits
ancillary_qubits: the list of ancillary qubits
"""
anci_idx = len(ancillary_qubits) - 1
for idx in (range(2, len(control_qubits)))[::-1]:
qc.ccx(control_qubits[idx], ancillary_qubits[anci_idx - 1],
ancillary_qubits[anci_idx])
anci_idx -= 1
qc.ccx(control_qubits[0], control_qubits[1], ancillary_qubits[anci_idx])
def mcmt(self,
q_controls,
q_ancillae,
single_control_gate_fun,
q_targets,
mode="basic"):
"""
Apply a Multi-Control, Multi-Target using a generic gate.
It can also be used to implement a generic Multi-Control gate, as the target could also be of length 1.
Args:
q_controls: The list of control qubits
q_ancillae: The list of ancillary qubits
single_control_gate_fun: The single control gate function (e.g QuantumCircuit.cz or QuantumCircuit.ch)
q_targets: A list of qubits or a QuantumRegister to which the gate function should be applied.
mode (string): The implementation mode to use (at the moment, only the basic mode is supported)
"""
# check controls
if isinstance(q_controls, QuantumRegister):
control_qubits = [qb for qb in q_controls]
elif isinstance(q_controls, list):
control_qubits = q_controls
else:
raise AquaError(
'MCT needs a list of qubits or a quantum register for controls.')
# check target
if isinstance(q_targets, QuantumRegister):
target_qubits = [qb for qb in q_targets]
elif isinstance(q_targets, list):
target_qubits = q_targets
else:
raise AquaError(
'MCT needs a list of qubits or a quantum register for targets.')
# check ancilla
if q_ancillae is None:
ancillary_qubits = []
elif isinstance(q_ancillae, QuantumRegister):
ancillary_qubits = [qb for qb in q_ancillae]
elif isinstance(q_ancillae, list):
ancillary_qubits = q_ancillae
else:
raise AquaError(
'MCT needs None or a list of qubits or a quantum register for ancilla.'
)
all_qubits = control_qubits + target_qubits + ancillary_qubits
self._check_qargs(all_qubits)
self._check_dups(all_qubits)
if len(q_controls) == 1:
for qubit in target_qubits:
single_control_gate_fun(self, q_controls[0], qubit)
return
if mode == 'basic':
# last ancillary qubit is the control of the gate
ancn = len(ancillary_qubits)
_ccx_v_chain_compute(self, control_qubits, ancillary_qubits)
for qubit in target_qubits:
single_control_gate_fun(self, ancillary_qubits[ancn - 1], qubit)
_ccx_v_chain_uncompute(self, control_qubits, ancillary_qubits)
else:
raise AquaError(
'Unrecognized mode "{0}" for building mcmt circuit, at the moment only "basic" mode is supported.'
.format(mode))
QuantumCircuit.mcmt = mcmt
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import pytest
import qiskit_alt
project = qiskit_alt.project
project.ensure_init(calljulia="juliacall")
def test_always_passes():
assert True
def test_interface_lib():
assert qiskit_alt.project.julia.__name__ == 'juliacall'
def test_Main():
Main = qiskit_alt.project.julia.Main
assert Main.sind(90) == 1.0
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/infiniteregrets/QiskitBot
|
infiniteregrets
|
from math import sqrt, pi
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import oracle_simple
import composed_gates
def get_circuit(n, oracles):
"""
Build the circuit composed by the oracle black box and the other quantum gates.
:param n: The number of qubits (not including the ancillas)
:param oracles: A list of black box (quantum) oracles; each of them selects a specific state
:returns: The proper quantum circuit
:rtype: qiskit.QuantumCircuit
"""
cr = ClassicalRegister(n)
## Testing
if n > 3:
#anc = QuantumRegister(n - 1, 'anc')
# n qubits for the real number
# n - 1 qubits for the ancillas
qr = QuantumRegister(n + n - 1)
qc = QuantumCircuit(qr, cr)
else:
# We don't need ancillas
qr = QuantumRegister(n)
qc = QuantumCircuit(qr, cr)
## /Testing
print("Number of qubits is {0}".format(len(qr)))
print(qr)
# Initial superposition
for j in range(n):
qc.h(qr[j])
# The length of the oracles list, or, in other words, how many roots of the function do we have
m = len(oracles)
# Grover's algorithm is a repetition of an oracle box and a diffusion box.
# The number of repetitions is given by the following formula.
print("n is ", n)
r = int(round((pi / 2 * sqrt((2**n) / m) - 1) / 2))
print("Repetition of ORACLE+DIFFUSION boxes required: {0}".format(r))
oracle_t1 = oracle_simple.OracleSimple(n, 5)
oracle_t2 = oracle_simple.OracleSimple(n, 0)
for j in range(r):
for i in range(len(oracles)):
oracles[i].get_circuit(qr, qc)
diffusion(n, qr, qc)
for j in range(n):
qc.measure(qr[j], cr[j])
return qc, len(qr)
def diffusion(n, qr, qc):
"""
The Grover diffusion operator.
Given the arry of qiskit QuantumRegister qr and the qiskit QuantumCircuit qc, it adds the diffusion operator to the appropriate qubits in the circuit.
"""
for j in range(n):
qc.h(qr[j])
# D matrix, flips state |000> only (instead of flipping all the others)
for j in range(n):
qc.x(qr[j])
# 0..n-2 control bits, n-1 target, n..
if n > 3:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1],
[qr[j] for j in range(n, n + n - 1)])
else:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1], None)
for j in range(n):
qc.x(qr[j])
for j in range(n):
qc.h(qr[j])
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Remove all barriers in a circuit"""
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler.passes.utils import control_flow
class RemoveBarriers(TransformationPass):
"""Return a circuit with any barrier removed.
This transformation is not semantics preserving.
Example:
.. plot::
:include-source:
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')
"""
@control_flow.trivial_recurse
def run(self, dag: DAGCircuit) -> DAGCircuit:
"""Run the RemoveBarriers pass on `dag`."""
dag.remove_all_ops_named("barrier")
return dag
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure([0, 1], [0, 1])
circ.draw("mpl")
from qiskit import transpile, schedule as build_schedule
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
transpiled_circ = transpile(circ, backend) # Undefined Hadamard is replaced by U1
schedule = build_schedule(transpiled_circ, backend)
schedule.draw()
from qiskit import pulse
with pulse.build() as h_q0:
pulse.play(pulse.library.Gaussian(duration=256, amp=0.2, sigma=50, name='custom'),
pulse.DriveChannel(0))
circ.add_calibration('h', [0], h_q0)
schedule = build_schedule(circ, backend)
schedule.draw()
circ = QuantumCircuit(2, 2)
circ.x(0)
circ.x(0)
circ.x(1)
circ.measure([0, 1], [0, 1])
circ.draw("mpl")
schedule = build_schedule(circ, backend, method="as_late_as_possible")
schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw()
schedule = build_schedule(circ, backend, method="as_soon_as_possible")
schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/h-rathee851/Pulse_application_qiskit
|
h-rathee851
|
from qiskit.tools.jupyter import *
from qiskit import IBMQ
IBMQ.load_account()
#provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider=IBMQ.get_provider(hub='ibm-q-research', group='uni-maryland-1', project='main')
backend = provider.get_backend('ibmq_rome')
backend_config = backend.configuration()
backend_defaults = backend.defaults()
assert backend_config.open_pulse, "Backend doesn't support Pulse"
inst_sched_map=backend_defaults.instruction_schedule_map
print(inst_sched_map)
from qiskit.visualization.pulse_v2 import draw
from qiskit import execute
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns") # The configuration returns dt in seconds, so multiply by
# 1e9 to get nanoseconds
import numpy as np
from qiskit import pulse # This is where we access all of our Pulse features!
from qiskit.pulse import Play
# This Pulse module helps us build sampled pulses for common pulse shapes
from qiskit.pulse import library as pulse_lib
from pulsecalibration import PulseCalibration as PulseCali
%load_ext autoreload
%autoreload
PC=PulseCali(backend=backend,qubit=0)
print(backend_defaults.qubit_freq_est)
f01=PC.find_freq_ground(verbose=True,visual=True)
f01_1=PC.get_qubit_freq_ground()
f01_1
PC=PulseCali(backend=backend,qubit=0,qubit_freq_ground=f01)
amp01=PC.find_pi_amp_ground(verbose=True,visual=True)
amp01_1=PC.get_pi_amp_ground()
amp01_1
PC=PulseCali(backend=backend,qubit=0,qubit_freq_ground=f01,pi_amp_ground=amp01)
f12=PC.find_freq_excited(verbose=True,visual=True)
PC=PulseCali(backend=backend,qubit=0,qubit_freq_ground=f01,pi_amp_ground=amp01,qubit_freq_excited=f12)
f12_1=PC.get_qubit_freq_excited()
f12_1
amp12=PC.find_pi_amp_excited(verbose=True,visual=True)
amp12_1=PC.get_pi_amp_excited()
amp12_1
PC=PulseCali(backend,0,qubit_freq_ground=f01,qubit_freq_excited=f12,
pi_amp_ground=amp01, pi_amp_excited=amp12)
PC.T1_ground(verbose=True,visual=True)
PC.T1_excited(verbose=True,visual=True)
PC.T2_ground(verbose=True,visual=True)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
from numpy import pi
# Create a quantum circuit with a single qubit
# The default initial state of qubit will be |0> or [1,0]
qc = QuantumCircuit(1)
#Apply the Pauli X-gate on the qubit to make the input to y gate as |1>
#qc.h(0)
#qc.h(0)
#Apply the Pauli z-gate on the |1> qubit
qc.rz(pi/4,0)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
# visualize the output as an animation
visualize_transition(qc)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Compatibility classes for changes to save instruction return types.
These subclasses include a `__getattr__` method that allows existing
code which used numpy.ndarray attributes to continue functioning with
a deprecation warning.
Numpy functions that consumed these classes should already work due to
them having an `__array__` method for implicit array conversion.
"""
import warnings
import numpy as np
import qiskit.quantum_info as qi
def _forward_attr(attr):
"""Return True if attribute should be passed to legacy class"""
# Pass Iterable magic methods on to the Numpy array. We can't pass
# `__getitem__` (and consequently `__setitem__`, `__delitem__`) on because
# `Statevector` implements them itself.
if attr[:2] == '__' or attr in ['_data', '_op_shape']:
return False
return True
def _deprecation_warning(instance, instances_name):
class_name = instance.__class__.__name__
warnings.warn(
f"The return type of saved {instances_name} has been changed from"
f" a `numpy.ndarray` to a `qiskit.quantum_info.{class_name}` as"
" of qiskit-aer 0.10. Accessing numpy array attributes is deprecated"
" and will result in an error in a future release. To continue using"
" saved result objects as arrays you can explicitly cast them using "
" `np.asarray(object)`.",
DeprecationWarning,
stacklevel=3,
)
class Statevector(qi.Statevector):
"""Aer result backwards compatibility wrapper for qiskit Statevector."""
def __getattr__(self, attr):
if _forward_attr(attr) and hasattr(self._data, attr):
_deprecation_warning(self, "statevectors")
return getattr(self._data, attr)
return getattr(super(), attr)
def __eq__(self, other):
return (
isinstance(self, type(other)) and
self._op_shape == other._op_shape and
np.allclose(self.data, other.data, rtol=self.rtol, atol=self.atol)
)
def __bool__(self):
# Explicit override to the default behaviour for Python objects to
# prevent the new `__len__` from messing with it.
return True
# Magic methods for the iterable/collection interface that need forwarding,
# but bypass `__getattr__`. `__getitem__` is defined by `Statevector`, so
# that can't be forwarded (and consequently neither can `__setitem__`
# without introducing an inconsistency).
def __len__(self):
_deprecation_warning(self, "statevectors")
return self._data.__len__()
def __iter__(self):
_deprecation_warning(self, "statevectors")
return self._data.__iter__()
def __contains__(self, value):
_deprecation_warning(self, "statevectors")
return self._data.__contains__(value)
def __reversed__(self):
_deprecation_warning(self, "statevectors")
return self._data.__reversed__()
class DensityMatrix(qi.DensityMatrix):
"""Aer result backwards compatibility wrapper for qiskit DensityMatrix."""
def __getattr__(self, attr):
if _forward_attr(attr) and hasattr(self._data, attr):
_deprecation_warning(self, "density matrices")
return getattr(self._data, attr)
return getattr(super(), attr)
def __eq__(self, other):
return (
isinstance(self, type(other)) and
self._op_shape == other._op_shape and
np.allclose(self.data, other.data, rtol=self.rtol, atol=self.atol)
)
def __len__(self):
_deprecation_warning(self, "density matrices")
return self._data.__len__()
def __iter__(self):
_deprecation_warning(self, "density matrices")
return self._data.__iter__()
def __contains__(self, value):
_deprecation_warning(self, "density matrices")
return self._data.__contains__(value)
def __reversed__(self):
_deprecation_warning(self, "density matrices")
return self._data.__reversed__()
def __getitem__(self, key):
_deprecation_warning(self, "density matrices")
return self._data.__getitem__(key)
def __setitem__(self, key, value):
_deprecation_warning(self, "density matrices")
return self._data.__setitem__(key, value)
class Operator(qi.Operator):
"""Aer result backwards compatibility wrapper for qiskit Operator."""
def __getattr__(self, attr):
if _forward_attr(attr) and hasattr(self._data, attr):
_deprecation_warning(self, "unitaries")
return getattr(self._data, attr)
return getattr(super(), attr)
def __eq__(self, other):
return (
isinstance(self, type(other)) and
self._op_shape == other._op_shape and
np.allclose(self.data, other.data, rtol=self.rtol, atol=self.atol)
)
def __bool__(self):
# Explicit override to the default behaviour for Python objects to
# prevent the new `__len__` from messing with it.
return True
def __len__(self):
_deprecation_warning(self, "unitaries")
return self._data.__len__()
def __iter__(self):
_deprecation_warning(self, "unitaries")
return self._data.__iter__()
def __contains__(self, value):
_deprecation_warning(self, "unitaries")
return self._data.__contains__(value)
def __reversed__(self):
_deprecation_warning(self, "unitaries")
return self._data.__reversed__()
def __getitem__(self, key):
_deprecation_warning(self, "unitaries")
return self._data.__getitem__(key)
def __setitem__(self, key, value):
_deprecation_warning(self, "unitaries")
return self._data.__setitem__(key, value)
class SuperOp(qi.SuperOp):
"""Aer result backwards compatibility wrapper for qiskit SuperOp."""
def __getattr__(self, attr):
if _forward_attr(attr) and hasattr(self._data, attr):
_deprecation_warning(self, "superoperators")
return getattr(self._data, attr)
return getattr(super(), attr)
def __eq__(self, other):
return (
isinstance(self, type(other)) and
self._op_shape == other._op_shape and
np.allclose(self.data, other.data, rtol=self.rtol, atol=self.atol)
)
def __bool__(self):
# Explicit override to the default behaviour for Python objects to
# prevent the new `__len__` from messing with it.
return True
def __len__(self):
_deprecation_warning(self, "superoperators")
return self._data.__len__()
def __iter__(self):
_deprecation_warning(self, "superoperators")
return self._data.__iter__()
def __contains__(self, value):
_deprecation_warning(self, "superoperators")
return self._data.__contains__(value)
def __reversed__(self):
_deprecation_warning(self, "superoperators")
return self._data.__reversed__()
def __getitem__(self, key):
_deprecation_warning(self, "superoperators")
return self._data.__getitem__(key)
def __setitem__(self, key, value):
_deprecation_warning(self, "superoperators")
return self._data.__setitem__(key, value)
class StabilizerState(qi.StabilizerState):
"""Aer result backwards compatibility wrapper for qiskit StabilizerState."""
def __deprecation_warning(self):
warnings.warn(
"The return type of saved stabilizers has been changed from"
" a `dict` to a `qiskit.quantum_info.StabilizerState` as of qiskit-aer 0.10."
" Accessing dict attributes is deprecated and will result in an"
" error in a future release. Use the `.clifford.to_dict()` methods to access "
" the stored Clifford operator and convert to a dictionary.",
DeprecationWarning,
stacklevel=3,
)
def __getattr__(self, attr):
if _forward_attr(attr) and hasattr(dict, attr):
self.__deprecation_warning()
return getattr(self._data.to_dict(), attr)
return getattr(super(), attr)
def __getitem__(self, item):
if item in ["stabilizer", "destabilizer"]:
warnings.warn(
"The return type of saved stabilizers has been changed from"
" a `dict` to a `qiskit.quantum_info.StabilizerState` as of qiskit-aer 0.10."
" Accessing dict items is deprecated and will result in an"
" error in a future release. Use the `.clifford.to_dict()` methods to access "
" the stored Clifford operator and convert to a dictionary.",
DeprecationWarning, stacklevel=2)
return self._data.to_dict()[item]
raise TypeError("'StabilizerState object is not subscriptable'")
def __bool__(self):
# Explicit override to the default behaviour for Python objects to
# prevent the new `__len__` from messing with it.
return True
def __len__(self):
self.__deprecation_warning()
return self._data.to_dict().__len__()
def __iter__(self):
self.__deprecation_warning()
return self._data.to_dict().__iter__()
def __contains__(self, value):
self.__deprecation_warning()
return self._data.to_dict().__contains__(value)
def __reversed__(self):
self.__deprecation_warning()
return self._data.to_dict().__reversed__()
def _add(self, other):
raise NotImplementedError(f"{type(self)} does not support addition")
def _multiply(self, other):
raise NotImplementedError(f"{type(self)} does not support scalar multiplication")
|
https://github.com/derivation/quantum_image_edge_detection
|
derivation
|
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from skimage.transform import resize
filename = './schrodin_yang.png'
im = mpimg.imread(filename)
n_pixels = 2**5
im = resize(im, (n_pixels, n_pixels))
data = im[:,:,0].ravel()
fig, ax = plt.subplots()
ax.imshow(im)
n_qubits = int(np.log2(len(data)))
from qiskit_aqua.components.initial_states import Custom
init_state = Custom(n_qubits, state_vector=data)
circ = init_state.construct_circuit('circuit')
qr = circ.qregs
# circ.draw()
circ.h(qr[0][0])
from qiskit import BasicAer, execute
simulator = BasicAer.get_backend('statevector_simulator')
sim_result = execute(circ, simulator).result()
final_state = sim_result.get_statevector(circ)
edge = np.real(final_state)
n_rows = int(np.sqrt(len(edge)))
n_cols = n_rows
edge = edge.reshape(n_rows, n_cols)
edge[:,::2] = 0
fig, ax = plt.subplots(1,2)
ax[0].imshow(edge)
ax[1].imshow(im)
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
import random
from random import seed
from random import random
from numpy import where
from collections import Counter
from sklearn.datasets import make_blobs
from matplotlib import pyplot
import numpy as np
import matplotlib.pyplot as plt
from sklearn import mixture
from sklearn.neighbors import KernelDensity
import random
def my_circle(center, rx, ry, Nmax):
R = 1
x2=[]
y2=[]
for i in range(Nmax):
r2=np.sqrt(random.random())
theta2=2 * np.pi * random.random()
x2.append(rx*r2 * np.cos(theta2) + center[0])
y2.append(ry*r2 * np.sin(theta2) + center[1])
return np.transpose([x2,y2])
def my_plot(data,lab,counter):
for label, _ in counter.items():
row_ix = where(lab == label)[0]
pyplot.scatter(data[row_ix, 0], data[row_ix, 1], label=str(label))
pyplot.legend()
pyplot.xlim([0, 1])
pyplot.ylim([0, 1])
pyplot.show()
def data1a():
seed(30)
X1=my_circle([0.3,0.5],0.25,0.4,750)
X2=my_circle([0.7,0.5],0.25,0.4,750)
y1=[0] * 750
y2=[1] * 750
X_1=np.concatenate((X1,X2))
y_1=np.concatenate((y1, y2))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data1b():
seed(30)
X1=my_circle([0.4,0.2],0.25,0.15,375)
X2=my_circle([0.6,0.5],0.25,0.15,750)
X3=my_circle([0.4,0.8],0.25,0.15,375)
y1=[0] * 375
y2=[1] * 750
y3=[0] * 375
X_1=np.concatenate((X1,X2,X3))
y_1=np.concatenate((y1, y2,y3))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data1c():
seed(30)
X1=my_circle([0.3,0.2],0.25,0.12,375)
X2=my_circle([0.7,0.4],0.25,0.12,375)
X3=my_circle([0.3,0.6],0.25,0.12,375)
X4=my_circle([0.7,0.8],0.25,0.12,375)
y1=[0] * 375
y2=[1] * 375
y3=[0] * 375
y4=[1] * 375
X_1=np.concatenate((X1,X2,X3,X4))
y_1=np.concatenate((y1, y2,y3,y4))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data2a():
seed(30)
X1=my_circle([0.25,0.25],0.2,0.2,375)
X2=my_circle([0.25,0.75],0.2,0.2,375)
X3=my_circle([0.75,0.75],0.2,0.2,375)
X4=my_circle([0.75,0.25],0.2,0.2,375)
y1=[0] * 375
y2=[1] * 375
y3=[0] * 375
y4=[1] * 375
X_1=np.concatenate((X1,X2,X3,X4))
y_1=np.concatenate((y1, y2,y3,y4))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data2b():
seed(30)
r=0.12
n=166
X1=my_circle([0.2,0.2],r,r,n)
X2=my_circle([0.5,0.2],r,r,n)
X3=my_circle([0.8,0.2],r,r,n)
X4=my_circle([0.2,0.5],r,r,n)
X5=my_circle([0.5,0.5],r,r,n)
X6=my_circle([0.8,0.5],r,r,n)
X7=my_circle([0.2,0.8],r,r,n)
X8=my_circle([0.5,0.8],r,r,n)
X9=my_circle([0.8,0.8],r,r,n)
y1=[0] * n
y2=[1] * n
y3=[0] * n
y4=[1] * n
y5=[0] * n
y6=[1] * n
y7=[0] * n
y8=[1] * n
y9=[0] * n
X_1=np.concatenate((X1,X2,X3,X4,X5,X6,X7,X8,X9))
y_1=np.concatenate((y1, y2,y3,y4,y5,y6,y7,y8,y9))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data2c():
seed(30)
r=0.1
n=93
X1=my_circle([0.15,0.15],r,r,n)
X2=my_circle([0.38,0.15],r,r,n)
X3=my_circle([0.62,0.15],r,r,n)
X4=my_circle([0.85,0.15],r,r,n)
X5=my_circle([0.15,0.38],r,r,n)
X6=my_circle([0.38,0.38],r,r,n)
X7=my_circle([0.62,0.38],r,r,n)
X8=my_circle([0.85,0.38],r,r,n)
X9=my_circle([0.15,0.62],r,r,n)
X10=my_circle([0.38,0.62],r,r,n)
X11=my_circle([0.62,0.62],r,r,n)
X12=my_circle([0.85,0.62],r,r,n)
X13=my_circle([0.15,0.85],r,r,n)
X14=my_circle([0.38,0.85],r,r,n)
X15=my_circle([0.62,0.85],r,r,n)
X16=my_circle([0.85,0.85],r,r,n)
y1=[0] * n
y2=[1] * n
y3=[0] * n
y4=[1] * n
y5=[1] * n
y6=[0] * n
y7=[1] * n
y8=[0] * n
y9=[0] * n
y10=[1] * n
y11=[0] * n
y12=[1] * n
y13=[1] * n
y14=[0] * n
y15=[1] * n
y16=[0] * n
X_1=np.concatenate((X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12,X13,X14,X15,X16))
y_1=np.concatenate((y1, y2,y3,y4,y5,y6,y7,y8,y9,y10,y11,y12,y13,y14,y15,y16))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data3a():
seed(30)
X1 = []
radius = 0.25
n=750
index = 0
while index < n:
x=random.random()
y=random.random()
if (x-0.5)**2 + (y-0.5)**2 > radius**2:
X1 = X1 + [[x,y]]
index = index + 1
y1=[1] *750
X2=my_circle([0.5,0.5],radius,radius,750)
y2=[0] *750
X_1=np.concatenate((X1,X2))
y_1=np.concatenate((y1, y2))
# Generate uniform noise
counter = Counter(y_1)
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data3b():
seed(30)
X1 = []
radius = 0.15
n=750
index = 0
while index < n:
x=random.random()
y=random.random()
if ((x-0.25)**2 + (y-0.25)**2 > radius**2 and (x-0.75)**2 + (y-0.75)**2 > radius**2):
X1 = X1 + [[x,y]]
index = index + 1
y1=[1] *750
X2=my_circle([0.25,0.25],radius,radius,375)
X3=my_circle([0.75,0.75],radius,radius,375)
y2=[0] *750
X_1=np.concatenate((X1,X2,X3))
y_1=np.concatenate((y1, y2))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data3c():
seed(30)
X1 = []
radius = 0.15
n=750
n2=187
index = 0
while index < n:
x=random.random()
y=random.random()
if ((x-0.25)**2 + (y-0.25)**2 > radius**2 and (x-0.75)**2 + (y-0.75)**2 > radius**2 and (x-0.75)**2 + (y-0.25)**2 > radius**2 and (x-0.25)**2 + (y-0.75)**2 > radius**2 ):
X1 = X1 + [[x,y]]
index = index + 1
y1=[1] *750
X2=my_circle([0.25,0.25],radius,radius,n2)
X3=my_circle([0.75,0.75],radius,radius,n2)
X4=my_circle([0.75,0.25],radius,radius,n2)
X5=my_circle([0.25,0.75],radius,radius,n2)
y2=[0] *748
X_1=np.concatenate((X1,X2,X3,X4,X5))
y_1=np.concatenate((y1, y2))
# Generate uniform noise
counter = Counter(y_1)
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
# Plot
my_plot(data1a()[0],data1a()[1],data1a()[2])
# Plot
my_plot(data1b()[0],data1b()[1],data1b()[2])
# Plot
my_plot(data1c()[0],data1c()[1],data1c()[2])
# Plot
my_plot(data2a()[0],data2a()[1],data2a()[2])
# Plot
my_plot(data2b()[0],data2b()[1],data2b()[2])
# Plot
my_plot(data2c()[0],data2c()[1],data2c()[2])
# Plot
my_plot(data3a()[0],data3a()[1],data3a()[2])
# Plot
my_plot(data3b()[0],data3b()[1],data3b()[2])
# Plot
my_plot(data3c()[0],data3c()[1],data3c()[2])
|
https://github.com/FMZennaro/QuantumGames
|
FMZennaro
|
!conda create --name qiscoin python=3.7
!source activate qiscoin
!pip install qiskit
!pip install gym
!pip install stable-baselines
!pip install tensorflow==1.14.0
!git clone https://github.com/FMZennaro/gym-qcircuit.git
!pip install -e gym-qcircuit
|
https://github.com/derivation/quantum_image_edge_detection
|
derivation
|
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from skimage.transform import resize
filename = './schrodin_yang.png'
im = mpimg.imread(filename)
n_pixels = 2**5
im = resize(im, (n_pixels, n_pixels))
data = im[:,:,0].ravel()
fig, ax = plt.subplots()
ax.imshow(im)
n_qubits = int(np.log2(len(data)))
from qiskit_aqua.components.initial_states import Custom
init_state = Custom(n_qubits, state_vector=data)
circ = init_state.construct_circuit('circuit')
qr = circ.qregs
# circ.draw()
circ.h(qr[0][0])
from qiskit import BasicAer, execute
simulator = BasicAer.get_backend('statevector_simulator')
sim_result = execute(circ, simulator).result()
final_state = sim_result.get_statevector(circ)
edge = np.real(final_state)
n_rows = int(np.sqrt(len(edge)))
n_cols = n_rows
edge = edge.reshape(n_rows, n_cols)
edge[:,::2] = 0
fig, ax = plt.subplots(1,2)
ax[0].imshow(edge)
ax[1].imshow(im)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import qiskit
qiskit.__qiskit_version__
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.monitor import job_monitor
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Load our saved IBMQ accounts.
IBMQ.load_account()
nQubits = 14 # number of physical qubits
a = 101 # the hidden integer whose bitstring is 1100101
# make sure that a can be represented with nQubits
a = a % 2**(nQubits)
# Creating registers
# qubits for querying the oracle and finding the hidden integer
qr = QuantumRegister(nQubits)
# for recording the measurement on qr
cr = ClassicalRegister(nQubits)
circuitName = "BernsteinVazirani"
bvCircuit = QuantumCircuit(qr, cr)
# Apply Hadamard gates before querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Apply barrier so that it is not optimized by the compiler
bvCircuit.barrier()
# Apply the inner-product oracle
for i in range(nQubits):
if (a & (1 << i)):
bvCircuit.z(qr[i])
else:
bvCircuit.iden(qr[i])
# Apply barrier
bvCircuit.barrier()
#Apply Hadamard gates after querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Measurement
bvCircuit.barrier(qr)
bvCircuit.measure(qr, cr)
bvCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
results = execute(bvCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
backend = IBMQ.get_backend('ibmq_16_melbourne')
shots = 1000
bvCompiled = transpile(bvCircuit, backend=backend, optimization_level=1)
job_exp = execute(bvCircuit, backend=backend, shots=shots)
job_monitor(job_exp)
results = job_exp.result()
answer = results.get_counts(bvCircuit)
threshold = int(0.01 * shots) #the threshold of plotting significant measurements
filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} #filter the answer for better view of plots
removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) #number of counts removed
filteredAnswer['other_bitstrings'] = removedCounts #the removed counts is assigned to a new index
plot_histogram(filteredAnswer)
print(filteredAnswer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
# Create a circuit with a register of three qubits
circ = QuantumCircuit(3)
# H gate on qubit 0, putting this qubit in a superposition of |0> + |1>.
circ.h(0)
# A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state.
circ.cx(0, 1)
# CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state.
circ.cx(0, 2)
# Draw the circuit
circ.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import GroverOptimizer, MinimumEigenOptimizer
from qiskit_optimization.translators import from_docplex_mp
from docplex.mp.model import Model
model = Model()
x0 = model.binary_var(name="x0")
x1 = model.binary_var(name="x1")
x2 = model.binary_var(name="x2")
model.minimize(-x0 + 2 * x1 - 3 * x2 - 2 * x0 * x2 - 1 * x1 * x2)
qp = from_docplex_mp(model)
print(qp.prettyprint())
grover_optimizer = GroverOptimizer(6, num_iterations=10, sampler=Sampler())
results = grover_optimizer.solve(qp)
print(results.prettyprint())
exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
exact_result = exact_solver.solve(qp)
print(exact_result.prettyprint())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import time, os, logging, warnings
import numpy as np
from qiskit import IBMQ
from qiskit.test.mock import FakeMumbai
from qiskit.providers.aer import AerSimulator
from qiskit.providers.aer.noise import NoiseModel
from qiskit_optimization.algorithms import CplexOptimizer
from qiskit_optimization.algorithms.optimization_algorithm import OptimizationResultStatus
from utilities.helpers import create_qaoa_meo, create_quadratic_programs_from_paths
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()
max_iter = 5 # set maximum number of optimizer iterations in qaoa online simulation
def qaoa_callback(eval_ct: int, opt_pars: np.ndarray, mean: float, stdev: float) -> None:
"""Print number of iteration in QAOA and log."""
print("Evaluation count:", eval_ct)
logger.info(f"\n Evaluation count {eval_ct} with parameters {opt_pars} and mean {mean:.2f}")
if eval_ct == max_iter:
logger.info(" reached maximum number of evaluations \n")
# select linear programs to solve
qps = create_quadratic_programs_from_paths(TEST_DIR)
# init local backend simulator with noise model
device = FakeMumbai()
local = AerSimulator.from_backend(device)
noise_model = NoiseModel.from_backend(device)
conf = device.configuration()
# init IBM Q Experience Simulator
IBMQ.load_account()
ibmq = IBMQ.get_provider(hub='ibm-q').get_backend('simulator_statevector')
# init Optimizers
cplex = CplexOptimizer()
quantum_instance_kwargs = {"shots": 4096, "noise_model": noise_model, "optimization_level": 3}
qaoa_local_sim = create_qaoa_meo(backend=local, max_iter=max_iter, **quantum_instance_kwargs)
qaoa_ibmq_sim = create_qaoa_meo(backend=ibmq, coupling_map=conf.coupling_map, basis_gates=conf.basis_gates,
max_iter=max_iter, qaoa_callback=qaoa_callback, **quantum_instance_kwargs)
# set online job informations in IBM Q Experience
qaoa_ibmq_sim.min_eigen_solver.quantum_instance.backend_options["job_tags"] = ["qaoa", "dense", "mumbai"]
def set_job_name(qp):
qaoa_ibmq_sim.min_eigen_solver.quantum_instance.backend_options["job_name"] = "qaoa_dense_" \
+ qp.name + "_" + str(qp.get_num_vars())
warnings.filterwarnings("ignore", category=DeprecationWarning)
logger.setLevel(logging.INFO)
count_fail_qaoa = 0
for qp_name, qp in qps.items() :
print(qp_name)
print("number of qubits: ", qp.get_num_vars())
output_file_handler = logging.FileHandler(filename=RES_DIR + qp.name + ".log")
logger.addHandler(output_file_handler)
if qp.get_num_vars() >= 15:
set_job_name(qp)
qaoa = qaoa_ibmq_sim
logstring = "ibmq_simulator_statevector"
else:
qaoa = qaoa_local_sim
logstring = "local_qasm_simulator"
with open(RES_DIR + qp.name + '.res', 'w') as file:
file.write(str("Start " + qp.name + "\n " + str(qp.get_num_vars()) + " qubits needed"))
file.write("\n " + logstring + " \n")
logger.info("\n " + logstring + " \n")
print(logstring)
try:
res_classic = cplex.solve(qp)
res_quantum = qaoa.solve(qp)
if res_quantum.status != OptimizationResultStatus.SUCCESS:
print("QAOA minimum eigen solver found no solution.")
file.write("\n QAOA minimum eigen solver found no solution. \n")
count_fail_qaoa = count_fail_qaoa + 1
if count_fail_qaoa == 3:
file.write("\n Stop testing \n")
break
else:
print("QAOA minimum eigen solver successful!")
count_fail_qaoa = 0
if res_quantum.fval == res_classic.fval:
file.write("\n QAOA found optimal solution\n")
else:
print("\n optimal value QAOA "+str(res_quantum.fval) \
+ " , cplex:"+ str(res_classic.fval))
file.write("\n QAOA:\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 Cplex or QAOA solver produced an exception:\n")
file.write(str(ex))
count_fail_qaoa = count_fail_qaoa + 1
if count_fail_qaoa == 3:
file.write("\n Stop testing because of Exception! \n")
break
logger.removeHandler(output_file_handler)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# If you introduce a list with less colors than bars, the color of the bars will
# alternate following the sequence from the list.
import numpy as np
from qiskit.quantum_info import DensityMatrix
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0, 1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
matrix = DensityMatrix(qc)
plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, backend=FakeBoeblingen())
|
https://github.com/soultanis/Quantum-SAT-Solver
|
soultanis
|
import pylab
import numpy as np
from qiskit.providers.ibmq import least_busy
from qiskit import LegacySimulators, execute, IBMQ, Aer
from qiskit.tools.visualization import plot_histogram
from qiskit_aqua import QuantumInstance
from qiskit_aqua import run_algorithm
from qiskit_aqua.algorithms import Grover
from qiskit_aqua.components.oracles import SAT
m = 2
n = 2
satProblem = '3SATm-n\\3sat' + str(m) + '-' + str(n) + '.cnf'
with open(satProblem, 'r') as f:
sat_cnf = f.read()
print(sat_cnf)
sat_oracle = SAT(sat_cnf)
algorithm = Grover(sat_oracle)
sim_backend = Aer.get_backend('qasm_simulator')
result = algorithm.run(sim_backend)
print(result['result'])
plot_histogram(result['measurements'])
# Authenticate for access to remote backends
try:
import Qconfig
IBMQ.load_accounts()
except:
print("""WARNING: There's no connection with the API for remote backends.
Have you initialized a file with your personal token?
For now, there's only access to local simulator backends...""")
ibmq_backend = least_busy(IBMQ.backends(simulator=False))
result = algorithm.run(ibmq_backend)
print(result['result'])
plot_histogram(result['measurements'])
params = {
'problem': {'name': 'search'},
'algorithm': {
'name': 'Grover'
},
'oracle': {
'name': 'SAT',
'cnf': sat_cnf
},
'backend': {
'shots': 100
}
}
result_dict = run_algorithm(params, backend=backend)
plot_histogram(result_dict['measurements'])
from __future__ import print_function
def even_ones(s):
# Two states:
# - 0 (even number of ones seen so far)
# - 1 (odd number of ones seen so far)
rules = {(0, '0'): 0,
(0, '1'): 1,
(1, '0'): 1,
(1, '1'): 0}
# There are 0 (which is an even number) ones in the empty
# string so we start with state = 0.
state = 0
for c in s:
state = rules[state, c]
return state == 0
# Example usage:
s = "100110"
print('Output for {} = {}'.format(s, even_ones(s)))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""NumTensorFactors pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import NumTensorFactors
from qiskit.test import QiskitTestCase
class TestNumTensorsFactorPass(QiskitTestCase):
"""Tests for NumTensorFactors analysis methods."""
def test_empty_dag(self):
"""Empty DAG has 0 number of tensor factors."""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 0)
def test_just_qubits(self):
"""A dag with 8 operations and 1 tensor factor."""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
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])
dag = circuit_to_dag(circuit)
pass_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 1)
def test_depth_one(self):
"""A dag with operations in parallel (2 tensor factors)"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
dag = circuit_to_dag(circuit)
pass_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
config = backend.configuration()
# Basic Features
print("This backend is called {0}, and is on version {1}. It has {2} qubit{3}. It "
"{4} OpenPulse programs. The basis gates supported on this device are {5}."
"".format(config.backend_name,
config.backend_version,
config.n_qubits,
'' if config.n_qubits == 1 else 's',
'supports' if config.open_pulse else 'does not support',
config.basis_gates))
config.dt # units of seconds
config.meas_levels
config.dtm
config.meas_map
config.drive(0)
config.measure(0)
config.acquire(0)
props = backend.properties()
def describe_qubit(qubit, properties):
"""Print a string describing some of reported properties of the given qubit."""
# Conversion factors from standard SI units
us = 1e6
ns = 1e9
GHz = 1e-9
print("Qubit {0} has a \n"
" - T1 time of {1} microseconds\n"
" - T2 time of {2} microseconds\n"
" - U2 gate error of {3}\n"
" - U2 gate duration of {4} nanoseconds\n"
" - resonant frequency of {5} GHz".format(
qubit,
properties.t1(qubit) * us,
properties.t2(qubit) * us,
properties.gate_error('sx', qubit),
properties.gate_length('sx', qubit) * ns,
properties.frequency(qubit) * GHz))
describe_qubit(0, props)
defaults = backend.defaults()
q0_freq = defaults.qubit_freq_est[0] # Hz
q0_meas_freq = defaults.meas_freq_est[0] # Hz
GHz = 1e-9
print("DriveChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_freq * GHz))
print("MeasureChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_meas_freq * GHz))
calibrations = defaults.instruction_schedule_map
print(calibrations)
measure_schedule = calibrations.get('measure', range(config.n_qubits))
measure_schedule.draw(backend=backend)
# You can use `has` to see if an operation is defined. Ex: Does qubit 3 have an x gate defined?
calibrations.has('x', 3)
# Some circuit operations take parameters. U1 takes a rotation angle:
calibrations.get('u1', 0, P0=3.1415)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
|
PavanCyborg
|
from qiskit import BasicAer
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import Shor
N = 15
shor = Shor(N)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
ret = shor.run(quantum_instance)
print("The list of factors of {} as computed by the Shor's algorithm is {}.".format(N, ret['factors'][0]))
|
https://github.com/quantumjim/pewpew_qiskit_workshops
|
quantumjim
|
%matplotlib notebook
import pew # setting up tools for the pewpew
pew.init() # initialize the game engine...
screen = pew.Pix() # ...and the screen
screen.pixel(1,2,3) # put a bright pixel at (1,2)
pew.show(screen) # update screen to display the above change
pew.tick(5) # pause for 5 seconds before quitting
import pew # setting up tools for the pewpew
pew.init() # initialize the game engine...
screen = pew.Pix() # ...and the screen
# loop over the square centered on (1,2) and make all dim
(X,Y) = (1,2)
for dX in [+1,0,-1]:
for dY in [+1,0,-1]:
screen.pixel(X+dX,Y+dY,2)
pew.show(screen) # update screen to display the above changes
pew.tick(5) # pause for 5 seconds before quitting
import pew # setting up tools for the pewpew
pew.init() # initialize the game engine...
screen = pew.Pix() # ...and the screen
# loop over the square centered on (1,2) and make all dim
(X,Y) = (1,2)
for dX in [+1,0,-1]:
for dY in [+1,0,-1]:
screen.pixel(X+dX,Y+dY,2)
screen.pixel(X,Y,0) # turn off pixel at (1,2)
pew.show(screen) # update screen to display the above changes
pew.tick(5) # pause for 5 seconds before quitting
import pew # setting up tools for the pewpew
pew.init() # initialize the game engine...
screen = pew.Pix() # ...and the screen
# loop over the square centered on (1,2) and make all dim
(X,Y) = (1,2)
for dX in [+1,0,-1]:
for dY in [+1,0,-1]:
screen.pixel(X+dX,Y+dY,2)
screen.pixel(X,Y,0) # turn off pixel at (1,2)
while True: # loop which checks for user input and responds
keys = pew.keys() # get current key presses
if keys!=0:
if keys&pew.K_UP: # if UP is pressed, turn the pixel at (1,2) on (to a brightness of 3)
screen.pixel(X,Y,3)
pew.show(screen) # update screen to display the above changes
pew.tick(1/6) # pause for a sixth of a second
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test -CZ-CX- joint synthesis function."""
import unittest
from test import combine
import numpy as np
from ddt import ddt
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford
from qiskit.synthesis.linear_phase.cx_cz_depth_lnn import synth_cx_cz_depth_line_my
from qiskit.synthesis.linear import (
synth_cnot_depth_line_kms,
random_invertible_binary_matrix,
)
from qiskit.synthesis.linear.linear_circuits_utils import check_lnn_connectivity
from qiskit.test import QiskitTestCase
@ddt
class TestCXCZSynth(QiskitTestCase):
"""Test the linear reversible circuit synthesis functions."""
@combine(num_qubits=[3, 4, 5, 6, 7, 8, 9, 10])
def test_cx_cz_synth_lnn(self, num_qubits):
"""Test the CXCZ synthesis code for linear nearest neighbour connectivity."""
seed = 1234
rng = np.random.default_rng(seed)
num_gates = 10
num_trials = 8
for _ in range(num_trials):
# Generate a random CZ circuit
mat_z = np.zeros((num_qubits, num_qubits))
cir_z = QuantumCircuit(num_qubits)
for _ in range(num_gates):
i = rng.integers(num_qubits)
j = rng.integers(num_qubits)
if i != j:
cir_z.cz(i, j)
if j > i:
mat_z[i][j] = (mat_z[i][j] + 1) % 2
else:
mat_z[j][i] = (mat_z[j][i] + 1) % 2
# Generate a random CX circuit
mat_x = random_invertible_binary_matrix(num_qubits, seed=rng)
mat_x = np.array(mat_x, dtype=bool)
cir_x = synth_cnot_depth_line_kms(mat_x)
# Joint Synthesis
cir_zx_test = QuantumCircuit.compose(cir_z, cir_x)
cir_zx = synth_cx_cz_depth_line_my(mat_x, mat_z)
# Check that the output circuit 2-qubit depth is at most 5n
depth2q = cir_zx.depth(filter_function=lambda x: x.operation.num_qubits == 2)
self.assertTrue(depth2q <= 5 * num_qubits)
# Check that the output circuit has LNN connectivity
self.assertTrue(check_lnn_connectivity(cir_zx))
# Assert that we get the same elements as other methods
self.assertEqual(Clifford(cir_zx), Clifford(cir_zx_test))
if __name__ == "__main__":
unittest.main()
|
https://github.com/sooodos/Quantum-Computing-Learning-Gate
|
sooodos
|
from qiskit import QuantumCircuit
from QCLG_lvl3.oracles.secret_number_oracle import SecretNUmberOracle
class BernsteinVazirani:
@classmethod
def bernstein_vazirani(cls, random_binary, eval_mode: bool) -> QuantumCircuit:
# Construct secret number oracle
secret_number_oracle = SecretNUmberOracle.create_secret_number_oracle(random_binary=random_binary, eval_mode=eval_mode)
num_of_qubits = secret_number_oracle.num_qubits
# Construct circuit according to the length of the number
dj_circuit = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
dj_circuit_before_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
# Apply H-gates
for qubit in range(num_of_qubits - 1):
dj_circuit_before_oracle.h(qubit)
# Put output qubit in state |->
dj_circuit_before_oracle.x(num_of_qubits - 1)
dj_circuit_before_oracle.h(num_of_qubits - 1)
dj_circuit += dj_circuit_before_oracle
# Add oracle
dj_circuit += secret_number_oracle
dj_circuit_after_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
# Repeat H-gates
for qubit in range(num_of_qubits - 1):
dj_circuit_after_oracle.h(qubit)
dj_circuit_after_oracle.barrier()
# Measure
for i in range(num_of_qubits - 1):
dj_circuit_after_oracle.measure(i, i)
dj_circuit += dj_circuit_after_oracle
if not eval_mode:
print("Circuit before the oracle\n")
print(QuantumCircuit.draw(dj_circuit_before_oracle))
print("Circuit after the oracle\n")
print(QuantumCircuit.draw(dj_circuit_after_oracle))
print(dj_circuit)
return dj_circuit
|
https://github.com/JohnBurke4/qaoa_testing_framework
|
JohnBurke4
|
import networkx as nx
import sys
sys.path.append(
"/Users/johnburke/Desktop/QAOA Code/")
from qiskit import Aer, transpile
from scipy.optimize import minimize
from QAOA_Circuit import QAOACircuit
from QAOA_Cost_Function import CostFunction
import numpy as np
class Result:
def __init__(self, fun, x, nfev):
self.fun = fun
self.x = x
self.nfev = nfev
def addHistory(self, history):
self.history = history
class QAOAScaffolding:
circuit = None
simulator = None
built = False
def __init__(self, numQubits, problemType, problem):
self.numQubits = numQubits
self.problemType = problemType
self.problem = problem
def build(self, layers, mixerType, initType, shots):
qc = QAOACircuit(self.numQubits, layers, mixerType, self.problem, self.problemType, initType)
qc.build()
self.layers = layers
self.circuit = qc
self.simulator = Aer.get_backend('qasm_simulator')
self.shots = shots
# if ('maxcut' in self.problemType):
cost = CostFunction(self.problemType, self.problem)
self.costFunction = cost
self.built = True
def getExpectation(self, params, method = 'average_expectation', customSimulator= None, goal=0, randomGuess=None):
if (customSimulator):
counts = customSimulator(params, self.shots)
else:
qc = self.circuit.getCircuitWithParameters(params)
qc = transpile(qc, backend=self.simulator)
counts = self.simulator.run(qc, shots=self.shots).result().get_counts()
if method == 'best_expectation':
return self.costFunction.getBestExpectation(counts, goal, randomGuess, self.shots)
elif method == "most_common_expectation":
return self.costFunction.getMostCommonExpectation(counts)
elif method == "desired_expectation":
return self.costFunction.getDesiredExpectation(counts, self.shots)
# elif method == "count_of_best":
# return self.costFunction.getDesiredExpectation(counts, self.shots)
return self.costFunction.getExpectation(counts)
def minimizeExectation(self, initialParamsType = 'constant', minimizerType = 'scipy', customParameters = [], saveHistory = False, measurementStrategy = "average_expectation", customSimulator = None, goal=0, graph=None, guess=1):
if (not self.built):
print("Circuit not built")
return False
initialParams = []
parameterCount = self.circuit.getNumberOfParameters()
if (initialParamsType == 'constant'):
initialParams = [1.0] * parameterCount
elif (initialParamsType =='random'):
initialParams = np.random.uniform(0.0, np.pi, parameterCount)
elif (initialParamsType == 'custom'):
initialParams = customParameters
if (minimizerType == 'scipy'):
return self.__scipyMinimize(initialParams, measurementStrategy, customSimulator=customSimulator)
elif (minimizerType == 'brute_force'):
return self.__bruteForceMinimize(parameterCount, saveHistory, measurementStrategy)
elif (minimizerType == 'brute_force_custom'):
return self.__bruteForceCustom(parameterCount, saveHistory, measurementStrategy, customSimulator=customSimulator)
elif (minimizerType == 'annealing'):
return self.__annealingMinimize(initialParams, 1000, 1, saveHistory, measurementStrategy)
elif (minimizerType == 'z_custom'):
return self.__bruteForceZCustom(parameterCount ,saveHistory)
elif (minimizerType == 'y_custom_1'):
return self.__bruteForceYCustom1(parameterCount ,saveHistory)
elif (minimizerType == 'y_custom_2'):
return self.__bruteForceYCustom2(parameterCount, measurementStrategy,saveHistory)
elif (minimizerType == 'y_custom_3'):
return self.__bruteForceYCustom3(parameterCount, saveHistory, graph=graph)
elif (minimizerType == 'ma_rz_custom'):
return self.__customMARZOptimizer(parameterCount, saveHistory, graph=graph, guess=guess)
elif (minimizerType == 'ma_rz_custom_2'):
return self.__customMARZOptimizer2(parameterCount, saveHistory, graph=graph, guess=guess)
elif (minimizerType == 'ry_custom'):
return self.__customCXRYOptimizer(parameterCount, saveHistory, graph=graph)
def __scipyMinimize(self, initialParams, measurementStrategy = 'average_expectation', customSimulator=None):
res = minimize(self.getExpectation,
initialParams,
args=(measurementStrategy, customSimulator),
method='COBYLA',
options={'maxiter':1000})
return res
def __bruteForceMinimize(self, parameterCount, saveHistory = False, measurementStrategy = 'average_expectation'):
possibleValues = 100
values = np.linspace(0, 2*np.pi, possibleValues, endpoint=False)
bestExpectation = 0
bestParameters = []
allValues = []
for i in range(0, possibleValues ** parameterCount):
parameters = [values[int(i / (possibleValues ** j)) % possibleValues] for j in range(0, parameterCount)]
expectation = self.getExpectation(parameters, measurementStrategy)
if (saveHistory):
allValues.append((parameters, expectation))
if (expectation < bestExpectation):
bestExpectation = expectation
bestParameters = parameters
res = Result(bestExpectation, bestParameters, possibleValues ** parameterCount)
if (saveHistory):
res.addHistory(allValues)
return res
def __annealingMinimize(self, initialParams, temp, stepSize, saveHistory = False, measurementStrategy = 'average_expectation'):
def temp_reduction(temp, alpha, type='linear', beta=1):
if (type == 'linear'):
return temp - alpha
if (type == 'geometric'):
return temp * alpha
if (type == 'slow'):
return (temp / (1 + beta * alpha))
def perturb_params(params, curr_temp, max_temp):
new_params = params.copy()
max_terms_changed = int((curr_temp / max_temp)) * len(new_params)
if (max_terms_changed <= 0):
max_terms_changed = 1
states_changed = max_terms_changed
else:
states_changed = np.random.randint(1, max_terms_changed)
scale = (curr_temp / max_temp) * np.pi
for i in range(states_changed):
index = np.random.randint(0, len(new_params))
new_params[index] = new_params[index] + np.random.uniform(-scale , scale)
return np.array(new_params) % (np.pi / 2)
curr_cost = self.getExpectation(initialParams, measurementStrategy)
curr_temp = temp
curr_params = initialParams
niter = 0
allValues = []
while curr_temp > 1:
niter += 1
curr_temp = temp_reduction(curr_temp, stepSize)
new_params = perturb_params(curr_params, curr_temp, temp)
new_cost = self.getExpectation(new_params, measurementStrategy)
if (saveHistory):
allValues.append((new_params, new_cost))
if (new_cost < curr_cost):
curr_cost = new_cost
curr_params = new_params
else:
cost_dif = (curr_cost - new_cost) * 1000
prob = np.e ** (cost_dif / curr_temp)
if (np.random.random() <= prob):
curr_cost = new_cost
curr_params = new_params
res = Result(curr_cost, curr_params, niter)
if (saveHistory):
res.addHistory(allValues)
return res
def __bruteForceCustom(self, parameterCount, saveHistory = False, measurementStrategy = 'average_expectation', customSimulator=None):
possibleParams = [0.0, np.pi/2, np.pi]
bestExpectation = 0.0
parameters = [0.0] * parameterCount
for i in range(0, parameterCount):
testParams = parameters
for param in possibleParams:
testParams[i] = param
expectation = self.getExpectation(testParams, measurementStrategy, customSimulator)
print(expectation, testParams)
if (expectation < bestExpectation):
bestExpectation = expectation
parameters[i] = param
def __bruteForceZCustom(self, parameterCount, saveHistory = False, customSimulator=None):
possibleParams = [0.0, np.pi/2, 2*np.pi/2, 3*np.pi/2]
parameters = [0.0] * parameterCount
bestCost = 0.0
for param1 in possibleParams:
for param2 in possibleParams:
for param3 in possibleParams:
params = [param1, param2, param3]
newCost = self.getExpectation(params, "desired_expectation")
if (newCost < bestCost):
parameters = params
bestCost = newCost
res = Result(bestCost, parameters, 16)
return res
def __bruteForceYCustom1(self, parameterCount, saveHistory = False, customSimulator=None):
parameters = [0.0] * parameterCount
bestCost = 0.0
for i in range(0, parameterCount):
exp1 = self.getExpectation(parameters, "average_expectation")
parameters[i] = np.pi/2
exp2 = self.getExpectation(parameters, "average_expectation")
bestCost = exp2
if (exp1 < exp2):
parameters[i] = 0
bestCost = exp1
res = Result(bestCost, parameters, parameterCount)
return res
def __bruteForceYCustom2(self, parameterCount, measurementStrategy = 'average_expectation', saveHistory = False, customSimulator=None):
theta = np.pi/4
parameters = [theta] * parameterCount
bestCost = 0.0
# parameters[0] = np.pi/2
# parameters[1] = np.pi/2
# parameters[2] = np.pi/2
# parameters[3] = 0
# parameters[4] = 0
# parameters[5] = np.pi/2
# parameters[6] = 0
# parameters[7] = 0
# parameters[8] = np.pi/2
# parameters[9] = 0
# parameters[10] = 0
# parameters[11] = np.pi/2
# parameters[12] = 0
# parameters[13] = 0
# parameters[14] = 0
# parameters[15] = np.pi/2
# parameters[16] = 0
# parameters[17] = 0
bestCost = self.getExpectation(parameters, measurementStrategy)
iterations = 0
# allWorse = False
# while not allWorse:
# currBestCost = 0
# currBestI = -1
# bestChange = 0
# for i in range(0, parameterCount):
# if (parameters[i] == theta):
# iterations += 1
# parameters[i] = 0
# exp = self.getExpectation(parameters, measurementStrategy)
# if (exp < currBestCost):
# currBestCost = exp
# currBestI = i
# bestChange = 0
# parameters[i] = np.pi/2
# exp = self.getExpectation(parameters, measurementStrategy)
# if (exp < currBestCost):
# currBestCost = exp
# currBestI = i
# bestChange = np.pi/2
# # parameters[i] = np.pi/4
# # exp = self.getExpectation(parameters, measurementStrategy)
# # if (exp < currBestCost):
# # currBestCost = exp
# # currBestI = i
# # bestChange = np.pi/4
# parameters[i] = theta
# if (currBestCost < bestCost):
# parameters[currBestI] = bestChange
# bestCost = currBestCost
# else:
# allWorse = True
# for i in range(0, parameterCount):
# if (parameters[i] == theta):
# parameters[i] = 0
# exp = self.getExpectation(parameters, measurementStrategy)
# if (exp < bestCost):
# bestCost = exp
# else:
# parameters[i] = theta
# for i in range(0, parameterCount):
# if (parameters[i] == theta):
# parameters[i] = np.pi/2
# exp = self.getExpectation(parameters, measurementStrategy)
# if (exp < bestCost):
# bestCost = exp
# else:
# parameters[i] = theta
# bestCost = self.getExpectation(parameters, measurementStrategy)
res = Result(bestCost, parameters, iterations)
return res
def __bruteForceYCustom3(self, parameterCount, saveHistory = False, customSimulator=None, graph=None):
edges = list(graph.edges())
v = len(graph.nodes)
orderedEdges = []
rightEdges = []
j = list(range(1, v))
for e in edges:
e1 = e[0]
e2 = e[1]
if (e1 > e2):
rightEdges.append((e2, e1))
else:
rightEdges.append(e)
for e in rightEdges.copy():
# print(e)
e1 = e[0]
e2 = e[1]
if (e2 in j):
rightEdges.remove(e)
orderedEdges.append(e)
j.remove(e2)
bestCost = 0.0
v = len(orderedEdges)
parameters = [np.pi/2] * v + [0.0] * (parameterCount - v)
bestCost = self.getExpectation(parameters, "average_expectation")
allWorse = False
while not allWorse:
currBestCost = 0
currBestI = -1
for i in range(0, parameterCount):
if (parameters[i] != np.pi/2):
parameters[i] = np.pi/2
exp = self.getExpectation(parameters, "average_expectation")
if (exp < currBestCost):
currBestCost = exp
currBestI = i
parameters[i] = 0.0
else:
parameters[i] = 0
exp = self.getExpectation(parameters, "average_expectation")
if (exp < currBestCost):
currBestCost = exp
currBestI = i
parameters[i] = np.pi/2
if (currBestCost < bestCost):
if (parameters[currBestI] == np.pi/2):
parameters[currBestI] = 0
else:
parameters[currBestI] = np.pi/2
bestCost = currBestCost
else:
allWorse = True
res = Result(bestCost, parameters, parameterCount)
return res
def __customMARZOptimizer(self, parameterCount, saveHistory = False, customSimulator=None, graph=None, guess=1):
edges = list(graph.edges())
v = len(graph.nodes)
parameters = [np.pi/guess] * len(edges) + [np.pi/4]
bestCost = self.getExpectation(parameters, "average_expectation")
for i in range(0, len(edges)):
parametersCopy = parameters.copy()
parametersCopy[i] = 0.0
cost = self.getExpectation(parametersCopy, "average_expectation")
if (cost < bestCost):
parameters = parametersCopy
bestCost = cost
res = Result(bestCost, parameters, len(edges))
return res
def __customMARZOptimizer2(self, parameterCount, saveHistory = False, customSimulator=None, graph=None, guess=1):
edges = list(graph.edges())
v = len(graph.nodes)
parameters = [np.pi/6] + [np.pi/4]
bestCost = self.getExpectation(parameters, "average_expectation")
# for i in range(1, v+1):
# parametersCopy = parameters.copy()
# parametersCopy[i] = 0.0
# cost = self.getExpectation(parametersCopy, "average_expectation")
# if (cost < bestCost):
# parameters = parametersCopy
# bestCost = cost
# parametersCopy[i] = np.pi/2
# cost = self.getExpectation(parametersCopy, "average_expectation")
# if (cost < bestCost):
# parameters = parametersCopy
# bestCost = cost
res = Result(bestCost, parameters, len(edges))
def __customCXRYOptimizer(self, parameterCount, saveHistory = False, customSimulator=None, graph=None):
edges = list(graph.edges())
v = len(graph.nodes)
initialCut = int(len(edges) / 2)
parameters = [np.pi/(initialCut/2)]
bestCost = self.getExpectation(parameters, "average_expectation")
cutL = initialCut
for i in range(1, 20):
parametersCopy = [np.pi/(i/2)]
cost = self.getExpectation(parametersCopy, "average_expectation")
print(i, cost)
if (cost < bestCost):
parameters = parametersCopy
bestCost = cost
cutL = i
res = Result(bestCost, cutL, len(edges))
return res
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, backend=FakeBoeblingen())
|
https://github.com/tanjinadnanabir/qbosons-qiskit-hackathon
|
tanjinadnanabir
|
from qiskit import BasicAer
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.algorithms.optimizers import COBYLA, SLSQP
from qiskit.circuit.library import TwoLocal, ZZFeatureMap,RealAmplitudes
from qiskit_machine_learning.algorithms import VQC
from qiskit_machine_learning.datasets import ad_hoc_data
seed = 1376
algorithm_globals.random_seed = seed
import pandas as pd
import numpy as np
Iris_data=pd.read_csv('Iris.csv')
Iris_data.drop(['Id'], axis=1)
# print(Iris_data)
# Iris_data.head()
# import numpy as np
# d = np.loadtxt("Iris.csv", delimiter=",")
feature_cols = [
'SepalLengthCm',
'SepalWidthCm',
'PetalLengthCm',
'PetalWidthCm'
]
target_col = ['Species']
from sklearn.model_selection import train_test_split
xtrain = Iris_data[feature_cols]
ytrain = Iris_data[target_col]#.astype(int)
# ytrain = pd.get_dummies(Iris_data, columns = ['Species'])
# print(ytrain)
ytrain_new = pd.get_dummies(ytrain, columns=["Species"])
# print("The transform data using get_dummies")
# print(ytrain_new)
x_train, x_test, y_train, y_test = train_test_split(xtrain, ytrain_new, test_size=0.25, random_state=42)
x_train.shape, x_test.shape, y_train.shape, y_test.shape
# sv = Statevector.from_label('0' * n)
# feature_map = ZZFeatureMap(feature_dimension=len(feature_cols), reps=2, entanglement="linear")
feature_map = ZZFeatureMap(feature_dimension=4, reps=3, entanglement='linear', insert_barriers=True)
# ansatz = RealAmplitudes(4, reps=1)
ansatz = TwoLocal(num_qubits=4, reps=3, rotation_blocks=['ry','rz'],
entanglement_blocks='cx', entanglement='circular', insert_barriers=True)
# ansatz = TwoLocal(feature_map.num_qubits, ['ry', 'rz'], 'cz', reps=3)
circuit = feature_map.combine(ansatz)
circuit.decompose().draw(output='mpl')
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import clear_output
# callback function that draws a live plot when the .fit() method is called
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
vqc = VQC(feature_map=feature_map,
ansatz=ansatz,
optimizer=COBYLA(maxiter=250),
quantum_instance=QuantumInstance(BasicAer.get_backend('statevector_simulator'),
shots=1024,
seed_simulator=seed,
seed_transpiler=seed),callback=callback_graph
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
vqc.fit(x_train, y_train.to_numpy())
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
vqc.score(x_test, y_test.to_numpy())
print(f"Testing accuracy: {score:0.2f}")
import os
from qiskit import QuantumCircuit, transpile, Aer
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Kraus, SuperOp
from qiskit.providers.aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
from qiskit.test.mock import FakeVigo
device_backend = FakeVigo()
backend = Aer.get_backend('aer_simulator')
counts1 = []
values1 = []
noise_model = None
device = QasmSimulator.from_backend(device_backend)
coupling_map = device.configuration().coupling_map
noise_model = NoiseModel.from_backend(device)
basis_gates = noise_model.basis_gates
print(noise_model)
print()
algorithm_globals.random_seed = seed
qi = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed,
coupling_map=coupling_map, noise_model=noise_model,)
vqc = VQC(feature_map=feature_map,
ansatz=ansatz,
optimizer=COBYLA(maxiter=250),
quantum_instance=qi,callback=callback_graph
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
vqc.fit(x_train, y_train.to_numpy())
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
vqc.score(x_test, y_test.to_numpy())
print(f"Testing accuracy: {score:0.2f}")
from qiskit.utils.mitigation import CompleteMeasFitter
counts2 = []
values2 = []
if noise_model is not None:
algorithm_globals.random_seed = seed
qi2 = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed,
coupling_map=coupling_map, noise_model=noise_model,
measurement_error_mitigation_cls=CompleteMeasFitter,
cals_matrix_refresh_period=30)
vqc = VQC(feature_map=feature_map,
ansatz=ansatz,
optimizer=COBYLA(maxiter=250),
quantum_instance=qi2,callback=callback_graph
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
vqc.fit(x_train, y_train.to_numpy())
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
vqc.score(x_test, y_test.to_numpy())
print(f"Testing accuracy: {score:0.2f}")
from qiskit.algorithms.optimizers import SPSA
vqc = VQC(feature_map=feature_map,
ansatz=ansatz,
optimizer=SPSA(maxiter=100),
quantum_instance=QuantumInstance(BasicAer.get_backend('statevector_simulator'),
shots=1024,
seed_simulator=seed,
seed_transpiler=seed),callback=callback_graph
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
vqc.fit(x_train, y_train.to_numpy())
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
vqc.score(x_test, y_test.to_numpy())
print(f"Testing accuracy: {score:0.2f}")
vqc = VQC(feature_map=feature_map,
ansatz=ansatz,
optimizer=SPSA(maxiter=250),
quantum_instance=qi,callback=callback_graph
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
vqc.fit(x_train, y_train.to_numpy())
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
vqc.score(x_test, y_test.to_numpy())
print(f"Testing accuracy: {score:0.2f}")
vqc = VQC(feature_map=feature_map,
ansatz=ansatz,
optimizer=SPSA(maxiter=250),
quantum_instance=qi2,callback=callback_graph
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
vqc.fit(x_train, y_train.to_numpy())
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
vqc.score(x_test, y_test.to_numpy())
print(f"Testing accuracy: {score:0.2f}")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
es_problem = driver.run()
from qiskit_nature.second_q.mappers import JordanWignerMapper
mapper = JordanWignerMapper()
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
numpy_solver = NumPyMinimumEigensolver()
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD
ansatz = UCCSD(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
mapper,
initial_state=HartreeFock(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
mapper,
),
)
vqe_solver = VQE(Estimator(), ansatz, SLSQP())
vqe_solver.initial_point = [0.0] * ansatz.num_parameters
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.circuit.library import TwoLocal
tl_circuit = TwoLocal(
rotation_blocks=["h", "rx"],
entanglement_blocks="cz",
entanglement="full",
reps=2,
parameter_prefix="y",
)
another_solver = VQE(Estimator(), tl_circuit, SLSQP())
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
calc = GroundStateEigensolver(mapper, vqe_solver)
res = calc.solve(es_problem)
print(res)
calc = GroundStateEigensolver(mapper, numpy_solver)
res = calc.solve(es_problem)
print(res)
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.drivers import GaussianForcesDriver
from qiskit_nature.second_q.mappers import DirectMapper
from qiskit_nature.second_q.problems import HarmonicBasis
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
basis = HarmonicBasis([2, 2, 2, 2])
vib_problem = driver.run(basis=basis)
vib_problem.hamiltonian.truncation_order = 2
mapper = DirectMapper()
solver_without_filter = NumPyMinimumEigensolver()
solver_with_filter = NumPyMinimumEigensolver(
filter_criterion=vib_problem.get_default_filter_criterion()
)
gsc_wo = GroundStateEigensolver(mapper, solver_without_filter)
result_wo = gsc_wo.solve(vib_problem)
gsc_w = GroundStateEigensolver(mapper, solver_with_filter)
result_w = gsc_w.solve(vib_problem)
print(result_wo)
print("\n\n")
print(result_w)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.