repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/Interlin-q/diskit
|
Interlin-q
|
import sys
sys.path.append("..")
from diskit import *
import warnings
warnings.filterwarnings("ignore")
circuit_topo = Topology()
circuit_topo.create_qmap(3, [2, 3, 3], "sys")
circuit_topo.qmap, circuit_topo.emap
print("Total Number of Qubits in Topology : ", circuit_topo.num_qubits())
print("Total Number of QPUs in Topology: ", circuit_topo.num_hosts())
Qubit1 = circuit_topo.qmap["sys1"][2]
Qubit2 = circuit_topo.qmap["sys2"][1]
print("{} and {} are adjacent".format(Qubit1, Qubit2)
if circuit_topo.are_adjacent(Qubit1, Qubit2) else
"{} and {} are not adjacent".format(Qubit1, Qubit2))
for qubit in circuit_topo.qubits:
print("Qubit: {} --------- Host: {}".format(qubit, circuit_topo.get_host(qubit)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/COFAlumni-USB/qiskit-fall-2022
|
COFAlumni-USB
|
import numpy as np
import math
import qiskit as qiskit
from numpy import sqrt
from random import randint
from qiskit import *
from qiskit import Aer, QuantumCircuit, IBMQ, execute, quantum_info, transpile
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_histogram
from qiskit.tools import job_monitor
from qiskit.providers.fake_provider import FakeOpenPulse2Q, FakeOpenPulse3Q, FakeManilaV2, FakeManila
provider = IBMQ.load_account()
print('se ha ejecutado correctamente')
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Se añade el circ_measure, y el Grover_Iteration con rangos de registro
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
#Se define la variable circ
circ = QuantumCircuit(x_register+y_register,measure_register)
#Se describen las compuertas y barreras
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
circ.count_ops() #número de compuertas
circ.depth() #calcula la profundidad del circuito
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
#nota: son las mismas instruccions expresadas a la hora de dar el resultado gráfico arriba, el circuito
#completamente estructurado.
#circ.draw('mpl') EN ESTE CASO NO LO UTILIZAREMOS solo daremos instrucciones al circuito
#circ.draw('mpl')
#simulación Aer Simulator
backend = Aer.get_backend('aer_simulator') #simulador a usar
job = execute(circ, backend, shots=1024) #descripción del trabajo
result = job.result()
counts = result.get_counts(circ)
plot_histogram(counts) #expresa los datos en un histograma
#Simulador de prueba FakeManilaV2
backend = FakeManilaV2() #la única diferencia es que ahora establecemos un backend determinado
#para el circuito a simular
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
circ.count_ops()
circ.depth()
transpiled_circ = transpile(circ, backend)
transpiled_circ.draw()
#Resultados de transpilación con FakeManilaV2
transpiled_circ.count_ops()
transpiled_circ.depth()
job = backend.run(transpiled_circ) #la variable establece la función de correr el backend = FakeManilaV2
counts = job.result().get_counts()
plot_histogram(counts) #analiza los datos a través del histograma
#Resultados de Simulación con FakeManilaV2
#Simulador de prueba FakeManila
backend = FakeManila()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
circ.count_ops()
circ.depth()
transpiled_circ = transpile(circ, backend)
transpiled_circ.draw()
#Resultados de transpilación con FakeManila
transpiled_circ.count_ops()
transpiled_circ.depth()
job = backend.run(transpiled_circ) #la variable establece la función de correr el backend = FakeManila
counts = job.result().get_counts()
plot_histogram(counts) #analiza los datos a través del histograma
#Resultados de Simulación con FakeManila
Como observamos, tenemos un poco de ruido.(Con el backend=FakeManila)
#Simulador de prueba FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
circ.count_ops()
circ.depth()
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
#Resultados de Simulación con FakeOpenPulse2Q
Como observamos, tenemos demasiado ruido en comparación
con las otras simulaciones.(Con el backend=FakeOpenPulse2Q)
#Simulador de prueba FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
circ.count_ops()
circ.depth()
transpiled_circ = transpile(circ, backend)
transpiled_circ.draw()
#Resultados de transpilación con FakeOpenPulse3Q
transpiled_circ.count_ops()
transpiled_circ.depth()
job = backend.run(transpiled_circ)
counts = job.result().get_counts()
plot_histogram(counts)
#Resultado de Simulación con FakeOpenPulse3Q
En esta simulación, no poseemos ruido.(Con el backend=FakeOpenPulse3Q)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
all_pairs = ['00','01','10','11']
for pair in all_pairs:
#
# your code is here
#
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
#
# OUR SOLUTION
#
# initial case
# We assume that the probability of getting head is 1 at the beginning,
# because Asja will start with one euro.
prob_head = 1
prob_tail = 0
#
# first coin-flip
#
# if the last result was head
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
# if the last result was tail
# we know that prob_tail is 0 at the beginning
# but we still keep these two lines to have the same code for each iteration
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
# update the probabilities at the end of coin toss
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
#
# second coin-flip
#
# we do the same calculations
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
#
# third coin-flip
#
# we do the same calculations
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
# print prob_head and prob_tail
print("the probability of getting head",prob_head)
print("the probability of getting tail",prob_tail)
#
# your solution is here
#
prob_head = 0.00001
prob_tail = 0.99999
def toss(prob_head, prob_tail):
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
return prob_head, prob_tail
# toss the biased coin 10 times
for i in range(10):
prob_head, prob_tail = toss(prob_head, prob_tail)
print("After 10 coin tosses - prob of heads: " + str(prob_head) + " | prob of tails: " + str(prob_tail))
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("ggplot")
from pprint import pprint
import pickle
import time
import datetime
%matplotlib inline
with open("e2d1_raw.pkl", "rb") as f:
raw = pickle.load(f)
with open("e2d1_qrem.pkl", "rb") as f:
qrem = pickle.load(f)
with open("e2d1_zne.pkl", "rb") as f:
zne = pickle.load(f)
with open("e2d1_zne_pt.pkl", "rb") as f:
zne_pt = pickle.load(f)
num_steps_list = raw["num_steps_list"]
raw_fid_list = raw["fid"]
raw_stddev_list = raw["stddev"]
num_steps_list = qrem["num_steps_list"]
qrem_fid_list = qrem["fid"]
qrem_stddev_list = qrem["stddev"]
num_steps_list = zne["num_steps_list"]
zne_fid_list = zne["fid"]
zne_stddev_list = zne["stddev"]
num_steps_list = zne_pt["num_steps_list"]
zne_pt_fid_list = zne_pt["fid"]
zne_pt_stddev_list = zne_pt["stddev"]
plt.clf()
plt.figure(dpi=200)
plt.scatter(num_steps_list, raw_fid_list)
plt.scatter(num_steps_list, qrem_fid_list)
plt.scatter(num_steps_list, zne_fid_list)
plt.scatter(num_steps_list, zne_pt_fid_list)
limit = 13
plt.clf()
plt.figure(dpi=200)
plt.scatter(num_steps_list[:limit], raw_fid_list[:limit], marker="o")
plt.scatter(num_steps_list[:limit], qrem_fid_list[:limit], marker="v")
plt.scatter(num_steps_list[:limit], zne_fid_list[:limit], marker="x")
plt.scatter(num_steps_list[:limit], zne_pt_fid_list[:limit], marker="*")
plt.xlabel("number of trotter steps")
plt.ylabel("state fidelity")
plt.legend(("without error mitigations", "with QREM", "with QREM and ZNE", "with QREM, ZNE and Pauli Twirling"))
plt.title("The effect of error mitigations")
zne_pt_fid_list[12]
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qsvm_datasets import *
from qiskit_aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name
from qiskit_aqua.input import get_input_instance
from qiskit_aqua import run_algorithm
# setup aqua logging
import logging
from qiskit_aqua._logging import set_logging_config, build_logging_config
# set_logging_config(build_logging_config(logging.DEBUG)) # choose INFO, DEBUG to see the log
from qiskit import IBMQ
IBMQ.load_accounts()
feature_dim=2 # we support feature_dim 2 or 3
sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=20, test_size=10, n=feature_dim, gap=0.3, PLOT_DATA=True)
datapoints, class_to_label = split_dataset_to_data_and_labels(test_input)
print(class_to_label)
params = {
'problem': {'name': 'svm_classification', 'random_seed': 10598},
'algorithm': {
'name': 'QSVM.Kernel'
},
'backend': {'name': 'qasm_simulator', 'shots': 1024},
'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entanglement': 'linear'}
}
algo_input = get_input_instance('SVMInput')
algo_input.training_dataset = training_input
algo_input.test_dataset = test_input
algo_input.datapoints = datapoints[0] # 0 is data, 1 is labels
result = run_algorithm(params, algo_input)
print("testing success ratio: ", result['testing_accuracy'])
print("predicted classes:", result['predicted_classes'])
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
sample_Total, training_input, test_input, class_labels = Breast_cancer(training_size=20, test_size=10, n=2, PLOT_DATA=True)
# n =2 is the dimension of each data point
datapoints, class_to_label = split_dataset_to_data_and_labels(test_input)
label_to_class = {label:class_name for class_name, label in class_to_label.items()}
print(class_to_label, label_to_class)
algo_input = get_input_instance('SVMInput')
algo_input.training_dataset = training_input
algo_input.test_dataset = test_input
algo_input.datapoints = datapoints[0]
result = run_algorithm(params, algo_input)
print("testing success ratio: ", result['testing_accuracy'])
print("ground truth: {}".format(map_label_to_class_name(datapoints[1], label_to_class)))
print("predicted: {}".format(result['predicted_classes']))
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
|
https://github.com/JackHidary/quantumcomputingbook
|
JackHidary
|
"""키스킷 간단한 예제 프로그램."""
# 키스킷 패키지를 가져오세요.
import qiskit
# 1개 큐비트를 갖는 양자 레지스터를 생성하세요.
qreg = qiskit.QuantumRegister(1, name='qreg')
# 1개 큐비트와 연결된 고전 레지스터를 생성하세요.
creg = qiskit.ClassicalRegister(1, name='creg')
# 위의 두 레지스터들로 구성된 양자 회로를 생성하세요.
circ = qiskit.QuantumCircuit(qreg, creg)
# NOT연산을 추가하세요.
circ.x(qreg[0])
# 측정하기를 추가하세요.
circ.measure(qreg, creg)
# 회로를 출력합니다.
print(circ.draw())
# 양자 회로를 실행할 시뮬레이터 백엔드를 가져옵니다.
backend = qiskit.BasicAer.get_backend("qasm_simulator")
# 회로를 가져온 백엔드 위에서 실행하고 측정결과를 얻습니다.
job = qiskit.execute(circ, backend, shots=10)
result = job.result()
# 측정결과를 출력합니다.
print(result.get_counts())
|
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/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))
ghz.draw(output='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.
"""Tests for core modules of timeline drawer."""
from qiskit import QuantumCircuit, transpile
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import core, stylesheet, generators, layouts
class TestCanvas(QiskitTestCase):
"""Test for canvas."""
def setUp(self):
super().setUp()
self.style = stylesheet.QiskitTimelineStyle()
circ = QuantumCircuit(4)
circ.h(0)
circ.barrier()
circ.cx(0, 2)
circ.cx(1, 3)
self.circ = transpile(
circ,
scheduling_method="alap",
basis_gates=["h", "cx"],
instruction_durations=[("h", 0, 200), ("cx", [0, 2], 1000), ("cx", [1, 3], 1000)],
optimization_level=0,
)
def test_time_range(self):
"""Test calculating time range."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter = {"margin.left_percent": 0.1, "margin.right_percent": 0.1}
canvas.time_range = (0, 100)
ref_range = [-10.0, 110.0]
self.assertListEqual(list(canvas.time_range), ref_range)
def test_load_program(self):
"""Test loading program."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [],
"barriers": [],
"gate_links": [],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 8)
ref_coord = {
self.circ.qregs[0][0]: -1.0,
self.circ.qregs[0][1]: -2.0,
self.circ.qregs[0][2]: -3.0,
self.circ.qregs[0][3]: -4.0,
}
self.assertDictEqual(canvas.assigned_coordinates, ref_coord)
def test_gate_link_overlap(self):
"""Test shifting gate link overlap."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update(
{
"margin.link_interval_percent": 0.01,
"margin.left_percent": 0,
"margin.right_percent": 0,
}
)
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 2)
self.assertListEqual(drawings_tested[0][1].xvals, [706.0])
self.assertListEqual(drawings_tested[1][1].xvals, [694.0])
ref_keys = list(canvas._collections.keys())
self.assertEqual(drawings_tested[0][0], ref_keys[0])
self.assertEqual(drawings_tested[1][0], ref_keys[1])
def test_object_outside_xlimit(self):
"""Test eliminating drawings outside the horizontal limit."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [generators.gen_bit_name, generators.gen_timeslot],
"barriers": [],
"gate_links": [],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.set_time_range(t_start=400, t_end=600)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 12)
def test_non_transpiled_delay_circuit(self):
"""Test non-transpiled circuit containing instruction which is trivial on duration."""
circ = QuantumCircuit(1)
circ.delay(10, 0)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [],
"barriers": [],
"gate_links": [],
}
with self.assertWarns(DeprecationWarning):
canvas.load_program(circ)
self.assertEqual(len(canvas._collections), 1)
def test_multi_measurement_with_clbit_not_shown(self):
"""Test generating bit link drawings of measurements when clbits is disabled."""
circ = QuantumCircuit(2, 2)
circ.measure(0, 0)
circ.measure(1, 1)
circ = transpile(
circ,
scheduling_method="alap",
basis_gates=[],
instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)],
optimization_level=0,
)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({"control.show_clbits": False})
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.load_program(circ)
canvas.update()
self.assertEqual(len(canvas._output_dataset), 0)
def test_multi_measurement_with_clbit_shown(self):
"""Test generating bit link drawings of measurements when clbits is enabled."""
circ = QuantumCircuit(2, 2)
circ.measure(0, 0)
circ.measure(1, 1)
circ = transpile(
circ,
scheduling_method="alap",
basis_gates=[],
instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)],
optimization_level=0,
)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({"control.show_clbits": True})
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.load_program(circ)
canvas.update()
self.assertEqual(len(canvas._output_dataset), 2)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
# pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module
# pylint: disable=attribute-defined-outside-init,unsubscriptable-object
"""Module for estimating import times."""
from sys import executable
from subprocess import call
class QiskitImport:
def time_qiskit_import(self):
call((executable, "-c", "import qiskit"))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import MCXGate
gate = MCXGate(4)
from qiskit import QuantumCircuit
circuit = QuantumCircuit(5)
circuit.append(gate, [0, 1, 4, 2, 3])
circuit.draw('mpl')
|
https://github.com/qclib/qclib
|
qclib
|
# 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.
# pylint: disable=missing-docstring,invalid-name,no-member
# pylint: disable=attribute-defined-outside-init
# pylint: disable=unused-argument
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.compiler import transpile
from qiskit.quantum_info.random import random_unitary
class IsometryTranspileBench:
params = ([0, 1, 2, 3], [3, 4, 5, 6])
param_names = ["number of input qubits", "number of output qubits"]
def setup(self, m, n):
q = QuantumRegister(n)
qc = QuantumCircuit(q)
if not hasattr(qc, "iso"):
raise NotImplementedError
iso = random_unitary(2**n, seed=0).data[:, 0 : 2**m]
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
qc.iso(iso, q[:m], q[m:])
self.circuit = qc
def track_cnot_counts_after_mapping_to_ibmq_16_melbourne(self, *unused):
coupling = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
circuit = transpile(
self.circuit,
basis_gates=["u1", "u3", "u2", "cx"],
coupling_map=coupling,
seed_transpiler=0,
)
counts = circuit.count_ops()
cnot_count = counts.get("cx", 0)
return cnot_count
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for qiskit/version.py"""
from qiskit import __qiskit_version__
from qiskit import __version__
from qiskit.test import QiskitTestCase
class TestVersion(QiskitTestCase):
"""Tests for qiskit/version.py"""
def test_qiskit_version(self):
"""Test qiskit-version sets the correct version for terra."""
with self.assertWarnsRegex(DeprecationWarning, "__qiskit_version__"):
self.assertEqual(__version__, __qiskit_version__["qiskit-terra"])
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### added h gate ###
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)
qc.h(1)
return qc
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#
# your solution is here
#
# let's import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
# let's import randrange for random choices
from random import randrange
#
# your code is here
#
|
https://github.com/108mk/Quantum_Algorithms_and_Qiskit
|
108mk
|
#!conda deactivate
!conda update anaconda-navigator
!conda update conda
!conda update conda
!conda update anaconda
import numpy as np
a = np.array([[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 0., 1.],
[ 0., 0., 1., 0.]])
p = q =r= s = 1
b = np.array([[ p, 0., q, 0.],
[ 0., 0., 0., 0.],
[ r, 0., s, 0.],
[ 0., 0., 0., 0.]])
a@b
a@b@a
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.result import QuasiDistribution
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.optimization import PortfolioOptimization
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_optimization.algorithms import MinimumEigenOptimizer
import numpy as np
import matplotlib.pyplot as plt
import datetime
# set number of assets (= number of qubits)
num_assets = 4
seed = 123
# Generate expected return and covariance matrix from (random) time-series
stocks = [("TICKER%s" % i) for i in range(num_assets)]
data = RandomDataProvider(
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=seed,
)
data.run()
mu = data.get_period_return_mean_vector()
sigma = data.get_period_return_covariance_matrix()
# plot sigma
plt.imshow(sigma, interpolation="nearest")
plt.show()
q = 0.5 # set risk factor
budget = num_assets // 2 # set budget
penalty = num_assets # set parameter to scale the budget penalty term
portfolio = PortfolioOptimization(
expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget
)
qp = portfolio.to_quadratic_program()
qp
def print_result(result):
selection = result.x
value = result.fval
print("Optimal: selection {}, value {:.4f}".format(selection, value))
eigenstate = result.min_eigen_solver_result.eigenstate
probabilities = (
eigenstate.binary_probabilities()
if isinstance(eigenstate, QuasiDistribution)
else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()}
)
print("\n----------------- Full result ---------------------")
print("selection\tvalue\t\tprobability")
print("---------------------------------------------------")
probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True)
for k, v in probabilities:
x = np.array([int(i) for i in list(reversed(k))])
value = portfolio.to_quadratic_program().objective.evaluate(x)
print("%10s\t%.4f\t\t%.4f" % (x, value, v))
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(qp)
print_result(result)
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=500)
ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full")
vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(qp)
print_result(result)
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qp)
print_result(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
from qiskit import ClassicalRegister , QuantumCircuit, QuantumRegister
import numpy as np
qr = QuantumRegister(2)
cr = ClassicalRegister(3) #For tree classicals bites
qc = QuantumCircuit(qr , cr)
qc.h(qr[0]) #auxiliary qubit
qc.x(qr[1]) # eigenvector
#qc.cp((3/2)*np.pi , qr[0] , qr[1])
qc.cp(3*np.pi , qr[0] , qr[1])
qc.h(qr[0])
qc.measure(qr[0] , cr[0]) # this is the controlled-U^(2^n-1) operator for determine phi_n
qc.draw("mpl")
qc.reset(qr[0])
qc.h(qr[0])
# la valeur du bit du poids le plus faible est dans cr[0].
#Si cr[0] = 1 on enléve le bit de poids le plus faible en fesant la rotation alpha_2
#et on continu le bit n-1 devient le bit le bit de poids le plus faible
#si cr[0] est à 0 alors on peut appliquer directement la matrice unitaire associé sans avoir
#à faire de rotation inverse alpha_k
with qc.if_test((cr[0] , 1)) as else_:
qc.p(-np.pi/2 , qr[0])
#qc.cp((3/8)*np.pi , qr[0] ,qr[1])
qc.cp((3/2)*np.pi , qr[0] ,qr[1])
qc.h(qr[0]) # For make measure in X basis {|0> , |1>}
qc.measure(qr[0] , cr[1])
qc.draw("mpl")
qc.reset(qr[0])
qc.h(qr[0])
# la valeur du bit du poids le plus faible est dans cr[0].
#Si cr[0] = 1 on enléve le bit de poids le plus faible en fesant la rotation alpha_2
#et on continu le bit n-1 devient le bit le bit de poids le plus faible
#si cr[0] est à 0 alors on peut appliquer directement la matrice unitaire associé sans avoir
#à faire de rotation inverse alpha_k
with qc.if_test((cr[1] , 1)) as else_:
qc.p(-(3/4)*np.pi , qr[0])
qc.cp((3/4)*np.pi , qr[0] ,qr[1])
qc.h(qr[0]) # For make measure in X basis {|0> , |1>}
qc.measure(qr[0] , cr[2])
qc.draw("mpl")
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
import qiskit.tools.jupyter
%qiskit_version_table
|
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.
# pylint: disable=missing-function-docstring, missing-module-docstring
import unittest
from inspect import signature
from math import pi
import numpy as np
from scipy.linalg import expm
from ddt import data, ddt, unpack
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, execute
from qiskit.exceptions import QiskitError
from qiskit.circuit.exceptions import CircuitError
from qiskit.test import QiskitTestCase
from qiskit.circuit import Gate, ControlledGate
from qiskit.circuit.library import (
U1Gate,
U2Gate,
U3Gate,
CU1Gate,
CU3Gate,
XXMinusYYGate,
XXPlusYYGate,
RZGate,
XGate,
YGate,
GlobalPhaseGate,
)
from qiskit import BasicAer
from qiskit.quantum_info import Pauli
from qiskit.quantum_info.operators.predicates import matrix_equal, is_unitary_matrix
from qiskit.utils.optionals import HAS_TWEEDLEDUM
from qiskit.quantum_info import Operator
from qiskit import transpile
class TestStandard1Q(QiskitTestCase):
"""Standard Extension Test. Gates with a single Qubit"""
def setUp(self):
super().setUp()
self.qr = QuantumRegister(3, "q")
self.qr2 = QuantumRegister(3, "r")
self.cr = ClassicalRegister(3, "c")
self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr)
def test_barrier(self):
self.circuit.barrier(self.qr[1])
self.assertEqual(len(self.circuit), 1)
self.assertEqual(self.circuit[0].operation.name, "barrier")
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_barrier_wires(self):
self.circuit.barrier(1)
self.assertEqual(len(self.circuit), 1)
self.assertEqual(self.circuit[0].operation.name, "barrier")
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_barrier_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.barrier, self.cr[0])
self.assertRaises(CircuitError, qc.barrier, self.cr)
self.assertRaises(CircuitError, qc.barrier, (self.qr, "a"))
self.assertRaises(CircuitError, qc.barrier, 0.0)
def test_conditional_barrier_invalid(self):
qc = self.circuit
barrier = qc.barrier(self.qr)
self.assertRaises(QiskitError, barrier.c_if, self.cr, 0)
def test_barrier_reg(self):
self.circuit.barrier(self.qr)
self.assertEqual(len(self.circuit), 1)
self.assertEqual(self.circuit[0].operation.name, "barrier")
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2]))
def test_barrier_none(self):
self.circuit.barrier()
self.assertEqual(len(self.circuit), 1)
self.assertEqual(self.circuit[0].operation.name, "barrier")
self.assertEqual(
self.circuit[0].qubits,
(self.qr[0], self.qr[1], self.qr[2], self.qr2[0], self.qr2[1], self.qr2[2]),
)
def test_ccx(self):
self.circuit.ccx(self.qr[0], self.qr[1], self.qr[2])
self.assertEqual(self.circuit[0].operation.name, "ccx")
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2]))
def test_ccx_wires(self):
self.circuit.ccx(0, 1, 2)
self.assertEqual(self.circuit[0].operation.name, "ccx")
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2]))
def test_ccx_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.ccx, self.cr[0], self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.ccx, self.qr[0], self.qr[0], self.qr[2])
self.assertRaises(CircuitError, qc.ccx, 0.0, self.qr[0], self.qr[2])
self.assertRaises(CircuitError, qc.ccx, self.cr, self.qr, self.qr)
self.assertRaises(CircuitError, qc.ccx, "a", self.qr[1], self.qr[2])
def test_ch(self):
self.circuit.ch(self.qr[0], self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "ch")
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_ch_wires(self):
self.circuit.ch(0, 1)
self.assertEqual(self.circuit[0].operation.name, "ch")
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_ch_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.ch, self.cr[0], self.cr[1])
self.assertRaises(CircuitError, qc.ch, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.ch, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.ch, (self.qr, 3), self.qr[0])
self.assertRaises(CircuitError, qc.ch, self.cr, self.qr)
self.assertRaises(CircuitError, qc.ch, "a", self.qr[1])
def test_cif_reg(self):
self.circuit.h(self.qr[0]).c_if(self.cr, 7)
self.assertEqual(self.circuit[0].operation.name, "h")
self.assertEqual(self.circuit[0].qubits, (self.qr[0],))
self.assertEqual(self.circuit[0].operation.condition, (self.cr, 7))
def test_cif_single_bit(self):
self.circuit.h(self.qr[0]).c_if(self.cr[0], True)
self.assertEqual(self.circuit[0].operation.name, "h")
self.assertEqual(self.circuit[0].qubits, (self.qr[0],))
self.assertEqual(self.circuit[0].operation.condition, (self.cr[0], True))
def test_crz(self):
self.circuit.crz(1, self.qr[0], self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "crz")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_cry(self):
self.circuit.cry(1, self.qr[0], self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "cry")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_crx(self):
self.circuit.crx(1, self.qr[0], self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "crx")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_crz_wires(self):
self.circuit.crz(1, 0, 1)
self.assertEqual(self.circuit[0].operation.name, "crz")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_cry_wires(self):
self.circuit.cry(1, 0, 1)
self.assertEqual(self.circuit[0].operation.name, "cry")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_crx_wires(self):
self.circuit.crx(1, 0, 1)
self.assertEqual(self.circuit[0].operation.name, "crx")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_crz_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.crz, 0, self.cr[0], self.cr[1])
self.assertRaises(CircuitError, qc.crz, 0, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.crz, 0, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.crz, self.qr[2], self.qr[1], self.qr[0])
self.assertRaises(CircuitError, qc.crz, 0, self.qr[1], self.cr[2])
self.assertRaises(CircuitError, qc.crz, 0, (self.qr, 3), self.qr[1])
self.assertRaises(CircuitError, qc.crz, 0, self.cr, self.qr)
# TODO self.assertRaises(CircuitError, qc.crz, 'a', self.qr[1], self.qr[2])
def test_cry_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.cry, 0, self.cr[0], self.cr[1])
self.assertRaises(CircuitError, qc.cry, 0, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.cry, 0, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.cry, self.qr[2], self.qr[1], self.qr[0])
self.assertRaises(CircuitError, qc.cry, 0, self.qr[1], self.cr[2])
self.assertRaises(CircuitError, qc.cry, 0, (self.qr, 3), self.qr[1])
self.assertRaises(CircuitError, qc.cry, 0, self.cr, self.qr)
# TODO self.assertRaises(CircuitError, qc.cry, 'a', self.qr[1], self.qr[2])
def test_crx_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.crx, 0, self.cr[0], self.cr[1])
self.assertRaises(CircuitError, qc.crx, 0, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.crx, 0, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.crx, self.qr[2], self.qr[1], self.qr[0])
self.assertRaises(CircuitError, qc.crx, 0, self.qr[1], self.cr[2])
self.assertRaises(CircuitError, qc.crx, 0, (self.qr, 3), self.qr[1])
self.assertRaises(CircuitError, qc.crx, 0, self.cr, self.qr)
# TODO self.assertRaises(CircuitError, qc.crx, 'a', self.qr[1], self.qr[2])
def test_cswap(self):
self.circuit.cswap(self.qr[0], self.qr[1], self.qr[2])
self.assertEqual(self.circuit[0].operation.name, "cswap")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2]))
def test_cswap_wires(self):
self.circuit.cswap(0, 1, 2)
self.assertEqual(self.circuit[0].operation.name, "cswap")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2]))
def test_cswap_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.cswap, self.cr[0], self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.cswap, self.qr[1], self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.cswap, self.qr[1], 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.cswap, self.cr[0], self.cr[1], self.qr[0])
self.assertRaises(CircuitError, qc.cswap, self.qr[0], self.qr[0], self.qr[1])
self.assertRaises(CircuitError, qc.cswap, 0.0, self.qr[0], self.qr[1])
self.assertRaises(CircuitError, qc.cswap, (self.qr, 3), self.qr[0], self.qr[1])
self.assertRaises(CircuitError, qc.cswap, self.cr, self.qr[0], self.qr[1])
self.assertRaises(CircuitError, qc.cswap, "a", self.qr[1], self.qr[2])
def test_cu1(self):
self.circuit.append(CU1Gate(1), [self.qr[1], self.qr[2]])
self.assertEqual(self.circuit[0].operation.name, "cu1")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cu1_wires(self):
self.circuit.append(CU1Gate(1), [1, 2])
self.assertEqual(self.circuit[0].operation.name, "cu1")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cu3(self):
self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr[2]])
self.assertEqual(self.circuit[0].operation.name, "cu3")
self.assertEqual(self.circuit[0].operation.params, [1, 2, 3])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cu3_wires(self):
self.circuit.append(CU3Gate(1, 2, 3), [1, 2])
self.assertEqual(self.circuit[0].operation.name, "cu3")
self.assertEqual(self.circuit[0].operation.params, [1, 2, 3])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cx(self):
self.circuit.cx(self.qr[1], self.qr[2])
self.assertEqual(self.circuit[0].operation.name, "cx")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cx_wires(self):
self.circuit.cx(1, 2)
self.assertEqual(self.circuit[0].operation.name, "cx")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cx_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.cx, self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.cx, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.cx, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.cx, (self.qr, 3), self.qr[0])
self.assertRaises(CircuitError, qc.cx, self.cr, self.qr)
self.assertRaises(CircuitError, qc.cx, "a", self.qr[1])
def test_cy(self):
self.circuit.cy(self.qr[1], self.qr[2])
self.assertEqual(self.circuit[0].operation.name, "cy")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cy_wires(self):
self.circuit.cy(1, 2)
self.assertEqual(self.circuit[0].operation.name, "cy")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cy_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.cy, self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.cy, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.cy, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.cy, (self.qr, 3), self.qr[0])
self.assertRaises(CircuitError, qc.cy, self.cr, self.qr)
self.assertRaises(CircuitError, qc.cy, "a", self.qr[1])
def test_cz(self):
self.circuit.cz(self.qr[1], self.qr[2])
self.assertEqual(self.circuit[0].operation.name, "cz")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cz_wires(self):
self.circuit.cz(1, 2)
self.assertEqual(self.circuit[0].operation.name, "cz")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cz_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.cz, self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.cz, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.cz, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.cz, (self.qr, 3), self.qr[0])
self.assertRaises(CircuitError, qc.cz, self.cr, self.qr)
self.assertRaises(CircuitError, qc.cz, "a", self.qr[1])
def test_h(self):
self.circuit.h(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "h")
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_h_wires(self):
self.circuit.h(1)
self.assertEqual(self.circuit[0].operation.name, "h")
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_h_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.h, self.cr[0])
self.assertRaises(CircuitError, qc.h, self.cr)
self.assertRaises(CircuitError, qc.h, (self.qr, 3))
self.assertRaises(CircuitError, qc.h, (self.qr, "a"))
self.assertRaises(CircuitError, qc.h, 0.0)
def test_h_reg(self):
instruction_set = self.circuit.h(self.qr)
self.assertEqual(len(instruction_set), 3)
self.assertEqual(instruction_set[0].operation.name, "h")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
def test_h_reg_inv(self):
instruction_set = self.circuit.h(self.qr).inverse()
self.assertEqual(len(instruction_set), 3)
self.assertEqual(instruction_set[0].operation.name, "h")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
def test_iden(self):
self.circuit.i(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "id")
self.assertEqual(self.circuit[0].operation.params, [])
def test_iden_wires(self):
self.circuit.i(1)
self.assertEqual(self.circuit[0].operation.name, "id")
self.assertEqual(self.circuit[0].operation.params, [])
def test_iden_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.i, self.cr[0])
self.assertRaises(CircuitError, qc.i, self.cr)
self.assertRaises(CircuitError, qc.i, (self.qr, 3))
self.assertRaises(CircuitError, qc.i, (self.qr, "a"))
self.assertRaises(CircuitError, qc.i, 0.0)
def test_iden_reg(self):
instruction_set = self.circuit.i(self.qr)
self.assertEqual(len(instruction_set), 3)
self.assertEqual(instruction_set[0].operation.name, "id")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
def test_iden_reg_inv(self):
instruction_set = self.circuit.i(self.qr).inverse()
self.assertEqual(len(instruction_set), 3)
self.assertEqual(instruction_set[0].operation.name, "id")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
def test_rx(self):
self.circuit.rx(1, self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "rx")
self.assertEqual(self.circuit[0].operation.params, [1])
def test_rx_wires(self):
self.circuit.rx(1, 1)
self.assertEqual(self.circuit[0].operation.name, "rx")
self.assertEqual(self.circuit[0].operation.params, [1])
def test_rx_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.rx, self.cr[0], self.cr[1])
self.assertRaises(CircuitError, qc.rx, self.qr[1], 0)
self.assertRaises(CircuitError, qc.rx, 0, self.cr[0])
self.assertRaises(CircuitError, qc.rx, 0, 0.0)
self.assertRaises(CircuitError, qc.rx, self.qr[2], self.qr[1])
self.assertRaises(CircuitError, qc.rx, 0, (self.qr, 3))
self.assertRaises(CircuitError, qc.rx, 0, self.cr)
# TODO self.assertRaises(CircuitError, qc.rx, 'a', self.qr[1])
self.assertRaises(CircuitError, qc.rx, 0, "a")
def test_rx_reg(self):
instruction_set = self.circuit.rx(1, self.qr)
self.assertEqual(len(instruction_set), 3)
self.assertEqual(instruction_set[0].operation.name, "rx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_rx_reg_inv(self):
instruction_set = self.circuit.rx(1, self.qr).inverse()
self.assertEqual(len(instruction_set), 3)
self.assertEqual(instruction_set[0].operation.name, "rx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_rx_pi(self):
qc = self.circuit
qc.rx(pi / 2, self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "rx")
self.assertEqual(self.circuit[0].operation.params, [pi / 2])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_ry(self):
self.circuit.ry(1, self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "ry")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_ry_wires(self):
self.circuit.ry(1, 1)
self.assertEqual(self.circuit[0].operation.name, "ry")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_ry_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.ry, self.cr[0], self.cr[1])
self.assertRaises(CircuitError, qc.ry, self.qr[1], 0)
self.assertRaises(CircuitError, qc.ry, 0, self.cr[0])
self.assertRaises(CircuitError, qc.ry, 0, 0.0)
self.assertRaises(CircuitError, qc.ry, self.qr[2], self.qr[1])
self.assertRaises(CircuitError, qc.ry, 0, (self.qr, 3))
self.assertRaises(CircuitError, qc.ry, 0, self.cr)
# TODO self.assertRaises(CircuitError, qc.ry, 'a', self.qr[1])
self.assertRaises(CircuitError, qc.ry, 0, "a")
def test_ry_reg(self):
instruction_set = self.circuit.ry(1, self.qr)
self.assertEqual(instruction_set[0].operation.name, "ry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_ry_reg_inv(self):
instruction_set = self.circuit.ry(1, self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "ry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_ry_pi(self):
qc = self.circuit
qc.ry(pi / 2, self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "ry")
self.assertEqual(self.circuit[0].operation.params, [pi / 2])
def test_rz(self):
self.circuit.rz(1, self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "rz")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_rz_wires(self):
self.circuit.rz(1, 1)
self.assertEqual(self.circuit[0].operation.name, "rz")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_rz_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.rz, self.cr[0], self.cr[1])
self.assertRaises(CircuitError, qc.rz, self.qr[1], 0)
self.assertRaises(CircuitError, qc.rz, 0, self.cr[0])
self.assertRaises(CircuitError, qc.rz, 0, 0.0)
self.assertRaises(CircuitError, qc.rz, self.qr[2], self.qr[1])
self.assertRaises(CircuitError, qc.rz, 0, (self.qr, 3))
self.assertRaises(CircuitError, qc.rz, 0, self.cr)
# TODO self.assertRaises(CircuitError, qc.rz, 'a', self.qr[1])
self.assertRaises(CircuitError, qc.rz, 0, "a")
def test_rz_reg(self):
instruction_set = self.circuit.rz(1, self.qr)
self.assertEqual(instruction_set[0].operation.name, "rz")
self.assertEqual(instruction_set[2].operation.params, [1])
def test_rz_reg_inv(self):
instruction_set = self.circuit.rz(1, self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "rz")
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_rz_pi(self):
self.circuit.rz(pi / 2, self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "rz")
self.assertEqual(self.circuit[0].operation.params, [pi / 2])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_rzz(self):
self.circuit.rzz(1, self.qr[1], self.qr[2])
self.assertEqual(self.circuit[0].operation.name, "rzz")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_rzz_wires(self):
self.circuit.rzz(1, 1, 2)
self.assertEqual(self.circuit[0].operation.name, "rzz")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_rzz_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.rzz, 1, self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.rzz, 1, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.rzz, 1, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.rzz, 1, (self.qr, 3), self.qr[0])
self.assertRaises(CircuitError, qc.rzz, 1, self.cr, self.qr)
self.assertRaises(CircuitError, qc.rzz, 1, "a", self.qr[1])
self.assertRaises(CircuitError, qc.rzz, 0.1, self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.rzz, 0.1, self.qr[0], self.qr[0])
def test_s(self):
self.circuit.s(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "s")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_s_wires(self):
self.circuit.s(1)
self.assertEqual(self.circuit[0].operation.name, "s")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_s_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.s, self.cr[0])
self.assertRaises(CircuitError, qc.s, self.cr)
self.assertRaises(CircuitError, qc.s, (self.qr, 3))
self.assertRaises(CircuitError, qc.s, (self.qr, "a"))
self.assertRaises(CircuitError, qc.s, 0.0)
def test_s_reg(self):
instruction_set = self.circuit.s(self.qr)
self.assertEqual(instruction_set[0].operation.name, "s")
self.assertEqual(instruction_set[2].operation.params, [])
def test_s_reg_inv(self):
instruction_set = self.circuit.s(self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "sdg")
self.assertEqual(instruction_set[2].operation.params, [])
def test_sdg(self):
self.circuit.sdg(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "sdg")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_sdg_wires(self):
self.circuit.sdg(1)
self.assertEqual(self.circuit[0].operation.name, "sdg")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_sdg_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.sdg, self.cr[0])
self.assertRaises(CircuitError, qc.sdg, self.cr)
self.assertRaises(CircuitError, qc.sdg, (self.qr, 3))
self.assertRaises(CircuitError, qc.sdg, (self.qr, "a"))
self.assertRaises(CircuitError, qc.sdg, 0.0)
def test_sdg_reg(self):
instruction_set = self.circuit.sdg(self.qr)
self.assertEqual(instruction_set[0].operation.name, "sdg")
self.assertEqual(instruction_set[2].operation.params, [])
def test_sdg_reg_inv(self):
instruction_set = self.circuit.sdg(self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "s")
self.assertEqual(instruction_set[2].operation.params, [])
def test_swap(self):
self.circuit.swap(self.qr[1], self.qr[2])
self.assertEqual(self.circuit[0].operation.name, "swap")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_swap_wires(self):
self.circuit.swap(1, 2)
self.assertEqual(self.circuit[0].operation.name, "swap")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_swap_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.swap, self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.swap, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.swap, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.swap, (self.qr, 3), self.qr[0])
self.assertRaises(CircuitError, qc.swap, self.cr, self.qr)
self.assertRaises(CircuitError, qc.swap, "a", self.qr[1])
self.assertRaises(CircuitError, qc.swap, self.qr, self.qr2[[1, 2]])
self.assertRaises(CircuitError, qc.swap, self.qr[:2], self.qr2)
def test_t(self):
self.circuit.t(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "t")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_t_wire(self):
self.circuit.t(1)
self.assertEqual(self.circuit[0].operation.name, "t")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_t_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.t, self.cr[0])
self.assertRaises(CircuitError, qc.t, self.cr)
self.assertRaises(CircuitError, qc.t, (self.qr, 3))
self.assertRaises(CircuitError, qc.t, (self.qr, "a"))
self.assertRaises(CircuitError, qc.t, 0.0)
def test_t_reg(self):
instruction_set = self.circuit.t(self.qr)
self.assertEqual(instruction_set[0].operation.name, "t")
self.assertEqual(instruction_set[2].operation.params, [])
def test_t_reg_inv(self):
instruction_set = self.circuit.t(self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "tdg")
self.assertEqual(instruction_set[2].operation.params, [])
def test_tdg(self):
self.circuit.tdg(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "tdg")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_tdg_wires(self):
self.circuit.tdg(1)
self.assertEqual(self.circuit[0].operation.name, "tdg")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_tdg_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.tdg, self.cr[0])
self.assertRaises(CircuitError, qc.tdg, self.cr)
self.assertRaises(CircuitError, qc.tdg, (self.qr, 3))
self.assertRaises(CircuitError, qc.tdg, (self.qr, "a"))
self.assertRaises(CircuitError, qc.tdg, 0.0)
def test_tdg_reg(self):
instruction_set = self.circuit.tdg(self.qr)
self.assertEqual(instruction_set[0].operation.name, "tdg")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_tdg_reg_inv(self):
instruction_set = self.circuit.tdg(self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "t")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_u1(self):
self.circuit.append(U1Gate(1), [self.qr[1]])
self.assertEqual(self.circuit[0].operation.name, "u1")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u1_wires(self):
self.circuit.append(U1Gate(1), [1])
self.assertEqual(self.circuit[0].operation.name, "u1")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u1_reg(self):
instruction_set = self.circuit.append(U1Gate(1), [self.qr])
self.assertEqual(instruction_set[0].operation.name, "u1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_u1_reg_inv(self):
instruction_set = self.circuit.append(U1Gate(1), [self.qr]).inverse()
self.assertEqual(instruction_set[0].operation.name, "u1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_u1_pi(self):
qc = self.circuit
qc.append(U1Gate(pi / 2), [self.qr[1]])
self.assertEqual(self.circuit[0].operation.name, "u1")
self.assertEqual(self.circuit[0].operation.params, [pi / 2])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u2(self):
self.circuit.append(U2Gate(1, 2), [self.qr[1]])
self.assertEqual(self.circuit[0].operation.name, "u2")
self.assertEqual(self.circuit[0].operation.params, [1, 2])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u2_wires(self):
self.circuit.append(U2Gate(1, 2), [1])
self.assertEqual(self.circuit[0].operation.name, "u2")
self.assertEqual(self.circuit[0].operation.params, [1, 2])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u2_reg(self):
instruction_set = self.circuit.append(U2Gate(1, 2), [self.qr])
self.assertEqual(instruction_set[0].operation.name, "u2")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [1, 2])
def test_u2_reg_inv(self):
instruction_set = self.circuit.append(U2Gate(1, 2), [self.qr]).inverse()
self.assertEqual(instruction_set[0].operation.name, "u2")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [-pi - 2, -1 + pi])
def test_u2_pi(self):
self.circuit.append(U2Gate(pi / 2, 0.3 * pi), [self.qr[1]])
self.assertEqual(self.circuit[0].operation.name, "u2")
self.assertEqual(self.circuit[0].operation.params, [pi / 2, 0.3 * pi])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u3(self):
self.circuit.append(U3Gate(1, 2, 3), [self.qr[1]])
self.assertEqual(self.circuit[0].operation.name, "u3")
self.assertEqual(self.circuit[0].operation.params, [1, 2, 3])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u3_wires(self):
self.circuit.append(U3Gate(1, 2, 3), [1])
self.assertEqual(self.circuit[0].operation.name, "u3")
self.assertEqual(self.circuit[0].operation.params, [1, 2, 3])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u3_reg(self):
instruction_set = self.circuit.append(U3Gate(1, 2, 3), [self.qr])
self.assertEqual(instruction_set[0].operation.name, "u3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [1, 2, 3])
def test_u3_reg_inv(self):
instruction_set = self.circuit.append(U3Gate(1, 2, 3), [self.qr]).inverse()
self.assertEqual(instruction_set[0].operation.name, "u3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2])
def test_u3_pi(self):
self.circuit.append(U3Gate(pi, pi / 2, 0.3 * pi), [self.qr[1]])
self.assertEqual(self.circuit[0].operation.name, "u3")
self.assertEqual(self.circuit[0].operation.params, [pi, pi / 2, 0.3 * pi])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_x(self):
self.circuit.x(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "x")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_x_wires(self):
self.circuit.x(1)
self.assertEqual(self.circuit[0].operation.name, "x")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_x_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.x, self.cr[0])
self.assertRaises(CircuitError, qc.x, self.cr)
self.assertRaises(CircuitError, qc.x, (self.qr, "a"))
self.assertRaises(CircuitError, qc.x, 0.0)
def test_x_reg(self):
instruction_set = self.circuit.x(self.qr)
self.assertEqual(instruction_set[0].operation.name, "x")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_x_reg_inv(self):
instruction_set = self.circuit.x(self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "x")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_y(self):
self.circuit.y(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "y")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_y_wires(self):
self.circuit.y(1)
self.assertEqual(self.circuit[0].operation.name, "y")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_y_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.y, self.cr[0])
self.assertRaises(CircuitError, qc.y, self.cr)
self.assertRaises(CircuitError, qc.y, (self.qr, "a"))
self.assertRaises(CircuitError, qc.y, 0.0)
def test_y_reg(self):
instruction_set = self.circuit.y(self.qr)
self.assertEqual(instruction_set[0].operation.name, "y")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_y_reg_inv(self):
instruction_set = self.circuit.y(self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "y")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_z(self):
self.circuit.z(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "z")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_z_wires(self):
self.circuit.z(1)
self.assertEqual(self.circuit[0].operation.name, "z")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_z_reg(self):
instruction_set = self.circuit.z(self.qr)
self.assertEqual(instruction_set[0].operation.name, "z")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_z_reg_inv(self):
instruction_set = self.circuit.z(self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "z")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_global_phase(self):
qc = self.circuit
qc.append(GlobalPhaseGate(0.1), [])
self.assertEqual(self.circuit[0].operation.name, "global_phase")
self.assertEqual(self.circuit[0].operation.params, [0.1])
self.assertEqual(self.circuit[0].qubits, ())
def test_global_phase_inv(self):
instruction_set = self.circuit.append(GlobalPhaseGate(0.1), []).inverse()
self.assertEqual(len(instruction_set), 1)
self.assertEqual(instruction_set[0].operation.params, [-0.1])
def test_global_phase_matrix(self):
"""Test global_phase matrix."""
theta = 0.1
np.testing.assert_allclose(
np.array(GlobalPhaseGate(theta)),
np.array([[np.exp(1j * theta)]], dtype=complex),
atol=1e-7,
)
def test_global_phase_consistency(self):
"""Tests compatibility of GlobalPhaseGate with QuantumCircuit.global_phase"""
theta = 0.1
qc1 = QuantumCircuit(0, global_phase=theta)
qc2 = QuantumCircuit(0)
qc2.append(GlobalPhaseGate(theta), [])
np.testing.assert_allclose(
Operator(qc1),
Operator(qc2),
atol=1e-7,
)
def test_transpile_global_phase_consistency(self):
"""Tests compatibility of transpiled GlobalPhaseGate with QuantumCircuit.global_phase"""
qc1 = QuantumCircuit(0, global_phase=0.3)
qc2 = QuantumCircuit(0, global_phase=0.2)
qc2.append(GlobalPhaseGate(0.1), [])
np.testing.assert_allclose(
Operator(transpile(qc1, basis_gates=["u"])),
Operator(transpile(qc2, basis_gates=["u"])),
atol=1e-7,
)
@ddt
class TestStandard2Q(QiskitTestCase):
"""Standard Extension Test. Gates with two Qubits"""
def setUp(self):
super().setUp()
self.qr = QuantumRegister(3, "q")
self.qr2 = QuantumRegister(3, "r")
self.cr = ClassicalRegister(3, "c")
self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr)
def test_barrier_reg_bit(self):
self.circuit.barrier(self.qr, self.qr2[0])
self.assertEqual(len(self.circuit), 1)
self.assertEqual(self.circuit[0].operation.name, "barrier")
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2], self.qr2[0]))
def test_ch_reg_reg(self):
instruction_set = self.circuit.ch(self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "ch")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_ch_reg_reg_inv(self):
instruction_set = self.circuit.ch(self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "ch")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_ch_reg_bit(self):
instruction_set = self.circuit.ch(self.qr, self.qr2[1])
self.assertEqual(instruction_set[0].operation.name, "ch")
self.assertEqual(
instruction_set[1].qubits,
(
self.qr[1],
self.qr2[1],
),
)
self.assertEqual(instruction_set[2].operation.params, [])
def test_ch_reg_bit_inv(self):
instruction_set = self.circuit.ch(self.qr, self.qr2[1]).inverse()
self.assertEqual(instruction_set[0].operation.name, "ch")
self.assertEqual(
instruction_set[1].qubits,
(
self.qr[1],
self.qr2[1],
),
)
self.assertEqual(instruction_set[2].operation.params, [])
def test_ch_bit_reg(self):
instruction_set = self.circuit.ch(self.qr[1], self.qr2)
self.assertEqual(instruction_set[0].operation.name, "ch")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_crz_reg_reg(self):
instruction_set = self.circuit.crz(1, self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "crz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_crz_reg_reg_inv(self):
instruction_set = self.circuit.crz(1, self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "crz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_crz_reg_bit(self):
instruction_set = self.circuit.crz(1, self.qr, self.qr2[1])
self.assertEqual(instruction_set[0].operation.name, "crz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_crz_reg_bit_inv(self):
instruction_set = self.circuit.crz(1, self.qr, self.qr2[1]).inverse()
self.assertEqual(instruction_set[0].operation.name, "crz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_crz_bit_reg(self):
instruction_set = self.circuit.crz(1, self.qr[1], self.qr2)
self.assertEqual(instruction_set[0].operation.name, "crz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_crz_bit_reg_inv(self):
instruction_set = self.circuit.crz(1, self.qr[1], self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "crz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_cry_reg_reg(self):
instruction_set = self.circuit.cry(1, self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_cry_reg_reg_inv(self):
instruction_set = self.circuit.cry(1, self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_cry_reg_bit(self):
instruction_set = self.circuit.cry(1, self.qr, self.qr2[1])
self.assertEqual(instruction_set[0].operation.name, "cry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_cry_reg_bit_inv(self):
instruction_set = self.circuit.cry(1, self.qr, self.qr2[1]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_cry_bit_reg(self):
instruction_set = self.circuit.cry(1, self.qr[1], self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_cry_bit_reg_inv(self):
instruction_set = self.circuit.cry(1, self.qr[1], self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_crx_reg_reg(self):
instruction_set = self.circuit.crx(1, self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "crx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_crx_reg_reg_inv(self):
instruction_set = self.circuit.crx(1, self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "crx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_crx_reg_bit(self):
instruction_set = self.circuit.crx(1, self.qr, self.qr2[1])
self.assertEqual(instruction_set[0].operation.name, "crx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_crx_reg_bit_inv(self):
instruction_set = self.circuit.crx(1, self.qr, self.qr2[1]).inverse()
self.assertEqual(instruction_set[0].operation.name, "crx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_crx_bit_reg(self):
instruction_set = self.circuit.crx(1, self.qr[1], self.qr2)
self.assertEqual(instruction_set[0].operation.name, "crx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_crx_bit_reg_inv(self):
instruction_set = self.circuit.crx(1, self.qr[1], self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "crx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_cu1_reg_reg(self):
instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2])
self.assertEqual(instruction_set[0].operation.name, "cu1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_cu1_reg_reg_inv(self):
instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cu1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_cu1_reg_bit(self):
instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2[1]])
self.assertEqual(instruction_set[0].operation.name, "cu1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_cu1_reg_bit_inv(self):
instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2[1]]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cu1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_cu1_bit_reg(self):
instruction_set = self.circuit.append(CU1Gate(1), [self.qr[1], self.qr2])
self.assertEqual(instruction_set[0].operation.name, "cu1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_cu1_bit_reg_inv(self):
instruction_set = self.circuit.append(CU1Gate(1), [self.qr[1], self.qr2]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cu1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_cu3_reg_reg(self):
instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2])
self.assertEqual(instruction_set[0].operation.name, "cu3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1, 2, 3])
def test_cu3_reg_reg_inv(self):
instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cu3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2])
def test_cu3_reg_bit(self):
instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2[1]])
self.assertEqual(instruction_set[0].operation.name, "cu3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1, 2, 3])
def test_cu3_reg_bit_inv(self):
instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2[1]]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cu3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2])
def test_cu3_bit_reg(self):
instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr2])
self.assertEqual(instruction_set[0].operation.name, "cu3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1, 2, 3])
def test_cu3_bit_reg_inv(self):
instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr2]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cu3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2])
def test_cx_reg_reg(self):
instruction_set = self.circuit.cx(self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cx_reg_reg_inv(self):
instruction_set = self.circuit.cx(self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cx_reg_bit(self):
instruction_set = self.circuit.cx(self.qr, self.qr2[1])
self.assertEqual(instruction_set[0].operation.name, "cx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cx_reg_bit_inv(self):
instruction_set = self.circuit.cx(self.qr, self.qr2[1]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cx_bit_reg(self):
instruction_set = self.circuit.cx(self.qr[1], self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cx_bit_reg_inv(self):
instruction_set = self.circuit.cx(self.qr[1], self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cy_reg_reg(self):
instruction_set = self.circuit.cy(self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cy")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cy_reg_reg_inv(self):
instruction_set = self.circuit.cy(self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cy")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cy_reg_bit(self):
instruction_set = self.circuit.cy(self.qr, self.qr2[1])
self.assertEqual(instruction_set[0].operation.name, "cy")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cy_reg_bit_inv(self):
instruction_set = self.circuit.cy(self.qr, self.qr2[1]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cy")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cy_bit_reg(self):
instruction_set = self.circuit.cy(self.qr[1], self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cy")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cy_bit_reg_inv(self):
instruction_set = self.circuit.cy(self.qr[1], self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cy")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cz_reg_reg(self):
instruction_set = self.circuit.cz(self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cz_reg_reg_inv(self):
instruction_set = self.circuit.cz(self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cz_reg_bit(self):
instruction_set = self.circuit.cz(self.qr, self.qr2[1])
self.assertEqual(instruction_set[0].operation.name, "cz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cz_reg_bit_inv(self):
instruction_set = self.circuit.cz(self.qr, self.qr2[1]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cz_bit_reg(self):
instruction_set = self.circuit.cz(self.qr[1], self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cz_bit_reg_inv(self):
instruction_set = self.circuit.cz(self.qr[1], self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_swap_reg_reg(self):
instruction_set = self.circuit.swap(self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "swap")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_swap_reg_reg_inv(self):
instruction_set = self.circuit.swap(self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "swap")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
@unpack
@data(
(0, 0, np.eye(4)),
(
np.pi / 2,
np.pi / 2,
np.array(
[
[np.sqrt(2) / 2, 0, 0, -np.sqrt(2) / 2],
[0, 1, 0, 0],
[0, 0, 1, 0],
[np.sqrt(2) / 2, 0, 0, np.sqrt(2) / 2],
]
),
),
(
np.pi,
np.pi / 2,
np.array([[0, 0, 0, -1], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]),
),
(
2 * np.pi,
np.pi / 2,
np.array([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]),
),
(
np.pi / 2,
np.pi,
np.array(
[
[np.sqrt(2) / 2, 0, 0, 1j * np.sqrt(2) / 2],
[0, 1, 0, 0],
[0, 0, 1, 0],
[1j * np.sqrt(2) / 2, 0, 0, np.sqrt(2) / 2],
]
),
),
(4 * np.pi, 0, np.eye(4)),
)
def test_xx_minus_yy_matrix(self, theta: float, beta: float, expected: np.ndarray):
"""Test XX-YY matrix."""
gate = XXMinusYYGate(theta, beta)
np.testing.assert_allclose(np.array(gate), expected, atol=1e-7)
def test_xx_minus_yy_exponential_formula(self):
"""Test XX-YY exponential formula."""
theta, beta = np.random.uniform(-10, 10, size=2)
gate = XXMinusYYGate(theta, beta)
x = np.array(XGate())
y = np.array(YGate())
xx = np.kron(x, x)
yy = np.kron(y, y)
rz1 = np.kron(np.array(RZGate(beta)), np.eye(2))
np.testing.assert_allclose(
np.array(gate),
rz1 @ expm(-0.25j * theta * (xx - yy)) @ rz1.T.conj(),
atol=1e-7,
)
def test_xx_plus_yy_exponential_formula(self):
"""Test XX+YY exponential formula."""
theta, beta = np.random.uniform(-10, 10, size=2)
gate = XXPlusYYGate(theta, beta)
x = np.array(XGate())
y = np.array(YGate())
xx = np.kron(x, x)
yy = np.kron(y, y)
rz0 = np.kron(np.eye(2), np.array(RZGate(beta)))
np.testing.assert_allclose(
np.array(gate),
rz0.T.conj() @ expm(-0.25j * theta * (xx + yy)) @ rz0,
atol=1e-7,
)
class TestStandard3Q(QiskitTestCase):
"""Standard Extension Test. Gates with three Qubits"""
def setUp(self):
super().setUp()
self.qr = QuantumRegister(3, "q")
self.qr2 = QuantumRegister(3, "r")
self.qr3 = QuantumRegister(3, "s")
self.cr = ClassicalRegister(3, "c")
self.circuit = QuantumCircuit(self.qr, self.qr2, self.qr3, self.cr)
def test_ccx_reg_reg_reg(self):
instruction_set = self.circuit.ccx(self.qr, self.qr2, self.qr3)
self.assertEqual(instruction_set[0].operation.name, "ccx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_ccx_reg_reg_inv(self):
instruction_set = self.circuit.ccx(self.qr, self.qr2, self.qr3).inverse()
self.assertEqual(instruction_set[0].operation.name, "ccx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cswap_reg_reg_reg(self):
instruction_set = self.circuit.cswap(self.qr, self.qr2, self.qr3)
self.assertEqual(instruction_set[0].operation.name, "cswap")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cswap_reg_reg_inv(self):
instruction_set = self.circuit.cswap(self.qr, self.qr2, self.qr3).inverse()
self.assertEqual(instruction_set[0].operation.name, "cswap")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1]))
self.assertEqual(instruction_set[2].operation.params, [])
class TestStandardMethods(QiskitTestCase):
"""Standard Extension Test."""
@unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test")
def test_to_matrix(self):
"""test gates implementing to_matrix generate matrix which matches definition."""
from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate
from qiskit.circuit.library.generalized_gates.pauli import PauliGate
from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression
params = [0.1 * (i + 1) for i in range(10)]
gate_class_list = Gate.__subclasses__() + ControlledGate.__subclasses__()
simulator = BasicAer.get_backend("unitary_simulator")
for gate_class in gate_class_list:
if hasattr(gate_class, "__abstractmethods__"):
# gate_class is abstract
continue
sig = signature(gate_class)
free_params = len(set(sig.parameters) - {"label", "ctrl_state"})
try:
if gate_class == PauliGate:
# special case due to PauliGate using string parameters
gate = gate_class("IXYZ")
elif gate_class == BooleanExpression:
gate = gate_class("x")
elif gate_class == PauliEvolutionGate:
gate = gate_class(Pauli("XYZ"))
else:
gate = gate_class(*params[0:free_params])
except (CircuitError, QiskitError, AttributeError, TypeError):
self.log.info("Cannot init gate with params only. Skipping %s", gate_class)
continue
if gate.name in ["U", "CX"]:
continue
circ = QuantumCircuit(gate.num_qubits)
circ.append(gate, range(gate.num_qubits))
try:
gate_matrix = gate.to_matrix()
except CircuitError:
# gate doesn't implement to_matrix method: skip
self.log.info('to_matrix method FAILED for "%s" gate', gate.name)
continue
definition_unitary = execute([circ], simulator).result().get_unitary()
with self.subTest(gate_class):
# TODO check for exact equality once BasicAer can handle global phase
self.assertTrue(matrix_equal(definition_unitary, gate_matrix, ignore_phase=True))
self.assertTrue(is_unitary_matrix(gate_matrix))
@unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test")
def test_to_matrix_op(self):
"""test gates implementing to_matrix generate matrix which matches
definition using Operator."""
from qiskit.circuit.library.generalized_gates.gms import MSGate
from qiskit.circuit.library.generalized_gates.pauli import PauliGate
from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate
from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression
params = [0.1 * i for i in range(1, 11)]
gate_class_list = Gate.__subclasses__() + ControlledGate.__subclasses__()
for gate_class in gate_class_list:
if hasattr(gate_class, "__abstractmethods__"):
# gate_class is abstract
continue
sig = signature(gate_class)
if gate_class == MSGate:
# due to the signature (num_qubits, theta, *, n_qubits=Noe) the signature detects
# 3 arguments but really its only 2. This if can be removed once the deprecated
# n_qubits argument is no longer supported.
free_params = 2
else:
free_params = len(set(sig.parameters) - {"label", "ctrl_state"})
try:
if gate_class == PauliGate:
# special case due to PauliGate using string parameters
gate = gate_class("IXYZ")
elif gate_class == BooleanExpression:
gate = gate_class("x")
elif gate_class == PauliEvolutionGate:
gate = gate_class(Pauli("XYZ"))
else:
gate = gate_class(*params[0:free_params])
except (CircuitError, QiskitError, AttributeError, TypeError):
self.log.info("Cannot init gate with params only. Skipping %s", gate_class)
continue
if gate.name in ["U", "CX"]:
continue
try:
gate_matrix = gate.to_matrix()
except CircuitError:
# gate doesn't implement to_matrix method: skip
self.log.info('to_matrix method FAILED for "%s" gate', gate.name)
continue
if not hasattr(gate, "definition") or not gate.definition:
continue
definition_unitary = Operator(gate.definition).data
self.assertTrue(matrix_equal(definition_unitary, gate_matrix))
self.assertTrue(is_unitary_matrix(gate_matrix))
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test of NFT optimizer"""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from qiskit import BasicAer
from qiskit.circuit.library import RealAmplitudes
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.opflow import PauliSumOp
from qiskit_algorithms.optimizers import NFT
from qiskit_algorithms import VQE
class TestOptimizerNFT(QiskitAlgorithmsTestCase):
"""Test NFT optimizer using RY with VQE"""
def setUp(self):
super().setUp()
algorithm_globals.random_seed = 50
with self.assertWarns(DeprecationWarning):
self.qubit_op = PauliSumOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
def test_nft(self):
"""Test NFT optimizer by using it"""
with self.assertWarns(DeprecationWarning):
vqe = VQE(
ansatz=RealAmplitudes(),
optimizer=NFT(),
quantum_instance=QuantumInstance(
BasicAer.get_backend("statevector_simulator"),
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed,
),
)
result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op)
self.assertAlmostEqual(result.eigenvalue.real, -1.857275, places=6)
if __name__ == "__main__":
unittest.main()
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
# ******************************************************************************
# Copyright (c) 2020-2021 University of Stuttgart
#
# See the NOTICE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ******************************************************************************
import os
import shutil
import sys
import tempfile
import urllib.parse
from http.client import HTTPResponse
from importlib import reload
from urllib import request, error
import qiskit
from flask import abort
from app import app
def prepare_code_from_data(data, input_params):
"""Get implementation code from data. Set input parameters into implementation. Return circuit."""
temp_dir = tempfile.mkdtemp()
with open(os.path.join(temp_dir, "__init__.py"), "w") as f:
f.write("")
with open(os.path.join(temp_dir, "downloaded_code.py"), "w") as f:
f.write(data)
sys.path.append(temp_dir)
try:
import downloaded_code
# deletes every attribute from downloaded_code, except __name__, because importlib.reload
# doesn't reset the module's global variables
for attr in dir(downloaded_code):
if attr != "__name__":
delattr(downloaded_code, attr)
reload(downloaded_code)
if 'get_circuit' in dir(downloaded_code):
circuit = downloaded_code.get_circuit(**input_params)
elif 'qc' in dir(downloaded_code):
circuit = downloaded_code.qc
finally:
sys.path.remove(temp_dir)
shutil.rmtree(temp_dir, ignore_errors=True)
if not circuit:
raise ValueError
return circuit
def prepare_code_from_url(url, input_params, bearer_token: str = "", post_processing=False):
"""Get implementation code from URL. Set input parameters into implementation. Return circuit."""
try:
impl = _download_code(url, bearer_token)
except (error.HTTPError, error.URLError):
return None
if not post_processing:
circuit = prepare_code_from_data(impl, input_params)
return circuit
else:
result = prepare_post_processing_code_from_data(impl, input_params)
return result
def prepare_code_from_qasm(qasm):
return qiskit.QuantumCircuit.from_qasm_str(qasm)
def prepare_code_from_qasm_url(url, bearer_token: str = ""):
"""Get implementation code from URL. Set input parameters into implementation. Return circuit."""
try:
impl = _download_code(url, bearer_token)
except (error.HTTPError, error.URLError):
return None
return prepare_code_from_qasm(impl)
def prepare_post_processing_code_from_data(data, input_params):
"""Get implementation code from data. Set input parameters into implementation. Return circuit."""
temp_dir = tempfile.mkdtemp()
with open(os.path.join(temp_dir, "__init__.py"), "w") as f:
f.write("")
with open(os.path.join(temp_dir, "downloaded_code.py"), "w") as f:
f.write(data)
sys.path.append(temp_dir)
try:
import downloaded_code
# deletes every attribute from downloaded_code, except __name__, because importlib.reload
# doesn't reset the module's global variables
for attr in dir(downloaded_code):
if attr != "__name__":
delattr(downloaded_code, attr)
reload(downloaded_code)
if 'post_processing' in dir(downloaded_code):
result = downloaded_code.post_processing(**input_params)
finally:
sys.path.remove(temp_dir)
shutil.rmtree(temp_dir, ignore_errors=True)
if not result:
raise ValueError
return result
def _download_code(url: str, bearer_token: str = "") -> str:
req = request.Request(url)
if urllib.parse.urlparse(url).netloc == "platform.planqk.de":
if bearer_token == "":
app.logger.error("No bearer token specified, download from the PlanQK platform will fail.")
abort(401)
elif bearer_token.startswith("Bearer"):
app.logger.error("The bearer token MUST NOT start with \"Bearer\".")
abort(401)
req.add_header("Authorization", "Bearer " + bearer_token)
try:
res: HTTPResponse = request.urlopen(req)
except Exception as e:
app.logger.error("Could not open url: " + str(e))
if str(e).find("401") != -1:
abort(401)
if res.getcode() == 200 and urllib.parse.urlparse(url).netloc == "platform.planqk.de":
app.logger.info("Request to platform.planqk.de was executed successfully.")
if res.getcode() == 401:
abort(401)
return res.read().decode("utf-8")
|
https://github.com/duartefrazao/Quantum-Finance-Algorithms
|
duartefrazao
|
from qiskit import BasicAer,Aer
from qiskit.aqua import aqua_globals, QuantumInstance
from qiskit.aqua.algorithms import QAOA, NumPyMinimumEigensolver,VQE
from qiskit.circuit.parameter import Parameter
from qiskit.optimization.algorithms import MinimumEigenOptimizer, RecursiveMinimumEigenOptimizer,GroverOptimizer
from qiskit.optimization import QuadraticProgram
from qiskit import Aer
from qiskit.circuit.library import TwoLocal
from qiskit.aqua import QuantumInstance
from qiskit.finance.applications.ising import portfolio
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.finance.data_providers import RandomDataProvider
from qiskit.aqua.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import SLSQP
import numpy as np
import matplotlib.pyplot as plt
import datetime
import math as math
from math import sin,cos
from itertools import combinations
from qiskit.aqua.operators import PrimitiveOp, SummedOp
from qiskit.quantum_info.operators import Pauli,Operator
from qiskit import QuantumCircuit
from qiskit.extensions import HamiltonianGate
from qiskit.aqua.operators import (OperatorBase, Swap,X, I,Y, H, CircuitStateFn,
EvolutionFactory, LegacyBaseOperator)
aqua_globals.massive = True
from time import time
def qaoa(qubo,num_assets,num_assets_wanted, alternating):
num_ancila_qubits = 2
p = 1
maxiter = 10
specify_maxiter = True
ansatz = ((X^num_assets_wanted)^(I^(num_assets-num_assets_wanted)))#^(I^num_ancila_qubits)
mixer_iterations = math.ceil((num_assets/2))
""" print(mixer_iterations)
mixer = QuantumCircuit(num_assets+ 1)
theta = Parameter('θ')
cos = math.cos(theta / 2)
sin = math.sin(theta / 2)
np.array([[cos, -1j * sin],
[-1j * sin, cos]], dtype=dtype)
op = Operator(op)
for i in range(num_assets-1):
mixer.unitary(iswap_op, [i, i+1], label='iswap') """
""" num_qubits = num_assets + 2
mixer = QuantumCircuit(num_qubits)
num_iterations = math.ceil((num_assets) /2) - 1
theta = Parameter('θ1')
mixer.rx(theta,0)
mixer.rx(theta,1)
for iteration in range(num_iterations):
ancila = 0
for i in range(0,num_qubits - 3,+2):
mixer.cswap(num_qubits-1,i,i+1)
for i in range(1,num_qubits - 3,+2):
mixer.cswap(num_qubits-1,i,i+1)
if num_qubits%2 == 1:
mixer.cswap(num_qubits-1,num_qubits-3,0)
for i in range(3,num_qubits-1,+2):
mixer.cswap(0 + ancila%2,i,i+1)
ancila = ancila + 1
for i in range(2,num_qubits-1,+2):
mixer.cswap(0 + ancila%2,i,i+1)
ancila = ancila + 1
if num_qubits%2 == 1:
mixer.cswap(0 + ancila%2,num_qubits-1,2)
mixer.rx(-theta,0)
mixer.rx(-theta,1) """
#mixer = I^num_qubits
quantum_instance = QuantumInstance(Aer.get_backend('qasm_simulator'),
seed_simulator=aqua_globals.random_seed,
seed_transpiler=aqua_globals.random_seed,shots=20000)
if alternating:
#qaoa_mes = QAOA(quantum_instance=quantum_instance,p=p,initial_state=ansatz,optimizer=COBYLA(rhobeg=(np.pi/4)), alternating=alternating)
if specify_maxiter == True:
qaoa_mes = QAOA(quantum_instance=quantum_instance,p=p,initial_state=ansatz,optimizer=SLSQP(maxiter=maxiter),alternating=alternating)
else:
qaoa_mes = QAOA(quantum_instance=quantum_instance,p=p,initial_state=ansatz,optimizer=SLSQP(),alternating=alternating)
else:
if specify_maxiter == True:
qaoa_mes = QAOA(quantum_instance=quantum_instance,p=p,optimizer=SLSQP(maxiter=maxiter))
else:
qaoa_mes = QAOA(quantum_instance=quantum_instance,p=p,optimizer=SLSQP())
qaoa = MinimumEigenOptimizer(qaoa_mes)
start = time()
qaoa_result = qaoa.solve(qubo)
print(time()-start)
return qaoa_result
def vqe(qubo):
quantum_instance = QuantumInstance(BasicAer.get_backend('statevector_simulator'),
seed_simulator=aqua_globals.random_seed,
seed_transpiler=aqua_globals.random_seed)
vqe_mes = VQE(quantum_instance=quantum_instance, initial_point=[0., 0.])
vqe = MinimumEigenOptimizer(vqe_mes)
vqe_result = vqe.solve(qubo)
return vqe_result
def grover_optimizer(qubo,num_stocks):
quantum_instance = QuantumInstance(BasicAer.get_backend('statevector_simulator'),
seed_simulator=aqua_globals.random_seed,
seed_transpiler=aqua_globals.random_seed)
grover_mes =GroverOptimizer(6, quantum_instance=quantum_instance)
grover_result = grover_mes.solve(qubo)
return grover_result
def minimum_eigen(qubo):
quantum_instance = QuantumInstance(BasicAer.get_backend('statevector_simulator'),
seed_simulator=aqua_globals.random_seed,
seed_transpiler=aqua_globals.random_seed)
exact_mes = NumPyMinimumEigensolver()
exact = MinimumEigenOptimizer(exact_mes)
exact_result = exact.solve(qubo)
return exact_result
|
https://github.com/IvanIsCoding/Quantum
|
IvanIsCoding
|
%matplotlib inline
from qiskit import *
# The following code is for nicer display of the matrices
from IPython.display import display, Markdown
def format_float(x):
if x % 1 == 0:
return int(x)
else:
return x
def format_imaginary(z):
if abs(z.imag) < 1e-15:
return "{}".format(format_float(z.real))
elif abs(z.real) < 1e-15:
if z.imag == 1:
return "i"
elif z.imag == -1:
return "-i"
return "{}i".format(format_float(z.imag))
if z.imag > 0:
return "{} + {}i".format(z.real, abs(z.imag))
else:
return "{} - {}i".format(z.real, abs(z.imag))
def display_matrix(gate, gate_name="U"):
a00 = format_imaginary(gate[0][0])
a01 = format_imaginary(gate[0][1])
a10 = format_imaginary(gate[1][0])
a11 = format_imaginary(gate[1][1])
ans = r"${} = \begin{{bmatrix}} {} & {} \\ {} & {}\end{{bmatrix}}$".format(gate_name,a00, a01, a10, a11)
return Markdown(ans)
simulator = Aer.get_backend("unitary_simulator")
circuit = QuantumCircuit(1)
circuit.draw(output="mpl")
job = execute(circuit, backend=simulator)
result = job.result()
unitary = result.get_unitary()
print(unitary)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary, "X")
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.h(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary)
)
circuit = QuantumCircuit(1)
circuit.h(0)
circuit.z(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary)
)
circuit = QuantumCircuit(1)
circuit.z(0)
circuit.h(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary)
)
circuit = QuantumCircuit(1)
circuit.y(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary, "Y")
)
circuit = QuantumCircuit(1)
circuit.y(0)
circuit.y(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary, "U")
)
circuit = QuantumCircuit(1)
circuit.s(0)
circuit.s(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary, "U")
)
circuit = QuantumCircuit(1)
circuit.s(0)
circuit.sdg(0) # sdg = s dagger
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary, "U")
)
circuit = QuantumCircuit(1)
circuit.s(0)
#circuit.sdg(0)
circuit.s(0)
circuit.s(0)
circuit.s(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary, "U")
)
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.wrapper import available_backends, get_backend
from qiskit.wrapper import execute as q_execute
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q,c)
qc.h(q[0])
qc.h(q[1])
qc.cx(q[0], q[1])
qc.measure(q, c)
z = 0.995004165 + 1j * 0.099833417
z = z / abs(z)
u_error = np.array([[1, 0], [0, z]])
noise_params = {'U':
{'gate_time': 1,
'p_depol': 0.001,
'p_pauli': [0, 0, 0.01],
'U_error': u_error
}
}
config = {"noise_params": noise_params}
ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config)
ret = ret.result()
print(ret.get_counts())
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import Aer, QuantumCircuit
from qiskit.circuit.library import PhaseEstimation
qc= QuantumCircuit(3,3)
# dummy unitary circuit
unitary_circuit = QuantumCircuit(1)
unitary_circuit.h(0)
# QPE
qc.append(PhaseEstimation(2, unitary_circuit), list(range(3)))
qc.measure(list(range(3)), list(range(3)))
backend = Aer.get_backend('qasm_simulator')
result = backend.run(qc, shots = 8192).result()
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Ripple adder example based on Cuccaro et al., quant-ph/0410184.
"""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import BasicAer
from qiskit import execute
###############################################################
# Set the backend name and coupling map.
###############################################################
backend = BasicAer.get_backend("qasm_simulator")
coupling_map = [
[0, 1],
[0, 8],
[1, 2],
[1, 9],
[2, 3],
[2, 10],
[3, 4],
[3, 11],
[4, 5],
[4, 12],
[5, 6],
[5, 13],
[6, 7],
[6, 14],
[7, 15],
[8, 9],
[9, 10],
[10, 11],
[11, 12],
[12, 13],
[13, 14],
[14, 15],
]
###############################################################
# Make a quantum program for the n-bit ripple adder.
###############################################################
n = 2
a = QuantumRegister(n, "a")
b = QuantumRegister(n, "b")
cin = QuantumRegister(1, "cin")
cout = QuantumRegister(1, "cout")
ans = ClassicalRegister(n + 1, "ans")
qc = QuantumCircuit(a, b, cin, cout, ans, name="rippleadd")
def majority(p, a, b, c):
"""Majority gate."""
p.cx(c, b)
p.cx(c, a)
p.ccx(a, b, c)
def unmajority(p, a, b, c):
"""Unmajority gate."""
p.ccx(a, b, c)
p.cx(c, a)
p.cx(a, b)
# Build a temporary subcircuit that adds a to b,
# storing the result in b
adder_subcircuit = QuantumCircuit(cin, a, b, cout)
majority(adder_subcircuit, cin[0], b[0], a[0])
for j in range(n - 1):
majority(adder_subcircuit, a[j], b[j + 1], a[j + 1])
adder_subcircuit.cx(a[n - 1], cout[0])
for j in reversed(range(n - 1)):
unmajority(adder_subcircuit, a[j], b[j + 1], a[j + 1])
unmajority(adder_subcircuit, cin[0], b[0], a[0])
# Set the inputs to the adder
qc.x(a[0]) # Set input a = 0...0001
qc.x(b) # Set input b = 1...1111
# Apply the adder
qc &= adder_subcircuit
# Measure the output register in the computational basis
for j in range(n):
qc.measure(b[j], ans[j])
qc.measure(cout[0], ans[n])
###############################################################
# execute the program.
###############################################################
# First version: not mapped
job = execute(qc, backend=backend, coupling_map=None, shots=1024)
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)
result = job.result()
print(result.get_counts(qc))
# Both versions should give the same distribution
|
https://github.com/bertolinocastro/quantum-computing-algorithms
|
bertolinocastro
|
# A Quantum Circuit to Construct All Maximal Cliques Using Grover’s Search Algorithm
## Chu Ryang Wie
### DOI: https://arxiv.org/abs/1711.06146v2
from sympy import *
#import sympy.physics.quantum as qp # quantum physics
from sympy.physics.quantum.qubit import *
from sympy.physics.quantum import Dagger, TensorProduct
from sympy.physics.quantum.gate import *
from sympy.physics.quantum.qapply import *
N = Symbol('N', integer=True)
#N = 8
# base network G:
# 1 <-> 2 <-> 3
# Nodes: 1, 2, 3
# Edges: (1,2), (2,3)
# Adjacency matrix for network G
A = Matrix([
[0, 1, 0],
[1, 0, 1],
[0, 1, 0]
])
# creating qubits for n=3 basis
q = [Qubit(f'{dummy:03b}') for dummy in range(2**3)]
q
# creating psi state vector
kpsi = 1/sqrt(N)*sum(q)
bpsi = 1/sqrt(N)*Dagger(sum(q))
# TODO: create in terms of matrices the O operator perfectly as the circuit described in the paper
O = Matrix([
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0,-1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0,-1, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
])
# step: constructing the U operator basics using a network with n=3
# function to represent qubit as matrix: qubit_to_matrix()
U = 2*kpsi*bpsi
U = qubit_to_matrix(U)-Matrix.eye(2**3)
Hm = Matrix([[1,1],[1,-1]])
Hc = 1/sqrt(2)
H3 = Hc**3*kronecker_product(Hm,Hm,Hm)
q000 = qubit_to_matrix(q[0])
Ualt = H3*(2*q000*Dagger(q000)-Matrix.eye(8))*H3
def G(kpsi):
return matrix_to_qubit(U*O*qubit_to_matrix(kpsi))
# working with a network made by two nodes
# n = 2
# Nodes: 0, 1
# Edges: (0,1)
A = Matrix([
[0,1],
[1,0]
])
# tentando reescrever as contas utilizando seno e cosseno
theta = Symbol('theta')
# creating psi state vector
kpsi = sin(theta/2)*1/sqrt(1)*(Qubit(1,1)) + cos(theta/2)*1/sqrt(3)*(Qubit(0,0)+Qubit(0,1)+Qubit(1,0))
bpsi = sin(theta/2)*1/sqrt(1)*Dagger(Qubit(1,1)) + cos(theta/2)*1/sqrt(3)*Dagger(Qubit(0,0)+Qubit(0,1)+Qubit(1,0))
U = 2*kpsi*bpsi
U = qubit_to_matrix(U)-Matrix.eye(2**2)
O = Matrix([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0,-1]
])
# Creating Oracle based on paper algorithm
def O_operator(ket):
pass
# teste
Matrix.eye(8) - 2 * qubit_to_matrix(Qubit(0,0,0)*Dagger(Qubit(0,0,0)))
X = Matrix([
[0,1],
[1,0]
])
X
Z = Matrix([
[1,0],
[0,-1]
])
Tp = TensorProduct
X3 = Tp(Tp(Matrix.eye(2),Matrix.eye(2)),X)
Z3 = Matrix([
[1,0,0,0,0,0,0,0],
[0,-1,0,0,0,0,0,0],
[0,0,1,0,0,0,0,0],
[0,0,0,1,0,0,0,0],
[0,0,0,0,1,0,0,0],
[0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,1,0],
[0,0,0,0,0,0,0,1],
])
X3*Z3*X3
a= H3*4/sqrt(2)
p=sqrt(2)/4*a*Matrix([1,1,1,-1,1,1,-1,1])
sqrt(2)/4*a*Matrix([1,0,-1,0,0,-1,0,1])
X.as_matrix()
Tp = TensorProduct
XX = Tp(Tp(Matrix([[0,1],[1,0]]),Matrix([[0,1],[1,0]])),Matrix([[0,1],[1,0]]))
Z3 = Matrix([
[1,0,0,0,0,0,0,0],
[0,1,0,0,0,0,0,0],
[0,0,1,0,0,0,0,0],
[0,0,0,1,0,0,0,0],
[0,0,0,0,1,0,0,0],
[0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,1,0],
[0,0,0,0,0,0,0,-1],
])
XX*Z3*XX
XX*Z3
Z3*XX
HH = Tp(Tp(Matrix([[1,1],[1,-1]]),Matrix([[1,1],[1,-1]])),Matrix([[1,1],[1,-1]]))
HH
HH*XX*HH
CX = Matrix([
[1,0,0,0,0,0,0,0],
[0,1,0,0,0,0,0,0],
[0,0,1,0,0,0,0,0],
[0,0,0,1,0,0,0,0],
[0,0,0,0,1,0,0,0],
[0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1],
[0,0,0,0,0,0,1,0],
])
XX*HH*CX*HH*XX
HH*(2*Matrix([1,0,0,0,0,0,0,0])*Dagger(Matrix([1,0,0,0,0,0,0,0]))-Matrix.eye(8))*HH
CZ = Matrix([
[1,0,0,0,0,0,0,0],
[0,1,0,0,0,0,0,0],
[0,0,1,0,0,0,0,0],
[0,0,0,1,0,0,0,0],
[0,0,0,0,1,0,0,0],
[0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,1,0],
[0,0,0,0,0,0,0,-1]
])
XX*CZ*XX
HH*CX*HH
HH*XX*CZ*XX*HH
CZ
CX
H3 = kronecker_product(Matrix.eye(2),Matrix.eye(2),Matrix([[1,1],[1,-1]]))
H3
HH*XX*H3*CX*H3*XX*HH
|
https://github.com/danieljaffe/quantum-algorithms-qiskit
|
danieljaffe
|
#!pip install qiskit
import numpy as np
import matplotlib.pyplot as plt
from math import floor, pi, sqrt
from time import process_time
from qiskit import *
from qiskit.quantum_info.operators import Operator
from qiskit.visualization import plot_histogram
from qiskit.circuit import Gate
def get_bitstring_permutations(index, lst, n, args):
"""
This function populates a list with all the combinations of bit strings of length n
"""
if (index == n):
# append combination to list
lst.append(list.copy(args))
else:
# handle the case where the preceding bit is 0
args[index] = 0
get_bitstring_permutations(index + 1, lst, n, args)
# handle the case where the preceding bit is 1
args[index] = 1
get_bitstring_permutations(index + 1, lst, n, args)
def generate_uf(f, n):
"""
Parameters: f is an anonymous function and n is the number of bits in input: f:{0,1}^n -> {0,1}^n
This function returns an oracle gate representing the function f for all x in {0,1}^n and y in {0,1}^n,
the desired result is of the oracle is mapping the input x,y> to |x, y + f(x)> where + is addition modulo 2.
The function first finds the list of bitstring permutations of n bits, it then establishes a mapping which is
representative of the decimal number of the bitstring represents. For each |x,y>, it calculates
|x, y + f(x)>. Finally it constructs a permutation gate which treats each permutation as a different basis vector
in the 2^(n+1) dimensional complex Hilbert space that represents a system of 2*n qubits.
Returns: the permutation gate
"""
# generate list of all bitstrings of size n
bitstrings = []
get_bitstring_permutations(0, bitstrings, n + 1, [0] * (n + 1))
# initialize mapping and permutation list
perm_dict = dict()
perm_list = []
# populate mapping
for permutation, bitstring in enumerate(bitstrings):
values = [0] * (len(bitstrings))
values[permutation] = 1
perm_dict["".join(str(bit) for bit in bitstring)] = values
# Send each |xy> to |x, f(x) + y>
for bitstring in bitstrings:
params = bitstring[:n]
params.append((f(params) + bitstring[-1]) % 2)
perm_list.append(perm_dict["".join(str(bit) for bit in params)])
return Operator(np.array(perm_list))
def apply_H(circuit, apply_to_list):
"""
Apply Hadamards to all specified qubits (if apply_to_list[index] == 1).
Designed for a large amount of Hadamards being applied at once.
"""
for index, qubit in enumerate(apply_to_list):
if qubit == 1:
circuit.h(index)
return circuit
def initialize_dj(n):
"""
This function sets initial states and applies Hadamards to each qubit
Note: apply_H isn't called because it is actually more efficient to initialize in one loop as opposed to 2.
"""
# apply H to first n qubits and X H to the last qubit (ancilla qubit)
quantum_register = QuantumRegister(n + 1)
classical_register = ClassicalRegister(n)
quantum_circuit = QuantumCircuit(quantum_register, classical_register)
# In qiskit, all quantum registers start in the low energy |0> state so we must apply an x gate to our helper bit
# in order to put it in the state |1>
quantum_circuit.x(quantum_register[-1])
for index in range(n + 1):
quantum_circuit.h(quantum_register[index])
quantum_circuit.barrier()
return quantum_circuit, quantum_register, classical_register
def initialize_bv(states):
"""
This function sets initial states and applies Hadamards to each qubit
Note: apply_H isn't called because it is actually more efficient to initialize in one loop as opposed to 2.
"""
n = len(states)
circuit = QuantumCircuit(n, n-1)
for index, state in enumerate(states):
if state == 1:
circuit.x(index)
circuit.h(index)
return circuit
def deutsch_jozsa_algorithm(f, n, shots=1024, threshold=0.9):
"""
This function is intended to determine if f is constant or balanced for a given function f s.t.
f:{0,1}^n -> {0,1}. The algorithm initializes the qubits with H for the first n qubits and X and H for the last
qubit. The algorithm then constructs a Uf oracle gate based on the function input f. It then applies Uf to all
the qubits and applies H to the first n qubits. Finally, the simulator is run on the circuit and measures the
results. If upon measurement, the first n qubits are all 0, 1 is returned and the function is constant,
otherwise 0 is returned and the function is balanced.
This function has an anonymous function and integer n as parameters.
This function uses 9q-squared-qvm, so it assumes that n <= 9.
"""
# apply H to first n qubits and X H to the last qubit (ancilla qubit)
quantum_circuit, quantum_register, classical_register = initialize_dj(n)
# Generate Uf oracle from f (anonymous function)
uf_gate = generate_uf(f, n)
# Applying the uf_gate must be done with the qubits in the reverse order due to the implementation of qiskit
rv_qr = list()
for index in range(n + 1):
rv_qr.append(index)
rv_qr.reverse()
quantum_circuit.unitary(uf_gate, rv_qr)
quantum_circuit.barrier()
# Apply Hadamards to first n qubits
for index in range(n):
quantum_circuit.h(quantum_register[index])
# Run simulator
quantum_simulator = Aer.get_backend('qasm_simulator')
quantum_circuit.measure(quantum_register[0:n], classical_register)
# quantum_circuit.draw('mpl')
# plt.show()
# Evaluate the job results
# start = process_time()
job = execute(quantum_circuit, quantum_simulator, shots=shots)
# end = process_time()
# total_time = end - start
results = job.result()
counts = results.get_counts(quantum_circuit)
# NOTE: 1 = constant, 0 = balanced
# To compensate for the error rates of actual quantum machines, the threshold for being consider balanced is
# set to be threshold * shots, or a percentage of shots given at runtime.
# Function is constant
key = '0' * n
if key in counts:
if counts[key] >= threshold * shots:
return 1
key = '1' * n
if key in counts:
if counts[key] >= threshold * shots:
return 1
# Function is balanced
return 0
def f_balanced(args):
return args[0]
def f_constant(args):
return 1
input_size = 10
times = []
for i in range(1,input_size+1):
start = process_time()
res = deutsch_jozsa_algorithm(f_balanced, i, shots=1)
times.append(process_time()-start)
print(times)
plt.plot(range(1,input_size+1), times)
for x,y in zip(range(1,input_size+1),times):
label = "{:.3f}".format(y)
plt.annotate(label, # this is the text
(x,y), # this is the point to label
textcoords="offset points", # how to position the text
xytext=(0,10), # distance from text to points (x,y)
ha='right') # horizontal alignment can be left, right or center
plt.xticks(np.arange(0, input_size+1, step=1))
plt.yticks(np.arange(0, 15, step=1))
plt.ylabel("Execution Time (s)")
plt.xlabel("Input Size (n)")
plt.title("DJ: Execution Time for Balanced Function vs. Input Size")
times = []
for i in range(1,input_size+1):
start = process_time()
res = deutsch_jozsa_algorithm(f_constant, i, shots=1)
times.append(process_time()-start)
print(times)
plt.plot(range(1,input_size+1), times)
for x,y in zip(range(1,input_size+1),times):
label = "{:.3f}".format(y)
plt.annotate(label, # this is the text
(x,y), # this is the point to label
textcoords="offset points", # how to position the text
xytext=(0,10), # distance from text to points (x,y)
ha='right') # horizontal alignment can be left, right or center
plt.xticks(np.arange(0, input_size+1, step=1))
plt.yticks(np.arange(0, 14, step=1))
plt.ylabel("Execution Time (s)")
plt.xlabel("Input Size (n)")
plt.title("DJ: Execution Time for Constant Function vs. Input Size")
def bernstein_vazirani_algorithm(f, n):
initialize_list = [0] * n
# calculate b by f(0^n) = b
b = f(initialize_list)
# Initialize circuit by applying H to first n qubits and X H to last qubit (ancilla qubit)
initialize_list.append(1)
qubits = list(range(len(initialize_list)))
circuit = initialize_bv(initialize_list)
# Generate Uf oracle from f (anonymous function)
uf_gate = generate_uf(f, n)
# Applying the uf_gate must be done with the qubits in the reverse order due to the implementation of qiskit
rv_qubits = qubits[::-1]
circuit.unitary(uf_gate, rv_qubits)
# Apply H to all qubits except for the last qubit
apply_to_list = [1] * n
apply_to_list.append(0)
circuit = apply_H(circuit, apply_to_list)
circuit.measure(range(n),range(n))
# run simulator and measure qubits
simulator = Aer.get_backend("qasm_simulator")
job = execute(circuit, simulator, shots=1)
result = job.result()
counts = result.get_counts(circuit)
plot_histogram(counts)
for count in counts:
a = count
return a,b
def f_bv(x):
n = len(x)
y = 0
for i,x_i in enumerate(x):
y = (y + (x_i*(i%2)))%2
y = (y+(n%2))%2
return(y)
times = []
for i in range(1,input_size+1):
start = process_time()
res = bernstein_vazirani_algorithm(f_bv, i)
times.append(process_time()-start)
print(times)
plt.plot(range(1,input_size+1), times)
for x,y in zip(range(1,input_size+1),times):
label = "{:.3f}".format(y)
plt.annotate(label, # this is the text
(x,y), # this is the point to label
textcoords="offset points", # how to position the text
xytext=(0,10), # distance from text to points (x,y)
ha='right') # horizontal alignment can be left, right or center
plt.xticks(np.arange(0, input_size+1, step=1))
plt.yticks(np.arange(0, 15, step=1))
plt.ylabel("Execution Time (s)")
plt.xlabel("Input Size (n)")
plt.title("BV: Execution Time vs. Input Size")
def get_Z0(n):
"""
This function generates the Z0 gate satisfying the conditions for x in {0,1}^n Z0|x> -> -|x> iff x = 0^n
otherwise Z0|x> -> |x>
The parameter to this function is only the size n, a 2^n x 2^n dimensional matrix is created satisfying the
conditions above.
This function has one dependency, the DefGate function defined in pyquil.quil
This function is designed to absorb the negative in G, so the returned gate is actually -Z0
Returns -Z0
"""
# Create a 2^n x 2^n matrix with all 0's
gate = np.zeros((2 ** n, 2 ** n), dtype=int)
# since this is -Z0, set first element to 1 not -1
gate[0][0] = 1
# set all other elements on the diagonal to -1, again not 1 because this is -Z0
for i in range(1, 2 ** n):
gate[i][i] = -1
# Return gate
return Operator(gate)
def get_Zf(f, n):
"""
This function generates the Zf gate satisfying the condition for x in {0,1}^n where Zf|x> -> (-1)^f(X)|x>
This function requires that f(x) be calculated for all x, so f is passed as an anonymous function, the other
parameter is n.
The function has one dependency, the DefGate function defined in pyquil.quil
This function finds all permutations of bitstrings of length n, then initializes a 2^n x 2^n matrix of all 0's,
and sets all elements along the diagonal to either 1 or -1 depending on f(x)
Finally a gate representation of this matrix is returned.
"""
# generate bitstring permutations
bitstrings = list()
get_bitstring_permutations(0, bitstrings, n, [0] * n)
# initialize a 2^n x 2^n matrix of all 0's
gate = np.zeros((2 ** n, 2 ** n), dtype=int)
# set diagonals of matrix based on f(x)
for i in range(2 ** n):
gate[i][i] = -1 if f(bitstrings[i]) == 1 else 1
# create and return gate
return Operator(gate)
def grovers_algorithm(f, n, shots=1024, threshold=0.9):
"""
This function is intended to determine if there exists an x in {0,1}^n s.t. f(x) = 1 for a given function f s.t.
f:{0,1}^n -> {0,1}. The algorithm first constructs Zf, -Z0 gates, initializes with Hanamard matrices, and
applies G = -H^n o Z0 o H^n o Zf. This algorithm is not deterministic, so G is applied multiple times. More
specifically, G is run (pi / 4 * sqrt(n)) times. Furthermore, there are 10 trials to minimize the chance of a
false negative.
This function has an anonymous function and integer n as parameters.
This function runs the algorithm as described for each 10 trials, and then checks if for any of the outputted states
x, if f(x) = 1. If this is true, then 1 is returned, otherwise 0 is returned. The function returns 0 if there
is an issue with the simulator.
This function uses 9q-squared-qvm, so it assumes that n <= 9
"""
# Initialize the circuit and apply Hadamards to all qubits
quantum_circuit, quantum_register, classical_register = initialize_dj(n)
# Needed for application of custom gates since Operator works in reverse
rv_qr = list()
for index in range(n):
rv_qr.append(index)
rv_qr.reverse()
# Define and generate Z0 gate (really -Z0)
z0_gate = get_Z0(n)
# Define and generate Zf gate
zf_gate = get_Zf(f, n)
# Determine the number of times to apply G
iteration_count = floor(pi / 4 * sqrt(2 ** n))
# Apply G iteration_count times
for i in range(iteration_count):
# Apply Zf
quantum_circuit.unitary(zf_gate, rv_qr)
# Apply H to all qubits
for index in range(n):
quantum_circuit.h(quantum_register[index])
# Apply -Z0
quantum_circuit.unitary(z0_gate, rv_qr)
# Apply H to all qubits
for index in range(n):
quantum_circuit.h(quantum_register[index])
quantum_circuit.barrier()
# Run simulator
quantum_simulator = Aer.get_backend('qasm_simulator')
quantum_circuit.measure(quantum_register[0:n], classical_register)
# Display circuit diagram
quantum_circuit.draw('mpl')
plt.show()
# Execute and evaluate the job results
job = execute(quantum_circuit, quantum_simulator, shots=shots)
results = job.result()
counts = results.get_counts(quantum_circuit)
return counts
# Parse results and return 1 or 0 accordingly
# dict = {}
# for key in counts:
# if counts[key] >= (shots/(2**n)):
# dict[key] = counts[key]
# for key in dict:
# poop = list(key)
# poop = [int(i) for i in poop]
# poop.reverse()
# if f(poop) == 1:
# return 1
# return 0
def f_0(args):
return 0
def f_1(args):
return 1
def f_100(args):
n = len(args)
marked = [0]*(n-1)
marked.append(1)
if(args == marked):
return 1
return 0
input_size = 8
times = []
for i in range(1,input_size+1):
start = process_time()
res = grovers_algorithm(f_0, i, shots=1024, threshold=0.9)
times.append(process_time()-start)
print(times)
plt.plot(range(1,input_size+1), times)
for x,y in zip(range(1,input_size+1),times):
label = "{:.4f}".format(y)
plt.annotate(label, # this is the text
(x,y), # this is the point to label
textcoords="offset points", # how to position the text
xytext=(0,10), # distance from text to points (x,y)
ha='right') # horizontal alignment can be left, right or center
plt.xticks(np.arange(0, input_size+1, step=1))
plt.yticks(np.arange(0, 3.5, step=0.5))
plt.ylabel("Execution Time (s)")
plt.xlabel("Input Size (n)")
plt.title("Grover's: Execution Time of Zero-Function vs. Input Size")
times = []
for i in range(1,input_size+1):
start = process_time()
res = grovers_algorithm(f_1, i, shots=1024, threshold=0.9)
times.append(process_time()-start)
print(times)
plt.plot(range(1,input_size+1), times)
for x,y in zip(range(1,input_size+1),times):
label = "{:.4f}".format(y)
plt.annotate(label, # this is the text
(x,y), # this is the point to label
textcoords="offset points", # how to position the text
xytext=(0,10), # distance from text to points (x,y)
ha='right') # horizontal alignment can be left, right or center
plt.xticks(np.arange(0, input_size+1, step=1))
plt.yticks(np.arange(0, 3.5, step=0.5))
plt.ylabel("Execution Time (s)")
plt.xlabel("Input Size (n)")
plt.title("Grover's: Execution Time of One-Function vs. Input Size")
times = []
for i in range(1,input_size+1):
start = process_time()
res = grovers_algorithm(f_100, i, shots=1024, threshold=0.9)
times.append(process_time()-start)
print(times)
plt.plot(range(1,input_size+1), times)
for x,y in zip(range(1,input_size+1),times):
label = "{:.4f}".format(y)
plt.annotate(label, # this is the text
(x,y), # this is the point to label
textcoords="offset points", # how to position the text
xytext=(0,10), # distance from text to points (x,y)
ha='right') # horizontal alignment can be left, right or center
plt.xticks(np.arange(0, input_size+1, step=1))
plt.yticks(np.arange(0, 3.5, step=0.5))
plt.ylabel("Execution Time (s)")
plt.xlabel("Input Size (n)")
plt.title("Grover's: Execution Time of First-Bit-Function vs. Input Size")
def generate_uf_simons(f, n):
"""
Parameters: f is an anonymous function and n is the number of bits in input: f:{0,1}^n -> {0,1}^n
This function returns an oracle gate representing the function f for all x in {0,1}^n and y in {0,1}^n,
the desired result is of the oracle is mapping the input x,y> to |x, y + f(x)> where + is addition modulo 2.
The function first finds the list of bitstring permutations of n bits, it then establishes a mapping which is
representative of the decimal number of the bitstring represents. For each |x,y>, it calculates
|x, y + f(x)>. Finally it constructs a permutation gate which treats each permutation as a different basis vector
in the 2^(n+1) dimensional complex Hilbert space that represents a system of 2*n qubits.
Returns: the permutation gate
"""
# generate list of all bitstrings of size n
bitstrings = []
get_bitstring_permutations(0, bitstrings, 2 * n, [0] * (2 * n))
# initialize mapping and permutation list
perm_dict = dict()
perm_list = []
# populate mapping
for permutation, bitstring in enumerate(bitstrings):
values = [0]*(len(bitstrings))
values[permutation] = 1
perm_dict["".join(str(bit) for bit in bitstring)] = values
# Send each |xy> to |x, f(x) + y>
for bitstring in bitstrings:
params = bitstring[:n]
params2 = bitstring[n:2 * n]
f_values = f(bitstring[:n])
for i in range(n):
params.append((params2[i] + f_values[i]) % 2)
perm_list.append(perm_dict["".join(str(bit) for bit in params)])
return Operator(np.array(perm_list))
def simons_solver(Y, n):
"""
Inputs: Y is a linear system of n-1 equations in matrix form. n is the dimension of the input into f.
This function acts as a binary linear matrix solver.
Returns: the key string s, if found, or the zero bitstring
"""
# Create all possible bit strings to test for s
bitstrings = []
get_bitstring_permutations(0, bitstrings, n, [0] * n)
# For each possible s, test to see if it's a candidate
for s in bitstrings:
if s == [0] * n:
continue
candidate = True
# For each equation in Y, bit by bit test that y*s = [0]*n
for y in Y:
value = 0
for i in np.arange(n):
value = value + s[i] * y[i]
# If a bit doesn't evaluate to 0...
if (value % 2 == 1):
candidate = False
if (candidate):
return s
return [0] * n
def simons_algorithm(f, n):
"""
Inputs: f is a blackbox function (f:{0,1}^n -> {0,1}^n) that is either one-to-one or two-to-one. n is the
dimension of the input into f. This function finds and returns the key s, if one exists, for a two-to-one
function by first creating a matrix U_f that represents f, then applying the appropriate quantum gates to
generate a linear equation. By running the circuit until we generate n-1 unique equations, the set of equations can solve for s. The Classical solver returns s.
Returns: the key string s, if found, or the zero bitstring
"""
#Generate the oracle gate
oracle = generate_uf_simons(f, n)
#Initialize the circuit
circuit = QuantumCircuit(2*n, 2*n)
#initialize the simulator, use qasm_simulator
simulator = Aer.get_backend("qasm_simulator")
indices = list(range(2*n))
indices.reverse()
#apply Hadamards to first n qubits
for i in range(n):
circuit.h(i)
#apply oracle gate
circuit.unitary(oracle, indices, label="oracle")
#apply Hadamards again to first n qubits
for i in range(n):
circuit.h(i)
indices = list(range(n))
#measure first n qubits
circuit.measure(indices, indices)
#Run the entire process 20 times
for i in range(20):
s = set()
s_trials = []
#Run quantum circuit until at least n-1 unique eqautions are obtained
while(len(s) < n-1):
job = execute(circuit, simulator, shots=1)
result = job.result()
counts = result.get_counts()
for count in counts:
s.add(count[2*n:n-1:-1])
for bitstring in s:
s_trials.append([int(bit) for bit in bitstring])
s_trials = np.array(s_trials)
#Solve system of equations
val = simons_solver(s_trials, n)
if val == [0] * n:
continue
#if the correct function value is found, no need to keep searching
f_val = f(val)
if f_val == f([0]*n):
return val
#s not found, return 0 bit string
return [0] * n
def f_oto(x):
return x
def f_tto(x):
res = [0]
if (len(x)>1):
res = res + x[1:]
return res
input_size = 5
times = []
for i in range(1,input_size+1):
start = process_time()
res = simons_algorithm(f_oto, i)
times.append(process_time()-start)
print(times)
plt.plot(range(1,input_size+1), times)
for x,y in zip(range(1,input_size+1),times):
label = "{:.4f}".format(y)
plt.annotate(label, # this is the text
(x,y), # this is the point to label
textcoords="offset points", # how to position the text
xytext=(0,10), # distance from text to points (x,y)
ha='right') # horizontal alignment can be left, right or center
plt.xticks(np.arange(0, input_size+1, step=1))
plt.yticks(np.arange(0, 450, step=50))
plt.ylabel("Execution Time (s)")
plt.xlabel("Input Size (n)")
plt.title("Simon's: Execution Time of One-to-One Function vs. Input Size")
input_size = 5
times = []
for i in range(1,input_size+1):
start = process_time()
res = simons_algorithm(f_tto, i)
times.append(process_time()-start)
print(times)
plt.plot(range(1,input_size+1), times)
for x,y in zip(range(1,input_size+1),times):
label = "{:.4f}".format(y)
plt.annotate(label, # this is the text
(x,y), # this is the point to label
textcoords="offset points", # how to position the text
xytext=(0,10), # distance from text to points (x,y)
ha='right') # horizontal alignment can be left, right or center
plt.xticks(np.arange(0, input_size+1, step=1))
plt.yticks(np.arange(0, 10, step=1))
plt.ylabel("Execution Time (s)")
plt.xlabel("Input Size (n)")
plt.title("Simon's: Execution Time of Two-to-One Function vs. Input Size")
|
https://github.com/abhik-99/Qiskit-Summer-School
|
abhik-99
|
!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/vandnaChaturvedi/Qauntum_algorithms_Qiskit
|
vandnaChaturvedi
|
# @title Copyright 2020 The Cirq Developers
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
import cirq
except ImportError:
print("installing cirq...")
!pip install --quiet cirq
import cirq
print("installed cirq.")
qubits = cirq.GridQubit.square(3)
print(qubits[0])
print(qubits)
# This is an Pauli X gate. It is an object instance.
x_gate = cirq.X
# Applying it to the qubit at location (0, 0) (defined above)
# turns it into an operation.
x_op = x_gate(qubits[0])
print(x_op)
cz = cirq.CZ(qubits[0], qubits[1])
x = cirq.X(qubits[2])
moment = cirq.Moment(x, cz)
print(moment)
cz01 = cirq.CZ(qubits[0], qubits[1])
x2 = cirq.X(qubits[2])
cz12 = cirq.CZ(qubits[1], qubits[2])
moment0 = cirq.Moment([cz01, x2])
moment1 = cirq.Moment([cz12])
circuit = cirq.Circuit((moment0, moment1))
print(circuit)
q0, q1, q2 = [cirq.GridQubit(i, 0) for i in range(3)]
circuit = cirq.Circuit()
circuit.append([cirq.CZ(q0, q1), cirq.H(q2)])
print(circuit)
circuit.append([cirq.H(q0), cirq.CZ(q1, q2)])
print(circuit)
circuit = cirq.Circuit()
circuit.append([cirq.CZ(q0, q1), cirq.H(q2), cirq.H(q0), cirq.CZ(q1, q2)])
print(circuit)
from cirq.circuits import InsertStrategy
circuit = cirq.Circuit()
circuit.append([cirq.CZ(q0, q1)])
circuit.append([cirq.H(q0), cirq.H(q2)], strategy=InsertStrategy.EARLIEST)
print(circuit)
circuit = cirq.Circuit()
circuit.append([cirq.H(q0), cirq.H(q1), cirq.H(q2)], strategy=InsertStrategy.NEW)
print(circuit)
circuit = cirq.Circuit()
circuit.append([cirq.CZ(q1, q2)])
circuit.append([cirq.CZ(q1, q2)])
circuit.append([cirq.H(q0), cirq.H(q1), cirq.H(q2)], strategy=InsertStrategy.INLINE)
print(circuit)
circuit = cirq.Circuit()
circuit.append([cirq.H(q0)])
circuit.append([cirq.CZ(q1, q2), cirq.H(q0)], strategy=InsertStrategy.NEW_THEN_INLINE)
print(circuit)
def my_layer():
yield cirq.CZ(q0, q1)
yield [cirq.H(q) for q in (q0, q1, q2)]
yield [cirq.CZ(q1, q2)]
yield [cirq.H(q0), [cirq.CZ(q1, q2)]]
circuit = cirq.Circuit()
circuit.append(my_layer())
for x in my_layer():
print(x)
print(circuit)
circuit = cirq.Circuit(cirq.H(q0), cirq.H(q1))
print(circuit)
circuit = cirq.Circuit(cirq.H(q0), cirq.CZ(q0, q1))
for moment in circuit:
print(moment)
circuit = cirq.Circuit(cirq.H(q0), cirq.CZ(q0, q1), cirq.H(q1), cirq.CZ(q0, q1))
print(circuit[1:3])
subcircuit = cirq.Circuit(cirq.H(q1), cirq.CZ(q0, q1), cirq.CZ(q2, q1), cirq.H(q1))
subcircuit_op = cirq.CircuitOperation(subcircuit.freeze())
circuit = cirq.Circuit(cirq.H(q0), cirq.H(q2), subcircuit_op)
print(circuit)
circuit = cirq.Circuit(
cirq.CircuitOperation(
cirq.FrozenCircuit(cirq.H(q1), cirq.CZ(q0, q1), cirq.CZ(q2, q1), cirq.H(q1))
)
)
print(circuit)
subcircuit_op = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.CZ(q0, q1)))
# Create a copy of subcircuit_op that repeats twice...
repeated_subcircuit_op = subcircuit_op.repeat(2)
# ...and another copy that replaces q0 with q2 to perform CZ(q2, q1).
moved_subcircuit_op = subcircuit_op.with_qubit_mapping({q0: q2})
circuit = cirq.Circuit(repeated_subcircuit_op, moved_subcircuit_op)
print(circuit)
subcircuit_op = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.H(q0)))
circuit = cirq.Circuit(
subcircuit_op.repeat(3), subcircuit_op.repeat(2).with_qubit_mapping({q0: q1})
)
print(circuit)
qft_1 = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.H(q0)))
qft_2 = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.H(q1), cirq.CZ(q0, q1) ** 0.5, qft_1))
qft_3 = cirq.CircuitOperation(
cirq.FrozenCircuit(cirq.H(q2), cirq.CZ(q1, q2) ** 0.5, cirq.CZ(q0, q2) ** 0.25, qft_2)
)
# etc.
# A large CircuitOperation with other sub-CircuitOperations.
print('Original qft_3 CircuitOperation')
print(qft_3)
# Unroll the outermost CircuitOperation to a normal circuit.
print('Single layer unroll:')
print(qft_3.mapped_circuit(deep=False))
# Unroll all of the CircuitOperations recursively.
print('Recursive unroll:')
print(qft_3.mapped_circuit(deep=True))
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
from qiskit import QuantumCircuit
from qiskit.visualization import visualize_transition,circuit_drawer
from math import pi
qc=QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.draw(output="mpl")
qc=QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
circuit_drawer(qc,output="mpl")
qc=QuantumCircuit(1)
qc.h(0)
qc.draw(output="mpl")
visualize_transition(qc)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.optimizers import SLSQP
from qiskit.circuit.library import TwoLocal
num_qubits = 2
ansatz = TwoLocal(num_qubits, "ry", "cz")
optimizer = SLSQP(maxiter=1000)
ansatz.decompose().draw("mpl", style="iqx")
from qiskit.primitives import Estimator
estimator = Estimator()
from qiskit.algorithms.minimum_eigensolvers import VQE
vqe = VQE(estimator, ansatz, optimizer)
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)
])
result = vqe.compute_minimum_eigenvalue(H2_op)
print(result)
from qiskit.algorithms.optimizers import SPSA
estimator = Estimator(options={"shots": 1000})
vqe.estimator = estimator
vqe.optimizer = SPSA(maxiter=100)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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 Unroll3qOrMore pass"""
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit
from qiskit.circuit.library import CCXGate, RCCXGate
from qiskit.transpiler.passes import Unroll3qOrMore
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info.random import random_unitary
from qiskit.test import QiskitTestCase
from qiskit.extensions import UnitaryGate
from qiskit.transpiler import Target
class TestUnroll3qOrMore(QiskitTestCase):
"""Tests the Unroll3qOrMore pass, for unrolling all
gates until reaching only 1q or 2q gates."""
def test_ccx(self):
"""Test decompose CCX."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_cswap(self):
"""Test decompose CSwap (recursively)."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.cswap(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 17)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_decompose_conditional(self):
"""Test decompose a 3-qubit gate with a conditional."""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 0)
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
self.assertEqual(node.op.condition, (cr, 0))
def test_decompose_unitary(self):
"""Test unrolling of unitary gate over 4qubits."""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
unitary = random_unitary(16, seed=42)
circuit.unitary(unitary, [0, 1, 2, 3])
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
after_circ = dag_to_circuit(after_dag)
self.assertTrue(Operator(circuit).equiv(Operator(after_circ)))
def test_identity(self):
"""Test unrolling of identity gate over 3qubits."""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
gate = UnitaryGate(np.eye(2**3))
circuit.append(gate, range(3))
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
after_circ = dag_to_circuit(after_dag)
self.assertTrue(Operator(circuit).equiv(Operator(after_circ)))
def test_target(self):
"""Test target is respected by the unroll 3q or more pass."""
target = Target(num_qubits=3)
target.add_instruction(CCXGate())
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
qc.append(RCCXGate(), [0, 1, 2])
unroll_pass = Unroll3qOrMore(target=target)
res = unroll_pass(qc)
self.assertIn("ccx", res.count_ops())
self.assertNotIn("rccx", res.count_ops())
def test_basis_gates(self):
"""Test basis_gates are respected by the unroll 3q or more pass."""
basis_gates = ["rccx"]
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
qc.append(RCCXGate(), [0, 1, 2])
unroll_pass = Unroll3qOrMore(basis_gates=basis_gates)
res = unroll_pass(qc)
self.assertNotIn("ccx", res.count_ops())
self.assertIn("rccx", res.count_ops())
def test_target_over_basis_gates(self):
"""Test target is respected over basis_gates by the unroll 3q or more pass."""
target = Target(num_qubits=3)
basis_gates = ["rccx"]
target.add_instruction(CCXGate())
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
qc.append(RCCXGate(), [0, 1, 2])
unroll_pass = Unroll3qOrMore(target=target, basis_gates=basis_gates)
res = unroll_pass(qc)
self.assertIn("ccx", res.count_ops())
self.assertNotIn("rccx", res.count_ops())
def test_if_else(self):
"""Test that a simple if-else over 3+ qubits unrolls correctly."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx"])
true_body = QuantumCircuit(3, 1)
true_body.h(0)
true_body.ccx(0, 1, 2)
false_body = QuantumCircuit(3, 1)
false_body.rccx(2, 1, 0)
test = QuantumCircuit(3, 1)
test.h(0)
test.measure(0, 0)
test.if_else((0, True), true_body, false_body, [0, 1, 2], [0])
expected = QuantumCircuit(3, 1)
expected.h(0)
expected.measure(0, 0)
expected.if_else((0, True), pass_(true_body), pass_(false_body), [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the unroller recurses into nested control flow."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx"])
qubits = [Qubit() for _ in [None] * 3]
clbit = Clbit()
for_body = QuantumCircuit(qubits, [clbit])
for_body.ccx(0, 1, 2)
while_body = QuantumCircuit(qubits, [clbit])
while_body.rccx(0, 1, 2)
true_body = QuantumCircuit(qubits, [clbit])
true_body.while_loop((clbit, True), while_body, [0, 1, 2], [0])
test = QuantumCircuit(qubits, [clbit])
test.for_loop(range(2), None, for_body, [0, 1, 2], [0])
test.if_else((clbit, True), true_body, None, [0, 1, 2], [0])
expected_if_body = QuantumCircuit(qubits, [clbit])
expected_if_body.while_loop((clbit, True), pass_(while_body), [0, 1, 2], [0])
expected = QuantumCircuit(qubits, [clbit])
expected.for_loop(range(2), None, pass_(for_body), [0, 1, 2], [0])
expected.if_else(range(2), pass_(expected_if_body), None, [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_if_else_in_basis(self):
"""Test that a simple if-else over 3+ qubits unrolls correctly."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"])
true_body = QuantumCircuit(3, 1)
true_body.h(0)
true_body.ccx(0, 1, 2)
false_body = QuantumCircuit(3, 1)
false_body.rccx(2, 1, 0)
test = QuantumCircuit(3, 1)
test.h(0)
test.measure(0, 0)
test.if_else((0, True), true_body, false_body, [0, 1, 2], [0])
expected = QuantumCircuit(3, 1)
expected.h(0)
expected.measure(0, 0)
expected.if_else((0, True), pass_(true_body), pass_(false_body), [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_nested_control_flow_in_basis(self):
"""Test that the unroller recurses into nested control flow."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"])
qubits = [Qubit() for _ in [None] * 3]
clbit = Clbit()
for_body = QuantumCircuit(qubits, [clbit])
for_body.ccx(0, 1, 2)
while_body = QuantumCircuit(qubits, [clbit])
while_body.rccx(0, 1, 2)
true_body = QuantumCircuit(qubits, [clbit])
true_body.while_loop((clbit, True), while_body, [0, 1, 2], [0])
test = QuantumCircuit(qubits, [clbit])
test.for_loop(range(2), None, for_body, [0, 1, 2], [0])
test.if_else((clbit, True), true_body, None, [0, 1, 2], [0])
expected_if_body = QuantumCircuit(qubits, [clbit])
expected_if_body.while_loop((clbit, True), pass_(while_body), [0, 1, 2], [0])
expected = QuantumCircuit(qubits, [clbit])
expected.for_loop(range(2), None, pass_(for_body), [0, 1, 2], [0])
expected.if_else(range(2), pass_(expected_if_body), None, [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_custom_block_over_3q(self):
"""Test a custom instruction is unrolled in a control flow block."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"])
ghz = QuantumCircuit(5, 5)
ghz.h(0)
ghz.cx(0, 1)
ghz.cx(0, 2)
ghz.cx(0, 3)
ghz.cx(0, 4)
ghz.measure(0, 0)
ghz.measure(1, 1)
ghz.measure(2, 2)
ghz.measure(3, 3)
ghz.measure(4, 4)
ghz.reset(0)
ghz.reset(1)
ghz.reset(2)
ghz.reset(3)
ghz.reset(4)
for_block = QuantumCircuit(5, 5, name="ghz")
for_block.append(ghz, list(range(5)), list(range(5)))
qc = QuantumCircuit(5, 5)
qc.for_loop((1,), None, for_block, [2, 4, 1, 3, 0], [0, 1, 2, 3, 4])
result = pass_(qc)
expected = QuantumCircuit(5, 5)
expected.for_loop((1,), None, ghz, [2, 4, 1, 3, 0], [0, 1, 2, 3, 4])
self.assertEqual(result, expected)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import execute, pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), d0)
pulse_prog.draw()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
# define a quantum register with one qubit
qreg1 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg1 = ClassicalRegister(1)
# define our quantum circuit
mycircuit1 = QuantumCircuit(qreg1,creg1)
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit
mycircuit1.h(qreg1[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit1.measure(qreg1,creg1)
print("Everything looks fine, let's continue ...")
# draw the circuit
drawer(mycircuit1)
# reexecute me if you DO NOT see the circuit diagram
# execute the circuit 10000 times in the local simulator
job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=10000)
counts1 = job.result().get_counts(mycircuit1)
print(counts1) # print the outcomes
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
# define a quantum register with one qubit
qreg2 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg2 = ClassicalRegister(1)
# define our quantum circuit
mycircuit2 = QuantumCircuit(qreg2,creg2)
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit
mycircuit2.h(qreg2[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit once more
mycircuit2.h(qreg2[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit2.measure(qreg2,creg2)
print("Everyhing looks fine, let's continue ...")
# draw the circuit
drawer(mycircuit2)
# reexecute me if you DO NOT see the circuit diagram
# execute the circuit 10000 times in the local simulator
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=10000)
counts2 = job.result().get_counts(mycircuit2)
print(counts2)
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
#
# your code is here
#
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import transpile, QuantumCircuit
import qiskit.quantum_info as qi
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel, amplitude_damping_error
from qiskit.tools.visualization import plot_histogram
# CNOT matrix operator with qubit-0 as control and qubit-1 as target
cx_op = qi.Operator([[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0]])
# iSWAP matrix operator
iswap_op = qi.Operator([[1, 0, 0, 0],
[0, 0, 1j, 0],
[0, 1j, 0, 0],
[0, 0, 0, 1]])
# CNOT in terms of iSWAP and single-qubit gates
cx_circ = QuantumCircuit(2, name='cx<iSWAP>')
# Add gates
cx_circ.sdg(1)
cx_circ.h(1)
cx_circ.sdg(0)
cx_circ.unitary(iswap_op, [0, 1], label='iswap')
cx_circ.sdg(0)
cx_circ.h(0)
cx_circ.sdg(0)
cx_circ.unitary(iswap_op, [0, 1], label='iswap')
cx_circ.s(1)
print(cx_circ)
# Simulate the unitary for the circuit using Operator:
unitary = qi.Operator(cx_circ)
print(unitary)
f_ave = qi.average_gate_fidelity(cx_op, unitary)
print("Average Gate Fidelity: F = {:f}".format(f_ave))
'unitary' in AerSimulator().configuration().basis_gates
# Error parameters
param_q0 = 0.05 # damping parameter for qubit-0
param_q1 = 0.1 # damping parameter for qubit-1
# Construct the error
qerror_q0 = amplitude_damping_error(param_q0)
qerror_q1 = amplitude_damping_error(param_q1)
iswap_error = qerror_q1.tensor(qerror_q0)
# Build the noise model by adding the error to the "iswap" gate
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(iswap_error, 'iswap')
noise_model.add_basis_gates(['unitary'])
print(noise_model.basis_gates)
# Bell state circuit where iSWAPS should be inserted at barrier locations
bell_circ = QuantumCircuit(2, 2, name='bell')
bell_circ.h(0)
bell_circ.append(cx_circ, [0, 1])
bell_circ.measure([0,1], [0,1])
print(bell_circ)
# Create ideal simulator backend and transpile circuit
sim_ideal = AerSimulator()
tbell_circ = transpile(bell_circ, sim_ideal)
ideal_result = sim_ideal.run(tbell_circ).result()
ideal_counts = ideal_result.get_counts(0)
plot_histogram(ideal_counts,
title='Ideal output for iSWAP bell-state preparation')
# Create noisy simulator and transpile circuit
sim_noise = AerSimulator(noise_model=noise_model)
tbell_circ_noise = transpile(bell_circ, sim_noise)
# Run on the simulator without noise
noise_result = sim_noise.run(tbell_circ_noise).result()
noise_counts = noise_result.get_counts(bell_circ)
plot_histogram(noise_counts,
title='Noisy output for iSWAP bell-state preparation')
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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
from sklearn.preprocessing import StandardScaler
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)
scale = StandardScaler()
scale.fit(X_train)
X_train = scale.transform(X_train)
X_test = scale.transform(X_test)
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_test_pred ]
y_pred_1 = ["{}\n".format(i) for i in y_pred_1]
with open(r'ttn_1_layers_standard.csv', 'w') as fp:
fp.writelines(y_pred_1)
|
https://github.com/if-quantum/pairwise-tomography
|
if-quantum
|
# pylint: disable=missing-docstring
import unittest
import itertools
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, execute, Aer
from qiskit.quantum_info import state_fidelity
from qiskit.quantum_info import partial_trace
from qiskit.quantum_info.states import DensityMatrix
from pairwise_tomography.pairwise_state_tomography_circuits import pairwise_state_tomography_circuits
from pairwise_tomography.pairwise_fitter import PairwiseStateTomographyFitter
n_list = [3, 4]
nshots = 5000
pauli = {'I': np.eye(2),
'X': np.array([[0, 1], [1, 0]]),
'Y': np.array([[0, -1j], [1j, 0]]),
'Z': np.array([[1, 0], [0, -1]])}
def pauli_expectation(rho, i, j):
# i and j get swapped because of qiskit bit convention
return np.real(np.trace(np.kron(pauli[j], pauli[i]) @ rho))
class TestPairwiseStateTomography(unittest.TestCase):
def test_pairwise_tomography(self):
for n in n_list:
with self.subTest():
self.tomography_random_circuit(n)
def tomography_random_circuit(self, n):
q = QuantumRegister(n)
qc = QuantumCircuit(q)
psi = ((2 * np.random.rand(2 ** n) - 1)
+ 1j * (2 *np.random.rand(2 ** n) - 1))
psi /= np.linalg.norm(psi)
qc.initialize(psi, q)
rho = DensityMatrix.from_instruction(qc).data
circ = pairwise_state_tomography_circuits(qc, q)
job = execute(circ, Aer.get_backend("qasm_simulator"), shots=nshots)
fitter = PairwiseStateTomographyFitter(job.result(), circ, q)
result = fitter.fit()
result_exp = fitter.fit(output='expectation')
# Compare the tomography matrices with the partial trace of
# the original state using fidelity
for (k, v) in result.items():
trace_qubits = list(range(n))
trace_qubits.remove(k[0])
trace_qubits.remove(k[1])
rhok = partial_trace(rho, trace_qubits).data
try:
self.check_density_matrix(v, rhok)
except:
print("Problem with density matrix:", k)
raise
try:
self.check_pauli_expectaion(result_exp[k], rhok)
except:
print("Problem with expectation values:", k)
raise
def check_density_matrix(self, item, rho):
fidelity = state_fidelity(item, rho)
try:
self.assertAlmostEqual(fidelity, 1, delta=4 / np.sqrt(nshots))
except AssertionError:
print(fidelity)
raise
def check_pauli_expectaion(self, item, rho):
for (a, b) in itertools.product(pauli.keys(), pauli.keys()):
if not (a == "I" and b == "I"):
correct = pauli_expectation(rho, a, b)
tomo = item[(a, b)]
# The variance on the expectation values
sigma = np.sqrt((1 - correct ** 2) / nshots)
try:
# A delta of 4*sigma should guarantee that 99.98% of results
# are within bounds
self.assertAlmostEqual(tomo, correct, delta=4*sigma)
except AssertionError:
print(a, b, correct, tomo)
raise
def test_meas_qubit_specification(self):
n = 4
q = QuantumRegister(n)
qc = QuantumCircuit(q)
psi = ((2 * np.random.rand(2 ** n) - 1)
+ 1j * (2 *np.random.rand(2 ** n) - 1))
psi /= np.linalg.norm(psi)
qc.initialize(psi, q)
rho = DensityMatrix.from_instruction(qc).data
measured_qubits = [q[0], q[2], q[3]]
circ = pairwise_state_tomography_circuits(qc, measured_qubits)
job = execute(circ, Aer.get_backend("qasm_simulator"), shots=nshots)
fitter = PairwiseStateTomographyFitter(job.result(), circ, measured_qubits)
result = fitter.fit()
result_exp = fitter.fit(output='expectation')
# Compare the tomography matrices with the partial trace of
# the original state using fidelity
for (k, v) in result.items():
#TODO: This method won't work if measured_qubits is not ordered in
# wrt the DensityMatrix object.
trace_qubits = list(range(n))
trace_qubits.remove(measured_qubits[k[0]].index)
trace_qubits.remove(measured_qubits[k[1]].index)
print(trace_qubits, rho.shape)
rhok = partial_trace(rho, trace_qubits).data
try:
self.check_density_matrix(v, rhok)
except:
print("Problem with density matrix:", k)
raise
try:
self.check_pauli_expectaion(result_exp[k], rhok)
except:
print("Problem with expectation values:", k)
raise
def test_multiple_registers(self):
n = 4
q = QuantumRegister(n / 2)
p = QuantumRegister(n / 2)
qc = QuantumCircuit(q, p)
qc.h(q[0])
qc.rx(np.pi/4, q[1])
qc.cx(q[0], p[0])
qc.cx(q[1], p[1])
rho = DensityMatrix.from_instruction(qc).data
measured_qubits = q#[q[0], q[1], q[2]]
circ = pairwise_state_tomography_circuits(qc, measured_qubits)
job = execute(circ, Aer.get_backend("qasm_simulator"), shots=nshots)
fitter = PairwiseStateTomographyFitter(job.result(), circ, measured_qubits)
result = fitter.fit()
result_exp = fitter.fit(output='expectation')
# Compare the tomography matrices with the partial trace of
# the original state using fidelity
for (k, v) in result.items():
trace_qubits = list(range(n))
trace_qubits.remove(measured_qubits[k[0]].index)
trace_qubits.remove(measured_qubits[k[1]].index)
rhok = partial_trace(rho, trace_qubits).data
try:
self.check_density_matrix(v, rhok)
except:
print("Problem with density matrix:", k)
raise
try:
self.check_pauli_expectaion(result_exp[k], rhok)
except:
print("Problem with expectation values:", k)
raise
if __name__ == '__main__':
unittest.main()
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.circuit import Gate
from qiskit.visualization import plot_bloch_multivector
from math import pi
q = QuantumRegister(3, name='q')
c = ClassicalRegister(2, name='c')
circ = QuantumCircuit(q, c)
circ.reset(q)
circ.u3(pi/2,pi/2,pi/2,q[2])
circ.h(q[1])
circ.cx(q[1],q[0])
circ.barrier()
circ.cx(q[2],q[1])
circ.h(q[2])
circ.barrier()
circ.measure([q[2],q[1]],[c[1],c[0]])
circ.barrier()
circ.x(0).c_if(c,1)
circ.z(0).c_if(c,2)
circ.x(0).c_if(c,3)
circ.z(0).c_if(c,3)
circ.draw('mpl', reverse_bits=True)
theta = pi/3
phi = pi/2
q = QuantumRegister(3, name='q')
c = ClassicalRegister(2, name='c')
circ = QuantumCircuit(q, c)
circ.reset(q)
circ.u3(theta,phi,pi,q[2])
circ.h(q[1])
circ.cx(q[1],q[0])
circ.barrier()
circ.draw('mpl', reverse_bits=True)
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
state = job.result().get_statevector(circ)
plot_bloch_multivector(state)
circ.cx(q[2],q[1])
circ.h(q[2])
circ.barrier()
circ.measure([q[2],q[1]],[c[1],c[0]])
circ.barrier()
circ.x(0).c_if(c,1)
circ.z(0).c_if(c,2)
circ.x(0).c_if(c,3)
circ.z(0).c_if(c,3)
circ.draw('mpl', reverse_bits=True)
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
state = job.result().get_statevector(circ)
plot_bloch_multivector(state)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
#!/usr/bin/env python3
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test cases to verify qpy backwards compatibility."""
import argparse
import itertools
import random
import re
import sys
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.classicalregister import Clbit
from qiskit.circuit.quantumregister import Qubit
from qiskit.circuit.parameter import Parameter
from qiskit.circuit.parametervector import ParameterVector
from qiskit.quantum_info.random import random_unitary
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, QFT, DCXGate, PauliGate
from qiskit.circuit.gate import Gate
try:
from qiskit.qpy import dump, load
except ModuleNotFoundError:
from qiskit.circuit.qpy_serialization import dump, load
# This version pattern is taken from the pypa packaging project:
# https://github.com/pypa/packaging/blob/21.3/packaging/version.py#L223-L254
# which is dual licensed Apache 2.0 and BSD see the source for the original
# authors and other details
VERSION_PATTERN = (
"^"
+ r"""
v?
(?:
(?:(?P<epoch>[0-9]+)!)? # epoch
(?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
(?P<pre> # pre-release
[-_\.]?
(?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
[-_\.]?
(?P<pre_n>[0-9]+)?
)?
(?P<post> # post release
(?:-(?P<post_n1>[0-9]+))
|
(?:
[-_\.]?
(?P<post_l>post|rev|r)
[-_\.]?
(?P<post_n2>[0-9]+)?
)
)?
(?P<dev> # dev release
[-_\.]?
(?P<dev_l>dev)
[-_\.]?
(?P<dev_n>[0-9]+)?
)?
)
(?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
"""
+ "$"
)
def generate_full_circuit():
"""Generate a multiregister circuit with name, metadata, phase."""
qr_a = QuantumRegister(4, "a")
qr_b = QuantumRegister(4, "b")
cr_c = ClassicalRegister(4, "c")
cr_d = ClassicalRegister(4, "d")
full_circuit = QuantumCircuit(
qr_a,
qr_b,
cr_c,
cr_d,
name="MyCircuit",
metadata={"test": 1, "a": 2},
global_phase=3.14159,
)
full_circuit.h(qr_a)
full_circuit.cx(qr_a, qr_b)
full_circuit.barrier(qr_a)
full_circuit.barrier(qr_b)
full_circuit.measure(qr_a, cr_c)
full_circuit.measure(qr_b, cr_d)
return full_circuit
def generate_unitary_gate_circuit():
"""Generate a circuit with a unitary gate."""
unitary_circuit = QuantumCircuit(5, name="unitary_circuit")
unitary_circuit.unitary(random_unitary(32, seed=100), [0, 1, 2, 3, 4])
unitary_circuit.measure_all()
return unitary_circuit
def generate_random_circuits():
"""Generate multiple random circuits."""
random_circuits = []
for i in range(1, 15):
qc = QuantumCircuit(i, name=f"random_circuit-{i}")
qc.h(0)
if i > 1:
for j in range(i - 1):
qc.cx(0, j + 1)
qc.measure_all()
for j in range(i):
qc.reset(j)
qc.x(0).c_if(qc.cregs[0], i)
for j in range(i):
qc.measure(j, j)
random_circuits.append(qc)
return random_circuits
def generate_string_parameters():
"""Generate a circuit for the XYZ pauli string."""
op_circuit = QuantumCircuit(3, name="X^Y^Z")
op_circuit.append(PauliGate("XYZ"), op_circuit.qubits, [])
return op_circuit
def generate_register_edge_cases():
"""Generate register edge case circuits."""
register_edge_cases = []
# Circuit with shared bits in a register
qubits = [Qubit() for _ in range(5)]
shared_qc = QuantumCircuit(name="shared_bits")
shared_qc.add_bits(qubits)
shared_qr = QuantumRegister(bits=qubits)
shared_qc.add_register(shared_qr)
shared_qc.h(shared_qr)
shared_qc.cx(0, 1)
shared_qc.cx(0, 2)
shared_qc.cx(0, 3)
shared_qc.cx(0, 4)
shared_qc.measure_all()
register_edge_cases.append(shared_qc)
# Circuit with registers that have a mix of standalone and shared register
# bits
qr = QuantumRegister(5, "foo")
qr = QuantumRegister(name="bar", bits=qr[:3] + [Qubit(), Qubit()])
cr = ClassicalRegister(5, "foo")
cr = ClassicalRegister(name="classical_bar", bits=cr[:3] + [Clbit(), Clbit()])
hybrid_qc = QuantumCircuit(qr, cr, name="mix_standalone_bits_registers")
hybrid_qc.h(0)
hybrid_qc.cx(0, 1)
hybrid_qc.cx(0, 2)
hybrid_qc.cx(0, 3)
hybrid_qc.cx(0, 4)
hybrid_qc.measure(qr, cr)
register_edge_cases.append(hybrid_qc)
# Circuit with mixed standalone and shared registers
qubits = [Qubit() for _ in range(5)]
clbits = [Clbit() for _ in range(5)]
mixed_qc = QuantumCircuit(name="mix_standalone_bits_with_registers")
mixed_qc.add_bits(qubits)
mixed_qc.add_bits(clbits)
qr = QuantumRegister(bits=qubits)
cr = ClassicalRegister(bits=clbits)
mixed_qc.add_register(qr)
mixed_qc.add_register(cr)
qr_standalone = QuantumRegister(2, "standalone")
mixed_qc.add_register(qr_standalone)
cr_standalone = ClassicalRegister(2, "classical_standalone")
mixed_qc.add_register(cr_standalone)
mixed_qc.unitary(random_unitary(32, seed=42), qr)
mixed_qc.unitary(random_unitary(4, seed=100), qr_standalone)
mixed_qc.measure(qr, cr)
mixed_qc.measure(qr_standalone, cr_standalone)
register_edge_cases.append(mixed_qc)
# Circuit with out of order register bits
qr_standalone = QuantumRegister(2, "standalone")
qubits = [Qubit() for _ in range(5)]
clbits = [Clbit() for _ in range(5)]
ooo_qc = QuantumCircuit(name="out_of_order_bits")
ooo_qc.add_bits(qubits)
ooo_qc.add_bits(clbits)
random.seed(42)
random.shuffle(qubits)
random.shuffle(clbits)
qr = QuantumRegister(bits=qubits)
cr = ClassicalRegister(bits=clbits)
ooo_qc.add_register(qr)
ooo_qc.add_register(cr)
qr_standalone = QuantumRegister(2, "standalone")
cr_standalone = ClassicalRegister(2, "classical_standalone")
ooo_qc.add_bits([qr_standalone[1], qr_standalone[0]])
ooo_qc.add_bits([cr_standalone[1], cr_standalone[0]])
ooo_qc.add_register(qr_standalone)
ooo_qc.add_register(cr_standalone)
ooo_qc.unitary(random_unitary(32, seed=42), qr)
ooo_qc.unitary(random_unitary(4, seed=100), qr_standalone)
ooo_qc.measure(qr, cr)
ooo_qc.measure(qr_standalone, cr_standalone)
register_edge_cases.append(ooo_qc)
return register_edge_cases
def generate_parameterized_circuit():
"""Generate a circuit with parameters and parameter expressions."""
param_circuit = QuantumCircuit(1, name="parameterized")
theta = Parameter("theta")
lam = Parameter("λ")
theta_pi = 3.14159 * theta
pe = theta_pi / lam
param_circuit.append(U3Gate(theta, theta_pi, lam), [0])
param_circuit.append(U1Gate(pe), [0])
param_circuit.append(U2Gate(theta_pi, lam), [0])
return param_circuit
def generate_qft_circuit():
"""Generate a QFT circuit with initialization."""
k = 5
state = (1 / np.sqrt(8)) * np.array(
[
np.exp(-1j * 2 * np.pi * k * (0) / 8),
np.exp(-1j * 2 * np.pi * k * (1) / 8),
np.exp(-1j * 2 * np.pi * k * (2) / 8),
np.exp(-1j * 2 * np.pi * k * 3 / 8),
np.exp(-1j * 2 * np.pi * k * 4 / 8),
np.exp(-1j * 2 * np.pi * k * 5 / 8),
np.exp(-1j * 2 * np.pi * k * 6 / 8),
np.exp(-1j * 2 * np.pi * k * 7 / 8),
]
)
qubits = 3
qft_circ = QuantumCircuit(qubits, qubits, name="QFT")
qft_circ.initialize(state)
qft_circ.append(QFT(qubits), range(qubits))
qft_circ.measure(range(qubits), range(qubits))
return qft_circ
def generate_param_phase():
"""Generate circuits with parameterize global phase."""
output_circuits = []
# Generate circuit with ParameterExpression global phase
theta = Parameter("theta")
phi = Parameter("phi")
sum_param = theta + phi
qc = QuantumCircuit(5, 1, global_phase=sum_param, name="parameter_phase")
qc.h(0)
for i in range(4):
qc.cx(i, i + 1)
qc.barrier()
qc.rz(sum_param, range(3))
qc.rz(phi, 3)
qc.rz(theta, 4)
qc.barrier()
for i in reversed(range(4)):
qc.cx(i, i + 1)
qc.h(0)
qc.measure(0, 0)
output_circuits.append(qc)
# Generate circuit with Parameter global phase
theta = Parameter("theta")
bell_qc = QuantumCircuit(2, global_phase=theta, name="bell_param_global_phase")
bell_qc.h(0)
bell_qc.cx(0, 1)
bell_qc.measure_all()
output_circuits.append(bell_qc)
return output_circuits
def generate_single_clbit_condition_teleportation(): # pylint: disable=invalid-name
"""Generate single clbit condition teleportation circuit."""
qr = QuantumRegister(1)
cr = ClassicalRegister(2, name="name")
teleport_qc = QuantumCircuit(qr, cr, name="Reset Test")
teleport_qc.x(0)
teleport_qc.measure(0, cr[0])
teleport_qc.x(0).c_if(cr[0], 1)
teleport_qc.measure(0, cr[1])
return teleport_qc
def generate_parameter_vector():
"""Generate tests for parameter vector element ordering."""
qc = QuantumCircuit(11, name="parameter_vector")
input_params = ParameterVector("x_par", 11)
user_params = ParameterVector("θ_par", 11)
for i, param in enumerate(user_params):
qc.ry(param, i)
for i, param in enumerate(input_params):
qc.rz(param, i)
return qc
def generate_parameter_vector_expression(): # pylint: disable=invalid-name
"""Generate tests for parameter vector element ordering."""
qc = QuantumCircuit(7, name="vector_expansion")
entanglement = [[i, i + 1] for i in range(7 - 1)]
input_params = ParameterVector("x_par", 14)
user_params = ParameterVector("\u03B8_par", 1)
for i in range(qc.num_qubits):
qc.ry(user_params[0], qc.qubits[i])
for source, target in entanglement:
qc.cz(qc.qubits[source], qc.qubits[target])
for i in range(qc.num_qubits):
qc.rz(-2 * input_params[2 * i + 1], qc.qubits[i])
qc.rx(-2 * input_params[2 * i], qc.qubits[i])
return qc
def generate_evolution_gate():
"""Generate a circuit with a pauli evolution gate."""
# Runtime import since this only exists in terra 0.19.0
from qiskit.circuit.library import PauliEvolutionGate
from qiskit.synthesis import SuzukiTrotter
from qiskit.quantum_info import SparsePauliOp
synthesis = SuzukiTrotter()
op = SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)])
evo = PauliEvolutionGate([op] * 5, time=2.0, synthesis=synthesis)
qc = QuantumCircuit(2, name="pauli_evolution_circuit")
qc.append(evo, range(2))
return qc
def generate_control_flow_circuits():
"""Test qpy serialization with control flow instructions."""
from qiskit.circuit.controlflow import WhileLoopOp, IfElseOp, ForLoopOp
# If instruction
circuits = []
qc = QuantumCircuit(2, 2, name="control_flow")
qc.h(0)
qc.measure(0, 0)
true_body = QuantumCircuit(1)
true_body.x(0)
if_op = IfElseOp((qc.clbits[0], True), true_body=true_body)
qc.append(if_op, [1])
qc.measure(1, 1)
circuits.append(qc)
# If else instruction
qc = QuantumCircuit(2, 2, name="if_else")
qc.h(0)
qc.measure(0, 0)
false_body = QuantumCircuit(1)
false_body.y(0)
if_else_op = IfElseOp((qc.clbits[0], True), true_body, false_body)
qc.append(if_else_op, [1])
qc.measure(1, 1)
circuits.append(qc)
# While loop
qc = QuantumCircuit(2, 1, name="while_loop")
block = QuantumCircuit(2, 1)
block.h(0)
block.cx(0, 1)
block.measure(0, 0)
while_loop = WhileLoopOp((qc.clbits[0], 0), block)
qc.append(while_loop, [0, 1], [0])
circuits.append(qc)
# for loop range
qc = QuantumCircuit(2, 1, name="for_loop")
body = QuantumCircuit(2, 1)
body.h(0)
body.cx(0, 1)
body.measure(0, 0)
body.break_loop().c_if(0, True)
for_loop_op = ForLoopOp(range(5), None, body=body)
qc.append(for_loop_op, [0, 1], [0])
circuits.append(qc)
# For loop iterator
qc = QuantumCircuit(2, 1, name="for_loop_iterator")
for_loop_op = ForLoopOp(iter(range(5)), None, body=body)
qc.append(for_loop_op, [0, 1], [0])
circuits.append(qc)
return circuits
def generate_control_flow_switch_circuits():
"""Generate circuits with switch-statement instructions."""
from qiskit.circuit.controlflow import CASE_DEFAULT
circuits = []
qc = QuantumCircuit(2, 1, name="switch_clbit")
case_t = qc.copy_empty_like()
case_t.x(0)
case_f = qc.copy_empty_like()
case_f.z(1)
qc.switch(qc.clbits[0], [(True, case_t), (False, case_f)], qc.qubits, qc.clbits)
circuits.append(qc)
qreg = QuantumRegister(2, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg, name="switch_creg")
case_0 = QuantumCircuit(qreg, creg)
case_0.x(0)
case_1 = QuantumCircuit(qreg, creg)
case_1.z(1)
case_2 = QuantumCircuit(qreg, creg)
case_2.x(1)
qc.switch(
creg, [(0, case_0), ((1, 2), case_1), ((3, 4, CASE_DEFAULT), case_2)], qc.qubits, qc.clbits
)
circuits.append(qc)
return circuits
def generate_schedule_blocks():
"""Standard QPY testcase for schedule blocks."""
from qiskit.pulse import builder, channels, library
from qiskit.utils import optionals
# Parameterized schedule test is avoided.
# Generated reference and loaded QPY object may induce parameter uuid mismatch.
# As workaround, we need test with bounded parameters, however, schedule.parameters
# are returned as Set and thus its order is random.
# Since schedule parameters are validated, we cannot assign random numbers.
# We need to upgrade testing framework.
schedule_blocks = []
# Instructions without parameters
with builder.build() as block:
with builder.align_sequential():
builder.set_frequency(5e9, channels.DriveChannel(0))
builder.shift_frequency(10e6, channels.DriveChannel(1))
builder.set_phase(1.57, channels.DriveChannel(0))
builder.shift_phase(0.1, channels.DriveChannel(1))
builder.barrier(channels.DriveChannel(0), channels.DriveChannel(1))
builder.play(library.Gaussian(160, 0.1j, 40), channels.DriveChannel(0))
builder.play(library.GaussianSquare(800, 0.1, 64, 544), channels.ControlChannel(0))
builder.play(library.Drag(160, 0.1, 40, 1.5), channels.DriveChannel(1))
builder.play(library.Constant(800, 0.1), channels.MeasureChannel(0))
builder.acquire(1000, channels.AcquireChannel(0), channels.MemorySlot(0))
schedule_blocks.append(block)
# Raw symbolic pulse
if optionals.HAS_SYMENGINE:
import symengine as sym
else:
import sympy as sym
duration, amp, t = sym.symbols("duration amp t") # pylint: disable=invalid-name
expr = amp * sym.sin(2 * sym.pi * t / duration)
my_pulse = library.SymbolicPulse(
pulse_type="Sinusoidal",
duration=100,
parameters={"amp": 0.1},
envelope=expr,
valid_amp_conditions=sym.Abs(amp) <= 1.0,
)
with builder.build() as block:
builder.play(my_pulse, channels.DriveChannel(0))
schedule_blocks.append(block)
# Raw waveform
my_waveform = 0.1 * np.sin(2 * np.pi * np.linspace(0, 1, 100))
with builder.build() as block:
builder.play(my_waveform, channels.DriveChannel(0))
schedule_blocks.append(block)
return schedule_blocks
def generate_referenced_schedule():
"""Test for QPY serialization of unassigned reference schedules."""
from qiskit.pulse import builder, channels, library
schedule_blocks = []
# Completely unassigned schedule
with builder.build() as block:
builder.reference("cr45p", "q0", "q1")
builder.reference("x", "q0")
builder.reference("cr45m", "q0", "q1")
schedule_blocks.append(block)
# Partly assigned schedule
with builder.build() as x_q0:
builder.play(library.Constant(100, 0.1), channels.DriveChannel(0))
with builder.build() as block:
builder.reference("cr45p", "q0", "q1")
builder.call(x_q0)
builder.reference("cr45m", "q0", "q1")
schedule_blocks.append(block)
return schedule_blocks
def generate_calibrated_circuits():
"""Test for QPY serialization with calibrations."""
from qiskit.pulse import builder, Constant, DriveChannel
circuits = []
# custom gate
mygate = Gate("mygate", 1, [])
qc = QuantumCircuit(1, name="calibrated_circuit_1")
qc.append(mygate, [0])
with builder.build() as caldef:
builder.play(Constant(100, 0.1), DriveChannel(0))
qc.add_calibration(mygate, (0,), caldef)
circuits.append(qc)
# override instruction
qc = QuantumCircuit(1, name="calibrated_circuit_2")
qc.x(0)
with builder.build() as caldef:
builder.play(Constant(100, 0.1), DriveChannel(0))
qc.add_calibration("x", (0,), caldef)
circuits.append(qc)
return circuits
def generate_controlled_gates():
"""Test QPY serialization with custom ControlledGates."""
circuits = []
qc = QuantumCircuit(3, name="custom_controlled_gates")
controlled_gate = DCXGate().control(1)
qc.append(controlled_gate, [0, 1, 2])
circuits.append(qc)
custom_gate = Gate("black_box", 1, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
nested_qc = QuantumCircuit(3, name="nested_qc")
qc.append(custom_gate, [0])
controlled_gate = custom_gate.control(2)
nested_qc.append(controlled_gate, [0, 1, 2])
nested_qc.measure_all()
circuits.append(nested_qc)
qc_open = QuantumCircuit(2, name="open_cx")
qc_open.cx(0, 1, ctrl_state=0)
circuits.append(qc_open)
return circuits
def generate_open_controlled_gates():
"""Test QPY serialization with custom ControlledGates with open controls."""
circuits = []
qc = QuantumCircuit(3, name="open_controls_simple")
controlled_gate = DCXGate().control(1, ctrl_state=0)
qc.append(controlled_gate, [0, 1, 2])
circuits.append(qc)
custom_gate = Gate("black_box", 1, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
nested_qc = QuantumCircuit(3, name="open_controls_nested")
nested_qc.append(custom_gate, [0])
controlled_gate = custom_gate.control(2, ctrl_state=1)
nested_qc.append(controlled_gate, [0, 1, 2])
nested_qc.measure_all()
circuits.append(nested_qc)
return circuits
def generate_acquire_instruction_with_kernel_and_discriminator():
"""Test QPY serialization with Acquire instruction with kernel and discriminator."""
from qiskit.pulse import builder, AcquireChannel, MemorySlot, Discriminator, Kernel
schedule_blocks = []
with builder.build() as block:
builder.acquire(
100,
AcquireChannel(0),
MemorySlot(0),
kernel=Kernel(
name="my_kernel", my_params_1={"param1": 0.1, "param2": 0.2}, my_params_2=[0, 1]
),
)
schedule_blocks.append(block)
with builder.build() as block:
builder.acquire(
100,
AcquireChannel(0),
MemorySlot(0),
discriminator=Discriminator(
name="my_disc", my_params_1={"param1": 0.1, "param2": 0.2}, my_params_2=[0, 1]
),
)
schedule_blocks.append(block)
return schedule_blocks
def generate_layout_circuits():
"""Test qpy circuits with layout set."""
from qiskit.transpiler.layout import TranspileLayout, Layout
qr = QuantumRegister(3, "foo")
qc = QuantumCircuit(qr, name="GHZ with layout")
qc.h(0)
qc.cx(0, 1)
qc.swap(0, 1)
qc.cx(0, 2)
input_layout = {qr[index]: index for index in range(len(qc.qubits))}
qc._layout = TranspileLayout(
Layout(input_layout),
input_qubit_mapping=input_layout,
final_layout=Layout.from_qubit_list([qc.qubits[1], qc.qubits[0], qc.qubits[2]]),
)
return [qc]
def generate_control_flow_expr():
"""`IfElseOp`, `WhileLoopOp` and `SwitchCaseOp` with `Expr` nodes in their discriminators."""
from qiskit.circuit.classical import expr, types
body1 = QuantumCircuit(1)
body1.x(0)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
qc1 = QuantumCircuit(qr1, cr1)
qc1.if_test(expr.equal(cr1, 3), body1.copy(), [0], [])
qc1.while_loop(expr.logic_not(cr1[1]), body1.copy(), [0], [])
inner2 = QuantumCircuit(1)
inner2.x(0)
outer2 = QuantumCircuit(1, 1)
outer2.if_test(expr.logic_not(outer2.clbits[0]), inner2, [0], [])
qr2 = QuantumRegister(2, "q2")
cr1_2 = ClassicalRegister(3, "c1")
cr2_2 = ClassicalRegister(3, "c2")
qc2 = QuantumCircuit(qr2, cr1_2, cr2_2)
qc2.if_test(expr.logic_or(expr.less(cr1_2, cr2_2), cr1_2[1]), outer2, [1], [1])
inner3 = QuantumCircuit(1)
inner3.x(0)
outer3 = QuantumCircuit(1, 1)
outer3.switch(expr.logic_not(outer2.clbits[0]), [(False, inner2)], [0], [])
qr3 = QuantumRegister(2, "q2")
cr1_3 = ClassicalRegister(3, "c1")
cr2_3 = ClassicalRegister(3, "c2")
qc3 = QuantumCircuit(qr3, cr1_3, cr2_3)
qc3.switch(expr.bit_xor(cr1_3, cr2_3), [(0, outer2)], [1], [1])
cr1_4 = ClassicalRegister(256, "c1")
cr2_4 = ClassicalRegister(4, "c2")
cr3_4 = ClassicalRegister(4, "c3")
inner4 = QuantumCircuit(1)
inner4.x(0)
outer_loose = Clbit()
outer4 = QuantumCircuit(QuantumRegister(2, "q_outer"), cr2_4, [outer_loose], cr1_4)
outer4.if_test(
expr.logic_and(
expr.logic_or(
expr.greater(expr.bit_or(cr2_4, 7), 10),
expr.equal(expr.bit_and(cr1_4, cr1_4), expr.bit_not(cr1_4)),
),
expr.logic_or(
outer_loose,
expr.cast(cr1_4, types.Bool()),
),
),
inner4,
[0],
[],
)
qc4_loose = Clbit()
qc4 = QuantumCircuit(QuantumRegister(2, "qr4"), cr1_4, cr2_4, cr3_4, [qc4_loose])
qc4.rz(np.pi, 0)
qc4.switch(
expr.logic_and(
expr.logic_or(
expr.logic_or(
expr.less(cr2_4, cr3_4),
expr.logic_not(expr.greater_equal(cr3_4, cr2_4)),
),
expr.logic_or(
expr.logic_not(expr.less_equal(cr3_4, cr2_4)),
expr.greater(cr2_4, cr3_4),
),
),
expr.logic_and(
expr.equal(cr3_4, 2),
expr.not_equal(expr.bit_xor(cr1_4, 0x0F), 0x0F),
),
),
[(False, outer4)],
[1, 0],
list(cr2_4) + [qc4_loose] + list(cr1_4),
)
qc4.rz(np.pi, 0)
return [qc1, qc2, qc3, qc4]
def generate_circuits(version_parts):
"""Generate reference circuits."""
output_circuits = {
"full.qpy": [generate_full_circuit()],
"unitary.qpy": [generate_unitary_gate_circuit()],
"multiple.qpy": generate_random_circuits(),
"string_parameters.qpy": [generate_string_parameters()],
"register_edge_cases.qpy": generate_register_edge_cases(),
"parameterized.qpy": [generate_parameterized_circuit()],
}
if version_parts is None:
return output_circuits
if version_parts >= (0, 18, 1):
output_circuits["qft_circuit.qpy"] = [generate_qft_circuit()]
output_circuits["teleport.qpy"] = [generate_single_clbit_condition_teleportation()]
if version_parts >= (0, 19, 0):
output_circuits["param_phase.qpy"] = generate_param_phase()
if version_parts >= (0, 19, 1):
output_circuits["parameter_vector.qpy"] = [generate_parameter_vector()]
output_circuits["pauli_evo.qpy"] = [generate_evolution_gate()]
output_circuits["parameter_vector_expression.qpy"] = [
generate_parameter_vector_expression()
]
if version_parts >= (0, 19, 2):
output_circuits["control_flow.qpy"] = generate_control_flow_circuits()
if version_parts >= (0, 21, 0):
output_circuits["schedule_blocks.qpy"] = generate_schedule_blocks()
output_circuits["pulse_gates.qpy"] = generate_calibrated_circuits()
if version_parts >= (0, 24, 0):
output_circuits["referenced_schedule_blocks.qpy"] = generate_referenced_schedule()
output_circuits["control_flow_switch.qpy"] = generate_control_flow_switch_circuits()
if version_parts >= (0, 24, 1):
output_circuits["open_controlled_gates.qpy"] = generate_open_controlled_gates()
output_circuits["controlled_gates.qpy"] = generate_controlled_gates()
if version_parts >= (0, 24, 2):
output_circuits["layout.qpy"] = generate_layout_circuits()
if version_parts >= (0, 25, 0):
output_circuits[
"acquire_inst_with_kernel_and_disc.qpy"
] = generate_acquire_instruction_with_kernel_and_discriminator()
output_circuits["control_flow_expr.qpy"] = generate_control_flow_expr()
return output_circuits
def assert_equal(reference, qpy, count, version_parts, bind=None):
"""Compare two circuits."""
if bind is not None:
reference_parameter_names = [x.name for x in reference.parameters]
qpy_parameter_names = [x.name for x in qpy.parameters]
if reference_parameter_names != qpy_parameter_names:
msg = (
f"Circuit {count} parameter mismatch:"
f" {reference_parameter_names} != {qpy_parameter_names}"
)
sys.stderr.write(msg)
sys.exit(4)
reference = reference.bind_parameters(bind)
qpy = qpy.bind_parameters(bind)
if reference != qpy:
msg = (
f"Reference Circuit {count}:\n{reference}\nis not equivalent to "
f"qpy loaded circuit {count}:\n{qpy}\n"
)
sys.stderr.write(msg)
sys.exit(1)
# Check deprecated bit properties, if set. The QPY dumping code before Terra 0.23.2 didn't
# include enough information for us to fully reconstruct this, so we only test if newer.
if version_parts >= (0, 23, 2) and isinstance(reference, QuantumCircuit):
for ref_bit, qpy_bit in itertools.chain(
zip(reference.qubits, qpy.qubits), zip(reference.clbits, qpy.clbits)
):
if ref_bit._register is not None and ref_bit != qpy_bit:
msg = (
f"Reference Circuit {count}:\n"
"deprecated bit-level register information mismatch\n"
f"reference bit: {ref_bit}\n"
f"loaded bit: {qpy_bit}\n"
)
sys.stderr.write(msg)
sys.exit(1)
if (
version_parts >= (0, 24, 2)
and isinstance(reference, QuantumCircuit)
and reference.layout != qpy.layout
):
msg = f"Circuit {count} layout mismatch {reference.layout} != {qpy.layout}\n"
sys.stderr.write(msg)
sys.exit(4)
# Don't compare name on bound circuits
if bind is None and reference.name != qpy.name:
msg = f"Circuit {count} name mismatch {reference.name} != {qpy.name}\n{reference}\n{qpy}"
sys.stderr.write(msg)
sys.exit(2)
if reference.metadata != qpy.metadata:
msg = f"Circuit {count} metadata mismatch: {reference.metadata} != {qpy.metadata}"
sys.stderr.write(msg)
sys.exit(3)
def generate_qpy(qpy_files):
"""Generate qpy files from reference circuits."""
for path, circuits in qpy_files.items():
with open(path, "wb") as fd:
dump(circuits, fd)
def load_qpy(qpy_files, version_parts):
"""Load qpy circuits from files and compare to reference circuits."""
for path, circuits in qpy_files.items():
print(f"Loading qpy file: {path}")
with open(path, "rb") as fd:
qpy_circuits = load(fd)
for i, circuit in enumerate(circuits):
bind = None
if path == "parameterized.qpy":
bind = [1, 2]
elif path == "param_phase.qpy":
if i == 0:
bind = [1, 2]
else:
bind = [1]
elif path == "parameter_vector.qpy":
bind = np.linspace(1.0, 2.0, 22)
elif path == "parameter_vector_expression.qpy":
bind = np.linspace(1.0, 2.0, 15)
assert_equal(circuit, qpy_circuits[i], i, version_parts, bind=bind)
def _main():
parser = argparse.ArgumentParser(description="Test QPY backwards compatibilty")
parser.add_argument("command", choices=["generate", "load"])
parser.add_argument(
"--version",
"-v",
help=(
"Optionally specify the version being tested. "
"This will enable additional circuit features "
"to test generating and loading QPY."
),
)
args = parser.parse_args()
# Terra 0.18.0 was the first release with QPY, so that's the default.
version_parts = (0, 18, 0)
if args.version:
version_match = re.search(VERSION_PATTERN, args.version, re.VERBOSE | re.IGNORECASE)
version_parts = tuple(int(x) for x in version_match.group("release").split("."))
qpy_files = generate_circuits(version_parts)
if args.command == "generate":
generate_qpy(qpy_files)
else:
load_qpy(qpy_files, version_parts)
if __name__ == "__main__":
_main()
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 1量子ビット回路を定義
q1 = QuantumCircuit(1)
## 回路を描画
q1.draw(output="mpl")
# 量子ゲートで回路を作成
q1.x(0)
q1.x(0)
## 回路を描画
q1.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q1, vector_sim )
result = job.result().get_statevector(q1, decimals=3)
print(result)
# 1量子ビット回路を定義
q2 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q2.h(0)
# 回路を描画
q2.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q2, vector_sim )
result = job.result().get_statevector(q2, decimals=3)
print(result)
# 1量子ビット回路を定義
q3 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q3.h(0)
q3.h(0)
# 回路を描画
q3.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q3, vector_sim )
result = job.result().get_statevector(q3, decimals=3)
print(result)
# 1量子ビット回路を定義
q4 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q4.x(0)
q4.h(0)
# 回路を描画
q4.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q4, vector_sim )
result = job.result().get_statevector(q4, decimals=3)
print(result)
# 1量子ビット回路を定義
q5 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q5.h(0)
q5.z(0)
# 回路を描画
q5.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q5, vector_sim )
result = job.result().get_statevector(q5, decimals=3)
print(result)
# 1量子ビット回路を定義
q6 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q6.x(0)
q6.h(0)
q6.z(0)
# 回路を描画
q6.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q6, vector_sim )
result = job.result().get_statevector(q6, decimals=3)
print(result)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog.draw()
|
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 -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/ColibrITD-SAS/mpqp
|
ColibrITD-SAS
|
import pytest
from mpqp.qasm.qasm_to_qiskit import qasm2_to_Qiskit_Circuit
from qiskit import QuantumCircuit
@pytest.mark.parametrize(
"qasm_code, gate_names",
[
(
"""OPENQASM 2.0;""",
[],
),
(
"""OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0],q[1];
measure q[0] -> c[0];
measure q[1] -> c[1];""",
[
"h",
"cx",
],
),
],
)
def test_qasm2_to_Qiskit_Circuit(qasm_code: str, gate_names: list[str]):
circ = qasm2_to_Qiskit_Circuit(qasm_code)
assert isinstance(circ, QuantumCircuit)
for instr, expected_gate in zip(circ.data, gate_names):
assert instr.operation.name == expected_gate
|
https://github.com/Heisenbug-s-Dog/qnn_visualization
|
Heisenbug-s-Dog
|
# OpenMP: number of parallel threads.
%env OMP_NUM_THREADS=1
# Plotting
%matplotlib inline
import matplotlib.pyplot as plt
# PyTorch
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import datasets, models, transforms
# Pennylane
import pennylane as qml
from pennylane import numpy as np
# Other tools
import time
import copy
filtered_classes = ['cat', 'dog'] # Subset of CIFAR ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck')
n_qubits = 4 # Number of qubits
quantum = False # If set to "False", the dressed quantum circuit is replaced by
# An enterily classical net (defined by the next parameter).
classical_model = '512_nq_n' # Possible choices: '512_n','512_nq_n','551_512_n'. [nq=n_qubits, n=num_filtered_classes]
step = 0.001 # Learning rate
num_epochs = 3 # Number of training epochs
q_depth = 5 # Depth of the quantum circuit (number of variational layers)
gamma_lr_scheduler = 1 # Learning rate reduction applied every 10 epochs.
max_layers = 15 # Keep 15 even if not all are used.
q_delta = 0.01 # Initial spread of random quantum weights
rng_seed = 0 # Seed for random number generator
start_time = time.time() # start of the computation timer
batch_size = 16 # or 8 # Number of samples for each training step
STEPS = 40 # or 20
if quantum:
figname = 'cq'
else:
figname = 'cc'
torch.manual_seed(rng_seed)
dev = qml.device('default.qubit', wires=n_qubits)
# device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
def H_layer(nqubits):
"""Layer of single-qubit Hadamard gates.
"""
for idx in range(nqubits):
qml.Hadamard(wires=idx)
def RY_layer(w):
"""Layer of parametrized qubit rotations around the y axis.
"""
for idx, element in enumerate(w):
qml.RY(element, wires=idx)
def entangling_layer(nqubits):
"""Layer of CNOTs followed by another shifted layer of CNOT.
"""
# In other words it should apply something like :
# CNOT CNOT CNOT CNOT... CNOT
# CNOT CNOT CNOT... CNOT
for i in range(0, nqubits - 1, 2): # Loop over even indices: i=0,2,...N-2
qml.CNOT(wires=[i, i + 1])
for i in range(1, nqubits - 1,2): # Loop over odd indices: i=1,3,...N-3
qml.CNOT(wires=[i, i + 1])
@qml.qnode(dev, interface='torch')
def q_net(q_in, q_weights_flat):
# Reshape weights
q_weights = q_weights_flat.reshape(max_layers, n_qubits)
# Start from state |+> , unbiased w.r.t. |0> and |1>
H_layer(n_qubits)
# Embed features in the quantum node
RY_layer(q_in)
# Sequence of trainable variational layers
for k in range(q_depth):
entangling_layer(n_qubits)
RY_layer(q_weights[k+1])
# Expectation values in the Z basis
return [qml.expval(qml.PauliZ(j)) for j in range(n_qubits)]
class Quantumnet(nn.Module):
def __init__(self):
super().__init__()
self.pre_net = nn.Linear(512, n_qubits)
self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits))
self.post_net = nn.Linear(n_qubits, len(filtered_classes))
def forward(self, input_features):
pre_out = self.pre_net(input_features)
q_in = torch.tanh(pre_out) * np.pi / 2.0
# Apply the quantum circuit to each element of the batch, and append to q_out
q_out = torch.Tensor(0, n_qubits)
q_out = q_out.to(device)
for elem in q_in:
q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0)
q_out = torch.cat((q_out, q_out_elem))
return self.post_net(q_out)
# Build Model
model_hybrid = torchvision.models.resnet18(pretrained=True)
for param in model_hybrid.parameters():
param.requires_grad = False
if quantum:
model_hybrid.fc = Quantumnet()
elif classical_model == '512_n':
model_hybrid.fc = nn.Linear(512,len(filtered_classes))
elif classical_model == '512_nq_n':
model_hybrid.fc = nn.Sequential(nn.Linear(512, n_qubits),torch.nn.ReLU(),nn.Linear(n_qubits, len(filtered_classes)))
elif classical_model == '551_512_n':
model_hybrid.fc = nn.Sequential(nn.Linear(512, 512), torch.nn.ReLU(), nn.Linear(512, len(filtered_classes)))
# Use CUDA or CPU according to the "device" object.
model_hybrid = model_hybrid.to(device)
# Load model from file
path = './'
if quantum:
model_hybrid.load_state_dict(torch.load(
path+'quantum_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt'
)
)
else:
model_hybrid.load_state_dict(torch.load(
path+'classical_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt'
)
)
# Fixed pre-processing operations
data_transforms = {
'train': transforms.Compose([
#transforms.RandomResizedCrop(224), # uncomment for data augmentation
#transforms.RandomHorizontalFlip(), # uncomment for data augmentation
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
# Normalize input channels using mean values and standard deviations of ImageNet.
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
# =================== begin CIFAR dataset loading ===================
trainset_full = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=data_transforms['train'])
testset_full = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=data_transforms['val'])
image_datasets_full={'train': trainset_full, 'val': testset_full}
# CIFAR classes
class_names = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
# Get indices of samples associated to filtered_classes
filtered_labels=[class_names.index(cl) for cl in filtered_classes]
sub_indices={'train': [], 'val': []}
for phase in ['train', 'val']:
for idx, label in enumerate(image_datasets_full[phase].targets):
if label in filtered_labels:
sub_indices[phase].append(idx)
# Initialize sub-datasets according to filtered indices
image_datasets = {x: torch.utils.data.Subset(image_datasets_full[x], sub_indices[x])
for x in ['train', 'val']}
def labels_to_filtered(labels):
"""Maps CIFAR labels (0,1,2,3,4,5,6,7,8,9) to the index of filtered_labels"""
return [filtered_labels.index(label) for label in labels]
# =================== end CIFAR dataset loading ==========================
# Number of samples
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
# Initialize dataloader
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x],
batch_size=batch_size, shuffle=False, num_workers=0) for x in ['train', 'val']} # shuffle False
# Function to plot images from tensors
def imshow(inp, title=None):
"""Imshow for Tensor."""
inp = inp.numpy().transpose((1, 2, 0))
# We apply the inverse of the initial normalization operation.
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
inp = std * inp + mean
inp = np.clip(inp, 0, 1)
plt.imshow(inp)
if title is not None:
plt.title(title)
from loss_landscapes import random_plane
from loss_landscapes.metrics import Loss
import matplotlib
matplotlib.rcParams['figure.figsize'] = [18, 12]
data_iter = iter(dataloaders['train'])
# Get a batch of training data
X, y_cifar = next(data_iter)
y = torch.tensor(labels_to_filtered(y_cifar))
X, y = X.to(device), y.to(device)
print(y)
loss_func = nn.CrossEntropyLoss()
#loss_func = nn.MSELoss(reduce='false')
metric = Loss(loss_func, X, y)
landscape = random_plane(model_hybrid, metric, distance=10, steps=STEPS, normalization='filter')
fig = plt.figure()
plt.contour(landscape, levels=50)
plt.title('Loss Contours around Trained Model')
fig.show()
plt.savefig('./landscape/contours_{}_{}_{}_batch1.png'.format(figname, batch_size, STEPS), dpi=300)
fig = plt.figure()
ax = plt.axes(projection='3d')
X = np.array([[j for j in range(STEPS)] for i in range(STEPS)])
Y = np.array([[i for _ in range(STEPS)] for i in range(STEPS)])
ax.plot_surface(X, Y, landscape, rstride=1, cstride=1, cmap='viridis', edgecolor='none')
ax.set_title('Surface Plot of Loss Landscape')
fig.show()
ax.set_zlim([0, 1.5])
plt.savefig('./landscape/surface_{}_{}_{}_batch1.png'.format(figname, batch_size, STEPS), dpi=300)
with open('./landscape/landscape_{}_{}_{}_batch1.npy'.format(figname, batch_size, STEPS), 'wb') as f:
np.save(f, landscape)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
es_problem = driver.run()
from qiskit_nature.second_q.mappers import JordanWignerMapper
mapper = JordanWignerMapper()
from qiskit.algorithms.eigensolvers import NumPyEigensolver
numpy_solver = NumPyEigensolver(filter_criterion=es_problem.get_default_filter_criterion())
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.algorithms import GroundStateEigensolver, QEOM
from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD
ansatz = UCCSD(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
mapper,
initial_state=HartreeFock(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
mapper,
),
)
estimator = Estimator()
# This first part sets the ground state solver
# see more about this part in the ground state calculation tutorial
solver = VQE(estimator, ansatz, SLSQP())
solver.initial_point = [0.0] * ansatz.num_parameters
gse = GroundStateEigensolver(mapper, solver)
# The qEOM algorithm is simply instantiated with the chosen ground state solver and Estimator primitive
qeom_excited_states_solver = QEOM(gse, estimator, "sd")
from qiskit_nature.second_q.algorithms import ExcitedStatesEigensolver
numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, numpy_solver)
numpy_results = numpy_excited_states_solver.solve(es_problem)
qeom_results = qeom_excited_states_solver.solve(es_problem)
print(numpy_results)
print("\n\n")
print(qeom_results)
import numpy as np
def filter_criterion(eigenstate, eigenvalue, aux_values):
return np.isclose(aux_values["ParticleNumber"][0], 2.0)
new_numpy_solver = NumPyEigensolver(filter_criterion=filter_criterion)
new_numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, new_numpy_solver)
new_numpy_results = new_numpy_excited_states_solver.solve(es_problem)
print(new_numpy_results)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/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.
"""Gate cancellation pass testing"""
import unittest
import numpy as np
from qiskit.test import QiskitTestCase
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import U1Gate, RZGate, PhaseGate, CXGate, SXGate
from qiskit.circuit.parameter import Parameter
from qiskit.transpiler.target import Target
from qiskit.transpiler import PassManager, PropertySet
from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation, FixedPoint, Size
from qiskit.quantum_info import Operator
class TestCommutativeCancellation(QiskitTestCase):
"""Test the CommutativeCancellation pass."""
def setUp(self):
super().setUp()
self.com_pass_ = CommutationAnalysis()
self.pass_ = CommutativeCancellation()
self.pset = self.pass_.property_set = PropertySet()
def test_all_gates(self):
"""Test all gates on 1 and 2 qubits
q0:-[H]-[H]--[x]-[x]--[y]-[y]--[rz]-[rz]--[u1]-[u1]-[rx]-[rx]---.--.--.--.--.--.-
| | | | | |
q1:-------------------------------------------------------------X--X--Y--Y--.--.-
=
qr0:---[u1]---
qr1:----------
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.x(qr[0])
circuit.x(qr[0])
circuit.y(qr[0])
circuit.y(qr[0])
circuit.rz(0.5, qr[0])
circuit.rz(0.5, qr[0])
circuit.append(U1Gate(0.5), [qr[0]]) # TODO this should work with Phase gates too
circuit.append(U1Gate(0.5), [qr[0]])
circuit.rx(0.5, qr[0])
circuit.rx(0.5, qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cy(qr[0], qr[1])
circuit.cy(qr[0], qr[1])
circuit.cz(qr[0], qr[1])
circuit.cz(qr[0], qr[1])
passmanager = PassManager()
passmanager.append(CommutativeCancellation())
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(qr)
expected.append(RZGate(2.0), [qr[0]])
expected.rx(1.0, qr[0])
self.assertEqual(expected, new_circuit)
def test_commutative_circuit1(self):
"""A simple circuit where three CNOTs commute, the first and the last cancel.
qr0:----.---------------.-- qr0:------------
| |
qr1:---(+)-----(+)-----(+)- = qr1:-------(+)--
| |
qr2:---[H]------.---------- qr2:---[H]--.---
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[2])
circuit.cx(qr[2], qr[1])
circuit.cx(qr[0], qr[1])
passmanager = PassManager()
passmanager.append(CommutativeCancellation())
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[2])
expected.cx(qr[2], qr[1])
self.assertEqual(expected, new_circuit)
def test_consecutive_cnots(self):
"""A simple circuit equals identity
qr0:----.- ----.-- qr0:------------
| |
qr1:---(+)----(+)- = qr1:------------
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
self.assertEqual(expected, new_circuit)
def test_consecutive_cnots2(self):
"""
Two CNOTs that equals identity, with rotation gates inserted.
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.rx(np.pi, qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.rx(np.pi, qr[0])
passmanager = PassManager()
passmanager.append(
[CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")],
do_while=lambda property_set: not property_set["size_fixed_point"],
)
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(qr)
self.assertEqual(expected, new_circuit)
def test_2_alternating_cnots(self):
"""A simple circuit where nothing should be cancelled.
qr0:----.- ---(+)- qr0:----.----(+)-
| | | |
qr1:---(+)-----.-- = qr1:---(+)----.--
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.cx(qr[0], qr[1])
expected.cx(qr[1], qr[0])
self.assertEqual(expected, new_circuit)
def test_control_bit_of_cnot(self):
"""A simple circuit where nothing should be cancelled.
qr0:----.------[X]------.-- qr0:----.------[X]------.--
| | | |
qr1:---(+)-------------(+)- = qr1:---(+)-------------(+)-
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.x(qr[0])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.cx(qr[0], qr[1])
expected.x(qr[0])
expected.cx(qr[0], qr[1])
self.assertEqual(expected, new_circuit)
def test_control_bit_of_cnot1(self):
"""A simple circuit where the two cnots shoule be cancelled.
qr0:----.------[Z]------.-- qr0:---[Z]---
| |
qr1:---(+)-------------(+)- = qr1:---------
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.z(qr[0])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.z(qr[0])
self.assertEqual(expected, new_circuit)
def test_control_bit_of_cnot2(self):
"""A simple circuit where the two cnots shoule be cancelled.
qr0:----.------[T]------.-- qr0:---[T]---
| |
qr1:---(+)-------------(+)- = qr1:---------
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.t(qr[0])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.t(qr[0])
self.assertEqual(expected, new_circuit)
def test_control_bit_of_cnot3(self):
"""A simple circuit where the two cnots shoule be cancelled.
qr0:----.------[Rz]------.-- qr0:---[Rz]---
| |
qr1:---(+)-------- -----(+)- = qr1:----------
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.rz(np.pi / 3, qr[0])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.rz(np.pi / 3, qr[0])
self.assertEqual(expected, new_circuit)
def test_control_bit_of_cnot4(self):
"""A simple circuit where the two cnots shoule be cancelled.
qr0:----.------[T]------.-- qr0:---[T]---
| |
qr1:---(+)-------------(+)- = qr1:---------
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.t(qr[0])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.t(qr[0])
self.assertEqual(expected, new_circuit)
def test_target_bit_of_cnot(self):
"""A simple circuit where nothing should be cancelled.
qr0:----.---------------.-- qr0:----.---------------.--
| | | |
qr1:---(+)-----[Z]-----(+)- = qr1:---(+)----[Z]------(+)-
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.z(qr[1])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.cx(qr[0], qr[1])
expected.z(qr[1])
expected.cx(qr[0], qr[1])
self.assertEqual(expected, new_circuit)
def test_target_bit_of_cnot1(self):
"""A simple circuit where nothing should be cancelled.
qr0:----.---------------.-- qr0:----.---------------.--
| | | |
qr1:---(+)-----[T]-----(+)- = qr1:---(+)----[T]------(+)-
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.t(qr[1])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.cx(qr[0], qr[1])
expected.t(qr[1])
expected.cx(qr[0], qr[1])
self.assertEqual(expected, new_circuit)
def test_target_bit_of_cnot2(self):
"""A simple circuit where nothing should be cancelled.
qr0:----.---------------.-- qr0:----.---------------.--
| | | |
qr1:---(+)-----[Rz]----(+)- = qr1:---(+)----[Rz]-----(+)-
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.rz(np.pi / 3, qr[1])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.cx(qr[0], qr[1])
expected.rz(np.pi / 3, qr[1])
expected.cx(qr[0], qr[1])
self.assertEqual(expected, new_circuit)
def test_commutative_circuit2(self):
"""
A simple circuit where three CNOTs commute, the first and the last cancel,
also two X gates cancel and two Rz gates combine.
qr0:----.---------------.-------- qr0:-------------
| |
qr1:---(+)---(+)--[X]--(+)--[X]-- = qr1:--------(+)--
| |
qr2:---[Rz]---.---[Rz]-[T]--[S]-- qr2:--[U1]---.---
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.rz(np.pi / 3, qr[2])
circuit.cx(qr[2], qr[1])
circuit.rz(np.pi / 3, qr[2])
circuit.t(qr[2])
circuit.s(qr[2])
circuit.x(qr[1])
circuit.cx(qr[0], qr[1])
circuit.x(qr[1])
passmanager = PassManager()
passmanager.append(CommutativeCancellation())
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(qr)
expected.append(RZGate(np.pi * 17 / 12), [qr[2]])
expected.cx(qr[2], qr[1])
expected.global_phase = (np.pi * 17 / 12 - (2 * np.pi / 3)) / 2
self.assertEqual(expected, new_circuit)
def test_commutative_circuit3(self):
"""
A simple circuit where three CNOTs commute, the first and the last cancel,
also two X gates cancel and two Rz gates combine.
qr0:-------.------------------.------------- qr0:-------------
| |
qr1:------(+)------(+)--[X]--(+)-------[X]-- = qr1:--------(+)--
| |
qr2:------[Rz]--.---.----.---[Rz]-[T]--[S]-- qr2:--[U1]---.---
| |
qr3:-[Rz]--[X]-(+)------(+)--[X]-[Rz]------- qr3:--[Rz]-------
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.rz(np.pi / 3, qr[2])
circuit.rz(np.pi / 3, qr[3])
circuit.x(qr[3])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[2], qr[1])
circuit.cx(qr[2], qr[3])
circuit.rz(np.pi / 3, qr[2])
circuit.t(qr[2])
circuit.x(qr[3])
circuit.rz(np.pi / 3, qr[3])
circuit.s(qr[2])
circuit.x(qr[1])
circuit.cx(qr[0], qr[1])
circuit.x(qr[1])
passmanager = PassManager()
passmanager.append(
[CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")],
do_while=lambda property_set: not property_set["size_fixed_point"],
)
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(qr)
expected.append(RZGate(np.pi * 17 / 12), [qr[2]])
expected.append(RZGate(np.pi * 2 / 3), [qr[3]])
expected.cx(qr[2], qr[1])
self.assertEqual(
expected, new_circuit, msg=f"expected:\n{expected}\nnew_circuit:\n{new_circuit}"
)
def test_cnot_cascade(self):
"""
A cascade of CNOTs that equals identity.
"""
qr = QuantumRegister(10, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[4], qr[5])
circuit.cx(qr[5], qr[6])
circuit.cx(qr[6], qr[7])
circuit.cx(qr[7], qr[8])
circuit.cx(qr[8], qr[9])
circuit.cx(qr[8], qr[9])
circuit.cx(qr[7], qr[8])
circuit.cx(qr[6], qr[7])
circuit.cx(qr[5], qr[6])
circuit.cx(qr[4], qr[5])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[0], qr[1])
passmanager = PassManager()
# passmanager.append(CommutativeCancellation())
passmanager.append(
[CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")],
do_while=lambda property_set: not property_set["size_fixed_point"],
)
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(qr)
self.assertEqual(expected, new_circuit)
def test_cnot_cascade1(self):
"""
A cascade of CNOTs that equals identity, with rotation gates inserted.
"""
qr = QuantumRegister(10, "qr")
circuit = QuantumCircuit(qr)
circuit.rx(np.pi, qr[0])
circuit.rx(np.pi, qr[1])
circuit.rx(np.pi, qr[2])
circuit.rx(np.pi, qr[3])
circuit.rx(np.pi, qr[4])
circuit.rx(np.pi, qr[5])
circuit.rx(np.pi, qr[6])
circuit.rx(np.pi, qr[7])
circuit.rx(np.pi, qr[8])
circuit.rx(np.pi, qr[9])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[4], qr[5])
circuit.cx(qr[5], qr[6])
circuit.cx(qr[6], qr[7])
circuit.cx(qr[7], qr[8])
circuit.cx(qr[8], qr[9])
circuit.cx(qr[8], qr[9])
circuit.cx(qr[7], qr[8])
circuit.cx(qr[6], qr[7])
circuit.cx(qr[5], qr[6])
circuit.cx(qr[4], qr[5])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[0], qr[1])
circuit.rx(np.pi, qr[0])
circuit.rx(np.pi, qr[1])
circuit.rx(np.pi, qr[2])
circuit.rx(np.pi, qr[3])
circuit.rx(np.pi, qr[4])
circuit.rx(np.pi, qr[5])
circuit.rx(np.pi, qr[6])
circuit.rx(np.pi, qr[7])
circuit.rx(np.pi, qr[8])
circuit.rx(np.pi, qr[9])
passmanager = PassManager()
# passmanager.append(CommutativeCancellation())
passmanager.append(
[CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")],
do_while=lambda property_set: not property_set["size_fixed_point"],
)
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(qr)
self.assertEqual(expected, new_circuit)
def test_conditional_gates_dont_commute(self):
"""Conditional gates do not commute and do not cancel"""
# ┌───┐┌─┐
# q_0: ┤ H ├┤M├─────────────
# └───┘└╥┘ ┌─┐
# q_1: ──■───╫────■───┤M├───
# ┌─┴─┐ ║ ┌─┴─┐ └╥┘┌─┐
# q_2: ┤ X ├─╫──┤ X ├──╫─┤M├
# └───┘ ║ └─╥─┘ ║ └╥┘
# ║ ┌──╨──┐ ║ ║
# c: 2/══════╩═╡ 0x0 ╞═╩══╩═
# 0 └─────┘ 0 1
circuit = QuantumCircuit(3, 2)
circuit.h(0)
circuit.measure(0, 0)
circuit.cx(1, 2)
circuit.cx(1, 2).c_if(circuit.cregs[0], 0)
circuit.measure([1, 2], [0, 1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
self.assertEqual(circuit, new_circuit)
def test_basis_01(self):
"""Test basis priority change, phase gate"""
circuit = QuantumCircuit(1)
circuit.s(0)
circuit.z(0)
circuit.t(0)
circuit.rz(np.pi, 0)
passmanager = PassManager()
passmanager.append(CommutativeCancellation(basis_gates=["cx", "p", "sx"]))
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(1)
expected.rz(11 * np.pi / 4, 0)
expected.global_phase = 11 * np.pi / 4 / 2 - np.pi / 2
self.assertEqual(new_circuit, expected)
def test_target_basis_01(self):
"""Test basis priority change, phase gate, with target."""
circuit = QuantumCircuit(1)
circuit.s(0)
circuit.z(0)
circuit.t(0)
circuit.rz(np.pi, 0)
theta = Parameter("theta")
target = Target(num_qubits=2)
target.add_instruction(CXGate())
target.add_instruction(PhaseGate(theta))
target.add_instruction(SXGate())
passmanager = PassManager()
passmanager.append(CommutativeCancellation(target=target))
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(1)
expected.rz(11 * np.pi / 4, 0)
expected.global_phase = 11 * np.pi / 4 / 2 - np.pi / 2
self.assertEqual(new_circuit, expected)
def test_basis_02(self):
"""Test basis priority change, Rz gate"""
circuit = QuantumCircuit(1)
circuit.s(0)
circuit.z(0)
circuit.t(0)
passmanager = PassManager()
passmanager.append(CommutativeCancellation(basis_gates=["cx", "rz", "sx"]))
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(1)
expected.rz(7 * np.pi / 4, 0)
expected.global_phase = 7 * np.pi / 4 / 2
self.assertEqual(new_circuit, expected)
def test_basis_03(self):
"""Test no specified basis"""
circuit = QuantumCircuit(1)
circuit.s(0)
circuit.z(0)
circuit.t(0)
passmanager = PassManager()
passmanager.append(CommutativeCancellation())
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(1)
expected.s(0)
expected.z(0)
expected.t(0)
self.assertEqual(new_circuit, expected)
def test_basis_global_phase_01(self):
"""Test no specified basis, rz"""
circ = QuantumCircuit(1)
circ.rz(np.pi / 2, 0)
circ.p(np.pi / 2, 0)
circ.p(np.pi / 2, 0)
passmanager = PassManager()
passmanager.append(CommutativeCancellation())
ccirc = passmanager.run(circ)
self.assertEqual(Operator(circ), Operator(ccirc))
def test_basis_global_phase_02(self):
"""Test no specified basis, p"""
circ = QuantumCircuit(1)
circ.p(np.pi / 2, 0)
circ.rz(np.pi / 2, 0)
circ.p(np.pi / 2, 0)
passmanager = PassManager()
passmanager.append(CommutativeCancellation())
ccirc = passmanager.run(circ)
self.assertEqual(Operator(circ), Operator(ccirc))
def test_basis_global_phase_03(self):
"""Test global phase preservation if cummulative z-rotation is 0"""
circ = QuantumCircuit(1)
circ.rz(np.pi / 2, 0)
circ.p(np.pi / 2, 0)
circ.z(0)
passmanager = PassManager()
passmanager.append(CommutativeCancellation())
ccirc = passmanager.run(circ)
self.assertEqual(Operator(circ), Operator(ccirc))
def test_basic_classical_wires(self):
"""Test that transpile runs without internal errors when dealing with commutable operations
with classical controls. Regression test for gh-8553."""
original = QuantumCircuit(2, 1)
original.x(0).c_if(original.cregs[0], 0)
original.x(1).c_if(original.cregs[0], 0)
# This transpilation shouldn't change anything, but it should succeed. At one point it was
# triggering an internal logic error and crashing.
transpiled = PassManager([CommutativeCancellation()]).run(original)
self.assertEqual(original, transpiled)
def test_simple_if_else(self):
"""Test that the pass is not confused by if-else."""
base_test1 = QuantumCircuit(3, 3)
base_test1.x(1)
base_test1.cx(0, 1)
base_test1.x(1)
base_test2 = QuantumCircuit(3, 3)
base_test2.rz(0.1, 1)
base_test2.rz(0.1, 1)
test = QuantumCircuit(3, 3)
test.h(0)
test.x(0)
test.rx(0.2, 0)
test.measure(0, 0)
test.x(0)
test.if_else(
(test.clbits[0], True), base_test1.copy(), base_test2.copy(), test.qubits, test.clbits
)
expected = QuantumCircuit(3, 3)
expected.h(0)
expected.rx(np.pi + 0.2, 0)
expected.measure(0, 0)
expected.x(0)
expected_test1 = QuantumCircuit(3, 3)
expected_test1.cx(0, 1)
expected_test2 = QuantumCircuit(3, 3)
expected_test2.rz(0.2, 1)
expected.if_else(
(expected.clbits[0], True),
expected_test1.copy(),
expected_test2.copy(),
expected.qubits,
expected.clbits,
)
passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()])
new_circuit = passmanager.run(test)
self.assertEqual(new_circuit, expected)
def test_nested_control_flow(self):
"""Test that the pass does not add barrier into nested control flow."""
level2_test = QuantumCircuit(2, 1)
level2_test.cz(0, 1)
level2_test.cz(0, 1)
level2_test.cz(0, 1)
level2_test.measure(0, 0)
level1_test = QuantumCircuit(2, 1)
level1_test.for_loop((0,), None, level2_test.copy(), level1_test.qubits, level1_test.clbits)
level1_test.h(0)
level1_test.h(0)
level1_test.measure(0, 0)
test = QuantumCircuit(2, 1)
test.while_loop((test.clbits[0], True), level1_test.copy(), test.qubits, test.clbits)
test.measure(0, 0)
level2_expected = QuantumCircuit(2, 1)
level2_expected.cz(0, 1)
level2_expected.measure(0, 0)
level1_expected = QuantumCircuit(2, 1)
level1_expected.for_loop(
(0,), None, level2_expected.copy(), level1_expected.qubits, level1_expected.clbits
)
level1_expected.measure(0, 0)
expected = QuantumCircuit(2, 1)
expected.while_loop(
(expected.clbits[0], True), level1_expected.copy(), expected.qubits, expected.clbits
)
expected.measure(0, 0)
passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()])
new_circuit = passmanager.run(test)
self.assertEqual(new_circuit, expected)
def test_cancellation_not_crossing_block_boundary(self):
"""Test that the pass does cancel gates across control flow op block boundaries."""
test1 = QuantumCircuit(2, 2)
test1.x(1)
with test1.if_test((0, False)):
test1.cx(0, 1)
test1.x(1)
passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()])
new_circuit = passmanager.run(test1)
self.assertEqual(new_circuit, test1)
def test_cancellation_not_crossing_between_blocks(self):
"""Test that the pass does cancel gates in different control flow ops."""
test2 = QuantumCircuit(2, 2)
with test2.if_test((0, True)):
test2.x(1)
with test2.if_test((0, True)):
test2.cx(0, 1)
test2.x(1)
passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()])
new_circuit = passmanager.run(test2)
self.assertEqual(new_circuit, test2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
import scipy as sci
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
M_simulator = Aer.backends(name='qasm_simulator')[0]
def XOR(a,b):
if( (a+b)==1 ):
return 1
else:
return 0
def OR(a,b):
if( (a+b)>=1 ):
return 1
else:
return 0
def AND(a,b):
if( (a+b)==2 ):
return 1
else:
return 0
#====================================
a = [1,1,0,0]
b = [0,1,1,1]
C = 0
Sum = []
for i in range( len(a) ):
xor1 = XOR(a[0-i-1],b[0-i-1])
S = XOR(xor1,C)
and1 = AND(a[0-i-1],b[0-i-1])
and2 = AND(xor1,C)
C = OR(and1,and2)
Sum.insert(0,S)
if( C == 1 ):
Sum.insert(0,C)
print('Adding a = ',a,' + b = ',b,' ===> ',Sum)
q = QuantumRegister(3,name='q')
qc= QuantumCircuit(q,name='qc')
#------------------------------
qc.h( q[0] )
qc.h( q[1] )
qc.h( q[2] )
qc.p( 3*m.pi/2, q[0] )
qc.p( m.pi, q[1] )
qc.p( 0, q[2] )
oq.Wavefunction(qc);
q = QuantumRegister(3,name='q')
qc= QuantumCircuit(q,name='qc')
#------------------------------
qc.x( q[0] )
qc.x( q[1] )
oq.QFT(qc,q,3)
oq.Wavefunction(qc);
qa = QuantumRegister(2,name='a')
qb = QuantumRegister(2,name='b')
qc = QuantumCircuit(qa,qb,name='qc')
qc.x( qa[1] )
qc.x( qb[0] )
oq.Wavefunction(qc,systems=[2,2]);
qa = QuantumRegister(2,name='a')
qb = QuantumRegister(2,name='b')
qc = QuantumCircuit(qa,qb,name='qc')
#------------------------------------
qc.x( qa[1] )
qc.x( qb[0] )
print('_____ States to Add Together _____')
oq.Wavefunction(qc,systems=[2,2])
oq.QFT(qc,qa,2)
#----------------------------- phase contributions from |b>
qc.cp( m.pi, qb[0], qa[0] )
qc.cp( m.pi/2, qb[1], qa[0] )
qc.cp( m.pi, qb[1], qa[1] )
#-----------------------------
oq.QFT_dgr(qc,qa,2)
print('\n___ Sum Stored in |a> ___')
oq.Wavefunction(qc,systems=[2,2],show_systems=[True,False]);
A_States = [[0,1],[1,0],[1,1]]
B_States = [[1,0],[1,1]]
#------------------------------------
for a in range(len(A_States)):
A = A_States[a]
for b in range(len(B_States)):
B = B_States[b]
qa = QuantumRegister(2,name='a')
qb = QuantumRegister(2,name='b')
qc = QuantumCircuit(qa,qb,name='qc')
#-----------------------------------
if(A[0]==1):
qc.x( qa[0] )
if(A[1]==1):
qc.x( qa[1] )
if(B[0]==1):
qc.x( qb[0] )
if(B[1]==1):
qc.x( qb[1] )
oq.QFT(qc,qa,2)
qc.cp( m.pi, qb[0], qa[0] )
qc.cp( m.pi/2, qb[1], qa[0] )
qc.cp( m.pi, qb[1], qa[1] )
oq.QFT_dgr(qc,qa,2)
print('\nA:',A,' B:',B)
oq.Wavefunction(qc,systems=[2,2],show_systems=[True,False])
qa = QuantumRegister(3,name='a')
qb = QuantumRegister(2,name='b')
qc = QuantumCircuit(qa,qb,name='qc')
#-----------------------------------
qc.x( qa[1] )
qc.x( qb[0] )
qc.x( qb[1] )
print('_____ States to Add Together _____')
oq.Wavefunction(qc,systems=[3,2])
oq.QFT(qc,qa,3)
#------------------------------ phase contributions from |b>
qc.cp( m.pi/2, qb[0], qa[0] )
qc.cp( m.pi/4, qb[1], qa[0] )
qc.cp( m.pi, qb[0], qa[1] )
qc.cp( m.pi/2, qb[1], qa[1] )
qc.cp( m.pi, qb[1], qa[2] )
#------------------------------
oq.QFT_dgr(qc,qa,3)
print('\n___ Sum Stored in |a> ___')
oq.Wavefunction(qc,systems=[3,2],show_systems=[True,False]);
A = [0,1,1,0]
B = [1,1,0,1] #A and B need to be arrays of equal length (don't include the extra 0 qubit for A)
print('States to Add Together: ',A,' + ',B)
#=========================================
qa = QuantumRegister(len(A)+1,name='a')
qb = QuantumRegister(len(B),name='b')
qc = QuantumCircuit(qa,qb,name='qc')
#--------------------------------------
oq.Quantum_Adder(qc,qa,qb,A,B)
print('\n___ Sum Stored in |a> ___')
oq.Wavefunction(qc,systems=[len(A)+1,len(B)],show_systems=[True,False]);
qa = QuantumRegister(3,name='a')
qb = QuantumRegister(3,name='b')
qc = QuantumCircuit(qa,qb,name='qc')
#-----------------------------------
qc.x( qa[0] )
qc.x( qa[1] )
qc.x( qb[1] )
qc.x( qb[2] )
print('____ States to Subtract ____')
oq.Wavefunction(qc,systems=[3,3])
oq.QFT(qc,qa,3)
#------------------------------ phase contributions from |b>
qc.cp( -m.pi, qb[0], qa[0] )
qc.cp( -m.pi/2, qb[1], qa[0] )
qc.cp( -m.pi/4, qb[2], qa[0] )
qc.cp( -m.pi, qb[1], qa[1] )
qc.cp( -m.pi/2, qb[2], qa[1] )
qc.cp( -m.pi, qb[2], qa[2] )
#------------------------------
oq.QFT_dgr(qc,qa,3)
print('\n___ Difference Stored in |a> ___')
oq.Wavefunction(qc,systems=[3,3],show_systems=[True,False]);
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import qiskit.qasm3
program = """
OPENQASM 3.0;
include "stdgates.inc";
input float[64] a;
qubit[3] q;
bit[2] mid;
bit[3] out;
let aliased = q[0:1];
gate my_gate(a) c, t {
gphase(a / 2);
ry(a) c;
cx c, t;
}
gate my_phase(a) c {
ctrl @ inv @ gphase(a) c;
}
my_gate(a * 2) aliased[0], q[{1, 2}][0];
measure q[0] -> mid[0];
measure q[1] -> mid[1];
while (mid == "00") {
reset q[0];
reset q[1];
my_gate(a) q[0], q[1];
my_phase(a - pi/2) q[1];
mid[0] = measure q[0];
mid[1] = measure q[1];
}
if (mid[0]) {
let inner_alias = q[{0, 1}];
reset inner_alias;
}
out = measure q;
"""
circuit = qiskit.qasm3.loads(program)
circuit.draw("mpl")
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
import json
import csv
# Array of JSON Objects
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
# genera las distancias
index = -1
for sample in UNIFORM_CONVERGENCE_SAMPLE:
mean = sample["mean"]
index += 1
distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"]))
UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state
header = ['instance', 'iteration', 'distance']
length_instances = 2
with open('qaoa_multiple_distance.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
for i in range(length_instances):
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution()
iteration = 0
for sample in UNIFORM_CONVERGENCE_SAMPLE:
iteration += 1
mean = sample["mean"]
distance = sample["distance_pgs"]
state = 0
for probability in sample["probabilities"]:
state += 1
# write the data
data = [iteration, state, probability, mean]
writer.writerow(data)
writer_q.writerow([iteration, distance])
|
https://github.com/soumya-s3/qiskit_developer_test_notebook
|
soumya-s3
|
import numpy as np
from qiskit import QuantumCircuit
# Building the circuit
# 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)
# We can visualise the circuit using QuantumCircuit.draw()
circ.draw('mpl')
from qiskit.quantum_info import Statevector
# Set the initial state of the simulator to the ground state using from_int
state = Statevector.from_int(0, 2**3)
# Evolve the state by the quantum circuit
state = state.evolve(circ)
#draw using latex
state.draw('latex')
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Build
#------
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# END
# Execute
#--------
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Return counts
counts = result.get_counts(circuit)
print("\nTotal count for 00 and 11 are:",counts)
# END
# Visualize
#----------
# Using QuantumCircuit.draw(), as in previous example
circuit.draw('mpl')
# Analyze
#--------
# Plot a histogram
plot_histogram(counts)
# END
<h3 style="color: rgb(0, 125, 65)"><i>References</i></h3>
https://qiskit.org/documentation/tutorials.html
https://www.youtube.com/watch?v=P5cGeDKOIP0
https://qiskit.org/documentation/tutorials/circuits/01_circuit_basics.html
https://docs.quantum-computing.ibm.com/lab/first-circuit
|
https://github.com/sayana25/IQCQ-UPES-2023
|
sayana25
|
pip install qiskit
!pip install pylatexenc
pip install qiskit-aer
pip install git+https://github.com/Qiskit/qiskit-terra.git
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, plot_histogram, plot_state_city
Aer.backends()
# Construct quantum circuit without measure
circ = QuantumCircuit(2,2)
circ.h(0)
circ.cx(0, 1) #CNOT gate
circ.measure([0,1], [0,1])
circ.draw('mpl')
# Select the QasmSimulator from the Aer provider
simulator = Aer.get_backend('qasm_simulator')
# Execute and get memory
result = execute(circ, simulator, shots=100, memory=True).result()
memory = result.get_memory(circ)
print(memory)
# Select the StatevectorSimulator from the Aer provider
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
statevector = result.get_statevector(circ)
plot_state_city(statevector, title='Bell state')
def psiplus():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
qc.h(0)
qc.x(1)
qc.cx(0,1)
return qc
qc = psiplus()
qc.draw('mpl') # we draw the circuit
qc.measure_all() # we measure all the qubits
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
#lets first construct the circuit for the GHZ state
def GHZ():
circ = QuantumCircuit(3,3)
circ.h(0)
circ.cx(0,1)
circ.cx(1,2)
return circ
circ = GHZ()
circ.draw('mpl') # draw the circuit
circ.measure_all() # measure all the qubits
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(circ, backend, shots = 2000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # plot a histogram to see the possible outcomes and corresponding probabilities
def GHZlike():
circ = QuantumCircuit(3,3)
circ.h(0)
circ.z(0)
circ.x(1)
circ.x(2)
circ.cx(0,1)
circ.cx(1,2)
return circ
circ = GHZlike()
circ.draw('mpl') # draw the circuit
circ.measure_all() # measure all the qubits
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(circ, backend, shots = 2000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # plot a histogram to see the possible outcomes and corresponding probabilities
def GHZlike():
circ = QuantumCircuit(3,3)
circ.h(0)
circ.z(0)
circ.x(1)
circ.x(2)
circ.cx(0,1)
circ.cx(1,2)
return circ
qc = GHZlike()
qc.draw('mpl') # draw the circuit
# Execute and get counts
result = execute(qc, simulator).result()
statevector = result.get_statevector(qc)
plot_state_city(statevector, title='GHZ-like state')
# Construct an empty quantum circuit which makes the first bell state
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
print("Circuit unitary:\n", unitary)
|
https://github.com/qiskit-community/qiskit-dell-runtime
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test QRAO steps on various hardware and simulator backends"""
import pytest
from docplex.mp.model import Model
from qiskit.utils import QuantumInstance
from qiskit.algorithms.minimum_eigen_solvers import VQE
from qiskit.circuit.library import RealAmplitudes
from qiskit.algorithms.optimizers import SPSA
from qiskit import BasicAer
from qiskit_aer import Aer
from qiskit_optimization.algorithms import OptimizationResultStatus
from qiskit_optimization.translators import from_docplex_mp
from qiskit_ibm_provider import IBMProvider, least_busy, IBMAccountError
from qrao import (
QuantumRandomAccessOptimizer,
QuantumRandomAccessEncoding,
MagicRounding,
)
# pylint: disable=redefined-outer-name
# TODO:
# - update these tests to include solution checking once behavior can be made
# - deterministic.
# - This might just require us to set seeds in the QuantumInstance and
# - remove that as an argument altogether.
backends = [
(BasicAer.get_backend, "qasm_simulator"),
(Aer.get_backend, "qasm_simulator"),
(Aer.get_backend, "statevector_simulator"),
(Aer.get_backend, "aer_simulator"),
(Aer.get_backend, "aer_simulator_statevector"),
(Aer.get_backend, "aer_simulator_density_matrix"),
(Aer.get_backend, "aer_simulator_matrix_product_state"),
# The following takes forever, haven't yet waited long enough to know the
# real timescale
# (Aer.get_backend, "aer_simulator_extended_stabilizer"),
]
@pytest.fixture(scope="module")
def my_encoding():
"""Fixture to construct ``my_encoding`` for use in this file"""
# Load small reference problem
elist = [(0, 1), (0, 4), (0, 3), (1, 2), (1, 5), (2, 3), (2, 4), (4, 5), (5, 3)]
num_nodes = 6
mod = Model("maxcut")
nodes = list(range(num_nodes))
var = [mod.binary_var(name="x" + str(i)) for i in nodes]
mod.maximize(mod.sum((var[i] + var[j] - 2 * var[i] * var[j]) for i, j in elist))
problem = from_docplex_mp(mod)
encoding = QuantumRandomAccessEncoding(max_vars_per_qubit=3)
encoding.encode(problem)
return encoding
@pytest.fixture(scope="module")
def my_ansatz(my_encoding):
"""Fixture to construct ``my_ansatz`` for use in this file"""
return RealAmplitudes(my_encoding.num_qubits)
@pytest.mark.parametrize("relaxed_backend", backends)
@pytest.mark.parametrize("rounding_backend", backends)
@pytest.mark.filterwarnings("ignore::PendingDeprecationWarning")
@pytest.mark.filterwarnings(
"ignore:.*statevector_simulator.*:UserWarning"
) # ignore magic rounding's UserWarning when using statevector_simulator
@pytest.mark.backend
def test_backend(relaxed_backend, rounding_backend, my_encoding, my_ansatz, shots=3):
"""Smoke test of each backend combination"""
def cb(f, *args):
"Construct backend"
return f(*args)
relaxed_qi = QuantumInstance(backend=cb(*relaxed_backend), shots=shots)
rounding_qi = QuantumInstance(backend=cb(*rounding_backend), shots=shots)
vqe = VQE(
ansatz=my_ansatz,
optimizer=SPSA(maxiter=1, learning_rate=0.01, perturbation=0.1),
quantum_instance=relaxed_qi,
)
rounding_scheme = MagicRounding(rounding_qi)
qrao = QuantumRandomAccessOptimizer(
encoding=my_encoding, min_eigen_solver=vqe, rounding_scheme=rounding_scheme
)
result = qrao.solve()
assert result.status == OptimizationResultStatus.SUCCESS
@pytest.mark.backend
def test_magic_rounding_on_hardware_backend(my_encoding, my_ansatz):
"""Test *magic rounding* on a hardware backend, if available."""
try:
provider = IBMProvider()
except IBMAccountError:
pytest.skip("No hardware backend available")
print(f"Encoding requires {my_encoding.num_qubits} qubits")
backend = least_busy(
provider.backends(
min_num_qubits=my_encoding.num_qubits,
simulator=False,
operational=True,
)
)
print(f"Using backend: {backend}")
relaxed_qi = QuantumInstance(backend=Aer.get_backend("aer_simulator"), shots=100)
rounding_qi = QuantumInstance(backend=backend, shots=32)
vqe = VQE(
ansatz=my_ansatz,
optimizer=SPSA(maxiter=1, learning_rate=0.01, perturbation=0.1),
quantum_instance=relaxed_qi,
)
rounding_scheme = MagicRounding(quantum_instance=rounding_qi)
qrao = QuantumRandomAccessOptimizer(
encoding=my_encoding, min_eigen_solver=vqe, rounding_scheme=rounding_scheme
)
result = qrao.solve()
assert result.status == OptimizationResultStatus.SUCCESS
|
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
|
jonasmaziero
|
def qc_alice_encoding(cb):
from qiskit import QuantumCircuit
qc = QuantumCircuit(1, name='AE')
if cb == '00':
qc.id(0)
elif cb == '01':
qc.x(0)
elif cb == '10':
qc.z(0)
elif cb == '11':
qc.x(0); qc.z(0)
return qc
cb = '11'
qcae = qc_alice_encoding(cb)
qcae.draw('mpl')
from qiskit import QuantumCircuit # só pra mostrar o circuito quântico
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.barrier()
qcae = qc_alice_encoding(cb)
qc.append(qcae, [0])
qc.barrier()
qc.cx(0,1)
qc.h(0)
qc.measure([0,1],[0,1])
qc.draw('mpl')
def qc_dense_coding(cb):
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, name='DC')
qc.h(0); qc.cx(0,1) # compartilha o par emaranhado
qcae = qc_alice_encoding(cb); qc.append(qcae, [0]) # codificação da Alice
qc.cx(0,1); qc.h(0)#; qc.measure([0,1],[0,1]) # decodificação, medida na BB, do Bob
# OBS. Não consegui incluir um subcircuito que contenha medidas
return qc
from qiskit import QuantumCircuit
qc = QuantumCircuit(2,2)
qcdc = qc_dense_coding('00')
qc.append(qcdc, [0,1])
qc.draw('mpl')
from qiskit import Aer, execute, QuantumCircuit; simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13; from qiskit import QuantumCircuit
qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('00'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts()
from qiskit.tools.visualization import plot_histogram; plot_histogram(counts)
from qiskit import Aer, execute, QuantumCircuit
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
from qiskit import QuantumCircuit
qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('01'); qc.append(qcdc, [0,1])
qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
from qiskit import Aer, execute, QuantumCircuit
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
from qiskit import QuantumCircuit
qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('10'); qc.append(qcdc, [0,1])
qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
from qiskit import Aer, execute, QuantumCircuit
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
from qiskit import QuantumCircuit
qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('11'); qc.append(qcdc, [0,1])
qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
import qiskit
qiskit.IBMQ.save_account('72f5d1e3769658b4908c384492eb3a9bd6d6ac4ab1fdf613d7fbe72884114d62728d6fd60a8bf8d0b6698f2f5463a605742658fee1ce3318181105c6acb8120e',
overwrite = True)
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
from qiskit import QuantumCircuit, execute
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('00'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid)
job = device.retrieve_job('cmj6f1m0t6t00085y6r0')
from qiskit.tools.visualization import plot_histogram; plot_histogram(job.result().get_counts())
from qiskit import QuantumCircuit, execute
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('01'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid)
job = device.retrieve_job('cmj6f7c0t6t00085y6rg')
plot_histogram(job.result().get_counts())
from qiskit import QuantumCircuit, execute
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('10'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid)
job = device.retrieve_job('cmj6f9nstv5g008dwdb0')
plot_histogram(job.result().get_counts())
#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')
from qiskit import QuantumCircuit, execute; device = provider.get_backend('ibm_nairobi'); nshots = 2**13
qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('11'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid)
job = device.retrieve_job('cmj6g3g0t6t00085y6sg')
plot_histogram(job.result().get_counts())
import qiskit
qiskit.IBMQ.save_account('e20d3045c7c23a3be753606794714e9b47d4331ec46a41b2281e2d601bae27b2b3c1baa0b5cb54f3282a8b5248e552b14c9c556699010660fb94b11d00ff1073',
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')
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
from qiskit import QuantumRegister, execute
from qiskit.ignis.mitigation.measurement import complete_meas_cal
qr_ = QuantumRegister(2)
qubit_list_ = [0, 1] # qubits para os quais aplicaremos calibracao de medidas
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list_, qr = qr_)
meas_calibs # circuitos que serão executados para mitigação dos erros
state_labels # estados que serão preparados/medidos/corrigidos
job = execute(meas_calibs, backend=device, shots=nshots)
print(job.job_id())
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
job = device.retrieve_job('cmm4vmyrcq000080ceqg')
cal_results = job.result()
# função que usaremos para corrigir resultados experimentais
meas_fitter = CompleteMeasFitter(cal_results, state_labels)
# OBS. Uma vez feito isso para um chip e para uns certos qubits, depois é só usar
job = device.retrieve_job('cmj6f1m0t6t00085y6r0') # dados do experimento da codificação densa para '00'
unmitigated_counts = job.result().get_counts()
mitigated_results = meas_fitter.filter.apply(job.result()) # corrige os resultados usando mitigação
mitigated_counts = mitigated_results.get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit'])
def prob_erro(counts, target, nshots): # Calcula a probabilidade de erro
if target in counts:
pacerto = counts[target]/nshots
perro = 1 - pacerto
return perro
print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '00', nshots))
print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '00',nshots))
job = device.retrieve_job('cmj6f7c0t6t00085y6rg') # dados do experimento da codificação densa para '01'
unmitigated_counts = job.result().get_counts()
mitigated_results = meas_fitter.filter.apply(job.result()) # corrige os resultados usando mitigação
mitigated_counts = mitigated_results.get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit'])
print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '10', nshots))
print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '10',nshots))
job = device.retrieve_job('cmj6f9nstv5g008dwdb0'); unmitigated_counts = job.result().get_counts()
mitigated_results = meas_fitter.filter.apply(job.result()) # corrige os resultados usando mitigação
mitigated_counts = mitigated_results.get_counts(); from qiskit.tools.visualization import plot_histogram
plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit'])
print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '01', nshots))
print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '01',nshots))
job = device.retrieve_job('cmj6g3g0t6t00085y6sg') # dados do experimento da codificação densa para '11'
unmitigated_counts = job.result().get_counts(); mitigated_results = meas_fitter.filter.apply(job.result())
mitigated_counts = mitigated_results.get_counts(); from qiskit.tools.visualization import plot_histogram
plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit'])
print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '11', nshots))
print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '11',nshots))
def qc_Eswap():
from qiskit import QuantumCircuit
qc = QuantumCircuit(4, name='Eswap')
qc.h([0,3]); qc.cx(0,1); qc.cx(3,2) # cria os pares emaranhados
qc.barrier()
qc.cx(1,2); qc.h(1) # muda da base computacional para a base de Bell
qc.barrier()
qc.cx(2,3); qc.cz(1,3) # envia a informação 'clássica'
return qc
qces = qc_Eswap(); qces.draw('mpl')
from qiskit import Aer, QuantumCircuit; import qiskit
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.visualization import plot_state_city
simulator = Aer.get_backend('qasm_simulator'); qc = QuantumCircuit(4); qces = qc_Eswap(); qc.append(qces, [0,1,2,3])
qstc = state_tomography_circuits(qc, [0,3]); job = execute(qstc, backend=simulator, shots=nshots)
qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq'); plot_state_city(rho)
from qiskit.quantum_info import state_fidelity
F = state_fidelity(rho,Phip); print('F = ',F)
import qiskit
qiskit.IBMQ.save_account('72f5d1e3769658b4908c384492eb3a9bd6d6ac4ab1fdf613d7fbe72884114d62728d6fd60a8bf8d0b6698f2f5463a605742658fee1ce3318181105c6acb8120e',
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')
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
from qiskit import QuantumCircuit, execute
qc = QuantumCircuit(4); qces = qc_Eswap(); qc.append(qces, [0,1,2,3])
qstc = state_tomography_circuits(qc, [0,3])
job = execute(qstc, backend=device, shots=nshots)
jobid = job.job_id(); print(jobid)
job = device.retrieve_job('cmjp9zf5mym0008dvmzg')
qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq')
from qiskit.visualization import plot_state_city; plot_state_city(rho)
rho
import math; import numpy as np
Phip = np.array([1/math.sqrt(2),0,0,1/math.sqrt(2)]); Phip
from qiskit.quantum_info import state_fidelity
F = state_fidelity(rho,Phip); print('F = ',F)
import qiskit
qiskit.IBMQ.save_account('dabd4674f7b3794f740813fec0c5478bfefdebb7d1dca9b7acd41e3f90ed2c8a8b80af26fb3236289fbfc70d0ea334829a836453ac46f96fee68abcb22495ef4',
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')
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
from qiskit import QuantumRegister, execute
from qiskit.ignis.mitigation.measurement import complete_meas_cal
qr = QuantumRegister(4)
qubit_list = [0, 3]
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr)
job = execute(meas_calibs, backend=device, shots=nshots)
print(job.job_id())
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
job = device.retrieve_job('cmr2snercp70008sfsw0')
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels)
from qiskit import QuantumCircuit, execute
qc = QuantumCircuit(4); qces = qc_Eswap(); qc.append(qces, [0,1,2,3])
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
qstc = state_tomography_circuits(qc, [0,3])
job = device.retrieve_job('cmjp9zf5mym0008dvmzg')
mitigated_results = meas_fitter.filter.apply(job.result())
qstf = StateTomographyFitter(mitigated_results, qstc)
rho = qstf.fit(method='lstsq')
from qiskit.visualization import plot_state_city; plot_state_city(rho)
import numpy as np
import math
from qiskit.quantum_info import state_fidelity
Phip = np.array([1/math.sqrt(2),0,0,1/math.sqrt(2)])
F = state_fidelity(rho,Phip)
print('F = ',F)
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
# The code below is a hack in case Travis' kernel fails.
#import os
#os.environ['KMP_DUPLICATE_LIB_OK'] ='True'
import sys
sys.path.append('../../Pyfiles')
# Pull in the helper files.
from experiments import *
# Set up the experiment
circuitID = 1
epochs = 20
import numpy as np
import sys
np.set_printoptions(threshold=sys.maxsize)
lr_list=[round(((i+1)/10)**2,2) for i in range(20)]
ds_list=['0','1a','2a','3c']
for dsID in ds_list:
# Run the experiment
print('--------dataset',dsID,'is initialized------')
lr_acc=[]
for lr in lr_list:
# Load in the data
data = load_data(dsID)
# Generate the splittings
train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data)
# Make the feature map
feature_map= make_embedding_circuit()
# Make the classifier
ansatz = make_classifer_circuit(circuitID)
# Do the training
model = train_model(feature_map, ansatz, epochs, lr, train_X, train_y)
# Check the validation accuracy.
val_accuracy = check_accuracy(model, validate_X, validate_y)
lr_acc.append([lr,val_accuracy])
np.savetxt(r"Learning_Rate_Data\circuit{0}_data{1}.txt".format(circuitID,dsID),lr_acc,fmt='%.2f')
# Set up the experiment
circuitID = 1
epochs = 20
ds_list=['0','1a','2a','3c']
#selected learning rates
lr_opt=[3.24,2.89,0.36,3.24]
model_list=[]
for i in range(4):
data = load_data(ds_list[i])
# Generate the splittings
train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data)
# Make the feature map
feature_map= make_embedding_circuit()
# Make the classifier
ansatz = make_classifer_circuit(circuitID)
# Do the training
model = train_model(feature_map, ansatz, epochs, lr_opt[i], train_X, train_y)
model_list.append(model)
# Check the validation accuracy.
val_accuracy = check_accuracy(model, test_X, test_y)
import matplotlib.pyplot as plt
for lr in range(4):
data = load_data(ds_list[lr])
# Generate the splittings
train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data)
fig = plt.figure(figsize=(15, 10))
ax = fig.add_subplot(4, 2, 2*lr+1)
y_predict = []
for x in test_X:
output = model_list[lr](Tensor(x))
y_predict += [np.argmax(output.detach().numpy())]
print(check_accuracy(model_list[lr], test_X, test_y))
# plot results
# red == wrongly classified
for x, y_target, y_ in zip(test_X, test_y, y_predict):
if y_target == 1:
ax.plot(x[0], x[1], 'bo')
else:
ax.plot(x[0], x[1], 'go')
if y_target != y_:
ax.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2)
ax = fig.add_subplot(4, 2, 2*lr+2)
for x, y_target, y_ in zip(test_X, test_y, y_predict):
if y_target == 1:
ax.plot(x[0], x[1], 'bo')
else:
ax.plot(x[0], x[1], 'go')
X1 = np.linspace(0, 1, num=10)
Z1 = np.zeros((len(X1), len(X1)))
# Contour map
for j in range(len(X1)):
for k in range(len(X1)):
# Fill Z with the labels (numerical values)
# the inner loop goes over the columns of Z,
# which corresponds to sweeping x-values
# Therefore, the role of j,k is flipped in the signature
Z1[j, k] = np.argmax(model_list[lr](Tensor([X1[k],X1[j],X1[k],X1[j]])).detach().numpy())
ax.contourf(X1, X1, Z1, cmap='bwr', levels=30)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import NormalDistribution
# can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example.
A = np.eye(2)
b = np.zeros(2)
# specify the number of qubits that are used to represent the different dimenions of the uncertainty model
num_qubits = [2, 2]
# specify the lower and upper bounds for the different dimension
low = [0, 0]
high = [0.12, 0.24]
mu = [0.12, 0.24]
sigma = 0.01 * np.eye(2)
# construct corresponding distribution
bounds = list(zip(low, high))
u = NormalDistribution(num_qubits, mu, sigma, bounds)
# plot contour of probability density function
x = np.linspace(low[0], high[0], 2 ** num_qubits[0])
y = np.linspace(low[1], high[1], 2 ** num_qubits[1])
z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1])
plt.contourf(x, y, z)
plt.xticks(x, size=15)
plt.yticks(y, size=15)
plt.grid()
plt.xlabel("$r_1$ (%)", size=15)
plt.ylabel("$r_2$ (%)", size=15)
plt.colorbar()
plt.show()
# specify cash flow
cf = [1.0, 2.0]
periods = range(1, len(cf) + 1)
# plot cash flow
plt.bar(periods, cf)
plt.xticks(periods, size=15)
plt.yticks(size=15)
plt.grid()
plt.xlabel("periods", size=15)
plt.ylabel("cashflow ($)", size=15)
plt.show()
# estimate real value
cnt = 0
exact_value = 0.0
for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])):
for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])):
prob = u.probabilities[cnt]
for t in range(len(cf)):
# evaluate linear approximation of real value w.r.t. interest rates
exact_value += prob * (
cf[t] / pow(1 + b[t], t + 1)
- (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2)
)
cnt += 1
print("Exact value: \t%.4f" % exact_value)
# specify approximation factor
c_approx = 0.125
# create fixed income pricing application
from qiskit_finance.applications.estimation import FixedIncomePricing
fixed_income = FixedIncomePricing(
num_qubits=num_qubits,
pca_matrix=A,
initial_interests=b,
cash_flow=cf,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=u,
)
fixed_income._objective.draw()
fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits)
# load probability distribution
fixed_income_circ.append(u, range(u.num_qubits))
# apply function
fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits))
fixed_income_circ.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
# construct amplitude estimation
problem = fixed_income.to_estimation_problem()
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (fixed_income.interpret(result)))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.library import QFT
def create_qpe_circuit(theta, num_qubits):
'''Creates a QPE circuit given theta and num_qubits.'''
# Step 1: Create a circuit with two quantum registers and one classical register.
first = QuantumRegister(size=num_qubits, name='first') # the first register for phase estimation
second = QuantumRegister(size=1, name='second') # the second register for storing eigenvector |psi>
classical = ClassicalRegister(size=num_qubits, name='readout') # classical register for readout
qpe_circuit = QuantumCircuit(first, second, classical)
# Step 2: Initialize the qubits.
# All qubits are initialized in |0> by default, no extra code is needed to initialize the first register.
qpe_circuit.x(second) # Initialize the second register with state |psi>, which is |1> in this example.
# Step 3: Create superposition in the first register.
qpe_circuit.barrier() # Add barriers to separate each step of the algorithm for better visualization.
qpe_circuit.h(first)
# Step 4: Apply a controlled-U^(2^j) black box.
qpe_circuit.barrier()
for j in range(num_qubits):
qpe_circuit.cp(theta*2*np.pi*(2**j), j, num_qubits) # Theta doesn't contain the 2 pi factor.
# Step 5: Apply an inverse QFT to the first register.
qpe_circuit.barrier()
qpe_circuit.compose(QFT(num_qubits, inverse=True), inplace=True)
# Step 6: Measure the first register.
qpe_circuit.barrier()
qpe_circuit.measure(first, classical)
return qpe_circuit
num_qubits = 4
qpe_circuit_fixed_phase = create_qpe_circuit(1/2, num_qubits) # Create a QPE circuit with fixed theta=1/2.
qpe_circuit_fixed_phase.draw('mpl')
from qiskit.circuit import Parameter
theta = Parameter('theta') # Create a parameter `theta` whose values can be assigned later.
qpe_circuit_parameterized = create_qpe_circuit(theta, num_qubits)
qpe_circuit_parameterized.draw('mpl')
number_of_phases = 21
phases = np.linspace(0, 2, number_of_phases)
individual_phases = [[ph] for ph in phases] # Phases need to be expressed as a list of lists.
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
results = Sampler().run(
[qpe_circuit_parameterized]*len(individual_phases),
parameter_values=individual_phases
).result()
from qiskit.tools.visualization import plot_histogram
idx = 6
plot_histogram(results.quasi_dists[idx].binary_probabilities(), legend=[f'$\\theta$={phases[idx]:.3f}'])
def most_likely_bitstring(results_dict):
'''Finds the most likely outcome bit string from a result dictionary.'''
return max(results_dict, key=results_dict.get)
def find_neighbors(bitstring):
'''Finds the neighbors of a bit string.
Example:
For bit string '1010', this function returns ('1001', '1011')
'''
if bitstring == len(bitstring)*'0':
neighbor_left = len(bitstring)*'1'
else:
neighbor_left = format((int(bitstring,2)-1), '0%sb'%len(bitstring))
if bitstring == len(bitstring)*'1':
neighbor_right = len(bitstring)*'0'
else:
neighbor_right = format((int(bitstring,2)+1), '0%sb'%len(bitstring))
return (neighbor_left, neighbor_right)
def estimate_phase(results_dict):
'''Estimates the phase from a result dictionary of a QPE circuit.'''
# Find the most likely outcome bit string N1 and its neighbors.
num_1_key = most_likely_bitstring(results_dict)
neighbor_left, neighbor_right = find_neighbors(num_1_key)
# Get probabilities of N1 and its neighbors.
num_1_prob = results_dict.get(num_1_key)
neighbor_left_prob = results_dict.get(neighbor_left)
neighbor_right_prob = results_dict.get(neighbor_right)
# Find the second most likely outcome N2 and its probability P2 among the neighbors.
if neighbor_left_prob is None:
# neighbor_left doesn't exist
if neighbor_right_prob is None:
# both neighbors don't exist, N2 is N1
num_2_key = num_1_key
num_2_prob = num_1_prob
else:
# If only neighbor_left doesn't exist, N2 is neighbor_right.
num_2_key = neighbor_right
num_2_prob = neighbor_right_prob
elif neighbor_right_prob is None:
# If only neighbor_right doesn't exist, N2 is neighbor_left.
num_2_key = neighbor_left
num_2_prob = neighbor_left_prob
elif neighbor_left_prob > neighbor_right_prob:
# Both neighbors exist and neighbor_left has higher probability, so N2 is neighbor_left.
num_2_key = neighbor_left
num_2_prob = neighbor_left_prob
else:
# Both neighbors exist and neighbor_right has higher probability, so N2 is neighor_right.
num_2_key = neighbor_right
num_2_prob = neighbor_right_prob
# Calculate the estimated phases for N1 and N2.
num_qubits = len(num_1_key)
num_1_phase = (int(num_1_key, 2) / 2**num_qubits)
num_2_phase = (int(num_2_key, 2) / 2**num_qubits)
# Calculate the weighted average phase from N1 and N2.
phase_estimated = (num_1_phase * num_1_prob + num_2_phase * num_2_prob) / (num_1_prob + num_2_prob)
return phase_estimated
qpe_solutions = []
for idx, result_dict in enumerate(results.quasi_dists):
qpe_solutions.append(estimate_phase(result_dict.binary_probabilities()))
ideal_solutions = np.append(
phases[:(number_of_phases-1)//2], # first period
np.subtract(phases[(number_of_phases-1)//2:-1], 1) # second period
)
ideal_solutions = np.append(ideal_solutions, np.subtract(phases[-1], 2)) # starting point of the third period
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 6))
plt.plot(phases, ideal_solutions, '--', label='Ideal solutions')
plt.plot(phases, qpe_solutions, 'o', label='QPE solutions')
plt.title('Quantum Phase Estimation Algorithm')
plt.xlabel('Input Phase')
plt.ylabel('Output Phase')
plt.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
|
PacktPublishing
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created Nov 2020, Updated March 2022
@author: hassi
"""
from qiskit import Aer, IBMQ
# Do the necessary import for our program
from qiskit.utils import QuantumInstance
from qiskit.algorithms import Grover, AmplificationProblem
from qiskit.circuit.library import PhaseOracle
# Import basic plot tools
from qiskit.tools.visualization import plot_histogram
from IPython.core.display import display
global oracle_method, oracle_type
def log_length(oracle_input):
from math import sqrt, pow, pi
filtered = [c.lower() for c in oracle_input if c.isalpha()]
result = len(filtered)
num_iterations=int(pi/4*(sqrt(pow(2,result))))
return num_iterations
def create_oracle(oracle_method):
oracle_text={"log":"~A & ~B & C"}
# set the input
global num_iterations
print("Enter the oracle input string, such as:"+oracle_text[oracle_method]+"\nor enter 'def' for a default string.")
oracle_input=input('\nOracle input:\n ')
if oracle_input=="def":
oracle_type=oracle_text[oracle_method]
else:
oracle_type = oracle_input
num_iterations=log_length(oracle_type)
print("Iterations: ", num_iterations)
return(oracle_type)
def run_grover(oracle_type, oracle_method, backend):
# Create and run the oracle on the selected backen
oracle = PhaseOracle(oracle_type)
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
algorithm = Grover(iterations=num_iterations, quantum_instance=QuantumInstance(backend, shots=1024))
# Display the results
result = algorithm.amplify(problem)
display(plot_histogram(result.circuit_results[0]))
print("Backend:",backend.name()+"\nResult:",result.top_measurement)
# Main loop
def main():
# set the oracle method: "Log" for logical expression
oracle_method="log"
while oracle_method!=0:
print("Ch 11: Grover search with Aqua")
print("------------------------------")
# Set the oracle type
oracle_type=create_oracle(oracle_method)
print("Oracle method:",oracle_method)
print("Oracle for:", oracle_type)
# Run on a simulator
backend = Aer.get_backend('qasm_simulator')
run_grover(oracle_type, oracle_method, backend)
# Run the algorithm on an IBM Quantum backend
print("Getting provider...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(n_qubits=5, operational=True, simulator=False))
run_grover(oracle_type, oracle_method, backend)
if __name__ == '__main__':
main()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
qreg = QuantumRegister(4) # quantum register with 4 qubits
creg = ClassicalRegister(4) # classical register with 4 bits
mycircuit = QuantumCircuit(qreg,creg) # quantum circuit with quantum and classical registers
# apply h-gate (Hadamard) to each qubit
for i in range(4):
mycircuit.h(qreg[i])
# measure both qubits
mycircuit.measure(qreg,creg)
# execute the circuit 1600 times, and print the outcomes
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1600)
counts = job.result().get_counts(mycircuit)
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts[outcome],"times")
# find the angle theta
u2 = [(13/16)**0.5,(3/16)**0.5]
print(u2)
from math import acos # acos is the inverse of function cosine
from math import pi
def angle_between_two_quantum_states(quantum_state1,quantum_state2):
inner_product = quantum_state1[0] * quantum_state2[0] + quantum_state1[1] * quantum_state2[1]
return acos(inner_product)
# angle between |u> and |0>
theta2 = angle_between_two_quantum_states(u2,[1,0])
print(theta2)
# COPY-PASTE the functions from the notebook "B80_Reflections"
def amplitudes_of_a_quantum_state(quantum_circuit):
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# the following code is used to get the quantum state of a quantum circuit
job = execute(quantum_circuit,Aer.get_backend('statevector_simulator'))
current_quantum_state=job.result().get_statevector(quantum_circuit)
# now we read the real parts of the amplitudes
the_first_amplitude = current_quantum_state[0].real # amplitude of |0>
the_second_amplitude = current_quantum_state[1].real # amplitude of |1>
return[the_first_amplitude,the_second_amplitude]
# end of function
def visualize_quantum_states(quantum_states):
# import the useful tool for drawing figures in pythpn
from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text
# import the constant pi
from math import pi
figure(figsize=(6,6), dpi=80) # size of the figure
gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle
# auxiliary points
plot(-1.3,0)
plot(1.3,0)
plot(0,1.3)
plot(0,-1.3)
# axes
arrow(0,0,1.1,0,head_width=0.04, head_length=0.08)
arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08)
arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08)
arrow(0,0,0,1.1,head_width=0.04, head_length=0.08)
# draw all quantum states
for quantum_state in quantum_states:
# show the quantum state as an arrow on the diagram
state_name = quantum_state[0] # label of the quantum state
x_value = quantum_state[1] # amplitude of |0>
y_value = quantum_state[2] # amplitude of |1>
# draw the arrow
arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.04,color='blue')
# the following code is used to write the name of quantum states
if x_value<0: text_x_value=x_value-0.1
else: text_x_value=x_value+0.05
if y_value<0: text_y_value=y_value-0.1
else: text_y_value=y_value+0.05
text(text_x_value,text_y_value,state_name)
show() # show the diagram
# end of function
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
all_visited_quantum_states2 =[]
qreg2 = QuantumRegister(1) # quantum register with 1 qubit
creg2 = ClassicalRegister(1) # classical register with 1 bit
mycircuit2 = QuantumCircuit(qreg2,creg2) # quantum circuit with quantum and classical registers
# set the qubit to |u>
# rotate by theta2
# do not forget to multiply it by 2
mycircuit2.ry(2*theta2,qreg2[0])
# read and store the current quantum state
[x,y] = amplitudes_of_a_quantum_state(mycircuit2)
all_visited_quantum_states2.append(['u',x,y])
# this is (-2*theta2) in the first iteration
rotation_angle_for_the_first_reflection2 = -2 * theta2
# this is always (2*theta2) more than (-1*rotation_angle_for_the_first_reflection2)
rotation_angle_for_the_second_reflection2 = (2*theta2) + (-1*rotation_angle_for_the_first_reflection2)
# the first reflection: rotate by rotation_angle_for_the_first_reflection2
mycircuit2.ry(2*rotation_angle_for_the_first_reflection2,qreg2[0])
# read and store the current quantum state
[x,y] = amplitudes_of_a_quantum_state(mycircuit2)
all_visited_quantum_states2.append(['r',x,y]) # the label is r (reflected state)
# the second reflection: rotate by rotation_angle_for_the_second_reflection2
mycircuit2.ry(2*rotation_angle_for_the_second_reflection2,qreg2[0])
# read and store the current quantum state
[x,y] = amplitudes_of_a_quantum_state(mycircuit2)
all_visited_quantum_states2.append(['n',x,y]) # the label is n (new state)
visualize_quantum_states(all_visited_quantum_states2)
# measure both qubits
mycircuit2.measure(qreg2,creg2)
# execute the circuit 100 times, and print the outcomes
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=100)
counts2 = job.result().get_counts(mycircuit2)
for outcome in counts2:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts2[outcome],"times")
print(all_visited_quantum_states2)
# find the angle theta
u3 = [(63/64)**0.5,(1/64)**0.5]
print(u3)
from math import acos # acos is the inverse of function cosine
from math import pi
def angle_between_two_quantum_states(quantum_state1,quantum_state2):
inner_product = quantum_state1[0] * quantum_state2[0] + quantum_state1[1] * quantum_state2[1]
return acos(inner_product)
# angle between |u> and |0>
theta3 = angle_between_two_quantum_states(u3,[1,0])
print(theta3)
# COPY-PASTE the functions from the notebook "B80_Reflections"
def amplitudes_of_a_quantum_state(quantum_circuit):
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# the following code is used to get the quantum state of a quantum circuit
job = execute(quantum_circuit,Aer.get_backend('statevector_simulator'))
current_quantum_state=job.result().get_statevector(quantum_circuit)
# now we read the real parts of the amplitudes
the_first_amplitude = current_quantum_state[0].real # amplitude of |0>
the_second_amplitude = current_quantum_state[1].real # amplitude of |1>
return[the_first_amplitude,the_second_amplitude]
# end of function
def visualize_quantum_states(quantum_states):
# import the useful tool for drawing figures in pythpn
from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text
# import the constant pi
from math import pi
figure(figsize=(6,6), dpi=80) # size of the figure
gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle
# auxiliary points
plot(-1.3,0)
plot(1.3,0)
plot(0,1.3)
plot(0,-1.3)
# axes
arrow(0,0,1.1,0,head_width=0.04, head_length=0.08)
arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08)
arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08)
arrow(0,0,0,1.1,head_width=0.04, head_length=0.08)
# draw all quantum states
for quantum_state in quantum_states:
# show the quantum state as an arrow on the diagram
state_name = quantum_state[0] # label of the quantum state
x_value = quantum_state[1] # amplitude of |0>
y_value = quantum_state[2] # amplitude of |1>
# draw the arrow
arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.04,color='blue')
# the following code is used to write the name of quantum states
if x_value<0: text_x_value=x_value-0.1
else: text_x_value=x_value+0.05
if y_value<0: text_y_value=y_value-0.1
else: text_y_value=y_value+0.05
text(text_x_value,text_y_value,state_name)
show() # show the diagram
# end of function
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
all_visited_quantum_states3 =[]
qreg3 = QuantumRegister(1) # quantum register with 1 qubit
creg3 = ClassicalRegister(1) # classical register with 1 bit
mycircuit3 = QuantumCircuit(qreg3,creg3) # quantum circuit with quantum and classical registers
# set the qubit to |u>
# rotate by theta3
# do not forget to multiply it by 2
mycircuit3.ry(2*theta3,qreg3[0])
# read and store the current quantum state
[x,y] = amplitudes_of_a_quantum_state(mycircuit3)
all_visited_quantum_states3.append(['u',x,y])
# this is -2 * theta3 in the first iteration
rotation_angle_for_the_first_reflection3 = -2 * theta3
# this is always (2*theta3) more than (-1*rotation_angle_for_the_first_reflection3)
rotation_angle_for_the_second_reflection3 = (2*theta3) + (-1*rotation_angle_for_the_first_reflection3)
for i in range(3): # three iterations # later check 4, 5, 6, 7, 8, 9, and 10
# the first reflection: rotate by rotation_angle_for_the_first_reflection3
mycircuit3.ry(2*rotation_angle_for_the_first_reflection3,qreg3[0])
# read and store the current quantum state
[x,y] = amplitudes_of_a_quantum_state(mycircuit3)
all_visited_quantum_states3.append(['r'+str(i+1),x,y]) # the labels are r1, r2, ... (reflected states)
# the second reflection: rotate by rotation_angle_for_the_second_reflection3
mycircuit3.ry(2*rotation_angle_for_the_second_reflection3,qreg3[0])
# read and store the current quantum state
[x,y] = amplitudes_of_a_quantum_state(mycircuit3)
all_visited_quantum_states3.append(['n'+str(i+1),x,y]) # the labels are n1, n2, ... (new states)
# this will be increased by (-4*theta2) after each iteration
rotation_angle_for_the_first_reflection3 = rotation_angle_for_the_first_reflection3 -4* theta3
# this is always (2*theta2) more than (-1*rotation_angle_for_the_first_reflection3)
rotation_angle_for_the_second_reflection3 = (2*theta3) + (-1*rotation_angle_for_the_first_reflection3)
# end of iterations
visualize_quantum_states(all_visited_quantum_states3)
# measure both qubits
mycircuit3.measure(qreg3,creg3)
# execute the circuit 100 times, and print the outcomes
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=100)
counts3 = job.result().get_counts(mycircuit3)
for outcome in counts3:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts3[outcome],"times")
print(all_visited_quantum_states3)
# find the angle theta
# k=8, 2^k = 256
u4 = [(255/256)**0.5,(1/256)**0.5]
print(u4)
from math import acos # acos is the inverse of function cosine
from math import pi
def angle_between_two_quantum_states(quantum_state1,quantum_state2):
inner_product = quantum_state1[0] * quantum_state2[0] + quantum_state1[1] * quantum_state2[1]
return acos(inner_product)
# angle between |u> and |0>
theta4 = angle_between_two_quantum_states(u4,[1,0])
print(theta4)
# COPY-PASTE the functions from the notebook "B80_Reflections"
def amplitudes_of_a_quantum_state(quantum_circuit):
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# the following code is used to get the quantum state of a quantum circuit
job = execute(quantum_circuit,Aer.get_backend('statevector_simulator'))
current_quantum_state=job.result().get_statevector(quantum_circuit)
# now we read the real parts of the amplitudes
the_first_amplitude = current_quantum_state[0].real # amplitude of |0>
the_second_amplitude = current_quantum_state[1].real # amplitude of |1>
return[the_first_amplitude,the_second_amplitude]
# end of function
def visualize_quantum_states(quantum_states):
# import the useful tool for drawing figures in pythpn
from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text
# import the constant pi
from math import pi
figure(figsize=(6,6), dpi=80) # size of the figure
gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle
# auxiliary points
plot(-1.3,0)
plot(1.3,0)
plot(0,1.3)
plot(0,-1.3)
# axes
arrow(0,0,1.1,0,head_width=0.04, head_length=0.08)
arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08)
arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08)
arrow(0,0,0,1.1,head_width=0.04, head_length=0.08)
# draw all quantum states
for quantum_state in quantum_states:
# show the quantum state as an arrow on the diagram
state_name = quantum_state[0] # label of the quantum state
x_value = quantum_state[1] # amplitude of |0>
y_value = quantum_state[2] # amplitude of |1>
# draw the arrow
arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.04,color='blue')
# the following code is used to write the name of quantum states
if x_value<0: text_x_value=x_value-0.1
else: text_x_value=x_value+0.05
if y_value<0: text_y_value=y_value-0.1
else: text_y_value=y_value+0.05
text(text_x_value,text_y_value,state_name)
show() # show the diagram
# end of function
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
how_many_times_state_one_observed = 0
decrease = False
number_of_iteration = 1
while decrease == False:
qreg4 = QuantumRegister(1) # quantum register with 1 qubit
creg4 = ClassicalRegister(1) # classical register with 1 bit
mycircuit4 = QuantumCircuit(qreg4,creg4) # quantum circuit with quantum and classical registers
# set the qubit to |u>
# rotate by theta4
# do not forget to multiply it by 2
mycircuit4.ry(2*theta4,qreg4[0])
# this is -2 * theta4 in the first iteration
rotation_angle_for_the_first_reflection4 = -2 * theta4
# this is always (2*theta4) more than (-1*rotation_angle_for_the_first_reflection4)
rotation_angle_for_the_second_reflection4 = (2*theta4) + (-1*rotation_angle_for_the_first_reflection4)
for i in range(number_of_iteration):
# the first reflection: rotate by rotation_angle_for_the_first_reflection4
mycircuit4.ry(2*rotation_angle_for_the_first_reflection4,qreg4[0])
# the second reflection: rotate by rotation_angle_for_the_second_reflcetion4
mycircuit4.ry(2*rotation_angle_for_the_second_reflection4,qreg4[0])
# this will be increased by (-4*theta4) after each iteration
rotation_angle_for_the_first_reflection4 = rotation_angle_for_the_first_reflection4 -4* theta4
# this is always (2*theta4) more than (-1*rotation_angle_for_the_first_reflection4)
rotation_angle_for_the_second_reflection4 = (2*theta4) + (-1*rotation_angle_for_the_first_reflection4)
# end of iterations
# measure both qubits
mycircuit4.measure(qreg4,creg4)
# execute the circuit 1000 times, and print the outcomes
job = execute(mycircuit4,Aer.get_backend('qasm_simulator'),shots=1000)
counts4 = job.result().get_counts(mycircuit4)
print(number_of_iteration,counts4) # print the outcomes
for outcome in counts4:
if outcome == '1':
# how_many_times_state_one_observed is more than 500 and has a less value than the previous one
# then it is time to STOP
if how_many_times_state_one_observed> 500 and how_many_times_state_one_observed > counts4[outcome]:
print("B is",number_of_iteration-1)
decrease = True
else: # we should continue
how_many_times_state_one_observed = counts4[outcome] # update how_many_times_state_one_observed
number_of_iteration = number_of_iteration + 1 # increase number_of_iteration
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" Spin gate tests."""
import numpy as np
from scipy.linalg import expm
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit
from qiskit_nature.second_q.operators import SpinOp
from qiskit_cold_atom.spins.spin_circuit_solver import SpinCircuitSolver
from qiskit_cold_atom.spins import SpinSimulator
from qiskit_cold_atom.spins.spins_gate_library import (
RLXGate,
RLYGate,
RLZGate,
RLZ2Gate,
RLXLYGate,
RydbergBlockade,
RydbergFull,
)
class TestSpinGates(QiskitTestCase):
"""Tests for the spin hardware gates"""
def setUp(self):
super().setUp()
self.backend = SpinSimulator()
self.spin = 3 / 2
self.solver = SpinCircuitSolver(spin=self.spin)
def test_lx_gate(self):
"""check matrix form of the lx gate"""
omega = np.pi / 2
circ = QuantumCircuit(1)
circ.append(RLXGate(omega), qargs=[0])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(1)
circ_decorated.rlx(omega, 0)
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit, spin=self.spin).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
expm(
-1j
* omega
* np.array(
[
[0.0, np.sqrt(3) / 2, 0, 0],
[np.sqrt(3) / 2, 0, 1, 0],
[0, 1, 0, np.sqrt(3) / 2],
[0, 0, np.sqrt(3) / 2, 0],
]
)
),
)
)
def test_lxly_gate(self):
"""check matrix form of the lxly gate"""
omega = np.pi
circ = QuantumCircuit(2)
circ.append(RLXLYGate(omega), qargs=[0, 1])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(2)
circ_decorated.rlxly(omega, [0, 1])
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit, spin=1 / 2).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
[
[1, 0, 0, 0],
[0, 0, -1j, 0],
[0, -1j, 0, 0],
[0, 0, 0, 1],
],
)
)
def test_ly_gate(self):
"""check matrix form of the ly gate"""
omega = np.pi / 2
circ = QuantumCircuit(1)
circ.append(RLYGate(omega), qargs=[0])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(1)
circ_decorated.rly(omega, 0)
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit, spin=self.spin).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
expm(
-1j
* omega
* np.array(
[
[0.0, -1j * np.sqrt(3) / 2, 0, 0],
[1j * np.sqrt(3) / 2, 0, -1j, 0],
[0, 1j, 0, -1j * np.sqrt(3) / 2],
[0, 0, 1j * np.sqrt(3) / 2, 0],
]
)
),
)
)
def test_lz_gate(self):
"""check matrix form of the lz gate"""
delta = np.pi / 2
circ = QuantumCircuit(1)
circ.append(RLZGate(delta), qargs=[0])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(1)
circ_decorated.rlz(delta, 0)
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit, spin=self.spin).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
expm(
-1j
* delta
* np.array(
[
[3 / 2, 0, 0, 0],
[0, 1 / 2, 0, 0],
[0, 0, -1 / 2, 0],
[0, 0, 0, -3 / 2],
]
)
),
)
)
def test_lz2_gate(self):
"""check matrix form of the lz2 gate"""
chi = np.pi / 2
circ = QuantumCircuit(1)
circ.append(RLZ2Gate(chi), qargs=[0])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(1)
circ_decorated.rlz2(chi, 0)
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit, spin=self.spin).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
expm(
-1j
* chi
* np.array(
[
[3 / 2, 0, 0, 0],
[0, 1 / 2, 0, 0],
[0, 0, -1 / 2, 0],
[0, 0, 0, -3 / 2],
]
)
** 2
),
)
)
def test_rydberg_block_gate(self):
"""check matrix form of the rydberg blockade gate on two qubits"""
chi = 2 * np.pi
# the expected unitary is the following
expected = np.exp(1j * np.pi / 2) * expm(
-1j
* chi
* np.array(
[
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 1],
]
)
)
# first test the RydbergBlockade only
with self.subTest("test generation of operator"):
from qiskit.quantum_info import Operator
self.assertTrue(np.allclose(Operator(RydbergBlockade(2, phi=chi)).data, expected))
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(2)
circ_decorated.rydberg_block(chi, [0, 1])
unitary = self.backend.run(circ_decorated).result().get_unitary()
self.assertTrue(np.allclose(unitary, expected))
def test_rydberg_full_gate(self):
"""check matrix form of the full rydberg Hamiltonian on two qubits"""
chi = 2 * np.pi
circ = QuantumCircuit(2)
circ.append(RydbergFull(2, omega=0, delta=0, phi=chi), qargs=[0, 1])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(2)
circ_decorated.rydberg_full(omega=0, delta=0, phi=chi, modes=range(2))
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
np.exp(1j * np.pi / 2)
* expm(
-1j
* chi
* np.array(
[
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 1],
]
)
),
)
)
# also test the sigma gates
circ = QuantumCircuit(2)
circ.append(RydbergFull(2, omega=np.pi, delta=0, phi=0), qargs=[0, 1])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(2)
circ_decorated.rydberg_full(omega=np.pi, delta=0, phi=0, modes=range(2))
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
expm(
-1j
* np.pi
/ 2
* np.array(
[
[0, 1, 1, 0],
[1, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 1, 0],
]
)
),
)
)
# also test the sigmaz gates
circ = QuantumCircuit(2)
circ.append(RydbergFull(2, omega=0, delta=np.pi, phi=0), qargs=[0, 1])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(2)
circ_decorated.rydberg_full(omega=0, delta=np.pi, phi=0, modes=range(2))
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
expm(
-1j
* np.pi
/ 2
* np.array(
[
[-2, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 2],
]
)
),
)
)
def test_spin_gate(self):
"""test the functionality of the base class for fermionic gates"""
test_gates = [RLXGate(0.8), RLYGate(2.4), RLZGate(5.6), RLZ2Gate(1.3)]
with self.subTest("test to_matrix and power"):
for gate in test_gates:
exp_matrix = gate.to_matrix() @ gate.to_matrix()
exp_gate = gate.power(2)
self.assertTrue(np.allclose(exp_matrix, exp_gate.to_matrix()))
with self.subTest("test generation of operator"):
from qiskit.quantum_info import Operator
for gate in test_gates:
self.assertTrue(isinstance(Operator(gate), Operator))
def test_identity_gates(self):
"""test that gates with parameters equal to zero still have a well-defined generator."""
test_gates = [RLXGate(0.0), RLYGate(0.0), RLZGate(0.0), RLZ2Gate(0.0)]
for gate in test_gates:
self.assertIsInstance(gate.generator, SpinOp)
|
https://github.com/JamesTheZhang/Qiskit2023
|
JamesTheZhang
|
########################################
# ENTER YOUR NAME AND WISC EMAIL HERE: #
########################################
# Name: Rochelle Li
# Email: rli484@wisc.edu
## Run this cell to make sure your grader is setup correctly
%set_env QC_GRADE_ONLY=true
%set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, 3)
## Write your code below this line ##
qc.h(0)
qc.h(2)
qc.cx(0,1)
## Do not change the code below here ##
answer1 = qc
qc.draw()
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2a
grade_ex2a(answer1)
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, 3)
qc.barrier(0, 1, 2)
## Write your code below this line ##
qc.cx(1,2)
qc.x(2)
qc.cx(2,0)
qc.x(2)
## Do not change the code below this line ##
answer2 = qc
qc.draw()
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2b
grade_ex2b(answer2)
answer3: bool
## Quiz: evaluate the results and decide if the following statement is True or False
q0 = 1
q1 = 0
q2 = 1
## Based on this, is it TRUE or FALSE that the Guard on the left is a liar?
## Assign your answer, either True or False, to answer3 below
answer3 = True
from qc_grader.challenges.fall_fest23 import grade_ex2c
grade_ex2c(answer3)
## Quiz: Fill in the correct numbers to make the following statement true:
## The treasure is on the right, and the Guard on the left is the liar
q0 = 0
q1 = 1
q2 = 1
## HINT - Remember that Qiskit uses little-endian ordering
answer4 = [q0, q1, q2]
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2d
grade_ex2d(answer4)
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
## in the code below, fill in the missing gates. Run the cell to see a drawing of the current circuit ##
qc.h(0)
qc.h(2)
qc.cx(0,1)
qc.barrier(0, 1, 2)
qc.cx(2, 1)
qc.x(2)
qc.cx(2, 0)
qc.x(2)
qc.barrier(0, 1, 2)
qc.swap(0,1)
qc.x(0)
qc.x(1)
qc.cx(2,1)
qc.x(2)
qc.cx(2,0)
qc.x(2)
## Do not change any of the code below this line ##
answer5 = qc
qc.draw(output="mpl")
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2e
grade_ex2e(answer5)
from qiskit import QuantumCircuit, Aer, transpile
from qiskit.visualization import plot_histogram
## This is the full version of the circuit. Run it to see the results ##
quantCirc = QuantumCircuit(3)
quantCirc.h(0), quantCirc.h(2), quantCirc.cx(0, 1), quantCirc.barrier(0, 1, 2), quantCirc.cx(2, 1), quantCirc.x(2), quantCirc.cx(2, 0), quantCirc.x(2)
quantCirc.barrier(0, 1, 2), quantCirc.swap(0, 1), quantCirc.x(1), quantCirc.cx(2, 1), quantCirc.x(0), quantCirc.x(2), quantCirc.cx(2, 0), quantCirc.x(2)
# Execute the circuit and draw the histogram
measured_qc = quantCirc.measure_all(inplace=False)
backend = Aer.get_backend('qasm_simulator') # the device to run on
result = backend.run(transpile(measured_qc, backend), shots=1000).result()
counts = result.get_counts(measured_qc)
plot_histogram(counts)
from qiskit.primitives import Sampler
from qiskit.visualization import plot_distribution
sampler = Sampler()
result = sampler.run(measured_qc, shots=1000).result()
probs = result.quasi_dists[0].binary_probabilities()
plot_distribution(probs)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(3, 'q')
anc = QuantumRegister(1, 'ancilla')
cr = ClassicalRegister(3, 'c')
qc = QuantumCircuit(qr, anc, cr)
qc.x(anc[0])
qc.h(anc[0])
qc.h(qr[0:3])
qc.cx(qr[0:3], anc[0])
qc.h(qr[0:3])
qc.barrier(qr)
qc.measure(qr, cr)
qc.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver()
problem = driver.run()
print(problem)
from qiskit_nature.second_q.problems import ElectronicBasis
driver.run_pyscf()
problem = driver.to_problem(basis=ElectronicBasis.MO, include_dipole=True)
print(problem.basis)
ao_problem = driver.to_problem(basis=ElectronicBasis.AO)
print(ao_problem.basis)
from qiskit_nature.second_q.formats.qcschema_translator import qcschema_to_problem
qcschema = driver.to_qcschema()
ao_problem = qcschema_to_problem(qcschema, basis=ElectronicBasis.AO)
from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema
basis_transformer = get_ao_to_mo_from_qcschema(qcschema)
mo_problem = basis_transformer.transform(ao_problem)
print(mo_problem.basis)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
from sympy import *
init_printing(use_unicode=True)
%matplotlib inline
p00,p01,p10,p11 = symbols('p_{00} p_{01} p_{10} p_{11}')
th,ph = symbols('theta phi')
Psi00 = Matrix([[cos(th)],[0],[0],[sin(th)]])
Psi01 = Matrix([[0],[sin(ph)],[cos(ph)],[0]])
Psi11 = Matrix([[0],[cos(ph)],[-sin(ph)],[0]])
Psi10 = Matrix([[-sin(th)],[0],[0],[cos(th)]])
#Psi00, Psi00.T, Psi00*Psi00.T
rhoX = p00*Psi00*Psi00.T + p01*Psi01*Psi01.T + p10*Psi10*Psi10.T + p11*Psi11*Psi11.T
simplify(rhoX)
def kp(x,y):
return KroneckerProduct(x,y)
I = Matrix([[1,0],[0,1]])
Y = Matrix([[0,-1j],[1j,0]])
Y = Matrix([[0,1],[1,0]])
Z = Matrix([[1,0],[0,-1]])
cxx,cyy,czz,az,bz = symbols('c_{xx} c_{yy} c_{zz} a_{z} b_{z}')
rhoX = (1/4)*(kp(I,I) + cxx*kp(X,X) + cyy*kp(Y,Y) + czz*kp(Z,Z) + az*kp(Z,I) + bz*kp(I,Z))
simplify(rhoX)
th,be,ga = symbols('theta beta gamma')
c00 = cos(th/2)*cos(be/2)*cos(ga/2) + sin(th/2)*sin(be/2)*sin(ga/2)
c01 = cos(th/2)*cos(be/2)*sin(ga/2) - sin(th/2)*sin(be/2)*cos(ga/2)
c10 = cos(th/2)*sin(be/2)*cos(ga/2) - sin(th/2)*cos(be/2)*sin(ga/2)
c11 = cos(th/2)*sin(be/2)*sin(ga/2) + sin(th/2)*cos(be/2)*cos(ga/2)
simplify(c00**2 + c01**2 + c10**2 + c11**2) # ok!
P0 = Matrix([[1,0],[0,0]])
P1 = Matrix([[0,0],[0,1]])
def Ry(th):
return cos(th/2)*I - 1j*sin(th/2)*Y
def Cx_ab():
return KroneckerProduct(P0,I) + KroneckerProduct(P1,X)
def Cx_ba():
return KroneckerProduct(I,P0) + KroneckerProduct(X,P1)
MB = Cx_ab()*KroneckerProduct(Ry(th-ph),I)*Cx_ba()*KroneckerProduct(Ry(th+ph),I) # mudanca de base
simplify(MB)
from qiskit import *
import numpy as np
import math
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# retorna o circuito quantico que prepara um certo estado real de 1 qubit
# coef = array com os 2 coeficientes reais do estado na base computacional
def qc_psi_1qb_real(coef):
qr = QuantumRegister(1)
qc = QuantumCircuit(qr, name='psir_1qb')
th = 2*math.acos(np.abs(coef[0]))
qc.ry(th, qr[0])
return qc
eigvals = [0.1,0.9]
coef = np.sqrt(eigvals)
print(coef)
qc_psi_1qb_real_ = qc_psi_1qb_real(coef)
qc_psi_1qb_real_.draw('mpl')
from qiskit.quantum_info import Statevector
sv = Statevector.from_label('0')
sv
sv = sv.evolve(qc_psi_1qb_real_)
sv
# retorna o circuito quantico que prepara um certo estado real de 2 qubits
# coef = array com os 4 coeficientes reais do estado na base computacional
def qc_psi_2qb_real(coef):
qr = QuantumRegister(2)
qc = QuantumCircuit(qr, name = 'psir_2qb')
xi = 2*math.acos(math.sqrt(coef[0]**2+coef[1]**2))
coef1 = [math.sqrt(coef[0]**2+coef[1]**2),math.sqrt(1-coef[0]**2-coef[1]**2)]
c_psi_1qb_real_ = qc_psi_1qb_real(coef1)
qc.append(c_psi_1qb_real_, [qr[0]])
th0 = 2*math.atan(np.abs(coef[1])/np.abs(coef[0]))
th1 = 2*math.atan(np.abs(coef[3])/np.abs(coef[2]))
qc.x(0)
qc.cry(th0, 0, 1)
qc.x(0)
qc.cry(th1, 0, 1)
return qc
eigvals = [0.1, 0.2, 0.3, 0.4]
coef = np.sqrt(eigvals)
print(coef)
qc_psi_2qb_real_ = qc_psi_2qb_real(coef)
qc_psi_2qb_real_.draw('mpl')
sv = Statevector.from_label('00')
sv
sv = sv.evolve(qc_psi_2qb_real_)
sv # note o ordenamento, o 2º qb é o 1º e o 1º é o 2º (00,10,01,11)
def qc_ry(th):
qr = QuantumRegister(1)
qc = QuantumCircuit(qr, name = 'RY')
qc.ry(th, 0)
return qc
# retorna o circuito quantico que prepara um certo estado real de 3 qubits
# coef = array com os 8 coeficientes reais do estado na base computacional
def qc_psi_3qb_real(coef):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr, name = 'psir_3qb')
d = len(coef)
coef2 = np.zeros(d//2)
th = np.zeros(d//2)
for j in range(0,2):
for k in range(0,2):
coef2[int(str(j)+str(k),2)] = math.sqrt(coef[int(str(j)+str(k)+str(0),2)]**2+coef[int(str(j)+str(k)+str(1),2)]**2)
c_psi_2qb_real_ = qc_psi_2qb_real(coef2)
qc.append(c_psi_2qb_real_, [qr[0],qr[1]])
for j in range(0,2):
for k in range(0,2):
th[int(str(j)+str(k),2)] = 2*math.atan(np.abs(coef[int(str(j)+str(k)+str(1),2)])/np.abs(coef[int(str(j)+str(k)+str(0),2)]))
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
qc_ry_ = qc_ry(th[int(str(j)+str(k),2)])
ccry = qc_ry_.to_gate().control(2)
qc.append(ccry, [0,1,2])
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
return qc
list_bin = []
for j in range(0,2**3):
b = "{:03b}".format(j)
list_bin.append(b)
print(list_bin)
eigvals = [0.01,0.1,0.04,0.2,0.05,0.3,0.18,0.12]
coef = np.sqrt(eigvals)
print(coef)
qc_psi_3qb_real_ = qc_psi_3qb_real(coef)
qc_psi_3qb_real_.draw('mpl') # odernamento: '000', '001', '010', '011', '100', '101', '110', '111'
sv = Statevector.from_label('000')
sv
sv = sv.evolve(qc_psi_3qb_real_)
sv # ordenamento aqui: 000 100 010 110 001 101 011 111
# retorna o circuito quantico que prepara um certo estado real de 4 qubits
# coef = array com os 16 coeficientes reais do estado na base computacional
def qc_psi_4qb_real(coef):
qr = QuantumRegister(4)
qc = QuantumCircuit(qr, name = 'psir_4qb')
d = len(coef)
coef3 = np.zeros(d//2)
th = np.zeros(d//2)
for j in range(0,2):
for k in range(0,2):
for l in range(0,2):
coef3[int(str(j)+str(k)+str(l),2)] = math.sqrt(coef[int(str(j)+str(k)+str(l)+str(0),2)]**2+coef[int(str(j)+str(k)+str(l)+str(1),2)]**2)
c_psi_3qb_real_ = qc_psi_3qb_real(coef3)
qc.append(c_psi_3qb_real_, [qr[0],qr[1],qr[2]])
for j in range(0,2):
for k in range(0,2):
for l in range(0,2):
th[int(str(j)+str(k)+str(l),2)] = 2*math.atan(np.abs(coef[int(str(j)+str(k)+str(l)+str(1),2)])/np.abs(coef[int(str(j)+str(k)+str(l)+str(0),2)]))
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
if l == 0:
qc.x(2)
qc_ry_ = qc_ry(th[int(str(j)+str(k)+str(l),2)])
ccry = qc_ry_.to_gate().control(3)
qc.append(ccry, [0,1,2,3])
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
if l == 0:
qc.x(2)
return qc
list_bin = []
for j in range(0,2**4):
b = "{:04b}".format(j)
list_bin.append(b)
print(list_bin)
eigvals = np.zeros(2**4)
eigvals[0] = 0.008
for j in range(1,len(eigvals)-1):
eigvals[j] = eigvals[j-1]+0.005
#print(np.sum(eigvals))
eigvals[j+1] = 1 - np.sum(eigvals)
#print(eigvals)
#print(np.sum(eigvals))
coef = np.sqrt(eigvals)
print(coef)
qc_psi_4qb_real_ = qc_psi_4qb_real(coef)
qc_psi_4qb_real_.draw('mpl')
# '0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111'
sv = Statevector.from_label('0000')
sv
sv = sv.evolve(qc_psi_4qb_real_)
sv # ordenamento aqui: 0000 1000 0100 1100 0010 1010 0110 1110 0001 1001 0101 1101 0011 1011 0111 1111
sv[1]
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford, random_clifford
qc = QuantumCircuit(3)
cliff = random_clifford(2)
qc.append(cliff, [0, 1])
qc.ccx(0, 1, 2)
qc.draw('mpl')
|
https://github.com/Juan-Varela11/BNL_2020_Summer_Internship
|
Juan-Varela11
|
import numpy as np
from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.quantum_info.operators import Kraus, SuperOp
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.visualization import plot_histogram
# Qiskit Aer noise module imports
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import QuantumError, ReadoutError
from qiskit.providers.aer.noise.errors import pauli_error
from qiskit.providers.aer.noise.errors import depolarizing_error
from qiskit.providers.aer.noise.errors import thermal_relaxation_error
# Construct a 1-qubit bit-flip and phase-flip errors
p_error = 0.05
bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)])
phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)])
print(bit_flip)
print(phase_flip)
# Compose two bit-flip and phase-flip errors
bitphase_flip = bit_flip.compose(phase_flip)
print(bitphase_flip)
# Tensor product two bit-flip and phase-flip errors with
# bit-flip on qubit-0, phase-flip on qubit-1
error2 = phase_flip.tensor(bit_flip)
print(error2)
# Convert to Kraus operator
bit_flip_kraus = Kraus(bit_flip)
print(bit_flip_kraus)
# Convert to Superoperator
phase_flip_sop = SuperOp(phase_flip)
print(phase_flip_sop)
# Convert back to a quantum error
print(QuantumError(bit_flip_kraus))
# Check conversion is equivalent to original error
QuantumError(bit_flip_kraus) == bit_flip
# Measurement miss-assignement probabilities
p0given1 = 0.1
p1given0 = 0.05
ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]])
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates
error = depolarizing_error(0.05, 1)
noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3'])
# Print noise model info
print(noise_model)
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only
error = depolarizing_error(0.05, 1)
noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0])
# Print noise model info
print(noise_model)
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error on qubit 2 forall single qubit u1, u2, u3 gates on qubit 0
error = depolarizing_error(0.05, 1)
noise_model.add_nonlocal_quantum_error(error, ['u1', 'u2', 'u3'], [0], [2])
# Print noise model info
print(noise_model)
# Simulator
simulator = QasmSimulator()
# System Specification
n_qubits = 4
circ = QuantumCircuit(n_qubits, n_qubits)
# Test Circuit
circ.h(0)
for qubit in range(n_qubits - 1):
circ.cx(qubit, qubit + 1)
circ.measure(range(4), range(4))
print(circ)
# Ideal execution
job = execute(circ, simulator)
result_ideal = job.result()
plot_histogram(result_ideal.get_counts(0))
# Example error probabilities
p_reset = 0.03
p_meas = 0.1
p_gate1 = 0.05
# QuantumError objects
error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)])
error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)])
error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)])
error_gate2 = error_gate1.tensor(error_gate1)
# Add errors to noise model
noise_bit_flip = NoiseModel()
noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset")
noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure")
noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"])
noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"])
print(noise_bit_flip)
# Run the noisy simulation
job = execute(circ, simulator,
basis_gates=noise_bit_flip.basis_gates,
noise_model=noise_bit_flip)
result_bit_flip = job.result()
counts_bit_flip = result_bit_flip.get_counts(0)
# Plot noisy output
plot_histogram(counts_bit_flip)
# T1 and T2 values for qubits 0-3
T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
# Truncate random T2s <= T1s
T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)])
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_reset[j], "reset", [j])
noise_thermal.add_quantum_error(errors_measure[j], "measure", [j])
noise_thermal.add_quantum_error(errors_u1[j], "u1", [j])
noise_thermal.add_quantum_error(errors_u2[j], "u2", [j])
noise_thermal.add_quantum_error(errors_u3[j], "u3", [j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k])
print(noise_thermal)
# Run the noisy simulation
job = execute(circ, simulator,
basis_gates=noise_thermal.basis_gates,
noise_model=noise_thermal)
result_thermal = job.result()
counts_thermal = result_thermal.get_counts(0)
# Plot noisy output
plot_histogram(counts_thermal)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# 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 import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/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 RZXCalibrationBuilderNoEcho."""
from math import pi, erf
import numpy as np
from ddt import data, ddt
from qiskit.converters import circuit_to_dag
from qiskit import circuit, schedule, QiskitError
from qiskit.circuit.library.standard_gates import SXGate, RZGate
from qiskit.providers.fake_provider import FakeHanoi # TODO - include FakeHanoiV2, FakeSherbrooke
from qiskit.providers.fake_provider import FakeArmonk
from qiskit.pulse import (
ControlChannel,
DriveChannel,
GaussianSquare,
Waveform,
Play,
InstructionScheduleMap,
Schedule,
)
from qiskit.pulse import builder
from qiskit.pulse.transforms import target_qobj_transform
from qiskit.test import QiskitTestCase
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes.calibration.builders import (
RZXCalibrationBuilder,
RZXCalibrationBuilderNoEcho,
)
class TestCalibrationBuilder(QiskitTestCase):
"""Test the Calibration Builder."""
# CR parameters
__risefall = 4
__angle = np.pi / 2
__granularity = 16
@staticmethod
def get_cr_play(cr_schedule, name):
"""A helper function to filter CR pulses."""
def _filter_func(time_inst):
return isinstance(time_inst[1], Play) and time_inst[1].pulse.name.startswith(name)
return cr_schedule.filter(_filter_func).instructions[0][1]
def compute_stretch_duration(self, play_gaussian_square_pulse, theta):
"""Compute duration of stretched Gaussian Square pulse."""
pulse = play_gaussian_square_pulse.pulse
sigma = pulse.sigma
width = self.compute_stretch_width(play_gaussian_square_pulse, theta)
duration = width + sigma * self.__risefall
return round(duration / self.__granularity) * self.__granularity
def compute_stretch_width(self, play_gaussian_square_pulse, theta):
"""Compute width of stretched Gaussian Square pulse."""
pulse = play_gaussian_square_pulse.pulse
sigma = pulse.sigma
width = pulse.width
risefall_area = sigma * np.sqrt(2 * np.pi) * erf(self.__risefall)
full_area = risefall_area + width
target_area = abs(theta) / self.__angle * full_area
return max(0, target_area - risefall_area)
def u0p_play(self, cr_schedule):
"""Returns the positive CR pulse from cr_schedule."""
return self.get_cr_play(cr_schedule, "CR90p_u")
def u0m_play(self, cr_schedule):
"""Returns the negative CR pulse from cr_schedule."""
return self.get_cr_play(cr_schedule, "CR90m_u")
def d1p_play(self, cr_schedule):
"""Returns the positive rotary echo pulse from cr_schedule."""
return self.get_cr_play(cr_schedule, "CR90p_d")
def d1m_play(self, cr_schedule):
"""Returns the negative rotary echo pulse from cr_schedule."""
return self.get_cr_play(cr_schedule, "CR90m_d")
@ddt
class TestRZXCalibrationBuilder(TestCalibrationBuilder):
"""Test RZXCalibrationBuilder."""
def build_forward(
self,
backend,
theta,
u0p_play,
d1p_play,
u0m_play,
d1m_play,
):
"""A helper function to generate reference pulse schedule for forward direction."""
duration = self.compute_stretch_duration(u0p_play, theta)
width = self.compute_stretch_width(u0p_play, theta)
with builder.build(
backend,
default_alignment="sequential",
default_transpiler_settings={"optimization_level": 0},
) as ref_sched:
with builder.align_left():
# Positive CRs
u0p_params = u0p_play.pulse.parameters
u0p_params["duration"] = duration
u0p_params["width"] = width
builder.play(
GaussianSquare(**u0p_params),
ControlChannel(0),
)
d1p_params = d1p_play.pulse.parameters
d1p_params["duration"] = duration
d1p_params["width"] = width
builder.play(
GaussianSquare(**d1p_params),
DriveChannel(1),
)
builder.x(0)
with builder.align_left():
# Negative CRs
u0m_params = u0m_play.pulse.parameters
u0m_params["duration"] = duration
u0m_params["width"] = width
builder.play(
GaussianSquare(**u0m_params),
ControlChannel(0),
)
d1m_params = d1m_play.pulse.parameters
d1m_params["duration"] = duration
d1m_params["width"] = width
builder.play(
GaussianSquare(**d1m_params),
DriveChannel(1),
)
builder.x(0)
return ref_sched
def build_reverse(
self,
backend,
theta,
u0p_play,
d1p_play,
u0m_play,
d1m_play,
):
"""A helper function to generate reference pulse schedule for backward direction."""
duration = self.compute_stretch_duration(u0p_play, theta)
width = self.compute_stretch_width(u0p_play, theta)
with builder.build(
backend,
default_alignment="sequential",
default_transpiler_settings={"optimization_level": 0},
) as ref_sched:
# Hadamard gates
builder.call_gate(RZGate(np.pi / 2), qubits=(0,))
builder.call_gate(SXGate(), qubits=(0,))
builder.call_gate(RZGate(np.pi / 2), qubits=(0,))
builder.call_gate(RZGate(np.pi / 2), qubits=(1,))
builder.call_gate(SXGate(), qubits=(1,))
builder.call_gate(RZGate(np.pi / 2), qubits=(1,))
with builder.align_left():
# Positive CRs
u0p_params = u0p_play.pulse.parameters
u0p_params["duration"] = duration
u0p_params["width"] = width
builder.play(
GaussianSquare(**u0p_params),
ControlChannel(0),
)
d1p_params = d1p_play.pulse.parameters
d1p_params["duration"] = duration
d1p_params["width"] = width
builder.play(
GaussianSquare(**d1p_params),
DriveChannel(1),
)
builder.x(0)
with builder.align_left():
# Negative CRs
u0m_params = u0m_play.pulse.parameters
u0m_params["duration"] = duration
u0m_params["width"] = width
builder.play(
GaussianSquare(**u0m_params),
ControlChannel(0),
)
d1m_params = d1m_play.pulse.parameters
d1m_params["duration"] = duration
d1m_params["width"] = width
builder.play(
GaussianSquare(**d1m_params),
DriveChannel(1),
)
builder.x(0)
# Hadamard gates
builder.call_gate(RZGate(np.pi / 2), qubits=(0,))
builder.call_gate(SXGate(), qubits=(0,))
builder.call_gate(RZGate(np.pi / 2), qubits=(0,))
builder.call_gate(RZGate(np.pi / 2), qubits=(1,))
builder.call_gate(SXGate(), qubits=(1,))
builder.call_gate(RZGate(np.pi / 2), qubits=(1,))
return ref_sched
@data(-np.pi / 4, 0.1, np.pi / 4, np.pi / 2, np.pi)
def test_rzx_calibration_cr_pulse_stretch(self, theta: float):
"""Test that cross resonance pulse durations are computed correctly."""
backend = FakeHanoi()
inst_map = backend.defaults().instruction_schedule_map
cr_schedule = inst_map.get("cx", (0, 1))
with builder.build() as test_sched:
RZXCalibrationBuilder.rescale_cr_inst(self.u0p_play(cr_schedule), theta)
self.assertEqual(
test_sched.duration, self.compute_stretch_duration(self.u0p_play(cr_schedule), theta)
)
@data(-np.pi / 4, 0.1, np.pi / 4, np.pi / 2, np.pi)
def test_rzx_calibration_rotary_pulse_stretch(self, theta: float):
"""Test that rotary pulse durations are computed correctly."""
backend = FakeHanoi()
inst_map = backend.defaults().instruction_schedule_map
cr_schedule = inst_map.get("cx", (0, 1))
with builder.build() as test_sched:
RZXCalibrationBuilder.rescale_cr_inst(self.d1p_play(cr_schedule), theta)
self.assertEqual(
test_sched.duration, self.compute_stretch_duration(self.d1p_play(cr_schedule), theta)
)
def test_raise(self):
"""Test that the correct error is raised."""
theta = np.pi / 4
qc = circuit.QuantumCircuit(2)
qc.rzx(theta, 0, 1)
dag = circuit_to_dag(qc)
backend = FakeArmonk()
inst_map = backend.defaults().instruction_schedule_map
_pass = RZXCalibrationBuilder(inst_map)
qubit_map = {qubit: i for i, qubit in enumerate(dag.qubits)}
with self.assertRaises(QiskitError):
for node in dag.gate_nodes():
qubits = [qubit_map[q] for q in node.qargs]
_pass.get_calibration(node.op, qubits)
def test_ecr_cx_forward(self):
"""Test that correct pulse sequence is generated for native CR pair."""
# Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling
theta = np.pi / 4
qc = circuit.QuantumCircuit(2)
qc.rzx(theta, 0, 1)
backend = FakeHanoi()
inst_map = backend.defaults().instruction_schedule_map
_pass = RZXCalibrationBuilder(inst_map)
test_qc = PassManager(_pass).run(qc)
cr_schedule = inst_map.get("cx", (0, 1))
ref_sched = self.build_forward(
backend,
theta,
self.u0p_play(cr_schedule),
self.d1p_play(cr_schedule),
self.u0m_play(cr_schedule),
self.d1m_play(cr_schedule),
)
self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched))
def test_ecr_cx_reverse(self):
"""Test that correct pulse sequence is generated for non-native CR pair."""
# Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling
theta = np.pi / 4
qc = circuit.QuantumCircuit(2)
qc.rzx(theta, 1, 0)
backend = FakeHanoi()
inst_map = backend.defaults().instruction_schedule_map
_pass = RZXCalibrationBuilder(inst_map)
test_qc = PassManager(_pass).run(qc)
cr_schedule = inst_map.get("cx", (0, 1))
ref_sched = self.build_reverse(
backend,
theta,
self.u0p_play(cr_schedule),
self.d1p_play(cr_schedule),
self.u0m_play(cr_schedule),
self.d1m_play(cr_schedule),
)
self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched))
def test_pass_alive_with_dcx_ish(self):
"""Test if the pass is not terminated by error with direct CX input."""
cx_sched = Schedule()
# Fake direct cr
cx_sched.insert(0, Play(GaussianSquare(800, 0.2, 64, 544), ControlChannel(1)), inplace=True)
# Fake direct compensation tone
# Compensation tone doesn't have dedicated pulse class.
# So it's reported as a waveform now.
compensation_tone = Waveform(0.1 * np.ones(800, dtype=complex))
cx_sched.insert(0, Play(compensation_tone, DriveChannel(0)), inplace=True)
inst_map = InstructionScheduleMap()
inst_map.add("cx", (1, 0), schedule=cx_sched)
theta = pi / 3
rzx_qc = circuit.QuantumCircuit(2)
rzx_qc.rzx(theta, 1, 0)
pass_ = RZXCalibrationBuilder(instruction_schedule_map=inst_map)
with self.assertWarns(UserWarning):
# User warning that says q0 q1 is invalid
cal_qc = PassManager(pass_).run(rzx_qc)
self.assertEqual(cal_qc, rzx_qc)
class TestRZXCalibrationBuilderNoEcho(TestCalibrationBuilder):
"""Test RZXCalibrationBuilderNoEcho."""
def build_forward(
self,
theta,
u0p_play,
d1p_play,
):
"""A helper function to generate reference pulse schedule for forward direction."""
duration = self.compute_stretch_duration(u0p_play, 2.0 * theta)
width = self.compute_stretch_width(u0p_play, 2.0 * theta)
with builder.build() as ref_sched:
# Positive CRs
u0p_params = u0p_play.pulse.parameters
u0p_params["duration"] = duration
u0p_params["width"] = width
builder.play(
GaussianSquare(**u0p_params),
ControlChannel(0),
)
d1p_params = d1p_play.pulse.parameters
d1p_params["duration"] = duration
d1p_params["width"] = width
builder.play(
GaussianSquare(**d1p_params),
DriveChannel(1),
)
builder.delay(duration, DriveChannel(0))
return ref_sched
def test_ecr_cx_forward(self):
"""Test that correct pulse sequence is generated for native CR pair.
.. notes::
No echo builder only supports native direction.
"""
# Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling
theta = np.pi / 4
qc = circuit.QuantumCircuit(2)
qc.rzx(theta, 0, 1)
backend = FakeHanoi()
inst_map = backend.defaults().instruction_schedule_map
_pass = RZXCalibrationBuilderNoEcho(inst_map)
test_qc = PassManager(_pass).run(qc)
cr_schedule = inst_map.get("cx", (0, 1))
ref_sched = self.build_forward(
theta,
self.u0p_play(cr_schedule),
self.d1p_play(cr_schedule),
)
self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched))
# # TODO - write test for forward ECR native pulse
# def test_ecr_forward(self):
def test_pass_alive_with_dcx_ish(self):
"""Test if the pass is not terminated by error with direct CX input."""
cx_sched = Schedule()
# Fake direct cr
cx_sched.insert(0, Play(GaussianSquare(800, 0.2, 64, 544), ControlChannel(1)), inplace=True)
# Fake direct compensation tone
# Compensation tone doesn't have dedicated pulse class.
# So it's reported as a waveform now.
compensation_tone = Waveform(0.1 * np.ones(800, dtype=complex))
cx_sched.insert(0, Play(compensation_tone, DriveChannel(0)), inplace=True)
inst_map = InstructionScheduleMap()
inst_map.add("cx", (1, 0), schedule=cx_sched)
theta = pi / 3
rzx_qc = circuit.QuantumCircuit(2)
rzx_qc.rzx(theta, 1, 0)
pass_ = RZXCalibrationBuilderNoEcho(instruction_schedule_map=inst_map)
with self.assertWarns(UserWarning):
# User warning that says q0 q1 is invalid
cal_qc = PassManager(pass_).run(rzx_qc)
self.assertEqual(cal_qc, rzx_qc)
|
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))
ghz.draw(output='mpl')
|
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 converters."""
import os
import unittest
from qiskit.converters import ast_to_dag, circuit_to_dag
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import qasm
from qiskit.test import QiskitTestCase
class TestAstToDag(QiskitTestCase):
"""Test AST to DAG."""
def setUp(self):
super().setUp()
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
self.circuit = QuantumCircuit(qr, cr)
self.circuit.ccx(qr[0], qr[1], qr[2])
self.circuit.measure(qr, cr)
self.dag = circuit_to_dag(self.circuit)
def test_from_ast_to_dag(self):
"""Test Unroller.execute()"""
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
ast = qasm.Qasm(os.path.join(qasm_dir, "example.qasm")).parse()
dag_circuit = ast_to_dag(ast)
expected_result = """\
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
qreg r[3];
creg c[3];
creg d[3];
h q[0];
h q[1];
h q[2];
cx q[0],r[0];
cx q[1],r[1];
cx q[2],r[2];
barrier q[0],q[1],q[2];
measure q[0] -> c[0];
measure q[1] -> c[1];
measure q[2] -> c[2];
measure r[0] -> d[0];
measure r[1] -> d[1];
measure r[2] -> d[2];
"""
expected_dag = circuit_to_dag(QuantumCircuit.from_qasm_str(expected_result))
self.assertEqual(dag_circuit, expected_dag)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
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/Z-928/Bugs4Q
|
Z-928
|
from qiskit import Aer, QuantumCircuit, transpile
from qiskit.circuit.library import PhaseEstimation
qc= QuantumCircuit(3,3)
# dummy unitary circuit
unitary_circuit = QuantumCircuit(1)
unitary_circuit.h(0)
# QPE
qc.append(PhaseEstimation(2, unitary_circuit), list(range(3)))
qc.measure(list(range(3)), list(range(3)))
backend = Aer.get_backend('qasm_simulator')
qc_transpiled = transpile(qc, backend)
result = backend.run(qc, shots = 8192).result()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
"""Piecewise-polynomially-controlled Pauli rotations."""
from __future__ import annotations
from typing import List, Optional
import numpy as np
from qiskit.circuit import QuantumRegister, AncillaRegister, QuantumCircuit
from qiskit.circuit.exceptions import CircuitError
from .functional_pauli_rotations import FunctionalPauliRotations
from .polynomial_pauli_rotations import PolynomialPauliRotations
from .integer_comparator import IntegerComparator
class PiecewisePolynomialPauliRotations(FunctionalPauliRotations):
r"""Piecewise-polynomially-controlled Pauli rotations.
This class implements a piecewise polynomial (not necessarily continuous) function,
:math:`f(x)`, on qubit amplitudes, which is defined through breakpoints and coefficients as
follows.
Suppose the breakpoints :math:`(x_0, ..., x_J)` are a subset of :math:`[0, 2^n-1]`, where
:math:`n` is the number of state qubits. Further on, denote the corresponding coefficients by
:math:`[a_{j,1},...,a_{j,d}]`, where :math:`d` is the highest degree among all polynomials.
Then :math:`f(x)` is defined as:
.. math::
f(x) = \begin{cases}
0, x < x_0 \\
\sum_{i=0}^{i=d}a_{j,i}/2 x^i, x_j \leq x < x_{j+1}
\end{cases}
where if given the same number of breakpoints as polynomials, we implicitly assume
:math:`x_{J+1} = 2^n`.
.. note::
Note the :math:`1/2` factor in the coefficients of :math:`f(x)`, this is consistent with
Qiskit's Pauli rotations.
Examples:
>>> from qiskit import QuantumCircuit
>>> from qiskit.circuit.library.arithmetic.piecewise_polynomial_pauli_rotations import\
... PiecewisePolynomialPauliRotations
>>> qubits, breakpoints, coeffs = (2, [0, 2], [[0, -1.2],[-1, 1, 3]])
>>> poly_r = PiecewisePolynomialPauliRotations(num_state_qubits=qubits,
...breakpoints=breakpoints, coeffs=coeffs)
>>>
>>> qc = QuantumCircuit(poly_r.num_qubits)
>>> qc.h(list(range(qubits)));
>>> qc.append(poly_r.to_instruction(), list(range(qc.num_qubits)));
>>> qc.draw()
┌───┐┌──────────┐
q_0: ┤ H ├┤0 ├
├───┤│ │
q_1: ┤ H ├┤1 ├
└───┘│ │
q_2: ─────┤2 ├
│ pw_poly │
q_3: ─────┤3 ├
│ │
q_4: ─────┤4 ├
│ │
q_5: ─────┤5 ├
└──────────┘
References:
[1]: Haener, T., Roetteler, M., & Svore, K. M. (2018).
Optimizing Quantum Circuits for Arithmetic.
`arXiv:1805.12445 <http://arxiv.org/abs/1805.12445>`_
[2]: Carrera Vazquez, A., Hiptmair, R., & Woerner, S. (2022).
Enhancing the Quantum Linear Systems Algorithm using Richardson Extrapolation.
`ACM Transactions on Quantum Computing 3, 1, Article 2 <https://doi.org/10.1145/3490631>`_
"""
def __init__(
self,
num_state_qubits: Optional[int] = None,
breakpoints: Optional[List[int]] = None,
coeffs: Optional[List[List[float]]] = None,
basis: str = "Y",
name: str = "pw_poly",
) -> None:
"""
Args:
num_state_qubits: The number of qubits representing the state.
breakpoints: The breakpoints to define the piecewise-linear function.
Defaults to ``[0]``.
coeffs: The coefficients of the polynomials for different segments of the
piecewise-linear function. ``coeffs[j][i]`` is the coefficient of the i-th power of x
for the j-th polynomial.
Defaults to linear: ``[[1]]``.
basis: The type of Pauli rotation (``'X'``, ``'Y'``, ``'Z'``).
name: The name of the circuit.
"""
# store parameters
self._breakpoints = breakpoints if breakpoints is not None else [0]
self._coeffs = coeffs if coeffs is not None else [[1]]
# store a list of coefficients as homogeneous polynomials adding 0's where necessary
self._hom_coeffs = []
self._degree = len(max(self._coeffs, key=len)) - 1
for poly in self._coeffs:
self._hom_coeffs.append(poly + [0] * (self._degree + 1 - len(poly)))
super().__init__(num_state_qubits=num_state_qubits, basis=basis, name=name)
@property
def breakpoints(self) -> List[int]:
"""The breakpoints of the piecewise polynomial function.
The function is polynomial in the intervals ``[point_i, point_{i+1}]`` where the last
point implicitly is ``2**(num_state_qubits + 1)``.
Returns:
The list of breakpoints.
"""
if (
self.num_state_qubits is not None
and len(self._breakpoints) == len(self.coeffs)
and self._breakpoints[-1] < 2**self.num_state_qubits
):
return self._breakpoints + [2**self.num_state_qubits]
return self._breakpoints
@breakpoints.setter
def breakpoints(self, breakpoints: List[int]) -> None:
"""Set the breakpoints.
Args:
breakpoints: The new breakpoints.
"""
self._invalidate()
self._breakpoints = breakpoints
if self.num_state_qubits and breakpoints:
self._reset_registers(self.num_state_qubits)
@property
def coeffs(self) -> List[List[float]]:
"""The coefficients of the polynomials.
Returns:
The polynomial coefficients per interval as nested lists.
"""
return self._coeffs
@coeffs.setter
def coeffs(self, coeffs: List[List[float]]) -> None:
"""Set the polynomials.
Args:
coeffs: The new polynomials.
"""
self._invalidate()
self._coeffs = coeffs
# update the homogeneous polynomials and degree
self._hom_coeffs = []
self._degree = len(max(self._coeffs, key=len)) - 1
for poly in self._coeffs:
self._hom_coeffs.append(poly + [0] * (self._degree + 1 - len(poly)))
if self.num_state_qubits and coeffs:
self._reset_registers(self.num_state_qubits)
@property
def mapped_coeffs(self) -> List[List[float]]:
"""The coefficients mapped to the internal representation, since we only compare
x>=breakpoint.
Returns:
The mapped coefficients.
"""
mapped_coeffs = []
# First polynomial
mapped_coeffs.append(self._hom_coeffs[0])
for i in range(1, len(self._hom_coeffs)):
mapped_coeffs.append([])
for j in range(0, self._degree + 1):
mapped_coeffs[i].append(self._hom_coeffs[i][j] - self._hom_coeffs[i - 1][j])
return mapped_coeffs
@property
def contains_zero_breakpoint(self) -> bool | np.bool_:
"""Whether 0 is the first breakpoint.
Returns:
True, if 0 is the first breakpoint, otherwise False.
"""
return np.isclose(0, self.breakpoints[0])
def evaluate(self, x: float) -> float:
"""Classically evaluate the piecewise polynomial rotation.
Args:
x: Value to be evaluated at.
Returns:
Value of piecewise polynomial function at x.
"""
y = 0
for i in range(0, len(self.breakpoints)):
y = y + (x >= self.breakpoints[i]) * (np.poly1d(self.mapped_coeffs[i][::-1])(x))
return y
def _check_configuration(self, raise_on_failure: bool = True) -> bool:
"""Check if the current configuration is valid."""
valid = True
if self.num_state_qubits is None:
valid = False
if raise_on_failure:
raise AttributeError("The number of qubits has not been set.")
if self.num_qubits < self.num_state_qubits + 1:
valid = False
if raise_on_failure:
raise CircuitError(
"Not enough qubits in the circuit, need at least "
"{}.".format(self.num_state_qubits + 1)
)
if len(self.breakpoints) != len(self.coeffs) + 1:
valid = False
if raise_on_failure:
raise ValueError("Mismatching number of breakpoints and polynomials.")
return valid
def _reset_registers(self, num_state_qubits: Optional[int]) -> None:
"""Reset the registers."""
self.qregs = []
if num_state_qubits:
qr_state = QuantumRegister(num_state_qubits)
qr_target = QuantumRegister(1)
self.qregs = [qr_state, qr_target]
# Calculate number of ancilla qubits required
num_ancillas = num_state_qubits + 1
if self.contains_zero_breakpoint:
num_ancillas -= 1
if num_ancillas > 0:
qr_ancilla = AncillaRegister(num_ancillas)
self.add_register(qr_ancilla)
def _build(self):
"""If not already built, build the circuit."""
if self._is_built:
return
super()._build()
circuit = QuantumCircuit(*self.qregs, name=self.name)
qr_state = circuit.qubits[: self.num_state_qubits]
qr_target = [circuit.qubits[self.num_state_qubits]]
# Ancilla for the comparator circuit
qr_ancilla = circuit.qubits[self.num_state_qubits + 1 :]
# apply comparators and controlled linear rotations
for i, point in enumerate(self.breakpoints[:-1]):
if i == 0 and self.contains_zero_breakpoint:
# apply rotation
poly_r = PolynomialPauliRotations(
num_state_qubits=self.num_state_qubits,
coeffs=self.mapped_coeffs[i],
basis=self.basis,
)
circuit.append(poly_r.to_gate(), qr_state[:] + qr_target)
else:
# apply Comparator
comp = IntegerComparator(num_state_qubits=self.num_state_qubits, value=point)
qr_state_full = qr_state[:] + [qr_ancilla[0]] # add compare qubit
qr_remaining_ancilla = qr_ancilla[1:] # take remaining ancillas
circuit.append(
comp.to_gate(), qr_state_full[:] + qr_remaining_ancilla[: comp.num_ancillas]
)
# apply controlled rotation
poly_r = PolynomialPauliRotations(
num_state_qubits=self.num_state_qubits,
coeffs=self.mapped_coeffs[i],
basis=self.basis,
)
circuit.append(
poly_r.to_gate().control(), [qr_ancilla[0]] + qr_state[:] + qr_target
)
# uncompute comparator
circuit.append(
comp.to_gate().inverse(),
qr_state_full[:] + qr_remaining_ancilla[: comp.num_ancillas],
)
self.append(circuit.to_gate(), self.qubits)
|
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
|
PavanCyborg
|
#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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import execute, pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), d0)
pulse_prog.draw()
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
from ipywidgets import interact, interactive, fixed, interact_manual, FloatSlider, Layout
import ipywidgets as widgets
sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]})
plt.rcParams['figure.figsize'] = [12, 8]
# load dataframe
filepath = "../datasets/AllErrors/U3_5.csv"
df = pd.read_csv(filepath)
# reorder columns
df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'population', 'p0_0', 'p0_1', 'p1_0', 'p1_1']]
# filters
labels = ['theta', 'phi', 'lam', 'E']
depol_columns = ['depol_prob']
thermal_columns = ['t1', 't2', 'population']
readout_columns = ['p0_0', 'p0_1', 'p1_0', 'p1_1']
# filtered dataframes
ideal_only = df.query('depol_prob == 0 & t1 == inf & t2 == inf & p0_0 == 1 & p1_1 == 1')
df
# Explore Features
@interact
def show_gates_more_than(theta_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%')),
lam_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%')),
phi_values=widgets.SelectMultiple(options=df['phi'].unique(), value=tuple(df['phi'].unique()))):
filtered = df.loc[(df['theta'].between(theta_range[0],theta_range[1])) & (df['lam'].between(lam_range[0],lam_range[1])) & (df['phi'].isin(phi_values))]
sns.scatterplot(x='theta', y='E', hue="lam", data=filtered);
@interact
def show_gates_more_than(theta_range=widgets.FloatRangeSlider(value=[2.2, 2.6], min = 0.0, max=2*np.pi, layout=Layout(width='80%')),
lam_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%')),
phi_values=widgets.SelectMultiple(options=df['phi'].unique(), value=tuple(df['phi'].unique()))):
filtered = df.loc[(df['theta'].between(theta_range[0],theta_range[1])) & (df['lam'].between(lam_range[0],lam_range[1])) & (df['phi'].isin(phi_values))]
sns.scatterplot(x='theta', y='E', hue="lam", data=filtered);
@interact
def show_gates_more_than(theta_range=widgets.FloatRangeSlider(value=[2.2, 2.6], min = 0.0, max=2*np.pi, layout=Layout(width='80%')),
lam_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%')),
phi_values=widgets.SelectMultiple(options=df['phi'].unique(), value=tuple(df['phi'].unique()))):
filtered = df.loc[(df['theta'].between(theta_range[0],theta_range[1])) & (df['lam'].between(lam_range[0],lam_range[1])) & (df['phi'].isin(phi_values))]
sns.scatterplot(x='theta', y='E', hue="lam", data=filtered);
@interact
def show_gates_more_than(
theta_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%'), description='theta_range'),
lam_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%'), description='lam_range'),
phi_values=widgets.SelectMultiple(options=df['phi'].unique(), value=tuple(df['phi'].unique()), description='phi_values')):
filtered = df.loc[(df['p1_1'] == 1.0) & (df['theta'].between(theta_range[0],theta_range[1])) & (df['lam'].between(lam_range[0],lam_range[1])) & (df['phi'].isin(phi_values))]
display(theta_range, lam_range, phi_values);
return sns.scatterplot(x='theta', y='E', hue='p0_0', data=filtered);
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Module defining Qiskit OpenQASM conversions
"""
import qiskit
from qiskit.qasm3 import dumps
from qbraid.transpiler.annotations import weight
@weight(1)
def qiskit_to_qasm3(circuit: qiskit.QuantumCircuit) -> str:
"""Convert qiskit QuantumCircuit to QASM 3.0 string"""
return dumps(circuit)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization.problems import QuadraticProgram
# define a problem
qp = QuadraticProgram()
qp.binary_var("x")
qp.integer_var(name="y", lowerbound=-1, upperbound=4)
qp.maximize(quadratic={("x", "y"): 1})
qp.linear_constraint({"x": 1, "y": -1}, "<=", 0)
print(qp.prettyprint())
from qiskit_optimization.algorithms import CplexOptimizer, GurobiOptimizer
cplex_result = CplexOptimizer().solve(qp)
gurobi_result = GurobiOptimizer().solve(qp)
print("cplex")
print(cplex_result.prettyprint())
print()
print("gurobi")
print(gurobi_result.prettyprint())
result = CplexOptimizer(disp=True, cplex_parameters={"threads": 1, "timelimit": 0.1}).solve(qp)
print(result.prettyprint())
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_aer import Aer
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
meo = MinimumEigenOptimizer(QAOA(sampler=Sampler(), optimizer=COBYLA(maxiter=100)))
result = meo.solve(qp)
print(result.prettyprint())
print("\ndisplay the best 5 solution samples")
for sample in result.samples[:5]:
print(sample)
# docplex model
from docplex.mp.model import Model
docplex_model = Model("docplex")
x = docplex_model.binary_var("x")
y = docplex_model.integer_var(-1, 4, "y")
docplex_model.maximize(x * y)
docplex_model.add_constraint(x <= y)
docplex_model.prettyprint()
# gurobi model
import gurobipy as gp
gurobipy_model = gp.Model("gurobi")
x = gurobipy_model.addVar(vtype=gp.GRB.BINARY, name="x")
y = gurobipy_model.addVar(vtype=gp.GRB.INTEGER, lb=-1, ub=4, name="y")
gurobipy_model.setObjective(x * y, gp.GRB.MAXIMIZE)
gurobipy_model.addConstr(x - y <= 0)
gurobipy_model.update()
gurobipy_model.display()
from qiskit_optimization.translators import from_docplex_mp, from_gurobipy
qp = from_docplex_mp(docplex_model)
print("QuadraticProgram obtained from docpblex")
print(qp.prettyprint())
print("-------------")
print("QuadraticProgram obtained from gurobipy")
qp2 = from_gurobipy(gurobipy_model)
print(qp2.prettyprint())
from qiskit_optimization.translators import to_gurobipy, to_docplex_mp
gmod = to_gurobipy(from_docplex_mp(docplex_model))
print("convert docplex to gurobipy via QuadraticProgram")
gmod.display()
dmod = to_docplex_mp(from_gurobipy(gurobipy_model))
print("\nconvert gurobipy to docplex via QuadraticProgram")
print(dmod.export_as_lp_string())
ind_mod = Model("docplex")
x = ind_mod.binary_var("x")
y = ind_mod.integer_var(-1, 2, "y")
z = ind_mod.integer_var(-1, 2, "z")
ind_mod.maximize(3 * x + y - z)
ind_mod.add_indicator(x, y >= z, 1)
print(ind_mod.export_as_lp_string())
qp = from_docplex_mp(ind_mod)
result = meo.solve(qp) # apply QAOA to QuadraticProgram
print("QAOA")
print(result.prettyprint())
print("-----\nCPLEX")
print(ind_mod.solve()) # apply CPLEX directly to the Docplex model
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/veenaiyuri/qiskit-education
|
veenaiyuri
|
from QiskitEducation import *
qc = QuantumAlgorithm(3,3)
q = qc.q; c = qc.c
qc.h(q[0])
qc.h(q[1])
qc.cx(q[1], q[2])
qc.cx(q[0], q[1])
qc.h(q[0])
qc.measure(q[0], c[0])
qc.measure(q[1], c[1])
qc.cx(q[1], q[2])
qc.cz(q[0], q[2])
qc.h(q[2])
qc.measure(q[2], c[2])
data = qc.execute(histogram=True)
print(data['counts'])
qc.plot_histogram(data['counts'])
|
https://github.com/ohadlev77/sat-circuits-engine
|
ohadlev77
|
# Copyright 2022-2023 Ohad Lev.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0,
# or in the root directory of this package("LICENSE.txt").
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
`calc_iterations`, `find_iterations_unknown` functions.
`is_circuit_match` and `randint_exclude` functions can be considered
as sub-functions of `find_iterations_unknown`.
"""
import random
import copy
from typing import Tuple, Optional
import numpy as np
from qiskit import transpile, QuantumCircuit
from qiskit.providers.backend import Backend
from sat_circuits_engine.util import timer_dec
from sat_circuits_engine.util.settings import BACKENDS
from sat_circuits_engine.circuit import SATCircuit, GroverConstraintsOperator
from sat_circuits_engine.classical_processing.classical_verifier import ClassicalVerifier
from sat_circuits_engine.constraints_parse import ParsedConstraints, SATNoSolutionError
def calc_iterations(num_input_qubits: int, num_solutions: int) -> int:
"""
Simple classical calculation of the number of iterations over Grover's iterator
when the number of solutions for the SAT problem is known.
Args:
num_input_qubits (int): number of input qubits.
num_solutions (int): known number of solutions to the SAT problem.
Returns:
(int): the exact number of iterations needed for the given SAT problem.
"""
# N is the dimension of the Hilbert space spanned by `num_input_qubits`
N = 2**num_input_qubits
# The formula for calculating the number of iterations
iterations = int((np.pi / 4) * np.sqrt(N / num_solutions))
return iterations
@timer_dec("Found number of iterations in ")
def find_iterations_unknown(
num_input_qubits: int,
grover_constraints_operator: GroverConstraintsOperator,
parsed_constraints: ParsedConstraints,
precision: Optional[int] = 10,
backend: Optional[Backend] = BACKENDS(0),
step: Optional[float] = 6 / 5,
) -> Tuple[SATCircuit, int]:
"""
Finds an adequate (optimal or near optimal) number of iterations suitable for a given SAT problem
when the number of "solutions" or "marked states" is unknown.
The method being used is described in https://arxiv.org/pdf/quant-ph/9605034.pdf (section 4).
- In short, the original method steps are:
* Drawing a random number of iterations which is smaller than some number M.
* Executing the circuit.
* If a solution has been found (easy to verify classically) - done.
* If not - M is being multiplied by a fixed step size.
* Repeat.
- Here we implement a variation of the described method above - with the goal of finding
ad adequate number of iterations for the SAT problem, and not just a single solution.
* Instead of exiting the process when finding a solution, we then
execute the circuit `precision` times.
* If `precision` execution shots gives 100% "good" solutions - done, we have found
a number of iterations precise enough.
* If not - we continue with the original method scheme.
* If we couldn't find an adequate number of iterations for the given `precision`,
the precision is decremented and we iterate over the process again with a lower precision.
* If `precision` has been decremented to 0 - then we halt,
and probably the SAT problem has no solution.
- `precision` can be thought as the degree of accuracy - for large values of `precision`
more optimal results will be obtained, in a price of extra computational overhead.
Args:
num_input_qubits (int): number of input qubits.
grover_constraints_operator (GroverConstraintsOperator): Grover's operator for the SAT problem.
parsed_constraints (ParsedConstraints): a series of constraints,
already parsed to a specific format.
precision (Optional[int] = 10): number of "valid solutions" which is
enough to determine ad adequate number of iterations for the SAT problem.
backend (Optional[Backend] = BACKENDS(0)): a backend to run the circuits upon.
Default is the local AerSimulator (BACKENDS(0)).
step (Optional[float] = 6/5): step size to increment M in each iteration.
Returns: Tuple[SATCircuit, int]:
(SATCircuit): the overall SAT circuit obtained after finding number of iterations.
(int): the calculated number of iterations for the given SAT problem.
Raises:
SATNoSolutionError - if no adequate number of iterations has been found for
any level of precision.
"""
verifier = ClassicalVerifier(parsed_constraints)
# Diemnsion of the Hilbert space spanned by the input qubits
N = 2**num_input_qubits
# A container for SATCircuit objects with various numbers of iterations
qc_storage = {}
# If `precision == 0`` then probably there is no solution
while precision > 0:
# M is the upper limit for drawing a random number of iterations
M = 1
checked_iterations = set()
# For each level of precision we are looking for an adequate number of iterations
print(f"\nChecking iterations for precision = {precision}:")
while M <= np.sqrt(N):
# Figuring a guess for the number of iterations
iterations = False
while not iterations:
M = step * M
iterations = randint_exclude(start=0, end=int(M), exclude=checked_iterations)
print(f" Checking iterations = {iterations}")
# Obtaining the necessary SATCircuit object (preferably from the `qc_storage`)
if iterations in qc_storage.keys():
qc = qc_storage[iterations]
else:
qc = SATCircuit(num_input_qubits, grover_constraints_operator, iterations)
qc.add_input_reg_measurement()
qc_storage[iterations] = copy.deepcopy(qc)
# Checking whether `qc` with `iterations` iterations gives 100% correct solutions (= match)
match = is_circuit_match(qc, verifier, precision, backend)
if match:
return qc, iterations
checked_iterations.add(iterations)
# Degrading precision if failed to find an adequate number of iterations
precision -= 2
if precision <= 0:
raise SATNoSolutionError(
"Didn't find an suitable number of iterations."
"Probably the SAT problem has no solution."
)
def randint_exclude(start, end, exclude):
"""
Guessing a number of iterations which haven't been tried yet.
If it fails (`count >= 50`), returns False.
"""
randint = random.randint(start, end)
count = 0
while randint in exclude:
randint = random.randint(start, end)
count += 1
if count >= 50:
return False
return randint
def is_circuit_match(
qc: QuantumCircuit, verifier: ClassicalVerifier, precision: int, backend: Backend
) -> bool:
"""
Checks classically whether running `qc` `precision` times gives `precision` correct solutions.
Args:
qc (QuantumCircuit): the quantum circuit to run.
verifier (ClassicalVerifier): classical verifier object to verify solutions with.
precision (int): number of correct solutions required.
backend (Backend): backend to run circuits upon.
Returns:
(bool): True if the execution of `qc` yielded 100% correct solutions (`precision` times).
False otherwise.
"""
job = backend.run(transpile(qc, backend), shots=precision, memory=True)
outcomes = job.result().get_memory()
# In `outcomes` we have `precision` results - If all of them are solutions, we have a match.
match = True
for outcome in outcomes:
match = verifier.verify(outcome)
if not match:
break
return match
|
https://github.com/HuangJunye/Qiskit-for-GameDev
|
HuangJunye
|
#!/usr/bin/env python
#
# Copyright 2019 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pygame
from qiskit import BasicAer, execute
from qiskit.tools.visualization import plot_state_qsphere
from utils import load_image
class QSphere(pygame.sprite.Sprite):
"""Displays a qsphere"""
def __init__(self, circuit):
pygame.sprite.Sprite.__init__(self)
self.image = None
self.rect = None
self.set_circuit(circuit)
# def update(self):
# # Nothing yet
# a = 1
def set_circuit(self, circuit):
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circuit, backend_sv_sim)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circuit, decimals=3)
qsphere = plot_state_qsphere(quantum_state)
qsphere.savefig("utils/data/bell_qsphere.png")
self.image, self.rect = load_image('bell_qsphere.png', -1)
self.rect.inflate_ip(-100, -100)
self.image.convert()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
%matplotlib inline
from qiskit_finance import QiskitFinanceError
from qiskit_finance.data_providers import *
import datetime
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
data = RandomDataProvider(
tickers=["TICKER1", "TICKER2"],
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=1,
)
data.run()
means = data.get_mean_vector()
print("Means:")
print(means)
rho = data.get_similarity_matrix()
print("A time-series similarity measure:")
print(rho)
plt.imshow(rho)
plt.show()
cov = data.get_covariance_matrix()
print("A covariance matrix:")
print(cov)
plt.imshow(cov)
plt.show()
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
for (cnt, s) in enumerate(data._tickers):
print(s)
print(data._data[cnt])
data = RandomDataProvider(
tickers=["CompanyA", "CompanyB", "CompanyC"],
start=datetime.datetime(2015, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=1,
)
data.run()
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
stocks = ["GOOG", "AAPL"]
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
wiki = WikipediaDataProvider(
token=token,
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
)
wiki.run()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
if token != "REPLACE-ME":
if wiki._data:
if wiki._n <= 1:
print(
"Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers."
)
else:
rho = wiki.get_similarity_matrix()
print("A time-series similarity measure:")
print(rho)
plt.imshow(rho)
plt.show()
cov = wiki.get_covariance_matrix()
print("A covariance matrix:")
print(cov)
plt.imshow(cov)
plt.show()
else:
print("No wiki data loaded.")
if token != "REPLACE-ME":
if wiki._data:
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(stocks):
plt.plot(wiki._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
for (cnt, s) in enumerate(stocks):
print(s)
print(wiki._data[cnt])
else:
print("No wiki data loaded.")
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
nasdaq = DataOnDemandProvider(
token=token,
tickers=["GOOG", "AAPL"],
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 2),
)
nasdaq.run()
for (cnt, s) in enumerate(nasdaq._tickers):
plt.plot(nasdaq._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
lse = ExchangeDataProvider(
token=token,
tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"],
stockmarket=StockMarket.LONDON,
start=datetime.datetime(2018, 1, 1),
end=datetime.datetime(2018, 12, 31),
)
lse.run()
for (cnt, s) in enumerate(lse._tickers):
plt.plot(lse._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
try:
data = YahooDataProvider(
tickers=["MSFT", "AAPL", "GOOG"],
start=datetime.datetime(2021, 1, 1),
end=datetime.datetime(2021, 12, 31),
)
data.run()
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3)
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
data = None
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Special data types.
"""
from enum import Enum
from typing import NamedTuple, List, Union, NewType, Tuple, Dict
from qiskit import circuit
ScheduledGate = NamedTuple(
"ScheduledGate",
[
("t0", int),
("operand", circuit.Gate),
("duration", int),
("bits", List[Union[circuit.Qubit, circuit.Clbit]]),
("bit_position", int),
],
)
ScheduledGate.__doc__ = "A gate instruction with embedded time."
ScheduledGate.t0.__doc__ = "Time when the instruction is issued."
ScheduledGate.operand.__doc__ = "Gate object associated with the gate."
ScheduledGate.duration.__doc__ = "Time duration of the instruction."
ScheduledGate.bits.__doc__ = "List of bit associated with the gate."
ScheduledGate.bit_position.__doc__ = "Position of bit associated with this drawing source."
GateLink = NamedTuple(
"GateLink", [("t0", int), ("opname", str), ("bits", List[Union[circuit.Qubit, circuit.Clbit]])]
)
GateLink.__doc__ = "Dedicated object to represent a relationship between instructions."
GateLink.t0.__doc__ = "A position where the link is placed."
GateLink.opname.__doc__ = "Name of gate associated with this link."
GateLink.bits.__doc__ = "List of bit associated with the instruction."
Barrier = NamedTuple(
"Barrier",
[("t0", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int)],
)
Barrier.__doc__ = "Dedicated object to represent a barrier instruction."
Barrier.t0.__doc__ = "A position where the barrier is placed."
Barrier.bits.__doc__ = "List of bit associated with the instruction."
Barrier.bit_position.__doc__ = "Position of bit associated with this drawing source."
HorizontalAxis = NamedTuple(
"HorizontalAxis", [("window", Tuple[int, int]), ("axis_map", Dict[int, int]), ("label", str)]
)
HorizontalAxis.__doc__ = "Data to represent configuration of horizontal axis."
HorizontalAxis.window.__doc__ = "Left and right edge of graph."
HorizontalAxis.axis_map.__doc__ = "Mapping of apparent coordinate system and actual location."
HorizontalAxis.label.__doc__ = "Label of horizontal axis."
class BoxType(str, Enum):
"""Box type.
SCHED_GATE: Box that represents occupation time by gate.
DELAY: Box associated with delay.
TIMELINE: Box that represents time slot of a bit.
"""
SCHED_GATE = "Box.ScheduledGate"
DELAY = "Box.Delay"
TIMELINE = "Box.Timeline"
class LineType(str, Enum):
"""Line type.
BARRIER: Line that represents barrier instruction.
GATE_LINK: Line that represents a link among gates.
"""
BARRIER = "Line.Barrier"
GATE_LINK = "Line.GateLink"
class SymbolType(str, Enum):
"""Symbol type.
FRAME: Symbol that represents zero time frame change (Rz) instruction.
"""
FRAME = "Symbol.Frame"
class LabelType(str, Enum):
"""Label type.
GATE_NAME: Label that represents name of gate.
DELAY: Label associated with delay.
GATE_PARAM: Label that represents parameter of gate.
BIT_NAME: Label that represents name of bit.
"""
GATE_NAME = "Label.Gate.Name"
DELAY = "Label.Delay"
GATE_PARAM = "Label.Gate.Param"
BIT_NAME = "Label.Bit.Name"
class AbstractCoordinate(Enum):
"""Abstract coordinate that the exact value depends on the user preference.
RIGHT: The horizontal coordinate at t0 shifted by the left margin.
LEFT: The horizontal coordinate at tf shifted by the right margin.
TOP: The vertical coordinate at the top of the canvas.
BOTTOM: The vertical coordinate at the bottom of the canvas.
"""
RIGHT = "RIGHT"
LEFT = "LEFT"
TOP = "TOP"
BOTTOM = "BOTTOM"
class Plotter(str, Enum):
"""Name of timeline plotter APIs.
MPL: Matplotlib plotter interface. Show timeline in 2D canvas.
"""
MPL = "mpl"
# convenient type to represent union of drawing data
DataTypes = NewType("DataType", Union[BoxType, LabelType, LineType, SymbolType])
# convenient type to represent union of values to represent a coordinate
Coordinate = NewType("Coordinate", Union[float, AbstractCoordinate])
# Valid bit objects
Bits = NewType("Bits", Union[circuit.Qubit, circuit.Clbit])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can show the phase of each state and use
# degrees instead of radians
from qiskit.quantum_info import DensityMatrix
import numpy as np
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
qc.z(1)
matrix = DensityMatrix(qc)
plot_state_qsphere(matrix,
show_state_phases = True, use_degrees = True)
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
import sys
sys.path.append("..")
from mock_backends.ibm import *
import itertools
from qiskit.circuit.library import CXGate
from clonk.backend_utils.configurable_backend_v2 import ConfigurableFakeBackendV2
import rustworkx as rx
from abc import ABC, abstractmethod
class AbstractModularBackend(ConfigurableFakeBackendV2, ABC):
"""A mock backendv2, tailored for a tree structure with modular connectivity."""
def __init__(self, module_size=4, children=4, total_levels=3):
# Validate children for root module
assert (
1 < children <= module_size
), "Children must be between 2 and the module size, inclusive for the root module."
self.c_map = [] # To hold all edges
self.modules = {} # Maps module ID to its qubits
self.module_depths = {} # Maps module ID to its depth
self.module_size = module_size
self.children = children # Max children for the root module
self.total_levels = total_levels
self.long_edges = []
# Construct the modular system
self._construct_system()
# Remove duplicate edges and filter to keep only edges from lower to higher qubit IDs
self.c_map = list(set(self.c_map))
self.c_map = [edge for edge in self.c_map if edge[0] < edge[1]]
# Configure gates and measurements based on the generated system
gate_configuration = {CXGate: [(i, j) for i, j in self.c_map]}
measurable_qubits = list(range(max(max(pair) for pair in self.c_map) + 1))
super().__init__(
name=f"Modular{module_size}-{children}-{total_levels}",
description="A mock backend with modular architecture",
n_qubits=len(measurable_qubits),
gate_configuration=gate_configuration,
measurable_qubits=measurable_qubits,
gate_durations={CXGate: 1},
parameterized_gates={},
)
def add_long_edges(self, num_long_edges=1):
G = rx.PyGraph()
for node in range(self.num_qubits):
G.add_node(node)
for edge in self.c_map:
G.add_edge(edge[0], edge[1], 1)
long_edge_endpoints = set() # Track qubits that are endpoints of long-edges
for _ in range(num_long_edges):
all_pairs_lengths = rx.all_pairs_dijkstra_path_lengths(
G, edge_cost_fn=lambda x: 1
)
max_length = 0
candidates = []
for source, paths in all_pairs_lengths.items():
for target, length in paths.items():
if source < target and length > max_length:
# Check if either qubit is already an endpoint of a long-edge
if (
source not in long_edge_endpoints
and target not in long_edge_endpoints
):
max_length = length
candidates = [(source, target)]
# If candidates are found, select the first one as the new long-edge
if candidates:
long_edge = candidates[0]
self.long_edges.append(long_edge)
G.add_edge(long_edge[0], long_edge[1], 1)
long_edge_endpoints.update([long_edge[0], long_edge[1]])
def _find_module_by_qubit(self, qubit):
"""Find the module ID that a given qubit belongs to."""
for module_id, qubits in self.modules.items():
if qubit in qubits:
return module_id
return None
@abstractmethod
def _construct_system(self):
"""
Subclasses should implement this method to construct
the modular system based on their specific scheme.
"""
pass
class TreeModular(AbstractModularBackend):
def _construct_system(self):
# Implement the construction logic specific to the Tree scheme
# Start the recursive construction of the system
self._recursive_foo(
qubit_counter=0, current_level=1, parent_id=None, parent_qubit=None, depth=0
)
def _recursive_foo(
self, qubit_counter, current_level, parent_id, parent_qubit, depth
):
module_id = len(self.modules) # Unique ID for each module
self.module_depths[module_id] = depth
qubits = list(range(qubit_counter, qubit_counter + self.module_size))
self.modules[module_id] = qubits
# Create all-to-all connectivity within the module
edges = list(itertools.permutations(qubits, 2))
self.c_map.extend(edges)
# Connect this module to its parent module (if applicable)
if parent_qubit is not None:
self.c_map.append(
(parent_qubit, qubits[0])
) # Connection from parent to this module
self.c_map.append((qubits[0], parent_qubit)) # And vice versa
qubit_counter += self.module_size
if current_level < self.total_levels:
child_count = self.children if current_level == 1 else self.children - 1
for i in range(child_count):
qubit_counter = self._recursive_foo(
qubit_counter,
current_level + 1,
module_id,
qubits[i] if i < child_count - 1 else qubits[-1],
depth + 1,
)
return qubit_counter
class CorralModular(AbstractModularBackend):
def __init__(self, num_snails=8, corral_skip_pattern=(0, 0)):
self.num_snails = num_snails
self.corral_skip_pattern = corral_skip_pattern
# Initialize the modules dictionary to track which SNAIL neighborhood (module)
# each qubit is primarily associated with.
self.qubit_to_snail_map = {} # Maps qubits to their primary SNAIL (module)
super().__init__(
module_size=4, children=2, total_levels=2
) # Example values, adjust as needed
def _assign_qubit_to_module(self, qubit, snail):
# Assign a qubit to its first encountered SNAIL neighborhood if it hasn't been assigned yet.
if qubit not in self.qubit_to_snail_map:
self.qubit_to_snail_map[qubit] = snail
# Ensure the module entry exists for the SNAIL
if snail not in self.modules:
self.modules[snail] = []
self.modules[snail].append(qubit)
def _corral(self, num_snails, skip_pattern):
num_levels = 2
assert len(skip_pattern) == num_levels
snail_edge_list = []
for snail0, snail1 in zip(range(num_snails), range(1, num_snails + 1)):
for i in range(num_levels):
snail_edge_list.append(
(snail0, (skip_pattern[i] + snail1) % num_snails)
)
return snail_edge_list
def _snail_to_connectivity(self, snail_edge_list):
edge_list = []
for qubit, snail_edge in enumerate(snail_edge_list):
# Attempt to assign the qubit to a module based on its SNAIL edge
self._assign_qubit_to_module(qubit, snail_edge[0])
for temp_qubit, temp_snail_edge in enumerate(snail_edge_list):
if qubit != temp_qubit and (
snail_edge[0] in temp_snail_edge or snail_edge[1] in temp_snail_edge
):
edge_list.append((qubit, temp_qubit))
return edge_list
def _construct_system(self):
self.snail_edge_list = self._corral(self.num_snails, self.corral_skip_pattern)
self.c_map = self._snail_to_connectivity(self.snail_edge_list)
# Each SNAIL is treated as a module for depth purposes, though this could be adjusted
self.module_depths = {
snail: snail for snail in range(self.num_snails)
} # Example depth assignment
# Example usage
fake_modular = TreeModular(module_size=3, children=3, total_levels=3)
print("Modules:", fake_modular.modules)
print("Coupling Map:", fake_modular.c_map)
import matplotlib.pyplot as plt
import networkx as nx
def pretty_print_with_networkx(pb, label_text):
G = nx.Graph()
# Define colors for different levels
level_colors = [
"tab:blue",
"tab:orange",
"tab:green",
"tab:red",
"tab:purple",
"tab:brown",
"tab:pink",
"tab:gray",
]
# Module information for coloring and labeling
modules, module_depths = pb.modules, pb.module_depths
# Node colors and labels based on modules
node_colors = []
node_labels = {}
for module_id, qubits in modules.items():
depth = module_depths[module_id]
color = level_colors[depth % len(level_colors)]
for qubit in qubits:
node_colors.append(color)
node_labels[qubit] = f"Q{qubit}"
# Add nodes and edges (regular edges)
G.add_nodes_from([qubit for _, qubits in modules.items() for qubit in qubits])
G.add_edges_from(list(pb.coupling_map))
# Generate layout
pos = nx.kamada_kawai_layout(G)
fig, ax = plt.subplots(figsize=(8, 6)) # Adjust figure size as needed
# Draw the graph without long edges
nx.draw_networkx_nodes(
G, pos, node_size=400, node_color=node_colors, alpha=0.6, ax=ax
) # Adjust node_size here
nx.draw_networkx_labels(
G, pos, labels=node_labels, font_size=8, ax=ax
) # Adjust font_size if necessary
nx.draw_networkx_edges(
G,
pos,
edgelist=list(pb.coupling_map),
width=2,
edge_color="gray",
style="solid",
ax=ax,
)
# Draw long edges on top of the existing layout, if present
if hasattr(pb, "long_edges"):
nx.draw_networkx_edges(
G,
pos,
edgelist=pb.long_edges,
width=5,
edge_color="red",
style="dashed",
ax=ax,
)
ax.set_title(label_text)
ax.axis("off") # Turn off the axis
plt.close(
fig
) # Prevent it from displaying immediately in Jupyter or similar environments
return fig
pretty_print = pretty_print_with_networkx
# Example usage
fake_modular = TreeModular(module_size=4, children=3, total_levels=3)
fake_modular.add_long_edges(num_long_edges=1) # Example: Add 2 long-edges
print("Modules:", fake_modular.modules)
print("Coupling Map:", fake_modular.c_map)
print("Long Edges:", fake_modular.long_edges)
# Then, visualize
label_text = "Example Visualization with Long-Edges"
image = pretty_print(fake_modular, label_text)
# Display the image
# set image to active figure of plt
display(image)
# Generate the images with varying numbers of long edges
figures = []
# Adjusted loop to include iteration over number of long edges
for i in range(3, 6): # Module sizes
for k in range(1, 6): # Total levels
for j in range(i, i + 1): # Children
if k == 1 and j != 2:
continue # Skip configurations that don't make sense
try:
# Create a new instance for each configuration of i, j, k
pb = TreeModular(module_size=i, children=j, total_levels=k)
num_qubits = pb.num_qubits
# Determine the maximum number of long edges for this configuration
max_long_edges = 3 if k > 1 else 0 # At most 4, and 0 if levels=1
for x in range(max_long_edges + 1): # Iterate from 0 to max_long_edges
if num_qubits <= 64:
# Update long edges for the current configuration
pb.add_long_edges(num_long_edges=x)
label_text = f"Module Size: {i}, Children: {j}, Total Levels: {k}, Num Qubits: {num_qubits}, Long Edges: {x}"
print(label_text)
# Generate and store the figure for the current configuration
fig = pretty_print_with_networkx(pb, label_text)
figures.append(fig)
# Reset long edges for the next iteration
pb.long_edges = [] # Clear existing long edges before next addition
except AssertionError:
pass
from PIL import Image
import io
# Create an animation from the figures
# Assuming 'figures' is a list of matplotlib.figure.Figure objects generated from your loop
images = [] # This will hold the PIL Image objects
for fig in figures:
buf = io.BytesIO() # Create an in-memory buffer
fig.savefig(buf, format="png") # Save the figure to the buffer in PNG format
buf.seek(0) # Rewind the buffer to the beginning so we can read from it
img = Image.open(buf) # Open the image from the in-memory buffer
images.append(img) # Append the PIL Image to the list
plt.close(fig) # Close the figure to free memory
gif_path = "networkx_graph_animation.gif"
images[0].save(
gif_path,
save_all=True,
append_images=images[1:],
optimize=False,
duration=1500,
loop=0,
)
# Example usage
corral_modular = CorralModular(num_snails=8, corral_skip_pattern=(0, 0))
corral_modular.add_long_edges(num_long_edges=1) # Example: Add 2 long-edges
print("Modules:", corral_modular.modules)
print("Coupling Map:", corral_modular.c_map)
print("Long Edges:", corral_modular.long_edges)
# Then, visualize
label_text = "Example Visualization with Long-Edges"
image = pretty_print(corral_modular, label_text)
# Display the image
# set image to active figure of plt
display(image)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
def pretty_print_snails_3d(corral_modular):
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection="3d")
num_snails = corral_modular.num_snails
snail_edge_list = corral_modular._corral(
num_snails, corral_modular.corral_skip_pattern
)
snail_colors = [
"tab:blue",
"tab:orange",
"tab:green",
"tab:red",
"tab:purple",
"tab:brown",
"tab:pink",
"tab:gray",
]
# Parameters for the SNAIL posts and slats
post_height = 0.5 # Height of the SNAIL posts
post_radius = 0.05 # Radius of the SNAIL posts
z_offset = post_height / 4
z_lower = np.zeros(num_snails) + z_offset # Lower rung positioned at the base
z_upper = np.ones(num_snails) * 0.25 + z_offset # Upper rung
long_edge_height = (z_lower + z_upper) / 2 # Position long edges in between
# SNAIL positions
theta = np.linspace(0, 2 * np.pi, num_snails, endpoint=False)
x = np.cos(theta)
y = np.sin(theta)
# Draw the SNAIL posts
for i in range(num_snails):
color = snail_colors[corral_modular.module_depths[i] % len(snail_colors)]
ax.plot(
[x[i], x[i]],
[y[i], y[i]],
[0, post_height],
color=color,
lw=6,
solid_capstyle="round",
)
# Function to draw a slat between two points
def draw_slat(point1, point2, z_height, color="black", linestyle="-"):
ax.plot(
[point1[0], point2[0]],
[point1[1], point2[1]],
[z_height, z_height],
color=color,
lw=4,
linestyle=linestyle,
solid_capstyle="round",
)
# Divide the edge list into upper and lower rungs
# Take every second edge starting from the first
upper_rung_edges = snail_edge_list[::2]
# Take every second edge starting from the second
lower_rung_edges = snail_edge_list[1::2]
# Draw the upper rung slats
for snail0, snail1 in upper_rung_edges:
draw_slat((x[snail0], y[snail0]), (x[snail1], y[snail1]), z_upper[snail0])
# Draw the lower rung slats
for snail0, snail1 in lower_rung_edges:
draw_slat((x[snail0], y[snail0]), (x[snail1], y[snail1]), z_lower[snail0])
# Draw the long edges
for edge in corral_modular.long_edges:
# get the snail index for the qubits in the edge
snail0 = corral_modular._find_module_by_qubit(edge[0])
snail1 = corral_modular._find_module_by_qubit(edge[1])
draw_slat(
(x[snail0], y[snail0]),
(x[snail1], y[snail1]),
long_edge_height[edge[0]],
color="red",
linestyle="--",
)
# Set the aspect ratio and the viewing angle
ax.set_aspect("auto")
ax.view_init(elev=30.0, azim=-120)
# Hide the axes
ax.set_axis_off()
return fig
# Example usage:
corral_modular = CorralModular(num_snails=8, corral_skip_pattern=(0, 1))
corral_modular.add_long_edges(num_long_edges=1) # Example: Add 2 long-edges
corral_modular.module_depths = {i: i for i in range(8)} # Example module depths
fig = pretty_print_snails_3d(corral_modular)
from PIL import Image
def combine_images(image1, image2):
# Combine two images side by side
dst = Image.new(
"RGB", (image1.width + image2.width, max(image1.height, image2.height))
)
dst.paste(image1, (0, 0))
dst.paste(image2, (image1.width, 0))
return dst
# Generate the images with varying numbers of long edges for Corral configurations
paired_images = []
for num_snails in range(4, 9, 2): # Example range for number of snails
for skip_step in range(0, 3): # Example range for skip pattern steps
corral_skip_pattern = (0, skip_step) # Define skip pattern based on skip_step
try:
pb = CorralModular(
num_snails=num_snails, corral_skip_pattern=corral_skip_pattern
)
max_long_edges = min(4, num_snails // 2 - 1)
for x in range(max_long_edges + 1):
pb.add_long_edges(num_long_edges=x)
label_text = f"Num Snails: {num_snails}, Skip Pattern: {corral_skip_pattern}, Num Qubits: {num_qubits}, Long Edges: {x}"
print(label_text)
# Generate the figure for the 3D SNAIL visualization
fig_3d = pretty_print_snails_3d(pb)
buf_3d = io.BytesIO()
fig_3d.savefig(buf_3d, format="png")
buf_3d.seek(0)
img_3d = Image.open(buf_3d)
plt.close(fig_3d)
# Generate the figure for the network graph visualization
fig_networkx = pretty_print_with_networkx(pb, label_text)
buf_networkx = io.BytesIO()
fig_networkx.savefig(buf_networkx, format="png")
buf_networkx.seek(0)
img_networkx = Image.open(buf_networkx)
plt.close(fig_networkx)
# Combine the two images side by side
paired_img = combine_images(img_3d, img_networkx)
paired_images.append(paired_img)
pb.long_edges = [] # Clear existing long edges before next addition
except AssertionError:
pass
# Create the GIF from the paired images
gif_path = "corral_snails_and_networkx.gif"
paired_images[0].save(
gif_path,
save_all=True,
append_images=paired_images[1:],
optimize=False,
duration=1500,
loop=0,
)
print(f"GIF saved to {gif_path}")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXSimple
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc, style=IQXSimple())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can make the bars more transparent to better see the ones that are behind
# if they overlap.
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
state = Statevector(qc)
plot_state_city(state, alpha=0.6)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123456
from sklearn.datasets import make_blobs
features, labels = make_blobs(
n_samples=20,
centers=2,
center_box=(-1, 1),
cluster_std=0.1,
random_state=algorithm_globals.random_seed,
)
from qiskit import BasicAer
from qiskit.utils import QuantumInstance
sv_qi = QuantumInstance(
BasicAer.get_backend("statevector_simulator"),
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed,
)
from qiskit.circuit.library import ZZFeatureMap
from qiskit_machine_learning.kernels import QuantumKernel
feature_map = ZZFeatureMap(2)
previous_kernel = QuantumKernel(feature_map=feature_map, quantum_instance=sv_qi)
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=previous_kernel)
qsvc.fit(features, labels)
qsvc.score(features, labels)
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit.primitives import Sampler
fidelity = ComputeUncompute(sampler=Sampler())
from qiskit_machine_learning.kernels import FidelityQuantumKernel
feature_map = ZZFeatureMap(2)
new_kernel = FidelityQuantumKernel(feature_map=feature_map, fidelity=fidelity)
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=new_kernel)
qsvc.fit(features, labels)
qsvc.score(features, labels)
from qiskit import QuantumCircuit
from qiskit.circuit.library import RealAmplitudes
num_inputs = 2
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs, reps=1)
circuit = QuantumCircuit(num_inputs)
circuit.compose(feature_map, inplace=True)
circuit.compose(ansatz, inplace=True)
def parity(x):
return "{:b}".format(x).count("1") % 2
initial_point = algorithm_globals.random.random(ansatz.num_parameters)
from qiskit_machine_learning.neural_networks import CircuitQNN
circuit_qnn = CircuitQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=2,
quantum_instance=sv_qi,
)
from qiskit.algorithms.optimizers import COBYLA
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
classifier = NeuralNetworkClassifier(
neural_network=circuit_qnn,
loss="cross_entropy",
one_hot=True,
optimizer=COBYLA(maxiter=40),
initial_point=initial_point,
)
classifier.fit(features, labels)
classifier.score(features, labels)
from qiskit.primitives import Sampler
sampler = Sampler()
from qiskit_machine_learning.neural_networks import SamplerQNN
sampler_qnn = SamplerQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=2,
sampler=sampler,
)
classifier = NeuralNetworkClassifier(
neural_network=sampler_qnn,
loss="cross_entropy",
one_hot=True,
optimizer=COBYLA(maxiter=40),
initial_point=initial_point,
)
classifier.fit(features, labels)
classifier.score(features, labels)
import numpy as np
num_samples = 20
eps = 0.2
lb, ub = -np.pi, np.pi
features = (ub - lb) * np.random.rand(num_samples, 1) + lb
labels = np.sin(features[:, 0]) + eps * (2 * np.random.rand(num_samples) - 1)
from qiskit.circuit import Parameter
num_inputs = 1
feature_map = QuantumCircuit(1)
feature_map.ry(Parameter("input"), 0)
ansatz = QuantumCircuit(1)
ansatz.ry(Parameter("weight"), 0)
circuit = QuantumCircuit(num_inputs)
circuit.compose(feature_map, inplace=True)
circuit.compose(ansatz, inplace=True)
initial_point = algorithm_globals.random.random(ansatz.num_parameters)
from qiskit.opflow import PauliSumOp, StateFn
from qiskit_machine_learning.neural_networks import OpflowQNN
observable = PauliSumOp.from_list([("Z", 1)])
operator = StateFn(observable, is_measurement=True) @ StateFn(circuit)
opflow_qnn = OpflowQNN(
operator=operator,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
quantum_instance=sv_qi,
)
from qiskit.algorithms.optimizers import L_BFGS_B
from qiskit_machine_learning.algorithms import NeuralNetworkRegressor
regressor = NeuralNetworkRegressor(
neural_network=opflow_qnn,
optimizer=L_BFGS_B(maxiter=5),
initial_point=initial_point,
)
regressor.fit(features, labels)
regressor.score(features, labels)
from qiskit.primitives import Estimator
estimator = Estimator()
from qiskit_machine_learning.neural_networks import EstimatorQNN
estimator_qnn = EstimatorQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
estimator=estimator,
)
from qiskit.algorithms.optimizers import L_BFGS_B
from qiskit_machine_learning.algorithms import VQR
regressor = NeuralNetworkRegressor(
neural_network=estimator_qnn,
optimizer=L_BFGS_B(maxiter=5),
initial_point=initial_point,
)
regressor.fit(features, labels)
regressor.score(features, labels)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/deveshq/QC-with-qiskit
|
deveshq
|
#some necessary imports libraries
import numpy as np
from numpy import pi
import qiskit
from qiskit import *
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout, array_to_latex
from qiskit.providers.aer import noise
from qiskit.quantum_info import Operator
import matplotlib.pyplot as plt
%matplotlib inline
IBMQ.load_account()
backend = Aer.get_backend('qasm_simulator')
# Creating circuit
def ev_circ(qc,J,t):
#qc.h(qr[0])
#qc.barrier()
psi = J*t
for i in range(1):
#sigma_x sigma_x term
qc.ry(pi/2, qr[i])
qc.ry(pi/2, qr[i+1])
qc.cx(qr[i],qr[i+1])
qc.rz(2*psi, qr[i+1])
qc.cx(qr[i],qr[i+1])
qc.ry(-pi/2, qr[i+1])
qc.ry(-pi/2, qr[i])
qc.barrier()
#sigma_y sigma_y term
qc.rx(pi/2, qr[i])
qc.rx(pi/2, qr[i+1])
qc.cx(qr[i],qr[i+1])
qc.rz(2*psi, qr[i+1])
qc.cx(qr[i],qr[i+1])
qc.rx(-pi/2, qr[i+1])
qc.rx(-pi/2, qr[i])
qc.barrier()
#sigma_z sigma_z term
qc.cx(qr[i],qr[i+1])
qc.rz(2*psi, qr[i+1])
qc.cx(qr[i],qr[i+1])
return qc
#Simulating circuit
def sim(i):
[circ2[j].measure(qr[i],cr[0]) for j in range(len(circ2))]
result_sim = execute(circ2, backend, shots=1024).result()
a = result_sim.get_counts()
p0 = []
p1 = []
for k in range(len(a)):
if '0' in a[k]:
p0.append(a[k]['0'])
else:
p0.append(0)
if '1' in a[k]:
p1.append(a[k]['1'])
else:
p1.append(0)
p = (np.array(p0)-np.array(p1))/(2*1024)
return p
qc = QuantumCircuit(qr,cr)
t = 1
circ = ev_circ(qc,J,t)
circ.draw('mpl')
J = 0.01183898*2
total_t = 100
del_t = 1
num_steps = int(total_t/del_t)
qr = QuantumRegister(2, 'q')
cr = ClassicalRegister(1, 'c')
circ2 = []
d = []
for step in range(0, num_steps+1):
qc = QuantumCircuit(qr,cr)
t = (step)*del_t
d.append(J*t)
circ2.append(ev_circ(qc,J,t))
circ2[2].draw('mpl')
prob = {}
for i in range(2):
p = sim(i)
prob['q'+str(i)] = p
fig = plt.figure(figsize=[10,6])
plt.plot(d,prob['q0'])
plt.plot(d,prob['q1'])
#plt.title('')
plt.xlabel(rf'Jt $\longrightarrow$',fontsize=15)
plt.ylabel(rf'Magnetisation $\longrightarrow$',fontsize=15)
plt.legend(['q0','q1'])
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit_chemistry import QiskitChemistry
from qiskit import Aer
# from qiskit import IBMQ
# IBMQ.load_accounts()
# backend = IBMQ.get_backend('ibmq_16_melbourne')
from qiskit import Aer
backend = Aer.get_backend('statevector_simulator')
# Input dictionary to configure Qiskit AQUA Chemistry for the chemistry problem.
qiskit_chemistry_dict = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': 'H2/0.7_sto-3g.hdf5'},
'operator': {'name': 'hamiltonian'},
'algorithm': {'name': 'VQE'},
'optimizer': {'name': 'COBYLA'},
'variational_form': {'name': 'UCCSD'},
'initial_state': {'name': 'HartreeFock'}
}
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict, backend=backend)
print('Ground state energy: {}'.format(result['energy']))
for line in result['printable']:
print(line)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### removed h gate ###
return qc
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
with pulse.build() as hahn_echo:
with pulse.align_equispaced(duration=100):
pulse.play(x90, d0)
pulse.play(x180, d0)
pulse.play(x90, d0)
hahn_echo.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import json
import time
import warnings
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import Statevector
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.circuit.library import RawFeatureVector
from qiskit_machine_learning.neural_networks import SamplerQNN
algorithm_globals.random_seed = 42
def ansatz(num_qubits):
return RealAmplitudes(num_qubits, reps=5)
num_qubits = 5
circ = ansatz(num_qubits)
circ.decompose().draw("mpl")
def auto_encoder_circuit(num_latent, num_trash):
qr = QuantumRegister(num_latent + 2 * num_trash + 1, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.compose(ansatz(num_latent + num_trash), range(0, num_latent + num_trash), inplace=True)
circuit.barrier()
auxiliary_qubit = num_latent + 2 * num_trash
# swap test
circuit.h(auxiliary_qubit)
for i in range(num_trash):
circuit.cswap(auxiliary_qubit, num_latent + i, num_latent + num_trash + i)
circuit.h(auxiliary_qubit)
circuit.measure(auxiliary_qubit, cr[0])
return circuit
num_latent = 3
num_trash = 2
circuit = auto_encoder_circuit(num_latent, num_trash)
circuit.draw("mpl")
def domain_wall(circuit, a, b):
# Here we place the Domain Wall to qubits a - b in our circuit
for i in np.arange(int(b / 2), int(b)):
circuit.x(i)
return circuit
domain_wall_circuit = domain_wall(QuantumCircuit(5), 0, 5)
domain_wall_circuit.draw("mpl")
ae = auto_encoder_circuit(num_latent, num_trash)
qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1)
qc = qc.compose(domain_wall_circuit, range(num_latent + num_trash))
qc = qc.compose(ae)
qc.draw("mpl")
# Here we define our interpret for our SamplerQNN
def identity_interpret(x):
return x
qnn = SamplerQNN(
circuit=qc,
input_params=[],
weight_params=ae.parameters,
interpret=identity_interpret,
output_shape=2,
)
def cost_func_domain(params_values):
probabilities = qnn.forward([], params_values)
# we pick a probability of getting 1 as the output of the network
cost = np.sum(probabilities[:, 1])
# plotting part
clear_output(wait=True)
objective_func_vals.append(cost)
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()
return cost
opt = COBYLA(maxiter=150)
initial_point = algorithm_globals.random.random(ae.num_parameters)
objective_func_vals = []
# make the plot nicer
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
opt_result = opt.minimize(cost_func_domain, initial_point)
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} seconds")
test_qc = QuantumCircuit(num_latent + num_trash)
test_qc = test_qc.compose(domain_wall_circuit)
ansatz_qc = ansatz(num_latent + num_trash)
test_qc = test_qc.compose(ansatz_qc)
test_qc.barrier()
test_qc.reset(4)
test_qc.reset(3)
test_qc.barrier()
test_qc = test_qc.compose(ansatz_qc.inverse())
test_qc.draw("mpl")
test_qc = test_qc.assign_parameters(opt_result.x)
domain_wall_state = Statevector(domain_wall_circuit).data
output_state = Statevector(test_qc).data
fidelity = np.sqrt(np.dot(domain_wall_state.conj(), output_state) ** 2)
print("Fidelity of our Output State with our Input State: ", fidelity.real)
def zero_idx(j, i):
# Index for zero pixels
return [
[i, j],
[i - 1, j - 1],
[i - 1, j + 1],
[i - 2, j - 1],
[i - 2, j + 1],
[i - 3, j - 1],
[i - 3, j + 1],
[i - 4, j - 1],
[i - 4, j + 1],
[i - 5, j],
]
def one_idx(i, j):
# Index for one pixels
return [[i, j - 1], [i, j - 2], [i, j - 3], [i, j - 4], [i, j - 5], [i - 1, j - 4], [i, j]]
def get_dataset_digits(num, draw=True):
# Create Dataset containing zero and one
train_images = []
train_labels = []
for i in range(int(num / 2)):
# First we introduce background noise
empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape(
8, 4
)
# Now we insert the pixels for the one
for i, j in one_idx(2, 6):
empty[j][i] = algorithm_globals.random.uniform(0.9, 1)
train_images.append(empty)
train_labels.append(1)
if draw:
plt.title("This is a One")
plt.imshow(train_images[-1])
plt.show()
for i in range(int(num / 2)):
empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape(
8, 4
)
# Now we insert the pixels for the zero
for k, j in zero_idx(2, 6):
empty[k][j] = algorithm_globals.random.uniform(0.9, 1)
train_images.append(empty)
train_labels.append(0)
if draw:
plt.imshow(train_images[-1])
plt.title("This is a Zero")
plt.show()
train_images = np.array(train_images)
train_images = train_images.reshape(len(train_images), 32)
for i in range(len(train_images)):
sum_sq = np.sum(train_images[i] ** 2)
train_images[i] = train_images[i] / np.sqrt(sum_sq)
return train_images, train_labels
train_images, __ = get_dataset_digits(2)
num_latent = 3
num_trash = 2
fm = RawFeatureVector(2 ** (num_latent + num_trash))
ae = auto_encoder_circuit(num_latent, num_trash)
qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1)
qc = qc.compose(fm, range(num_latent + num_trash))
qc = qc.compose(ae)
qc.draw("mpl")
def identity_interpret(x):
return x
qnn = SamplerQNN(
circuit=qc,
input_params=fm.parameters,
weight_params=ae.parameters,
interpret=identity_interpret,
output_shape=2,
)
def cost_func_digits(params_values):
probabilities = qnn.forward(train_images, params_values)
cost = np.sum(probabilities[:, 1]) / train_images.shape[0]
# plotting part
clear_output(wait=True)
objective_func_vals.append(cost)
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()
return cost
with open("12_qae_initial_point.json", "r") as f:
initial_point = json.load(f)
opt = COBYLA(maxiter=150)
objective_func_vals = []
# make the plot nicer
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
opt_result = opt.minimize(fun=cost_func_digits, x0=initial_point)
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} seconds")
# Test
test_qc = QuantumCircuit(num_latent + num_trash)
test_qc = test_qc.compose(fm)
ansatz_qc = ansatz(num_latent + num_trash)
test_qc = test_qc.compose(ansatz_qc)
test_qc.barrier()
test_qc.reset(4)
test_qc.reset(3)
test_qc.barrier()
test_qc = test_qc.compose(ansatz_qc.inverse())
# sample new images
test_images, test_labels = get_dataset_digits(2, draw=False)
for image, label in zip(test_images, test_labels):
original_qc = fm.assign_parameters(image)
original_sv = Statevector(original_qc).data
original_sv = np.reshape(np.abs(original_sv) ** 2, (8, 4))
param_values = np.concatenate((image, opt_result.x))
output_qc = test_qc.assign_parameters(param_values)
output_sv = Statevector(output_qc).data
output_sv = np.reshape(np.abs(output_sv) ** 2, (8, 4))
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(original_sv)
ax1.set_title("Input Data")
ax2.imshow(output_sv)
ax2.set_title("Output Data")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
https://github.com/QuSTaR/kaleidoscope
|
QuSTaR
|
# -*- 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/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.
# pylint: disable=missing-class-docstring
"""Test the passmanager logic"""
import copy
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import U2Gate
from qiskit.converters import circuit_to_dag
from qiskit.transpiler import PassManager, PropertySet, TransformationPass, FlowController
from qiskit.transpiler.passes import CommutativeCancellation
from qiskit.transpiler.passes import Optimize1qGates, Unroller
from qiskit.test import QiskitTestCase
class TestPassManager(QiskitTestCase):
"""Test Pass manager logic."""
def test_callback(self):
"""Test the callback parameter."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
circuit.h(qr[0])
circuit.h(qr[0])
circuit.h(qr[0])
expected_start = QuantumCircuit(qr)
expected_start.append(U2Gate(0, np.pi), [qr[0]])
expected_start.append(U2Gate(0, np.pi), [qr[0]])
expected_start.append(U2Gate(0, np.pi), [qr[0]])
expected_start_dag = circuit_to_dag(expected_start)
expected_end = QuantumCircuit(qr)
expected_end.append(U2Gate(0, np.pi), [qr[0]])
expected_end_dag = circuit_to_dag(expected_end)
calls = []
def callback(**kwargs):
out_dict = kwargs
out_dict["dag"] = copy.deepcopy(kwargs["dag"])
calls.append(out_dict)
passmanager = PassManager()
passmanager.append(Unroller(["u2"]))
passmanager.append(Optimize1qGates())
passmanager.run(circuit, callback=callback)
self.assertEqual(len(calls), 2)
self.assertEqual(len(calls[0]), 5)
self.assertEqual(calls[0]["count"], 0)
self.assertEqual(calls[0]["pass_"].name(), "Unroller")
self.assertEqual(expected_start_dag, calls[0]["dag"])
self.assertIsInstance(calls[0]["time"], float)
self.assertEqual(calls[0]["property_set"], PropertySet())
self.assertEqual("MyCircuit", calls[0]["dag"].name)
self.assertEqual(len(calls[1]), 5)
self.assertEqual(calls[1]["count"], 1)
self.assertEqual(calls[1]["pass_"].name(), "Optimize1qGates")
self.assertEqual(expected_end_dag, calls[1]["dag"])
self.assertIsInstance(calls[0]["time"], float)
self.assertEqual(calls[0]["property_set"], PropertySet())
self.assertEqual("MyCircuit", calls[1]["dag"].name)
def test_callback_with_pass_requires(self):
"""Test the callback with a pass with another pass requirement."""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
circuit.z(qr[0])
circuit.cx(qr[0], qr[2])
circuit.z(qr[0])
expected_start = QuantumCircuit(qr)
expected_start.z(qr[0])
expected_start.cx(qr[0], qr[2])
expected_start.z(qr[0])
expected_start_dag = circuit_to_dag(expected_start)
expected_end = QuantumCircuit(qr)
expected_end.cx(qr[0], qr[2])
expected_end_dag = circuit_to_dag(expected_end)
calls = []
def callback(**kwargs):
out_dict = kwargs
out_dict["dag"] = copy.deepcopy(kwargs["dag"])
calls.append(out_dict)
passmanager = PassManager()
passmanager.append(CommutativeCancellation(basis_gates=["u1", "u2", "u3", "cx"]))
passmanager.run(circuit, callback=callback)
self.assertEqual(len(calls), 2)
self.assertEqual(len(calls[0]), 5)
self.assertEqual(calls[0]["count"], 0)
self.assertEqual(calls[0]["pass_"].name(), "CommutationAnalysis")
self.assertEqual(expected_start_dag, calls[0]["dag"])
self.assertIsInstance(calls[0]["time"], float)
self.assertIsInstance(calls[0]["property_set"], PropertySet)
self.assertEqual("MyCircuit", calls[0]["dag"].name)
self.assertEqual(len(calls[1]), 5)
self.assertEqual(calls[1]["count"], 1)
self.assertEqual(calls[1]["pass_"].name(), "CommutativeCancellation")
self.assertEqual(expected_end_dag, calls[1]["dag"])
self.assertIsInstance(calls[0]["time"], float)
self.assertIsInstance(calls[0]["property_set"], PropertySet)
self.assertEqual("MyCircuit", calls[1]["dag"].name)
def test_to_flow_controller(self):
"""Test that conversion to a `FlowController` works, and the result can be added to a
circuit and conditioned, with the condition only being called once."""
class DummyPass(TransformationPass):
def __init__(self, x):
super().__init__()
self.x = x
def run(self, dag):
return dag
def repeat(count):
def condition(_):
nonlocal count
if not count:
return False
count -= 1
return True
return condition
def make_inner(prefix):
inner = PassManager()
inner.append(DummyPass(f"{prefix} 1"))
inner.append(DummyPass(f"{prefix} 2"), condition=lambda _: False)
inner.append(DummyPass(f"{prefix} 3"), condition=lambda _: True)
inner.append(DummyPass(f"{prefix} 4"), do_while=repeat(1))
return inner.to_flow_controller()
self.assertIsInstance(make_inner("test"), FlowController)
outer = PassManager()
outer.append(make_inner("first"))
outer.append(make_inner("second"), condition=lambda _: False)
# The intent of this `condition=repeat(1)` is to ensure that the outer condition is only
# checked once and not flattened into the inner controllers; an inner pass invalidating the
# condition should not affect subsequent passes once the initial condition was met.
outer.append(make_inner("third"), condition=repeat(1))
calls = []
def callback(pass_, **_):
self.assertIsInstance(pass_, DummyPass)
calls.append(pass_.x)
outer.run(QuantumCircuit(), callback=callback)
expected = [
"first 1",
"first 3",
# it's a do-while loop, not a while, which is why the `repeat(1)` gives two calls
"first 4",
"first 4",
# If the outer pass-manager condition is called more than once, then only the first of
# the `third` passes will appear.
"third 1",
"third 3",
"third 4",
"third 4",
]
self.assertEqual(calls, expected)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.